Looking for some help on a tricky project. I have been dabbling with Arduino for simple projects, but this one has me stumped. I need to be able to toggle a video to play at a distance of 5' or less and a different video at 6' and further. I can get the ping sensor to do the simple function of reading the distance and displaying in the serial monitor. That all works fine and I can get the 'Keyboard.press and Keyboard.release functions to work too. That said, I have the issue of the Void Loop constantly activating the keyboard and printing out A's or D's (see code below). I simplified my code so I would just be working within 20 cm and I could use my hand to test the functions.
I am using a program on my PC that uses mapped keyboard presses to trigger the playback of the video files. For example, if i hit the 'D' key on my keyboard it will play a certain video and if I hit the 'A' key it will play a different video. Works great when it's a human pressing the buttons. However, the Arduino (my code) keeps hitting the keys over and over and it restarts the videos.
Is there a way to still ping for the distance parameters (6' >= press 'A') and (5' <= press 'D') and toggle the keyboard one time?
Code: Select all
#include <NewPing.h>
#include <Keyboard.h>
#define PING_PIN 12 // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(PING_PIN, PING_PIN, MAX_DISTANCE); // NewPing setup of pin and maximum distance.
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
void loop() {
delay(1000); // Wait 1s between pings.
Serial.print("Ping: ");
Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
Keyboard.begin();
if (sonar.ping_cm()>= 21)
{
Keyboard.press('A');
delay(100);
Keyboard.release('A');
delay(6000);
}
else if (sonar.ping_cm()<= 20){
Keyboard.press('D');
delay(100);
Keyboard.release('D');
delay(6000);
}
Keyboard.end();
}