I'm having trouble gaining traction on a line following robot project. I'm attempting to manually adjust the light threshold needed to activate each motor by reading each of the left and right photocells on two surfaces, i.e. a black strip and a white tile, and then averaging the light intensity to reach a new, adjusted threshold for different types of lighting conditions. In my code, I have one button being used to measure the intensity of the light on a light surface and another button being used to measure the light on a dark surface. Theoretically, the motor should not turn on until both buttons are pressed, such that the value of LightThreshold is determined by the button presses. This is not the case when I run the simulations.
It seems like the button is not accepting my input, resulting in 0 being passed into the button variable which causes the while loop to become an infinite loop. How would I allow the buttons to read my input in this case? I have copied my code below as well as a screenshot of my TinkerCAD simulation.
//Define Pin Mappings
#define BUTTON 7
#define BUTTON2 6
const int leftMotor = 9;
const int leftSensorPin = A0;
const int rightMotor = 8;
const int rightSensorPin = A1;
int leftLight1;
int rightLight1;
int leftLight2;
int rightLight2;
int avgLeftLight;
int avgRightLight;
int loopValue = 0;
int lightThreshold;
void setup()
{
//Set Baud Rate, Required to use
Serial.begin(9600);
pinMode(leftMotor, OUTPUT);
pinMode(leftSensorPin, INPUT);
pinMode(rightMotor, OUTPUT);
pinMode(rightSensorPin, INPUT);
pinMode(BUTTON, INPUT);
pinMode(BUTTON2, INPUT);
}
void loop()
{
while(loopValue != 2)
{
int button = readButtons();
if(button == 2)
{
leftLight1 = analogRead(leftSensorPin);
rightLight1 = analogRead(rightSensorPin);
}
else if (button == 1)
{
leftLight2 = analogRead(leftSensorPin);
rightLight2 = analogRead(rightSensorPin);
}
else loopValue == 0;
loopValue++;
}
avgLeftLight = (leftLight1 + + leftLight2) / 2;
avgRightLight = (rightLight1 + rightLight2) / 2;
lightThreshold = avgLeftLight + avgRightLight;
runBot();
}
void runBot()
{
//Read Sensor Values
int leftLightLevel = analogRead(leftSensorPin);
// If left motor sensor is greater than threshold
// then turn left motor on, else turn left motor off
int rightLightLevel = analogRead(rightSensorPin);
// If right motor sensor is greater than threshold
// then turn right motor on, else turn right motor off
if (leftLightLevel > lightThreshold)
digitalWrite(leftMotor, LOW);
else
digitalWrite(leftMotor, HIGH);
if (rightLightLevel > lightThreshold)
digitalWrite(rightMotor, LOW);
else
digitalWrite(rightMotor, HIGH);
}
int readButtons(void)
{
if (digitalRead(BUTTON) == 0) return 1;
else if (digitalRead(BUTTON2) == 0) return 2;
return 0;
}
