【发布时间】:2018-10-09 08:27:47
【问题描述】:
TL;DR - 我正在尝试使用我找到的代码与 Arduino 进行串行通信 here 并且没有发送任何内容(Arduino 被编程为响应,我检查了它的串行监视器是否可以)
你好, 我正在寻找一种通过 C++ 通过 linux 串行端口将信息发送到 Arduino Mega (2560) 单元的方法。
我遇到了以下解决方案:Solution 我正在使用这个人的代码进行写入(我能够从 arduino 读取数据)并使用相同的参数(它们有效,因为我能够从 Ardunio 接收数据)。 我对我的 Arduino 进行了编程,使其在看到至少 1 位信息时通过串行发送“Hi”,并通过 Arduino IDE 串行监视器检查它是否正常工作。
然而,当运行 C++ 代码时,arduino 没有响应。有人可能知道为什么吗?
完全公开 - 我将 @Lunatic999 的代码插入到一个类中,这样我就可以根据代码的需要创建它的实例。
fd = open(portNameC, O_RDWR | O_NOCTTY | O_SYNC); //open port ("opens file")
串口参数:
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( fd, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B19200);
cfsetispeed (&tty, (speed_t)B19200);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( fd, TCIFLUSH );
if ( tcsetattr ( fd, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
写(我把这段代码放在我调用的函数中)
unsigned char cmd[] = "INIT \r";
int n_written = 0,
spot = 0;
do {
n_written = write( fd, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
Arduino 代码:
bool dataRecieved = false;
int ledpin = 13;
void setup() {
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);
Serial.begin(19200);
}
void loop() {
while(!dataRecieved)
{
digitalWrite(ledpin,HIGH);
if (Serial.available() > 0)
{
dataRecieved = true;
}
}
digitalWrite(ledpin,LOW);
delay(1000);
digitalWrite(ledpin,HIGH);
delay(1000);
Serial.println("hi");
}
【问题讨论】:
-
循环中仅单个字节的写入系统调用是不必要的低效。相反,只需在一个系统调用中传递整个字符串,例如
n_written = write(fd, cmd, strlen(cmd));。然后检查返回值是否有错误。 -
"有人可能知道为什么吗?" -- 为什么你的串行终端初始化代码使用变量
USB作为文件描述符?而在打开和编写代码时,您使用变量fd。 -
@swadust 感谢您的评论。我试过: unsigned char cmd[] = {"INIT"}; int n_written = 0, cout’ to ‘const char*’ for argument ‘1’ to ‘size_t strlen(const char*)’ n_written = write(fd, cmd, strlen(cmd));编辑:否则我必须使用 write(fd, &cmd, strlen(cmd);
-
@sawdust 我知道,我在这个版本中没有注意到它。在我的代码中,它使用 fd,而不是 USB,我将对其进行更改以使其准确。对此感到抱歉。
标签: c++ linux arduino serial-port