Hey Guys, i am kinda new to Arduino so i will try to explain everything so you can get a better picture of my question:
First i am using an Arduino Mega to controll a pump by using a PWM. So I am at the point where i am sending a Constant from MatLab Simulink with a serial send block. I want to read it in the Arduino code that i have uploaded in the board and for now use it in the analogWrite() function to set this constant as the value for the PWM (0-255).
So this is the code:
float h;
int SensorVal;
float res;
char Arr[4];
void setup() {
// open a serial connection
Serial.begin(9600);
// put your setup code here, to run once:
pinMode(11, OUTPUT);
}
void loop() {
if (isnan(Serial.read())){
analogWrite(11, 0);
}else{
for( byte i=0;i<4;i++){
Arr[i]=Serial.read();
}
res = *((float *)&Arr);
analogWrite(11, res);
}
// read A10
SensorVal = analogRead(A10);
h=(float)(SensorVal)*100.0/600.0;
Serial.write((unsigned char *)(&h),4);
delay(500);
}
So my question is: Am I not converting the value correctly or am I not getting it rite from the serial port? OR is the whole logic gone down the drain?
Serial.read() is non blocking. if byte is not available the it returns -1 (that is why the return type is int).
so you must check if the returned value isn't -1 or check if data are available before read.
Yes, i just gave it a check to see if Serial.available is bigger than 0 so i know that i have something. I tried to see if i am getting something, or nothing or the same thing all over again. As you said I added the reading to a variable and used it to see what is happening and i wrote a check see if I am getting a -1. But i also changed the analogWrite function to see if i am actually getting to it or i am stuck in my ifs, and no i am actually getting to the analogWrite function.
...
Arr[i]=Serial.read();
}
res = *((float *)&Arr);
analogWrite(11, 255);//<---analogWrite(11, res)
So i am getting a Serial.available bigger than 0, and my reading is a number value and it is not -1. My Guess is that maybe the code is okay, but maybe i am sending wrong data from simulink :/.