【问题标题】:Fixing Communications between Arduino and C++ Mac OS X修复 Arduino 和 C++ Mac OS X 之间的通信
【发布时间】:2015-06-22 01:34:39
【问题描述】:

我在使用 Serial 从 C++ 到 Arduino 通信时遇到问题。我在这里使用了 Salil Kapur 讨论的方法:https://salilkapur.wordpress.com/2013/03/08/communicating-with-arduino-using-c/。我已经调整了他使用 c++ 直接写入 Arduino 文件的策略。对于我的特定任务,我需要向 Arduino 发送一串字符(这是 arduino 处理的命令)。我已经从 C++ 程序中的文件中读取了字符,但由于某种原因,当我发送它时,我没有从我的 Arduino 串行监视器中得到任何信息。我认为波特率可能是问题所在,但我并不肯定。我会给你我的代码以获得具体帮助。如果有人可以建议我如何让 C++ 将字符写入要读取的串行监视器:

C++:
#include
#include //For sleep()
#include //For FILE
#include //For ifstream
#include //For assert()
#include //For string
using namespace std;

int main()
{
   //Setting up the output to the Arduino
   FILE *arduino;
   arduino = fopen(“/dev/tty.usbmodem1411″,”w”);  //Declare the file in write mode
   if (arduino == NULL) perror (“Error opening file”);

   //Setting up the file input stream
   ifstream inFile (“input.txt”);
   assert(inFile.is_open());

   char input = '\0'; //Starts out as NULL

   while (input!= EOF) {
      fprintf(arduino,”%c “, input); //Writing to the file
      inFile >> input; //Getting the file input to make sure it isn’t the EOF
      sleep(1);
   }
   fclose(arduino);
}

Arduino 代码:

void setup()
{
   Serial.begin(9600);
}

void loop()
{
   char input;
   if(Serial.available()) //If anything is in the Serial 
   {
      input=Serial.read();

      Serial.println(input); //Print out any input
   }
}

来自 input.txt 的示例输入:

w a d s w d a a s d w

该字符串将根据 WASD 提供方向(上、下、左、右)。

【问题讨论】:

  • 您是否尝试过使用串行控制台(例如 PuTTY)与 Arduino 对话?
  • 我的问题是通过使用 boost asio 库解决的。它允许我从 .txt 文件中读取文本,然后通过串行方式将其发送到 arduino。

标签: c++ macos arduino serial-port


【解决方案1】:

可以使用文件句柄将数据写入串行设备,但首先尝试使用本机 Unix 串行通信 API 作为健全性检查可能会有所帮助。

看看 todbot.com 上的这篇帖子:Arduino-serial: C code to talk to Arduino

tod​​bot.com 的帖子描述了一个通过串行连接与 Arduino 对话的通用程序。源码有很多从命令行获取设置的代码,有点吓人,因为它很健壮,但是如果你想看看他是怎么做的,串行通信的业务端还是相当简单的。

我就该主题撰写了自己的系列文章,其中包含一些轻量级代码(在第 3 部分和第 4 部分中),这些代码演示了如何几乎完全按照您想要做的事情。

How to read serial data from an Arduino in Linux with C: Part 1

我希望这些链接中的某些内容有所帮助!串行通信很难,所以如果它不按你的方式进行,请不要太自责。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多