add simple serial receive and transmit test for uint8_t, uint16_t, int16_t and float

This commit is contained in:
interfisch 2019-06-09 22:45:45 +02:00
parent 4c99999b02
commit 1c8c75ce57
2 changed files with 70 additions and 0 deletions

View File

@ -0,0 +1,51 @@
import processing.serial.*;
Serial serialport;
void setup() {
printArray(Serial.list());
serialport = new Serial(this, Serial.list()[2], 9600);
println("start");
}
void draw() {
byte[] inBuffer = new byte[9];
while(serialport.available()>0) {
inBuffer = serialport.readBytes();
serialport.readBytes(inBuffer);
if (inBuffer!= null) {
int counter= inBuffer[0];
int value1= extract_uint16_t(inBuffer,1);
int value2= extract_int16_t(inBuffer,3);
float floatvalue = extract_float(inBuffer,5);
println("counter="+counter);
println("value1="+value1);
println("value2="+value2);
println("floatvalue="+floatvalue);
}
}
}
public int extract_uint16_t(byte array[], int startbyte) {
return ((int)array[startbyte] & 0xff) | ((int)array[startbyte+1] & 0xff)<<8;
}
public int extract_int16_t(byte array[], int startbyte) {
if ( ((int)array[startbyte+1] & 0x80) == 0x00 ) { //2's complement, not negative
return ( ((int)array[startbyte] & 0xff) | ((int)array[startbyte+1] & 0x7f)<<8 );
}else{ //value is negative
return -32768 + ( ((int)array[startbyte] & 0xff) | ((int)array[startbyte+1] & 0x7f)<<8 );
}
}
public float extract_float(byte array[], int startbyte) {
int MASK = 0xff;
int bits = 0;
int i = startbyte+3; //+3 because goes backwards and has 4 bytes
for (int shifter = 3; shifter >= 0; shifter--) {
bits |= ((int) array[i] & MASK) << (shifter * 8);
i--;
}
return Float.intBitsToFloat(bits);
}

View File

@ -0,0 +1,19 @@
uint8_t counter=0;
uint16_t value1=65531;
int16_t value2=-123;
float floatvalue=23.42;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));
Serial.write((uint8_t *) &counter, sizeof(counter));//uint8_t, 1 byte
Serial.write((uint8_t *) &value1, sizeof(value1)); //uint16_t, 2 bytes
Serial.write((uint8_t *) &value2, sizeof(value2)); //int16_t, 2 bytes
Serial.write((uint8_t *) &floatvalue, sizeof(floatvalue)); //float, 4 bytes
delay(500);
counter++;
}