WICHTIG: Der Betrieb von goMatlab.de wird privat finanziert fortgesetzt. - Mehr Infos...

Mein MATLAB Forum - goMatlab.de

Mein MATLAB Forum

 
Gast > Registrieren       Autologin?   

Partner:




Forum
      Option
[Erweitert]
  • Diese Seite per Mail weiterempfehlen
     


Gehe zu:  
Neues Thema eröffnen Neue Antwort erstellen

Sfunction memory Problem

 

babil
Forum-Newbie

Forum-Newbie


Beiträge: 1
Anmeldedatum: 21.04.10
Wohnort: ---
Version: ---
     Beitrag Verfasst am: 21.04.2010, 13:59     Titel: Sfunction memory Problem
  Antworten mit Zitat      
Hallo Zusammen,

ich habe ein Programm in c++ geschrieben, welches mittels RS232 Nachrichten an ein Gerät schickt. Das ganze habe ich in einer S-Function gepackt. Das erstelle Simulink Block funktioniert nur ein Mal und dann stürzt Matlab mit folgender Fehlermeldung ab:

Zitat:
Assertion failed: Forced Assertion at line 714 of file ".\memmgr\mem32aligned.cpp". Corrupted memory block found


Das hat anscheinend mit der Speicherbelegung zu tun. Kann vielleicht mir jemand helfen und einen Blick auf den Code werfen?

Vielen Dank
babil

Code:

//*** ComPortDll.cpp ***//

#include "ComPortDll.h"
#include "DatenOp.h"
#include <stdexcept>

#define S_FUNCTION_LEVEL 2
#define S_FUNCTION_NAME  ComPortDll

#include "simstruc.h"
using namespace std;
    //constructor
   Connx::Connx() {
          hCom=INVALID_HANDLE_VALUE;
          DataSent=0;
   }
   

   
   // Verbindung aufbauen
   void Connx::OpenPort(char* port) {
      hCom = CreateFileA( port,
                     GENERIC_READ | GENERIC_WRITE,
                     0,    // comm devices must be opened w/exclusive-access
                     NULL, // no security attributes
                     OPEN_EXISTING, // comm devices must use OPEN_EXISTING
                     0,    // not overlapped I/O
                     NULL  // hTemplate must be NULL for comm devices
                     );
      if (hCom == INVALID_HANDLE_VALUE) {
            // Handle the error.
           // ssSetErrorStatus(S,"Error encountered due to ...");
            //ssPrintf("Die Verbindung konnte nicht aufgebaut werden.");
      } else {
         //ssPrintf("Verbunden.");
         delete port;
      }
   }

   // Port settings
   void Connx::SetPort(int BaudRate,unsigned char ByteSize,unsigned char StopBits,unsigned char Parity){
      DCB dcb;
      BOOL fSuccess = GetCommState(hCom, &dcb);
        if (!fSuccess) {

            ssPrintf("Der Status der Verbindung konnte nicht gelesen werden.");
      } else {
         dcb.fBinary = TRUE;
            dcb.Parity = Parity;
            dcb.fOutxCtsFlow = FALSE;
            dcb.fOutxDsrFlow = FALSE;
            dcb.fDtrControl = DTR_CONTROL_DISABLE;
            dcb.fDsrSensitivity = FALSE;
            dcb.fTXContinueOnXoff = FALSE;
            dcb.BaudRate = BaudRate;
            dcb.ByteSize = ByteSize;
            dcb.fOutX = FALSE;
            dcb.fInX = FALSE;
            dcb.fErrorChar = FALSE;
            dcb.fNull = FALSE;
            dcb.fRtsControl = RTS_CONTROL_DISABLE;
            dcb.fAbortOnError = FALSE;
            dcb.StopBits = StopBits;

         fSuccess = SetCommState(hCom, &dcb); //neue Werte schreiben und überprüfen
           if (!fSuccess) {

            ssPrintf("Die Verbindungseinstellungen konnten nicht gespeichert werden");
            }
      }
   }

   // Timeouts setzen
   void Connx::SetTimeouts(COMMTIMEOUTS timeouts) {
      timeouts.ReadIntervalTimeout = 1000;
      timeouts.ReadTotalTimeoutConstant = 1000;
      timeouts.ReadTotalTimeoutMultiplier = 1000;
      timeouts.WriteTotalTimeoutConstant = 1000;
      timeouts.WriteTotalTimeoutMultiplier = 1000;

      BOOL fSuccess = SetCommTimeouts(hCom,&timeouts);
      if (!fSuccess) {

               }
   }

      // Daten senden
     // void Connx::Write2Serial(unsigned char* buffer) {
   //       ULONG writtenBytes;
     //       BOOL handleWrite=WriteFile(hCom,buffer,sizeof(buffer),&writtenBytes,NULL);
      //      if (handleWrite==TRUE){
      //        ssPrintf ("success");
        //    }
     // }

      // Verbindung Trennen
      void Connx::CloseConnx() {
         CloseHandle(hCom);
      }
     // setze DataSent
     void Connx::setDataSent(int check) {
      DataSent=check;
     }
     // Get private Vatriablen
     int Connx::getDataSent() {
        if (DataSent==1) {
          return 1;
       } else {
          return 0;
       }
     }
     int Connx::getHandle() {
        if (hCom == INVALID_HANDLE_VALUE) {
          return 0;
       } else {
          return 1;
       }
     }

     // get Com
     HANDLE Connx::getCom() {
        return hCom;
     }
//*** Destructor
     
     Connx::~Connx() {
       
     }
//**************** DATENOPERATIONEN *********************//
//*** constructor ***//

    DatenOp::DatenOp() {
       i2b =new int[8];
      zK=new int[8];
      b2d=0;
   }
   void DatenOp::int2bin(int wert) {
      int rest;
      for (int i=7;i>=0;i--){
         rest = wert % 2;
         if (rest > 0) { i2b[i] = 1; } else { i2b[i] = 0; }
         wert = wert / 2;
      }
   }
//*** 2k nach der Wiki-methode bilden
   void DatenOp::zKomplement(){
       int invertieren=0;
       for (int i=7; i>=0; i--) {
           if (invertieren==0) {
               if (i2b[i]==0) {
                   zK[i]=0;
               } else {
                   zK[i]=1;
                   invertieren=1;
               }
           } else {
               if (i2b[i]==0) {
                   zK[i]=1;
               } else {
                   zK[i]=0;
               }
           }
       } // for ENDE
   }
//*** Binaer zu double ***//  
   void DatenOp::bin2double() {
      double power=0;
      double basis=2;
      int exponent=7;
      for (int i=0; i<=7; i++) {
         power=pow(basis,exponent-i);
         b2d=b2d+(power* zK[i]);
      }
   }
//*** Temperatur Sollwert berechnen ***//
   double DatenOp::TSollwert(int wert) {
      if (wert<0) {
         wert=wert*(-1);
         int2bin(wert);
         zKomplement();
         bin2double();
         return b2d;
      } else { return 0;}

}
//*** DatenOp destructor ***//
    DatenOp::~DatenOp(){
       delete [] i2b;
       delete [] zK;

   }

Connx myConnection;
DatenOp myDaten;



// Need to include simstruc.h for the definition of the SimStruct and
// its associated macro definitions.


#define Serial_Port 0
#define Serial_PARAM(S) ssGetSFcnParam(S,Serial_Port)

#define IS_PARAM_DOUBLE(pVal) (mxIsNumeric(pVal) && !mxIsLogical(pVal) &&\
!mxIsEmpty(pVal) && !mxIsSparse(pVal) && !mxIsComplex(pVal) && mxIsDouble(pVal))

// Function: mdlInitializeSizes ===============================================
// Abstract:
//    The sizes information is used by Simulink to determine the S-function
//    block's characteristics (number of inputs, outputs, states, etc.).
static void mdlInitializeSizes(SimStruct *S)
{
    // 1 Parameter
    ssSetNumSFcnParams(S, 1);

    // Parameter mismatch will be reported by Simulink
    if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
        return;
    }

    // Specify I/O
    if (!ssSetNumInputPorts(S, 5)) return;
    ssSetInputPortWidth(S, 0, 1);
    ssSetInputPortWidth(S, 1, 1);
    ssSetInputPortWidth(S, 2, 1);
    ssSetInputPortWidth(S, 3, 1);
    ssSetInputPortWidth(S, 4, 1);

    ssSetInputPortDirectFeedThrough(S, 0, 1);
    ssSetInputPortDirectFeedThrough(S, 1, 1);
    ssSetInputPortDirectFeedThrough(S, 2, 1);
    ssSetInputPortDirectFeedThrough(S, 3, 1);
    ssSetInputPortDirectFeedThrough(S, 4, 1);

    if (!ssSetNumOutputPorts(S,1)) return;
    ssSetOutputPortWidth(S, 0, DYNAMICALLY_SIZED);

    ssSetNumSampleTimes(S, 1);

    // Reserve place for C++ object
    ssSetNumPWork(S, 1);

    ssSetOptions(S,
                 SS_OPTION_WORKS_WITH_CODE_REUSE |
                 SS_OPTION_EXCEPTION_FREE_CODE);

}


// Function: mdlInitializeSampleTimes =========================================
// Abstract:
//   This function is used to specify the sample time(s) for your
//   S-function. You must register the same number of sample times as
//   specified in ssSetNumSampleTimes.
static void mdlInitializeSampleTimes(SimStruct *S)
{
    ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
    ssSetOffsetTime(S, 0, 0.0);
    ssSetModelReferenceSampleTimeDefaultInheritance(S);
}

// Function: mdlStart =======================================================
// Abstract:
//   This function is called once at start of model execution. If you
//   have states that should be initialized once, this is the place
//   to do it.
#define MDL_START
static void mdlStart(SimStruct *S)
{
   char_T* str;
   mxGetString(Serial_PARAM(S),str,5);
   myConnection.OpenPort(str);
   myConnection.SetPort();
   delete str;
}

// Function: mdlOutputs =======================================================
// Abstract:
//   In this function, you compute the outputs of your S-function
//   block. Generally outputs are placed in the output vector, ssGetY(S).
static void mdlOutputs(SimStruct *S, int_T tid)
{
    if (myConnection.getDataSent() == 0 && myConnection.getHandle() == 1 ){
   ssPrintf("inside");
    InputRealPtrsType  u = ssGetInputPortRealSignalPtrs(S,0); // Temperatur
    InputRealPtrsType  u1 = ssGetInputPortRealSignalPtrs(S,1); // Temp Rampe
    InputRealPtrsType  u2 = ssGetInputPortRealSignalPtrs(S,2); // Ventilator
    InputRealPtrsType  u3 = ssGetInputPortRealSignalPtrs(S,3); // Steckdose
    InputRealPtrsType  u4 = ssGetInputPortRealSignalPtrs(S,4); // Uhrkontakt
               real_T *y = ssGetOutputPortRealSignal(S, 0);


       double mySWert=myDaten.TSollwert(*u[0]);
       char sollwert = (char)mySWert;
       char temprampe=(char)*u1[0];
       char ventilator=(char)*u2[0];
       char steckdose=(char)*u3[0];
       char uhrkontakt=(char)*u4[0];
       int sw = (int)mySWert;
       int dt = (int)*u1[0];
       int vt = (int)*u2[0];
       int sd = (int)*u3[0];
       int uk = (int)*u4[0];
       int pruefsumme=(1+128+0+255+sw+0+dt+50+0+1+50+vt+sd+uk) % 256;
       char psumme=char(pruefsumme);
      unsigned char buf[18]={2,1,128,psumme,0,255,sollwert,0,temprampe,50,0,1,50,ventilator,steckdose,uhrkontakt,16,3};
       //unsigned char buf[20]={2,1,128,108,0,0,16,16,0,16,16,50,0,1,50,100,1,1,16,3};
      HANDLE myHCom=myConnection.getCom();
      ULONG writtenBytes;
       BOOL handleWrite=WriteFile(myHCom,buf,sizeof(buf),&writtenBytes,NULL);
       //myConnection.Write2Serial(buf);
      myConnection.setDataSent(1);
      } else {
        ssPrintf("ein Fehler ist aufgetreten");
      }


}

// Function: mdlTerminate =====================================================
// Abstract:
//   In this function, you should perform any actions that are necessary
//   at the termination of a simulation.  For example, if memory was
//   allocated in mdlStart, this is the place to free it.
static void mdlTerminate(SimStruct *S)
{
    myConnection.CloseConnx();
   myConnection.~Connx();
   myDaten.~DatenOp();
}


// Required S-function trailer
#ifdef  MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
#include "simulink.c"      /* MEX-file interface mechanism */
#else
#include "cg_sfun.h"       /* Code generation registration function */
#endif
//////////////////////////////////////////////
//////////////////////////////////////////////

 


Code:

// ComPortDll.h
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#include <tchar.h>
#include <assert.h>
#include <string.h>
#include <malloc.h>


   class Connx {
   public:
       Connx();
      void OpenPort(char* port);
      void SetPort(int BaudRate=19200, unsigned char ByteSize=8, unsigned char StopBits=ONESTOPBIT, unsigned char Parity=FALSE);
      void SetTimeouts(COMMTIMEOUTS timeouts);
        //void Write2Serial(unsigned char* buffer);
        void CloseConnx();
      void setDataSent(int check);
      int getDataSent();
      int getHandle();
      HANDLE getCom();
      ~Connx();
        private:
                HANDLE hCom;
            int DataSent;
   };

/////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
 


Code:

//*** DatenOp.h ***//
#include <math.h>
#include <malloc.h>

class DatenOp {
public:
     DatenOp();
     void int2bin(int wert);
     void zKomplement();
     void bin2double();
     char pruefsumme(char wert);
     double TSollwert(int wert);
    ~DatenOp();
private:
     int* i2b;
     int* zK;
     double b2d;
};
 
Private Nachricht senden Benutzer-Profile anzeigen


Neues Thema eröffnen Neue Antwort erstellen



Einstellungen und Berechtigungen
Beiträge der letzten Zeit anzeigen:

Du kannst Beiträge in dieses Forum schreiben.
Du kannst auf Beiträge in diesem Forum antworten.
Du kannst deine Beiträge in diesem Forum nicht bearbeiten.
Du kannst deine Beiträge in diesem Forum nicht löschen.
Du kannst an Umfragen in diesem Forum nicht mitmachen.
Du kannst Dateien in diesem Forum posten
Du kannst Dateien in diesem Forum herunterladen
.





 Impressum  | Nutzungsbedingungen  | Datenschutz | FAQ | goMatlab RSS Button RSS

Hosted by:


Copyright © 2007 - 2024 goMatlab.de | Dies ist keine offizielle Website der Firma The Mathworks

MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, SimBiology, SimHydraulics, SimEvents, and xPC TargetBox are registered trademarks and The MathWorks, the L-shaped membrane logo, and Embedded MATLAB are trademarks of The MathWorks, Inc.