I'm trying to send my Arduino sun position angular coordinates over the serial port, this is for a sun tracking skylight concept i have been stewing over for a long time now. Ideally i want to send floating point values so i did a bit of searching and found some stuff on bit shifting the binary serial data and recombining to give the final large value on the arduino. Only thing is I cant get it to work with matlabs fwrite over serial.
here's my matlab code
clear all
clc
s = serial('COM4');
set(s,'BaudRate',9600);
fopen(s);
a = uint16(1230); %random test number a
disp(sprintf('Initial uint16 value %5d is %16s in binary', ...
a,dec2bin(a)))
%out = fscanf(s)
%Find Highbyte by bitshifting
highbyte = bitshift(a,-8);
highbyte = uint8(highbyte);
disp(sprintf('Shifted uint8 highbyte value %5d is %16s in binary',highbyte,dec2bin(highbyte)))
% Find lowbyte by moving highbyte up 2^8 and subtracting from a
b= uint16(highbyte)*(2^8);
lowbyte = a-b;
lowbyte = uint8(lowbyte);
disp(sprintf('Shifted uint8 lowbyte value %5d is %16s in binary',lowbyte,dec2bin(lowbyte)))
%Write over serial
fwrite(s,highbyte)
fwrite(s,lowbyte)
%Read returned info
Highbyte = fscanf(s)
Lowbyte = fscanf(s)
angle = fscanf(s)
fclose(s)
delete(s)
clear s
and here's my Arduino code
int angle = 0;
int oldangle = 0;
int highbyte = 0;
int lowbyte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 1) {
// read the incoming byte:
highbyte = Serial.read();
if (Serial.available() > 0) {
lowbyte = Serial.read();
}
angle = (highbyte << 8) + lowbyte;
delay(1);
if (angle != oldangle) {
Serial.print("I received highbyte: ");
Serial.println(highbyte, BIN);
Serial.print("I received lowbyte: ");
Serial.println(lowbyte, BIN);
Serial.print("I received: ");
Serial.println(angle, BIN);
}
oldangle = angle;
}
}
Now im not sure if my matlab code is 100% correct, like do i even need to split the value on the matlab side and send it seperatly? Or will the serial buffer accept a few bytes of data at once? also is fwrite even the right command in this case? All the examples iv found use fprintf but it seems this is only for strings.. (which i understand is only useful for text)
anyway if i type say 88 into the arduino serial monitor i get values returned which make sense. ie.
I received highbyte: 111000
I received lowbyte: 111000
I received: 11100000111000
But again this test is sending the character 8 twice not the number 88.
If anyone has any experience with this kind of thing any pointers would be much appreciated. This has turned into a rather annoying roadblock for me and this project will be totally awesome once i have pulled a few of these details together.