C++中的串行端口,Unix
Serial port in c++ , Unix
我写了一个代码,通过串行端口将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<<"nntest1nn";
arduino.open("/dev/tty.usbmodem3a21");
cout<<"nntest2nn";
if(!arduino)
{
cout<<"nnERR: could not open portnn";
}
else
{
if(tcgetattr(arduino,&ttable)<0)
{
cout<<"nnERR: could not get terminal optionsnn";
}
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<<"nnERR: could not set new terminal optionsnn";
}
else
{
do
{
cout<<"nninsert 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()
,这是标准的输入文件描述符。
解决方案不是使用ofstream
进行arduino
,而是使用普通的文件描述符
int arduino = open("/dev/tty.usbmodem3a21",O_WRONLY);
相关文章:
- Qt Q串行端口未编程设备未关闭
- 在 linux c++ 中没有通过串行端口发送的数据
- 检查串行端口Linux中是否有传入数据(cbInQue for linux)
- 在不传输的情况下更改 Win32 中的串行端口波特率
- 增强 ASIO 和串行端口异步读取
- 串行端口写入究竟如何从缓冲区实际写入数据?
- 如何将参数这些串行端口传递到函数中
- 从 C/C++ 访问 Android 中的串行端口
- Qt两个串行端口发送和接收
- 通过串行端口从GPS传感器读取
- 提升 asio 串行端口"end of file"
- 通过串行端口发送多个值
- 与QSerialPort配合使用的串行端口仿真
- 如何通过boost::asio和shared_ptr创建串行端口
- 串行端口编码
- 使用来自串行端口的字符串数据来操作振镜扫描仪在更高的速度下会出错
- 写入和读取十六进制 TRAM QT 串行端口
- Unix 串行端口程序与 qt 崩溃
- C++中的串行端口,Unix
- 无法在 Matlab UNIX 上打开串行端口