I have an arduino set up in a simple manner that read a potentiometer and writes the output to the serial connection.
void setup() {
// initialize serial communication
Serial.begin(9600);
}
void loop() {
// read the value of A0, divide by 4 and
// send it as a byte over the serial connection
Serial.write(analogRead(A0) / 4);
delay(20);
}
I would like to have a prolog program that monitors this stream in the background. I would like it to log certain events but also for me to query the stream at any time.
I dont really know where to begin to set this up. How do I actually read a stream, and then how do I have two process/threads (Not sure what to call them). Where one process monitors the stream and a second process runs the top level so I can query a dynamic database?
I imagine something like:
:-dynamic currentvalue/1.
startthread1 :-
loop.
loop :- read_serial(X),
check(X),
retractall(currentvalue(_)),
assertz(currentvalue(X)),
loop.
check(X):-
X>100,
get_time(Time),
write_file(Time,X).
check(_).
*I omit the def of write_file
I think I would then query:
?- thread_create(startthread1, Id, [alias(serial_mon)]).
And then I should still have the top level available for me to query `currentvalue/1' when I want to ?
Will this work? How do I define read_serial/1. ? Also how would I stop the thread which I named serial_mon ?
update
I have changed the loop code to the following:
void loop() {
// read the value of A0, divide by 4 and
// send it as a byte over the serial connection
Serial.print(analogRead(A0) / 4);
Serial.print('.');
delay(100);
}
If I look at the serial monitor I now get output like this:
205.205.205.205. etc
Which I think I should be able to read by using read/2?
If my prolog code is simply:
go(File):-
open(File,read,Stream,[]),
read(Stream,X),
writeln(X),
close(Stream).
And I query :
?-go('/dev/ttyACM0').
I get no output. What have I done wrong?