简体   繁体   English

在Linux中写入串行端口

[英]Writing to a serial port in linux

I am trying to program a robot that has motordrivers on certain serial ports (ie ttyS9) 我正在尝试对在某些串行端口(即ttyS9)上具有马达驱动器的机器人进行编程

Through cutecom (as hex input), I can send the following input, which gives me the result I expect: 通过cutecom(作为十六进制输入),我可以发送以下输入,从而得到预期的结果:

5aaa0700fffff000

Now I am trying to achieve the same result with a C program, that does the following: 现在,我正在尝试使用C程序实现相同的结果,该程序执行以下操作:

int port9 = open("/dev/ttyS9", O_RDWR | O_NONBLOCK);

char buff[17] = "5aaa0700fffff000";

write(port9, buff, 16);

I've also tried to initialize buff with the hex values seperately: 我也尝试分别用十六进制值初始化buff

buff[0] = 0x5;
buff[1] = 0xa;

etc etc. 等等等

Both do not work. 两者都不起作用。 Is the problem in my code, or in the driver? 问题出在我的代码中还是驱动程序中?

I compile using gcc and then run it with sudo. 我使用gcc进行编译,然后使用sudo运行它。 The open function also returns values that are proper (no errors), as well as the write. 打开函数还返回正确的值(无错误)以及写入。

Filling a character array with strings will convert characters to their ascii representation not hex as you need. 用字符串填充字符数组会将字符转换为它们的ascii表示形式,而不是根据需要的十六进制形式。

char buff[17] = "5aaa0700fffff000"; // Incorrect for saving 0x5aaa0700fffff000 to buff

As i see, you want to write 8 byte 0x5aaa0700fffff000 on serial port, a char is 8bit (1 byte) and you have to send 8 bytes not 16, so the code should be something like this 如我所见,您想在串行端口上写入8个字节0x5aaa0700fffff000,一个char是8bit(1个字节),并且您必须发送8个字节而不是16个,所以代码应该是这样的

buff[0] = 0x5a;
buff[1] = 0xaa;
...
write(port9, buff, 8);

but maybe it's a number so you'll need unsigned long long int t= 0x5aaa0700fffff000; write(.., (char *)&t, 8); 但是也许这是一个数字,所以您需要unsigned long long int t= 0x5aaa0700fffff000; write(.., (char *)&t, 8); unsigned long long int t= 0x5aaa0700fffff000; write(.., (char *)&t, 8);

that means byte order in memory is completely different to one you'll gain with just assigning bytes as you read it from screen. 这意味着内存中的字节顺序与您从屏幕上读取字节时分配的字节完全不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM