-Hi
This is my first post because I usually take the time and fix the problem myself but I've tried many different variations of this code and have had no luck. Here is my problem:
I'm working on a serial communication protical and have been doing a good amount of testing on my UNO I use for code development. However when I try to run the same code on the MEGA this sketch does not work. Basically the sketch reads in serial data, an unsigned integer, and lights up a pin if the throttle and yaw parameters are above a threshold (I've tried multiple pins so this isn't the problem in this particular sketch). The data from the sender (I've tried many external sources but current am using Simulink) runs at 50ms and the main code runs at about 10ms. The data from the sender is 8 unsigned integers, that's why bitsIn is set to 16. I've tried using a ttl to usb converter on this sketch and used the MEGA's other serial pins so I can monitor what I'm actually receiving but I'm receiving garbage. Here is the code, could you tell me why this works on the UNO and not the MEGA?
int ledPin = 8; // the pin that the LED is attached to
int bitsIn =16; //Amount of expected bitsIn
int incomingByte[16]; //bitsIn
unsigned int number[8]; //array to store integers bytes in devided by 2
///Loop initializers
int i=0;
int a=0;
int b=0;
void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
// see if there's enough incoming serial data:
if (Serial.available() >= bitsIn) {
// read in all expected bytes
while ( i <= (bitsIn -1) ) {
incomingByte[i] = Serial.read();
i=i+1;
}
i=0;
//Convert bytes to unsigned integers
while(a <= (bitsIn /2-1)){
number[a] = incomingByte[b+1]*256 +incomingByte[b];
// Serial.print(number[a]);
a=a+1;
b=b+2;
}
a=0;
b=0;
//Assign Numbers to actual variable names
int throttle = number[1];//0-10,000
float yaw = (float)number[2];//1,000-2,000
float pitch = (float)number[3];//1,000-2,000
float roll = (float)number[4];//1,000-2,000
float yawmapped = map(yaw,1000,2000,-150,150);
///See if the header and footer where received as expected
if (number[0] == 15642 && number[6] == 29874) {
//light up an LED for throttle and yaw cases
if(throttle >= 1500 || yawmapped >= 45.55){
digitalWrite(ledPin, HIGH);
}
else if (throttle < 1100) {
digitalWrite(ledPin, LOW);
}
}
//Clear remaining bytes on buffer, this will also fix any initial asynchronous reads to start off
while(Serial.available()>0){
Serial.read();
}
}
///Delay to allow more bytes to come in
delay(10);
}