首页 > 解决方案 > 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.

  1. 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.

  2. 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.

标签: c++raspberry-piserial-porttermiosraspberry-pi-zero

解决方案


多亏了锯末,我知道问题出在“默认设置”的标志上。因为他们不是。为了修复我的代码,我在本关于 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;

推荐阅读