Hello everyone,
I’m having some issues with data I’m reading from an Arduino Uno.
Essentially I’m using the Arduino as a DAQ and sending over 4 analog inputs over the Serial. The first two inputs (A0 and A1) are single bytes. The second inputs (A2 and A3) are arrays of two bytes each. I’m sending them using the Arduino Serial.write() function which writes them directly in binary. I send the data in the following format over the Serial: A0A1A2A3/n. My Processing script then reads whatever I sent until /n. This constitutes one reading. I perform a reading and send the values every 2000us (such that sampling freq = 500Hz).
They are sending fine - if I print on Arduino what I’m sending there is no issue. The problems is in Processing.
If I connect a potentiometer to the analog inputs and increase the pot’s output from 0 to 5V I see that my A0 and A1 (single bytes) as read on Processing increase fine until the value 127 at which they jump around from 30, 255, and other values. This happens until, after increasing the pot output further, it settles at 160 and increases normally up to 255 (the 5V limit). Why is it jumping like this at 127 and why doesn’t it increase normally, linearly, until 160?
I understand that Arduino bytes are unsigned whereas Processing bytes are signed. I read and saw an easy conversion that I integrated into my code (essentially adding & 0xff to the read byte). I’ve been playing around with this conversion trying different things but to no avail.
Here is my code:
void serialEvent(Serial myPort) {
try {
val = myPort.readStringUntil('\n'); //The newline separator separates each Arduino loop. We will parse the seperate readings by each newline separator.
if (val!= null) { //We have a reading! Record it.
val_char = val.toCharArray();
if (val_char.length == 7) { // If the data was transmitted correctly - it will consist of 7 bytes (A0 =1, A1 = 1, A2 = 2, A3 = 2, \n =1.
val_int[0] = int(byte(val_char[0]) & 0xff);
val_int[1] = int(byte(val_char[1]) & 0xff);
val_int[2] = int(byte(val_char[2]) & 0xff);
val_int[3] = int(byte(val_char[3]) & 0xff);
val_int[4] = int(byte(val_char[4]) & 0xff);
val_int[5] = int(byte(val_char[5]) & 0xff);
electro_val_code[0] = val_int[0];
electro_val_code[1] = val_int[1];
hemo_val_code[0] = (val_int[2]*256) + val_int[3]; // Translating the two bytes into a single int.
hemo_val_code[1] = val_int[4]*256 + val_int[5];
print(electro_val_code[0]);
print(',');
print(electro_val_code[1]);
print(',');
print(hemo_val_code[0]);
print(',');
println(hemo_val_code[1]);
Thanks!
R