c# - C - Serial port read byte different from sent byte -
i sending , receiving data between virtual serial ports created using com0com.
on 1 side c program running in ubuntu vm guest , other side c#.net program running on windows 10 host.
i can send , receive data between ttys ports on ubuntu , virtual com ports on windows, in simple test seems byte received in c program different send c# program.
byte sent c#.net: 0x4b
byte received in c: 0xb
notice missing '4', it's not typo mistake.
the question why byte different?
c code
#include <stdio.h> #include <fcntl.h> #include <termios.h> #include <sys/select.h> #include <time.h> typedef unsigned char byte_t; // *** function: open_port int open_port(char* tty_path){ int fd; struct termios portsett; printf("attempting open port: %s\n", tty_path); fd = open(tty_path, o_rdwr | o_noctty | o_ndelay); printf("file descriptor: %d\n", fd); if(fd == -1){ printf("unable open port.\n"); } else { printf("port open.\n"); fcntl(fd, f_setfl, 0); printf("configuring port.\n"); cfsetispeed(&portsett, b115200); cfsetospeed(&portsett, b115200); portsett.c_cflag &= ~parenb; portsett.c_cflag &= ~cstopb; portsett.c_cflag &= ~csize; portsett.c_cflag |= ~cs8; tcsetattr(fd, tcsanow, &portsett); } return fd; } / *** function: write_to_port int write_to_port(int fd){ //send single byte device should respond byte_t commandbytes[1] = { 0x0 }; printf("attempting write serial port fd = %i.\n", fd); int writeresult = write(fd, commandbytes, 1); printf("write result: %i\n", writeresult); return writeresult; } / *** function: read_from_port int read_from_port(int fd){ byte_t readbuff[1]; int readresult = -1; printf("attempting read serial port fd = %i.\n", fd); readresult = read(fd, readbuff, sizeof(readbuff)); printf("read result: %d\n\n", readresult); if(readresult >= 1) printf("response: <0x%x>\n", readbuff[0]); //only expecting 1 byte response return readresult; } / *** function: main main() { /* using virtual serial port pairs on host read , write needs happen on different ttys */ char *tty_write_path = "/dev/ttys1"; char *tty_read_path = "/dev/ttys2"; int fd_write = open_port(tty_write_path); int fd_read = open_port(tty_read_path); write_to_port(fd_write); usleep(2000000); //give time response arrive read_from_port(fd_read); if(close(fd_write) != 0) printf("error closing file %i.\n", fd_write); if(close(fd_read) != 0) printf("error closing file %i.\n", fd_read); }
c# code
using system.io.ports; serialport m_comportwrite = new serialport("com9", 115200, parity.none, 8); m_comportwrite.open(); byte[] commandbytes = new byte[] { 0x4b }; m_comportwrite.write(commandbytes , 0, commandbytes .length);
seems set bits except cs8 here portsett.c_cflag |= ~cs8;
should
portsett.c_cflag |= cs8;
according other side settings (see 8)
serialport("com9", 115200, parity.none, 8);
Comments
Post a Comment