This project is elaborated on top of the Raspberry PI reads data from Arduino. You should check it out first is case you've not done it yet. It gives details and explanations will will not repeat here.
In this example, we will have the Arduino to read analog data from a light-sensor (photo resistor), and send those values to the Raspberry PI, through a USB Serial port.
In addition to the previous project (Raspberry PI reads data from Arduino), we also have on the Arduino a Light Emitting Diode (led) that goes on if the value read from the light sensor drops below a certain threshold (40 by default, see the sketch).
The user can override this behavior from the Raspberry PI: if the Raspberry PI sends a
'0' on the serial port, the led will go off. Any other character sent on the serial channel (like
'1') will turn it on.
See in the sketch the code higlighted in bold in the
The intend here is to show how to use the same serial channel to read and write data. Data are here exchanged both ways between the Raspberry PI and the Arduino.
loopmethod, the photo resistor value is read from pin
A0every 250ms, and sent on the serial port if the new value is different from the one previously read by more that 3 units, in an NMEA-like format.
JAVA_OPTIONS="" JAVA_OPTIONS="-Dserial.port=/dev/ttyACM0" sudo java $JAVA_OPTIONS -cp $CP arduino.raspberrypi.SerialReaderWriterThe
mainmethod of the
arduino.raspberrypi.SerialReaderWriter.javaclass opens the serial port, and creates a serial listener that will take care of displaying the valid sentences received from trhe Arduino.
Serial Communication. ... connect using settings: 9600, N, 8, 1. ... data received on serial port should be displayed below. Hit 'Q' to quit. Hit 'V' to toggle verbose on/off. Hit [return] when ready to start. Opening port [/dev/ttyACM0:9600] Port is opened. So? > Oops! Invalid String [$O5B $OSMSG,LR,29*50 $OSMSG,LR,33*5B $OSMSG,LR,29*50 $OSMSG,LR,35*5D $OSMSG,LR,29*50 $Ã¿34*5C $OSMSG,LR,29*50 $OSMSG,LR,33*5B $OSMSG,LR,29*50 $OSMSG,LR,33*5B $OSMSG,LR,29*50 $OSMSG,LR,35*5D $OSMSG,LR,29*50 $Ã¿] Oops! Invalid String [$OSMSG,LR,30] Oops! Invalid String [*58 $OSMSG,LR,34*5C $OSMSG,LR,28*51 $OSMSG,LR,32*5A $OS] v So? > 1 Writing  to the serial port... So? > 0 Writing  to the serial port... So? > q Bye!
GNDpin of the Arduino is connected to the previous pin of the photo resistor through a 10kΩ resistor, and to the led's cathode.
13of the Arduino is connected to the led's anode through a 10kΩ resistor.