//
// Arduino Nano program for Open Day robot
// Written 1-Dec-2023
//
void motors(int left, int right);
void setup()
{
// Digital output pins for motor control
pinMode(5, OUTPUT); // right motor forward
pinMode(6, OUTPUT); // right motor reverse
pinMode(7, OUTPUT); // left motor forward
pinMode(8, OUTPUT); // left motor reverse
}
void loop()
{
int left_sensor, right_sensor; // sensor variables
left_sensor = analogRead(0); // read left sensor voltage
right_sensor = analogRead(1); // read right sensor voltage
if (left_sensor < 512 && right_sensor < 512)
{
// When both sensors are off the track,
// stop both motors
motors(0, 0);
}
else if (left_sensor < 512)
{
// When left sensor is off the track,
// left motor forward, right motor stop
motors(1, 0);
}
else if (right_sensor < 512)
{
// When right sensor is off the track,
// left motor stop, right motor forward
motors(0, 1);
}
else
{
// When both sensors are on the track,
// both motors forward
motors(1, 1);
}
}
// motor control function
void motors(int left, int right)
{
// each argument controls one motor
// motor forward for all values > 0
// motor reverse for all values < 0
// motor stops when value is zero
digitalWrite(5, right > 0);
digitalWrite(6, right < 0);
digitalWrite(7, left > 0);
digitalWrite(8, left < 0);
}