I have two Arduino Megas. One has a potentiometer hooked up to the A0 pin. I am converting the number this potentiometer reads to two bits and sending it through Serial. I want the second Arduino to be able to print the 0-1023 value. I would think that val[2] would give me this, but for some reason nothing is printing. I assume it's because it is not getting a signal from the other TX. When I put the Serial.print's outside of the if(Serial.available) section of my code, it prints an infinite number of zeros. Anyone know why?
Here's my TX code (TX light on Arduino is lighting up):
/*
AnalogToSerial
Reads an analog input on pin 0, outputs to TX.
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(19,18); // RX, TX
int data [2];
int potPin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
pinMode(19, INPUT);
pinMode(18, OUTPUT);
}
void loop() {
val = analogRead(potPin); // reads the value of the potentiometer (value between 0 and 1023)
data[0] = val & 0xFF; //least significant 8 bit byte
data[1] = (val >> 8); //most significant 2 bits
Serial.print(data[0], HEX);
Serial.print(" ");
Serial.println(data[1], HEX);
mySerial.write(data[0]);
mySerial.write(data[1]); //bytes sent
delay(1); // delay in between reads for stability
}
And here's the RX (RX light on this Arduino is NOT lighting up):
/*
Analog Receive
Reads a 10 bit serial stream in two bytes
reassembles and converts to binary display using 8 LEDs
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(19,18); // RX, TX
int val[4]; // variable to read the value from the analog pin
int i;
int LED[8] = {4,5,6,7,8,9,10,11}; // LED port array
//////////// Binary Conversion //////////////////////////////////////////////////////////
void binary(int dec) {
int bval = dec/4; // convert dec value to binary, scale to 8 bits
for (i=0; i<8; i++) {
if (bval%2==0) digitalWrite (LED[i],LOW); // set LEDs accordingly
else digitalWrite (LED[i],HIGH);
bval=bval/2;
}
}
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
pinMode(19, INPUT);
pinMode(18, OUTPUT);
for (i=0; i<8; i++) {
pinMode (LED[i], OUTPUT);
}
}
void loop() {
if (mySerial.available()>1) {
val[0]=mySerial.read(); // least significant 8 bits
val[1]=mySerial.read(); // most significant 2 bits
val[2] = val[1]<<8 | val[0]; // reassebled 10 bit value, sore in val[2]
binary(val[2]); // convert to binary and display on LEDs
Serial.print(val[1],HEX); Serial.print(" ");
Serial.print(val[0],HEX); Serial.print(" ");
Serial.println(val[2],HEX);
}
}