【问题标题】:How to read data from Arduino board to pc using C?如何使用 C 将数据从 Arduino 板读取到 pc?
【发布时间】:2016-04-12 10:58:29
【问题描述】:

我在这里找到了将数据写入 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 中运行。

这是我应该在 PC 上运行的 C 代码:

#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 板不工作?

注意:它应该在每个字符输入后给出一个输出。

【问题讨论】:

  • 我怀疑你的代码可能有问题。
  • 你确定你的 arduino 在 /dev/ttyUSB0 吗?串行监视器是否在 Arduino IDE 中打开(打开时不能读/写)?将 if(file == -1) 更改为 if(file == NULL)。什么是arduino代码?顺便说一句,您正在尝试在您的 scanf 中读取带有%c 的数字(arduino 中的DEC),尝试使用%d

标签: c arduino serial-port usb


【解决方案1】:

你看不到任何东西的原因是当你打电话时

file = fopen("/dev/ttyUSB0","w+");

the arduino is reset,开机需要1-2秒。由于某种原因,读取无限期挂起。

fopen 旁边添加sleep(2); 可能会成功。

查看如何disable auto reset

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 2014-05-10
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多