简体   繁体   English

使用ubuntu上的代码块在C ++中读取arduino序列

[英]Reading arduino serial in C++ using codeblocks on ubuntu

I tried using and editing the code from Read and Write on serial port in Ubuntu with C/C++ and LibSerial and referencing from the Ubuntu manpage http://manpages.ubuntu.com/manpages/saucy/man3/LibSerial_SerialStream.3.html . 我尝试使用C / C ++和LibSerial在Ubuntu的串行端口上的“读写”中使用和编辑代码,并从Ubuntu手册页http://manpages.ubuntu.com/manpages/saucy/man3/LibSerial_SerialStream.3.html引用。

When I use the serial monitor from the Arduino IDE it works fine. 当我从Arduino IDE使用串行监视器时,它可以正常工作。 But when I wanted to read it using codeblocks with C++, all I got was some garbage values. 但是,当我想使用带有C ++的代码块读取它时,我得到的只是一些垃圾值。

Here's the code: 这是代码:

#include <SerialStream.h>
#include <iostream>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#define PORT "/dev/ttyUSB0"

using namespace std;
using namespace LibSerial;
...
SerialStreamBuf::BaudRateEnum baud_rate = SerialStreamBuf::BAUD_115200;
const SerialStreamBuf::CharSizeEnum csize = SerialStreamBuf::DEFAULT_CHAR_SIZE;
const SerialStreamBuf::ParityEnum parity = SerialStreamBuf::PARITY_NONE;
short stop_bits = 1;
const SerialStreamBuf::FlowControlEnum flow_c = SerialStreamBuf::FLOW_CONTROL_NONE;
...
SerialStream(PORT, baud_rate, csize, parity, stop_bits, flow_c);
SerialStream serial_port ;
serial_port.Open(PORT) ;
...
while( 1  ){
     char next_byte;
     serial_port.get(next_byte);
     std::cerr << next_byte;
     usleep(100);
 }

How do I fix this? 我该如何解决? I'm not good in object oriented programming so I'm not so sure about initializing the constructors. 我在面向对象的编程方面不太好,所以我不确定初始化构造函数。

You're defining two variables for the serial stream, but using the uninitialized one. 您为串行流定义了两个变量,但是使用了未初始化的变量。 Try replacing this: 尝试替换这个:

SerialStream(PORT, baud_rate, csize, parity, stop_bits, flow_c);
SerialStream serial_port ;
serial_port.Open(PORT) ;

With

SerialPort serial_port ;
serial_port.Open(PORT, baud_rate, csize, parity, stop_bits, flow_c);

and then use the ReadByte function. 然后使用ReadByte函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM