j0h

wiringpi wiringSerial on a regular PC

j0h
Jul 26th, 2021
1,035
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <unistd.h>       //read function
  4. #include <string.h>
  5. #include <wiringSerial.h> //simple serial port library
  6.  
  7. using namespace std;
  8. /*
  9.  * sudo apt-get install libwiringpi-dev
  10.  * This code is working on a x86_64 machine, not a raspberry pi.
  11.  *
  12.  * compiled with g++ -Wall -o readSerial  readSerial.cpp -lwiringPi
  13.  *
  14.  */
  15. int main(int argc, char ** argv)
  16. {
  17.     const char *SensorPort = "/dev/ttyACM0"; //Serial Device Address
  18.      
  19.     int levelSensor = serialOpen(SensorPort, 9600);
  20.     //serialPuts(levelSensor, "1"); //Send command to the serial device
  21.  
  22.     while (1){
  23.         char buffer[100];
  24.         ssize_t length = read(levelSensor, &buffer, sizeof(buffer));
  25.         if (length == -1){
  26.             cerr << "Error reading from serial port" << endl;
  27.             break;
  28.         }
  29.         else if (length == 0){
  30.             cerr << "No more data" << endl;
  31.             break;
  32.         }else{
  33.             buffer[length] = '\0';
  34.             cout << buffer; //Read serial data
  35.         }
  36.     }
  37.  
  38.     return 0;
  39. }
RAW Paste Data