【发布时间】: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