gpt4 book ai didi

c++ - c++ , Unix 中的串口

转载 作者:搜寻专家 更新时间:2023-10-31 02:24:44 24 4
gpt4 key购买 nike

我写了一段代码,通过串行端口将 mi 计算机连接到 arduino。

这是arduino的代码:

#include <Servo.h>

Servo servo;
const int pinServo = 2;
unsigned int angle;

void setup()
{
Serial.begin(9600);
servo.attach(pinServo);

servo.write(0);

}

void loop()
{
if(Serial.available()>0)
{
angle = Serial.read();

if(angle <= 179)
{
servo.write(angle);
}
}
}

这是 C++ 的:

#include <iostream>
#include <unistd.h>
#include <fstream>
#include <termios.h>

using namespace std;

int main()
{
unsigned int angle;
ofstream arduino;
struct termios ttable;

cout<<"\n\ntest1\n\n";

arduino.open("/dev/tty.usbmodem3a21");

cout<<"\n\ntest2\n\n";

if(!arduino)
{
cout<<"\n\nERR: could not open port\n\n";
}
else
{
if(tcgetattr(arduino,&ttable)<0)
{
cout<<"\n\nERR: could not get terminal options\n\n";
}
else
{
ttable.c_cflag &= ~PARENB;
ttable.c_cflag &= ~CSTOPB;
ttable.c_cflag &= ~CSIZE;
ttable.c_cflag |= CS8;
ttable.c_cflag &= ~CRTSCTS;
ttable.c_cflag |= CREAD | CLOCAL;
ttable.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
ttable.c_oflag &= ~OPOST;
ttable.c_cc[VMIN] = 0;
ttable.c_cc[VTIME] = 0;

cfsetospeed(&ttable,9600);

if(tcsetattr(arduino,TCSANOW,&ttable)<0)
{
cout<<"\n\nERR: could not set new terminal options\n\n";
}
else
{
do
{
cout<<"\n\ninsert a number between 0 and 179";
cin>>angle;
arduino<<angle;
}while(angle<=179);

arduino.close();
}
}
}

}

它应该连接到 arduino ,然后问我一个介于 0 和 179 之间的数字,然后将该数字发送到 arduino,该数字作为伺服电机的角度;但它在 arduino.open("/dev/tty.usbmodem3a21") 处停止。我能做什么?

最佳答案

我认为你的问题出现在这几行代码中

if(tcgetattr(arduino,&ttable)<0) {
// ...
}
else {
// ...

if(tcsetattr(arduino,TCSANOW,&ttable)<0) {
// ...
}
}

arduino 变量的类型是ofstream,其中tcgetattr()tcsetattr()期望使用 open() 获得的文件描述符在这一点上。

ofstream 提供了到 bool 的自动转换,因此隐含地提供了 int。假设

arduino.open("/dev/tty.usbmodem3a21");

一切顺利,您有效地将 1 传递给 tcgetattr()tcsetattr(),这是标准输入文件描述符。


解决方案不是为arduino 使用ofstream,而是使用普通的文件描述符

int arduino = open("/dev/tty.usbmodem3a21",O_WRONLY);

关于c++ - c++ , Unix 中的串口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com