import processing.serial.*;
Serial myPort; // Create object from Serial class
float val; // Data received from the serial port
float sensorData; // Data received from the serial port with 1,2,3,4 framing numbers filtered out
float low=0;
float high=0;
float value=0;
float byte1 = 0;
float byte2 = 0;
float byte3 = 0;
float byte4 = 0;
float filt = 0;
float us = 0;
float cm = 0;
float eps = 0.1; // change the value to float
//float nsamples = 100.0; // copy from the python file
void setup()
{
size(1000, 300);
println(Serial.list());
myPort = new Serial(this, "/dev/tty.usbserial-FTHBQ1K0", 9600);
// change the port
}
void draw()
{
while (myPort.available() > 0) { // If data is available
byte1 = byte2;
byte2 = byte3;
byte3 = byte4;
byte4 = myPort.read();
if ((byte1 == 1) & (byte2 == 2) & (byte3 == 3) & (byte4 == 4)){} // Filter out the framing numbers: 1,2,3,4
else {
low = myPort.read();
high = myPort.read();
value = (256*high + low);
filt = (1-eps)*filt+eps*value;
us = filt/8.0;
cm = us/58.0;
println("THE VALUE IS " + cm); //print to the screen
}
background(322); // Set background to white
int scale = 10 ;
rect (20,20,cm*scale,20);
}
}
Another thing I wanted to try is to make it work directly with Arduino, as I did in the inputs' assignment too, but this time sending the data to Processing and then reading it directly through there. First I tried an easy code, just to see if I could read what I was sending through the serial port with Arduino to processing.
#include SoftwareSerial.h
SoftwareSerial mySerial(1, 2); // RX, TX
void setup() {
pinMode(2,OUTPUT);
mySerial.begin(4800);
mySerial.println("Hello, world?");
}
void loop() {
mySerial.println("Hello");
}
I then opened processing and start coding to receive the data from Arduino
import processing.serial.*;
int cm = 0;
Serial myPort; // Create object from Serial class
void setup()
{
size(800, 200);
println(Serial.list());
myPort = new Serial(this, "/dev/tty.usbserial-FTHBQ1K0", 4800);
// change the port
}
void draw()
{
while (myPort.available() > 0) { // If data is available
String temp = myPort.readStringUntil('\n');
if(temp!=null){
cm = Integer.parseInt(trim(temp));
println("THE VALUE IS " + cm); //print to the screen
}
background(322); // Set background to white
float scale = 10 ;
rect (20,20,cm*scale,20);
}
}
Here's the result. Processing read fine the data sent with the Arduino, and even quicker than Python.