I am trying to etablish a comunication with a mass flow controler using linux and cpp , i write the code but i am not getting any response from my MFC. I try many think but isnt working.Did I miss somethink or i need to make some modfication ?
The MFC that i am using is an Alicat MFC, communicate via Serial Port using RS232 protocol and ASCII data.
Thats My code :
#include <stdio.h>
#include <string.h>
// Linux headers
#include <fcntl.h> // Contains file controls like O_RDWR
#include <errno.h> // Error integer and strerror() function
#include <termios.h> // Contains POSIX terminal control definitions
#include <unistd.h> // write(), read(), close()
#include <iostream>
struct termios tty;
using namespace std ;
int main(){
cout << "step_1\n";
int serial_port = open("/dev/ttyUSB0", O_RDWR| O_NOCTTY);
// Check for errors
if (serial_port < 0)
{
printf("Error %i from open: %s\n", errno, strerror(errno));
exit(-2);
}
if(tcgetattr(serial_port, &tty) != 0)
{
cout << ("Error %i from tcgetattr: %s\n", errno, strerror(errno));
exit(-3);
}
cout << "step_2\n";
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOP;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag |= CRTSCTS;
tty.c_cflag |= CREAD | CLOCAL;
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO; // Disable echo
tty.c_lflag &= ~ECHOE; // Disable erasure
tty.c_lflag &= ~ECHONL; // Disable new-line echo
tty.c_lflag &= ~ISIG;
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl./
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);
tty.c_oflag &= ~OPOST;
tty.c_oflag &= ~ONLCR;
tty.c_cc[VTIME] = 1;
tty.c_cc[VMIN] = 5;
cfsetispeed(&tty, B19200);
cfsetospeed(&tty, B19200);
tcflush( serial_port, TCIFLUSH );
cout << "step_3\n";
if (tcsetattr(serial_port, TCSANOW, &tty) != 0)
{
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
}
cout << "step_4\n";
tcflush( serial_port , TCIFLUSH );
cout<< "step_5\n";
unsigned char cmd[] = "A\r";
int n_written = 0,
spot = 0;
do {
n_written = write(serial_port, &cmd[spot], sizeof(cmd) - 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
int n = 0;
spot = 0;
char buf = '\0';
/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);
do {
n = read( serial_port, &buf, sizeof(buf));
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0);
if (n < 0) {
std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
std::cout << "Read nothing!" << std::endl;
}
else {
std::cout << "Response: " << response << std::endl;
}
return -1 ;
}