-1
com0comを使用して作成された仮想シリアルポート間でデータを送受信しています。C - 送信バイトと異なるシリアルポート読み取りバイト
片側はubuntu VMゲストで実行されているCプログラムで、もう一方はWindows 10ホストで実行されているC#.Netプログラムです。
UbuntuのttySポートとWindowsの仮想COMポート間でデータを送受信できますが、単純なテストではCプログラムで受信したバイトとC#プログラムで送信されたバイトが異なるようです。 C#.NETから送ら
バイト:Cで受信0x4B
バイト:0xB
お知らせ欠けている '4' は、それはタイプミスの間違いではありません。
なぜバイトが違うのですか?
Cコード
#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 to 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 to open port.\n");
} else {
printf("Port is 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 a single byte to device which should respond to this
byte_t commandBytes[1] = { 0x0 };
printf("Attempting to write to 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 to read from 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 one byte response
return readResult;
}
/*** Function: main
main()
{
/* Using virtual serial port pairs on host so
read and write needs to 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 for response to 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#コード
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);
'portSett.c_cflag | =〜CS8;'うーん?それは目的ですか? – Lundin
portSettを使用する前に "tcgetattr(fd、&portSett)"を呼び出すことは良い考えではないでしょうか? – TonyB