void setup() {
Serial.begin(115200);
// pinMode(led1, OUTPUT);
}
void loop() {
// Trigger pin, Echo pin, delay (ms), visual=true|info=false
ping(D2, D6, D4, D5, 25, true);
}
void ping(pin_t trig_pin_left, pin_t echo_pin_left, pin_t trig_pin_right, pin_t echo_pin_right, uint32_t wait, bool info)
{
uint32_t duration_left, duration_right, curr_val_left, curr_val_right;
static bool init = false;
if (!init) {
pinMode(trig_pin_left, OUTPUT);
digitalWriteFast(trig_pin_left, LOW);
pinMode(trig_pin_right, OUTPUT);
digitalWriteFast(trig_pin_right, LOW);
pinMode(echo_pin_left, INPUT);
pinMode(echo_pin_right, INPUT);
//delay(50);
init = true;
}
/* Trigger the sensor by sending a HIGH pulse of 10 or more microseconds */
digitalWriteFast(trig_pin_left, HIGH);
delayMicroseconds(10);
digitalWriteFast(trig_pin_left, LOW);
duration_left = pulseIn(echo_pin_left, HIGH);
digitalWriteFast(trig_pin_right, HIGH);
delayMicroseconds(10);
digitalWriteFast(trig_pin_right, LOW);
duration_right = pulseIn(echo_pin_right, HIGH);
/* Convert the time into a distance */
// Sound travels at 1130 ft/s (73.746 us/inch)
// or 340 m/s (29 us/cm), out and back so divide by 2
// Ref: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
//inches = duration / 74 / 2;
//Current distance in cm
curr_val_left = duration_left / 29 / 2;
curr_val_right = duration_right / 29 / 2;
if (info) { /* Visual Output */
Serial.printf("Left sonar%2d:", curr_val_left);
Serial.printf("Right sonar%2d:", curr_val_right);
Serial.println();
} else { /* Informational Output */
Serial.printlnf("%6d cm / %6d us", curr_val_left, duration_left);
Serial.printlnf("%6d cm / %6d us", curr_val_right, duration_right);
}
Above is my code for reading from 2 sonars. For some reason I am only reading from the left sonar and the right one always returns 0. I suspect the problem lies with the pulseIn() command but I don’t know how else to use the sonars. Any suggestions?
It doesn’t need to be too precise but I will implement the /58. I’ve tried swapping the sensors and pins and still I only ever get to read from one of them. I read around that for .ino files you can’t use 2 pulseIn() at the same time, but for the arduino the function can take two arguments while the photon only takes one. Is there another way of using this sonar without using the pulseIn() function? Or a way to turn it off for one pin and on for another?