using C code for serial port communication in matlab via mex file
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi,
I have implemented a C code for the serial port Communication. I want to use this function in matlab. I read the documentation about mex file (mex function) and i made the changes which i need for mexFunction. When i write mex serial_port.c to the command line everything is fine and matlab generates serial_port.mexa64. But when i want to use it and write serial_port() to the command line the serial port is not opening. what could be the problem?
here is my code:
#include "mex.h"
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
void mexFunction (int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
{
if(nrhs != 0) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs",
"zero inputs required.");
}
if(nlhs != 0) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs",
"Two output required.");
}
char serial;
struct termios SerialPortSettings;
serial= open("/dev/ttyACM1", O_RDWR | O_NOCTTY);
printf("%i \n",serial);
tcgetattr(serial, &SerialPortSettings);
cfsetispeed(&SerialPortSettings,B9600);
cfsetospeed(&SerialPortSettings,B9600);
SerialPortSettings.c_cflag &= ~PARENB;
SerialPortSettings.c_cflag &= ~CSTOPB;
SerialPortSettings.c_cflag &= ~CSIZE;
SerialPortSettings.c_cflag &= ~CS8;
SerialPortSettings.c_cflag &= ~CRTSCTS;
SerialPortSettings.c_cflag |= CREAD | CLOCAL ;
SerialPortSettings.c_cc[VMIN] = 9;
SerialPortSettings.c_cc[VTIME] = 0;
SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);
SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tcsetattr(serial,TCSANOW,&SerialPortSettings);
char writeb[9];
writeb[0]=1;
writeb[1]=2;
writeb[2]=0;
writeb[3]=0;
writeb[4]=0;
writeb[5]=0;
writeb[6]=0;
writeb[7]=200;
writeb[8]=writeb[0]+writeb[1]+writeb[2]+writeb[3]+writeb[4]+writeb[5]+writeb[6]+writeb[7];
int bytes_written=0;
bytes_written=write(serial,writeb,sizeof(writeb));
char readb[9];
int bytes_read;
int a;
bytes_read=read(serial,&readb,9);
a=readb[2];
printf("%i \n",a);
close(serial);
}
best regards
4 Kommentare
Walter Roberson
am 26 Mai 2017
There is no direct access from MATLAB or Simulink to C++ classes, unless perhaps there is something that can be done with custom code generation.
See however, the discussion at https://www.mathworks.com/matlabcentral/answers/783-i-have-a-c-class-how-can-i-interface-to-it-through-a-matlab-class
Antworten (0)
Siehe auch
Kategorien
Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!