2015-02-08 89 views
0

我尝试使用和编辑代码Read and Write on serial port in Ubuntu with C/C++ and LibSerial,并从Ubuntu的手册页引用http://manpages.ubuntu.com/manpages/saucy/man3/LibSerial_SerialStream.3.html在ubuntu上使用代码块读取arduino的串行代码

当我使用Arduino IDE的串行监视器时,它工作正常。但是当我想用C++使用代码块来读取它时,我得到的只是一些垃圾值。

下面的代码:

#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); 
} 

我该如何解决这个问题?我不擅长面向对象编程,所以我不太确定初始化构造函数。

回答

0

您正在为串行流定义两个变量,但使用未初始化的变量。尝试更换此:

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

随着

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

,然后使用ReadByte功能。

+0

编译器告诉我“错误:请求在'serial_port'中的成员'Open',它是非类类型'SerialPort()'”但我刚刚初始化了串口的SerialPort的内容的权利?为什么它给我这个错误? – Demyx 2015-02-17 23:43:15

+0

我已经解决了这个问题,而不是'SerialPort serial_port;'它应该是'SerialPort serial_port(“/ dev/ttyUSB0”)' – Demyx 2015-02-18 00:53:20