【问题标题】:serial communication with ARDUINO in C++在 C++ 中与 ARDUINO 的串行通信
【发布时间】:2016-10-01 04:14:41
【问题描述】:
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;

char j='a';
main()
{
fstream arduino;
arduino.open("/dev/ttyACM0",ios::in | ios::out);
//Opening device file

if(!arduino)
cout<<"error";
arduino<<2;
arduino.clear();
if(arduino >> j)
cout << "Value received: " << j << '\n';
else if(arduino.eof())
cerr << "Premature EOF\n";
else if(arduino.bad())
cerr << "Attempt to read from device failed.\n";
else
cerr << "Logical I/O error.\n";
arduino.close();
return 0;
}

arduino 代码: 诠释 p; 无效设置() { pinMode(13,输出); 序列号.开始(9600); }

   void loop() 
   {
       if(Serial.available())
       {
           p=Serial.read();
           if(p!=-1)
           {
               Serial.write(1);
               digitalWrite(13,HIGH);
               delay(5000);
            }   
        }
        else
        {
            digitalWrite(13,LOW);
            delay(1000);
        } 
    }

我已经在 C++ 中尝试使用此代码与 arduino 进行串行通信。我收到一个错误“过早的 eof”。这里有什么问题??

【问题讨论】:

    标签: c++ serial-communication


    【解决方案1】:

    假设您的 arduino 实际上已连接到该端口并回显它接收到的内容,您必须考虑两件事: a)在您的 arduino 代码控制串行端口之前,它首先尝试加载串行引导加载程序,因此第一个通信字节可能永远不会到达您的代码。 b) 即使是这样,arduino 也可能比您的计算机慢得多,并且在您进行检查之前可能没有时间处理答案。

    【讨论】:

    • 对于第一个问题,在发送任何内容之前,请尝试在程序开始时读取串行端口上可能存在的任何内容。对于第二个问题,试试std::this_thread::sleep_for,稍微延迟一下你的程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多