c - 设置同步文件写入超时而不用 time() 浪费微秒
问题描述
我目前正在将我的 PC 与对时间非常敏感的微控制器连接。事实上,如果我在发送最后一个字节和等待一个字节返回之间有几十微秒的时间可以玩,我会很幸运。
我在 PC 端尝试做的是尽快将数据发送到微控制器。这是我的代码:
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#define TIMEOUT 5 //give the PC 5 seconds
int main(){
int nwrite=0;
int fd=open("/dev/ttyS0",O_NOCTTY | O_WRONLY); //open port
if (fd > -1){
int start=time(NULL); //start clock
while (time(NULL)-start < TIMEOUT && nwrite == 0){
nwrite=write(fd,"\n",1); //try outputting enter
if (nwrite < 0){
close(fd); //close file because writing returned error
printf("Write Error");
return -1;
}
}
close(fd);
if (nwrite != 0){
printf("Byte sent out");
}
}else{
printf("Bad file");
}
return 0;
}
即使这样可以完成工作,但速度还不够快。这是我从打开到关闭的程序:
13:22:04.160431 open("/dev/ttyS0", O_WRONLY|O_NOCTTY) = 3
13:22:04.160738 time(NULL) = 1558545724
13:22:04.160913 time(NULL) = 1558545724
13:22:04.161088 write(3, "\n"..., 1) = 1
13:22:04.161278 time(NULL) = 1558545724
13:22:04.161450 close(3) = 0
我注意到这些时间命令每个处理至少需要 100 微秒。如果发生超时,是否可以使用其他函数代替 time() 中止写入序列?但是该函数需要比 time() 函数执行得更快。
解决方案
推荐阅读
- c# - C#编码。
.GetBytes() 向该输入返回不同的数据 - python - 来自不同文件的python类继承
- c# - 在空间网格中查找角点
- python - 构建/使用模块时的 Python 路径
- node.js - Nodejs - 在函数内部初始化的变量在函数外部未定义
- python - 解析字符串中特定子字符串的最pythonic方法?
- angular - 如何在输入元素中插入图像数据以生成 FIleList
- c++ - 读取一个csv文件并将其所有数据添加到C++中的向量中
- vba - 访问表单上未触发 DEL 键(文本框 KeyUp 事件)
- node.js - Microsoft Graph getSchedule 方法导致 InvalidAuthenticationToken 错误代码 80049217