I use the following code (loaded on an Arduino board with an Xbee shield) to send the output of two ultrasonic receivers - hooked to pin 3 and 5 - through the serial port to Processing:
int inUS1 = 3;
int inUS2 = 5;
int outled = 2;
int val1, val2;
unsigned long t, th1, tb1, th2, tb2;
int n = 1;
void setup()
{
Serial.begin(9600);
pinMode(inUS1, INPUT);
pinMode(inUS2, INPUT);
pinMode(outled, OUTPUT);
}
void loop()
{
tb1 = 0;
tb2 = 1;
val1 = digitalRead(inUS1);
val2 = digitalRead(inUS2);
if (n < 0){
Serial.print('A');
t = micros();
while (val1 == LOW){
val1 = digitalRead(inUS1);
digitalWrite(outled, HIGH);
th1 = micros() - t;
}
Serial.print(th1);
Serial.print(10, BYTE);
digitalWrite(outled, LOW);
Serial.print('B');
Serial.print(tb1);
Serial.print(10, BYTE);
}else{
Serial.print('C');
t = micros();
while (val2 == LOW){
val2 = digitalRead(inUS2);
digitalWrite(outled, HIGH);
th2 = micros() - t;
}
Serial.print(th2);
Serial.print(10, BYTE);
digitalWrite(outled, LOW);
Serial.print('D');
Serial.print(tb2);
Serial.print(10, BYTE);
}
n = n * (-1);
delay(100);
}
The US emitters are triggered by another Arduino board (with another Xbee shield) with the following code:
int outputPin = 12;
int val;
void setup()
{
Serial.begin(9600);
pinMode(outputPin, OUTPUT);
}
void loop()
{
if (Serial.available()) {
val = Serial.read();
if (val == 'A' || val == 'C') {
digitalWrite(outputPin, HIGH);
}
if (val == 'B' || val == 'D') {
digitalWrite(outputPin, LOW);
}
}
}
I get a strange result. The value for pin 5 is depending on the value on pin 3.
If I use only one receiver it works fine, it is when both are in use that I get a kind of interference between the two!
Any clue?