简体   繁体   English

用C ++与ARDUINO进行串行通信

[英]serial communication with ARDUINO in C++

#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 code: int p; arduino代码:int p; void setup() { pinMode(13,OUTPUT); void setup(){pinMode(13,OUTPUT); Serial.begin(9600); Serial.begin(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);
        } 
    }

i have tried this code in C++ for serial communication with the arduino. 我已经在C ++中尝试过使用此代码与arduino进行串行通信。 i got an error "premature eof". 我收到一个错误“ eof过早”。 what is the problem here?? 这里有什么问题??

Assuming your arduino is actually connected to that port and echoing what it receives, you have to take two things into account: a) Before your arduino code gets control of the serial port, it first tries to load the serial bootloader, so it is possible for the first bytes of communication to never reach your code. 假设您的arduino实际上已连接到该端口并回显它所接收的内容,则必须考虑两点:a)在您的arduino代码获得对串行端口的控制之前,它首先尝试加载串行引导程序,因此有可能使通信的第一个字节永远不会到达您的代码。 b) Even if it does, arduino is probably way slower than your computer and it may not have time to process the answer before you do the check. b)即使可以,但arduino可能比您的计算机慢得多,并且在进行检查之前可能没有时间处理答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM