0

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.

When I use the serial monitor from the Arduino IDE it works fine. But when I wanted to read it using codeblocks with C++, all I got was some garbage values.

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.

Community
  • 1
  • 1
Demyx
  • 11
  • 7

1 Answers1

0

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.

Photon
  • 3,182
  • 1
  • 15
  • 16
  • compiler told me "error: request for member ‘Open’ in ‘serial_port’, which is of non-class type ‘SerialPort()’" but I just initialized serial_port with the contents of SerialPort right? why is it giving me this error? – Demyx Feb 17 '15 at 23:43
  • I've solved the problem, instead of `SerialPort serial_port;` it should be `SerialPort serial_port("/dev/ttyUSB0")` – Demyx Feb 18 '15 at 00:53