在基于 unix 的软件上,它必须向 arduino 发送一个 0 到 179 之间的数字,arduino 会将这个数字作为一个角度应用于伺服电机,但我不知道我必须在 terminos 结构中更改哪些参数才能允许串行通信。
这是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<<"test-1";
arduino.open("/dev/tty.usbmodem3a21");
//cout<<"test-2";
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
{
//there goes the terminal options setting for the output;
ttable.c_cflag = -hupcl //to prevent the reset of arduino
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 的:
#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);
}
}
}
那么你能告诉我我必须改变“ttable”的什么吗?
最佳答案
一般来说,使用处于“原始”模式的串行端口从 C/C++ 与 Arduino 通信是最简单的。这基本上是 8N1,一次一个字节,TTY 对数据进行最少的操作。在 termios
中设置各种标志的简单方法此模式的结构是使用 cfmakeraw(3)
.根据手册页,这会执行以下操作:
struct termios config;
config.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP |
INLCR | IGNCR | ICRNL | IXON);
config.c_oflag &= ~OPOST;
config.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
config.c_cflag &= ~(CSIZE | PARENB);
config.c_cflag |= CS8;
为了更好的衡量,使用 config.c_cflag |= (CLOCAL | CREAD);
显式设置接收启用并忽略调制解调器控制.如果termios
您正在使用的结构是现有结构的拷贝(例如,使用 tcgetattr()
获得),然后还使用 config.c_iflag &= ~(IXOFF | IXANY);
完全禁用流控制.所以总而言之,它看起来像:
struct termios config;
cfmakeraw(&config);
config.c_cflag |= (CLOCAL | CREAD);
config.c_iflag &= ~(IXOFF | IXANY);
// set vtime, vmin, baud rate...
config.c_cc[VMIN] = 0; // you likely don't want to change this
config.c_cc[VTIME] = 0; // or this
cfsetispeed(&config, B9600);
cfsetospeed(&config, B9600);
// write port configuration to driver
tcsetattr(fd, TCSANOW, &config;
使用 C++ 文件流也有点棘手。您很可能想要非阻塞读/写并且没有控制 TTY,因此通常更容易使用 open(2)
与 O_NOCTTY
和 O_NDELAY
标志设置。
关于c++ - 用于与 arduino 进行串行通信的 struct termios 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27667299/