After going through @wallyk answer in how to open, read, and write from serial port in C ,I wrote a program to send data through my usb port. I need to send a 6 byte data of which the 1st byte should be in mark parity and the rest should be in space parity. that is the reason I have declared 2 variables msg1 and msg2
#include<stdio.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include<fcntl.h>// used for opening ttys0
#include<sys/ioctl.h>
#include<sched.h>
#include<string.h> // for memset
#include<time.h>
int set_interface_attribs (int fd, int speed, int parity)
{
struct termios tty;
memset (&tty, 0, sizeof tty); // initialize all in struct tty with 0
if (tcgetattr (fd, &tty) != 0)// gets parameters from fd and stores them in tty struct
{
perror("error from tcgetattr");
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars, CSIZE -> character size mask
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // ignore break signal
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;// 1 stop bit
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (fd, TCSANOW, &tty) != 0) // TCSANOW -> the change takes place immediately
{
perror("error from tcsetattr");
return -1;
}
return 0;
}
int main()
{
char *portname = "/dev/ttyUSB0";
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
perror("error opening");
return;
}
char msg1[1]={0x01};
char msg2[5]={0x02,0x08,0x00,0xff,0xf5};
set_interface_attribs (fd, B115200,PARENB|PARODD|CMSPAR); // set speed to 115200, bps,mark parity
// set no blocking
write (fd, msg1, sizeof msg1);
set_interface_attribs (fd, B115200,PARENB|CMSPAR); // set speed to 115200 bps, space parity
write (fd,msg2,sizeof msg2);
close(fd);
return 0;
}
But now all the data that I send seem to be in space parity and not mark parity. ie if I have configured the 1st byte to be sent in mark parity and the rest in space parity, then all are being sent in space parity. Now if I configure the 1st byte to be sent in space parity and the rest in mark parity, then all are being sent in mark parity.