我在这里找到了将数据写入 Arduino 板的教程:https://salilkapur.wordpress.com/2013/03/08/communicating-with-arduino-using-c/
代码使用file = fopen("/dev/ttyUSB0","w+");
打开端口进行读/写操作,并使用fprintf
将数据写入设备。但是当我尝试使用fscanf
从Arduino检索数据时(我使用Serial.print
从Arduino端将数据写回PC,并且数据是格式为 DEC
),它不起作用。
我可以使用 Arduino IDE 中的串行监视器查看输出,但无法在 C 程序的输出中查看输出。为什么它不工作?我需要做什么才能让它工作?
该程序在 Ubuntu 中运行。
这是我的 C 代码,应该在 PC 上运行:
#include <stdio.h>
int main()
{
FILE *file;
char a=0;
file = fopen("/dev/ttyUSB0","w+");
int i = 0;
if(file == -1)
printf("error");
for(i = 0 ; i < 3 ; i++)
{
fprintf(file,"C");
fscanf(file, "%c", &a);
printf("%c", a);
}
fclose(file);
}
我还尝试了一些变体,例如使用 %d
而不是 %c
、使用 int
代替 char 以及使用 fflush
。我不知道为什么它不起作用。难道是我的Arduino板不工作?
注意:它应该在每个字符输入后给出一个输出。
最佳答案
您无法读取任何内容的原因是当您调用
file = fopen("/dev/ttyUSB0","w+");
the arduino is reset ,开机需要1-2秒。由于某种原因,读取无限期地挂起。
在 fopen
旁边添加 sleep(2);
可能会达到目的。
关于c - 如何使用C语言从Arduino板读取数据到PC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36571268/