I am currently constructing an ROV(Remotely Operated Vehicle) and am having some trouble with my code. I am using one Arduino Mega 2560 in my control board which will read the outputs of the various switches and potentiometers, and then send that information serially to my other Mega 2560 on the vehicle. This board on the vehicle will use the information to perform various tasks.
My problem is that so far, I've only been able to figure out how to send 8 bytes of data at a time. This is not enough because I need to send multiple potentiometer values and several High or Low switches.
My second thought was to try and send multiple serial transmissions one after the other and organize the data into arrays. (See Transmitter Code). While I have been able to receive this data on the receiving board, the information comes in a sporadic order, which is not useful to me. I'm guessing that is because one of my programs goes faster than the other. This is the code I've come up with so far.
Note: I'm using the normal Serial port to communicate with my laptop, and Serial1 to communicate between the Arduinos.
Transmitter Code
int outByte[4];
int x;
void setup() {
Serial.begin(9600);
Serial1.begin(115200);
pinMode(11,INPUT);
pinMode(12,INPUT);
}
void loop() {
int y = 1;
for (int i = 0; i > -1; i = i + y){
outByte[0] = (digitalRead(11)); //Controls LED1 and is High or Low
outByte[1] = (digitalRead(12)); //Controls LED2 and is High or Low
outByte[2] = i; //Controls LED3 and is from 0 to 255
for (x = 0; x <= 2; ++x){
Serial.print(outByte[x]); //Communicate with computer
Serial1.write(outByte[x]); //Communicate with other Arduino
delay(1);
}
Serial.println();
if (i == 255) y = -1;
}
}
Receiver Code
const int led1 = 11;
const int led2 = 12;
const int led3 = 13;
int values[4];
int i;
int incomingValue;
void setup(){
int pin;
for (pin = 11; pin <= 13; ++pin){
pinMode (pin, OUTPUT); //Set pins 11 to 13 as outputs
}
Serial.begin(9600);
Serial1.begin(115200);
}
void loop(){
if(Serial1.available()){
for(i = 0; i < 3; i++){
values[i] = Serial1.read(); //Read the three pieces of data and organize them in the array
Serial.println(values[i]); //Print these values to the Serial Monitor
delay(1);
}
}
digitalWrite(led1, values[0]);
digitalWrite(led2, values[1]);
analogWrite(led3, values[2]);
}
To make things simple, I've coded so that two led's on the receiving board are controlled by two switches, and the last led is supposed to fluctuate from 0-255.
Like I mentioned before, this code gives me sporadic results on my receiving board. Sporadic meaning that each of the three leds choose one data point randomly and display that value. I need help figuring out how to make sure that I receive the instructions for the leds in the correct order (led1, led2, led3, repeat).
Thank you for any help.