c++ - Why does the raspberrypi not send the requested serial output?
问题描述
I want to send some serial output through the pins of my raspberrypi for serial communication with a drone flight controller. The controller only operates at a strange 100000 baudrate.
My code does not always set the baudrate correctly. Sometimes I have to reboot and restart the code 5 times to get the right baudrate.
The code does not send the requested data. It sends much more. The serial output of the console is disabled (by raspi-config).
I tried writing it in python, but the code is running too slow (I need image processing with OpenCV too) so I switched to C++. The python code was working fine. I already tried the serial library by wjwood : http://wjwwood.github.com/serial/ but it is also not working correctly whit the strange baudrate. Setting the baudrate with the stty command failed too. I tried setting the baudrate with the setispeed functions and the old termios structure. This didn't work too.
This is my code:
#include <fcntl.h>
#include <unistd.h>
#include <stropts.h>
#include <asm/termios.h>
#include <iostream>
int main()
{
int fd_ = ::open("/dev/ttyAMA0", O_RDWR);
struct termios2 options;
ioctl(fd_, TCGETS2, &options);
options.c_cflag |= PARENB;
options.c_cflag &= ~CBAUD;
options.c_cflag |= BOTHER;
options.c_ispeed = 100000;
options.c_ospeed = 100000;
options.c_cc[VTIME] = 10;
options.c_cc[VMIN] = 0;
unsigned char buf[25];
for (int i = 0; i != 25; i++)
{
buf[i] = 2 * i;
}
ioctl(fd_, TCSETS2, &options);
for (int i = 0; i != 25; i++)
{
std::cout << static_cast<int>(buf[i]) << " ";
}
std::cout << std::endl;
::write(fd_, &buf, 25);
::close(fd_);
}
Expected is a serial output like: 0x00 0x02 0x04 ... 0x30. But I get: 0x5E 0x4F 0x5E 0x40 ... 0x00 0x02 0x04 ... 0x30.
The more I send the more additional useless bytes are blocking the bus and confusing the flight controller.
解决方案
多亏了锯末,我知道问题出在“默认设置”的标志上。因为他们不是。为了修复我的代码,我在本关于 Linux 串行编程的指南的帮助下添加了这些标志:
options.c_cflag &= ~CRTSCTS;
options.c_cflag |= CREAD | CLOCAL;
options.c_lflag &= ~ICANON;
options.c_lflag &= ~ECHO;
options.c_lflag &= ~ECHOE;
options.c_lflag &= ~ECHONL;
options.c_lflag &= ~ISIG;
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);
options.c_oflag &= ~OPOST;
options.c_oflag &= ~ONLCR;
推荐阅读
- python - 用于字符串类型的请求正文中的 url 编码表单数据的 swagger UI 生成带有 ascii 值的 curl 命令
- html - 带有后元素的自定义复选框 - 不能可靠地居中
- r - 在 ggplot2 中绘制个体值和平均值:错误“错误:`mapping` must be created by `aes()`”
- reactjs - 反应导航标题右键
- c - 文件读取后将值分配给自定义类型
- java - 如何让 poi 创建 excel 更快?
- kdb - KDB:如何在 kdb-tick 架构中为联合联接序列化表?
- java - 如何将列表变量传递给构造函数/方法
- swift - 如何获得与协议父级的条件协议一致性?
- excel - 将 CSV 导入 Excel(可变宽度数据)导致 #REF 问题