mpatronska
Posts: 14
Joined: Sun Jun 07, 2015 7:05 am

Reading and writing to Arduino from RPi

Tue Jun 30, 2015 1:12 pm

Hi,

I read data from IR distance sensor from an Arduino that is connected to RPi. I see the data in the RPi.
I would like to control a servo motor connected to the Arduino from the RPi. For this task I have a separate thread that writes to the serial port.

The problem is that I'm constantly reading the input data from one thread that is responsible for reading and I'm not sure how to give the control to the thread that is responsible for writing, then when the second thread is done, to give control to the first.

Can someone give an example?

Thanks.

User avatar
xranby
Posts: 540
Joined: Sat Mar 03, 2012 10:02 pm
Contact: Website

Re: Reading and writing to Arduino from RPi

Tue Jun 30, 2015 2:30 pm

Please publish the code you have now inside a public GIT repository with a free software or public domain license.
We can then help you re-factor your code to read and write simultaneously to the serial port using two threads.

You usually solve this by first initializing the serial port and then give the InputStream to the thread that wants to read and the OutputStream to the thread that wants to write.

InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();



When you want the two threads to communicate with each other then you probably want to use a non blocking ring buffer or a ConcurrentLinkedQueue.
https://docs.oracle.com/javase/7/docs/a ... Queue.html
The ConcurrentLinkedQueue implements the "Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms by Maged M. Michael and Michael L. Scott "
http://web.archive.org/web/201410182301 ... ODC96.html
Xerxes Rånby @xranby I once had two, then I gave one away. Now both are in use every day!
twitter.com/xranby

Return to “Java”