Created
November 12, 2017 14:48
-
-
Save smetronic/90dda555c72d2848fb8cb0872385a1bd to your computer and use it in GitHub Desktop.
Reading Serial Data using C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdio.h> | |
#include <termios.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <wiringPi.h> | |
#include <wiringSerial.h> | |
#include <vector> | |
using namespace std; | |
int main(int argc, char ** argv) | |
{ | |
char *levelSensorPort = "/dev/ttyUSB0"; //Serial Device Address | |
int levelSensor = serialOpen(levelSensorPort, 19200); | |
wiringPiSetup(); | |
serialPuts(levelSensor, "DP"); //Send command to the serial device | |
while (1) | |
{ | |
char buffer[100]; | |
ssize_t length = read(levelSensor, &buffer, sizeof(buffer)); | |
if (length == -1) | |
{ | |
cerr << "Error reading from serial port" << endl; | |
break; | |
} | |
else if (length == 0) | |
{ | |
cerr << "No more data" << endl; | |
break; | |
} | |
else | |
{ | |
buffer[length] = '\0'; | |
cout << buffer; //Read serial data | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment