是的,它有问题。
serialOpen()
如果操作失败,则返回 -1,errno
设置为指示错误。
确保在程序的开头包含<stdlib.h>
、<stdio.h>
、<string.h>
、<errno.h>
和<wiringSerial.h>
,并使用例如打开串行端口
int fd;
fd = serialOpen("/dev/ttyS0", 115200);
if (fd == -1) {
fprintf(stderr, "Cannot open /dev/ttyS0: %s.\n", strerror(errno));
exit(EXIT_FAILURE);
}
write()
可能会返回一个简短的计数。您不能假设它成功发送了所有内容。我建议您使用辅助函数,例如
#ifdef __cplusplus
extern "C" {
#endif
int writeall(const int fd, const void *data, const size_t len)
{
const char *ptr = (const char *)data;
const char *const end = (const char *)data + len;
ssize_t n;
while (ptr < end) {
n = write(fd, ptr, (size_t)(end - ptr));
if (n > 0)
ptr += n;
else
if (n != -1)
return errno = EIO;
else
if (errno != EINTR)
return errno;
}
return 0;
}
#ifdef __cplusplus
}
#endif
成功返回 0,错误返回非零。你可以这样使用它:
if (writeall(fd, "\x3E\x52\x01\x53\x01\x01", 6)) {
fprintf(stderr, "Serial write error: %s.\n", strerror(errno));
/* If this is fatal, do exit(EXIT_FAILURE) here.
If the error is not a fatal one, let the program continue.
*/
}
不要做sleep()
。至少,请确保包含<termios.h>
,并执行
tcdrain(fd);
确保内核发送所有串行数据;它只会在到目前为止写入的所有内容fd
(fd
对串行端口或 tty 开放)之后返回。
另外,我建议不要使用serialPutchar()
, serialPuts()
, serialPrintf()
, 和serialGetchar()
,因为它们没有任何类型的错误检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句