Intro
First post. New Arduino user. Started programming in Basic and Extended Basic on the TI994A. Wrote test programs in C+ for a telephone company twenty-something years ago.
Project
I'm making a carnival game. Kid throws a ball through different sized holes. The successful throw is noted a sensor (IR break beam sensors were out of stock, so I'm using proximity sensors now, and the code reflects that), and that triggers a relay. The relay is attached to an irrigation sprinkler that sprays water on the stooge. It's sort of an alternative to a dunking booth. Future plans include adding background and 'good throw' lights and sound.
Code
Here's what I'm working with. I'm asking for feedback, since it's been a long time since I've programmed in C+
const int echoPinB = 6;
const int echoPinC = 7;
const int echoPinD = 8;
const int Relay1 = 9; //Just using one Relay right now
// defines variables
const int sprayShort = 1000; // Spray durations are variables to make them easy to change once the hardware is setup
const int sprayMedium = 2500;
const int sprayLong = 5000;
const int minDistance = 1; // Minimum distance is a variable because I don’t know what the sensors will return yet for the sprinkler to be triggered
int distance; //used in function to find distance
long duration; //used in function to find distance
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPinA, INPUT); // Sets the echoPin as an Input
pinMode(echoPinB, INPUT); // Sets the echoPin as an Input
pinMode(echoPinC, INPUT); // Sets the echoPin as an Input
pinMode(echoPinD, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication }
// Main Loop – checks distance or each pin and turns on sprinkler if distance is below minDistance
void loop() {
if (checkDistance (echoPinA) < minDistance)
//Then
RelayOn (Relay1,sprayShort);
if (checkDistance (echoPinB) < minDistance)
//Then
RelayOn (Relay1,sprayShort);
if (checkDistance (echoPinC) < minDistance)
//Then
RelayOn (Relay1,sprayShort);
if (checkDistance (echoPinD) < minDistance)
//Then
RelayOn (Relay1,sprayShort);
}
// Defines functions
// Function that returns the distance for a specified echoPin
int checkDistance(int echoPin){
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH); // Calculating the distance
distance= duration*0.034/2; //return returntype;
Return distance;
}
//Function that turns on a specific relay (in case I get more) for a specific period of time
int RelayOn (int RelayNumber, int Duration){
digitalWrite (RelayNumber,LOW) // Turns Relay ON
delay(Duration) // Wait
digitalWrite (RelayNumber, HIGH) // Turns Relay OFF
}