I've written two pieces of code, to create a serial communication between Arduino and a Raspberry Pi using C++. The codes are:
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 baud
}
void loop() {
Serial.println("Hello from arduino");
delay(500);
}
And the C++ code in Raspberry is :
#include <iostream>
#include <wiringPi.h>
#include <wiringSerial.h>
using namespace std ;
int serialDeviceId=0;
int main(void)
{
int pin=7;
serialDeviceId= serialOpen("/dev/ttyACM1",9600);
if(serialDeviceId==-1)
{
cout<<"Unable to open serial device"<<endl;
return 1;
}
if(wiringPiSetup()==-1)
{
return 0 ;
}
pinMode(pin,OUTPUT); // designing pin as an output
while(1)
{
digitalWrite(pin,0);
delay(500);
digitalWrite(pin,1);
delay(500);
}
return 0;
}
So now I would like to read the data from the serial port using always that wiringpi and I've found that I can use SerialGetchar, but I don't know exactly how to use it. I just need to need this part in my code so that I can receive that "Hello from from arduino" written in the serial, from my Arduino code.
This code should work for you on the Raspberry Pi. It is extremely simple! Make sure you get the correct device special file by running:
dmesg
and looking for line like this:
[610106.464745] usb 1-1.4: new full-speed USB device number 4 using dwc_otg
[610106.608642] usb 1-1.4: New USB device found, idVendor=2341, idProduct=0043
[610106.608655] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[610106.608663] usb 1-1.4: Manufacturer: Arduino (www.arduino.cc)
[610106.608671] usb 1-1.4: SerialNumber: 55731323536351E002E1
[610106.686193] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <wiringSerial.h>
int main ()
{
int fd ;
if((fd=serialOpen("/dev/ttyACM0",9600))<0){
fprintf(stderr,"Unable to open serial device: %s\n",strerror(errno));
return 1;
}
for (;;){
putchar(serialGetchar(fd));
fflush(stdout);
}
}
I assume you have a USB cable connecting one of the RaspberryPi USB ports to the USB port on the Arduino.