ฉันกำลังพยายามสร้างโปรแกรม linux ubuntu ที่จะอ่านข้อมูลจากพอร์ตอนุกรม tty (พอร์ต COM ใน windows) ฉันไม่ได้ใช้อะแดปเตอร์ USB แต่เป็นพอร์ต COM จริง นี่คือรหัสของฉันสำหรับการสื่อสารจนถึงตอนนี้:
int OpenPort(void)
{
int fd; // file description for sp
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
if(fd == -1) // port not opened
{
printf("Error:\n%s.\n", strerror(errno));
}
else
{
fcntl(fd, F_SETFL, 0);
printf("Success.\n");
}
return(fd);
} // Open sp
void Communicate(void)
{
struct termios settings;
tcgetattr( fd, &settings );
cfsetispeed(&settings, B9600); // Set bouds
cfsetospeed(&settings, B9600);
settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
settings.c_cflag &= ~CSTOPB;
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8;
tcflush( fd, TCIFLUSH );
if (tcsetattr(fd, TCSAFLUSH, &settings)!= 0)
{
printf("Error message");
}
//Create byte array
unsigned char send_bytes[] = { 0x1, 0x6, 0x2, 0xAA, 0x2, 0x3, 0xB8, 0x4 };
write(fd, send_bytes, sizeof(send_bytes)); // Send data
printf("Data sent. \n");
char buffer[64]; // buffer to receive data
printf("I'm reading data...\n");
int n = read(fd, buffer, sizeof(buffer));
if (n < 0)
printf("Failed to read\n");
int i;
printf("Showing data...\n");
for(i=0; i<sizeof(buffer); i++)
{
printf("Hex: %x\n", buffer[i]);
}
printf("Closing...\n");
close(fd);
printf("All done!\n");
}
ฉันมีปัญหาหลายประการที่นี่:
- หลังจากที่ฉันรันโปรแกรมเมื่อมันทำงานอย่างถูกต้อง แต่เมื่อฉันพยายามรันอีกครั้ง มันหยุดที่ "ฉันกำลังอ่านข้อมูล..." และจะไม่เริ่มทำงานแม้ว่าฉันจะรีสตาร์ทคอมพิวเตอร์แล้วก็ตาม หลังจากนั้นสักพักก็อนุญาตให้ฉันรันโปรแกรมอีกครั้ง
- หลังจากที่โปรแกรมส่งคืนข้อมูลแล้ว ควรส่งข้อมูลฐานสิบหกเช่น A7, 9F เป็นต้น แต่นี่จะให้ค่าจำนวนเต็มแก่ฉัน
- ฉันควรล้างอาร์เรย์บัฟเฟอร์เพื่อเพิ่มหน่วยความจำและทำอย่างไร
ใครสามารถช่วยแก้ปัญหาเหล่านี้ได้บ้าง?