/*
Arduino | coding-help
Using Sparkfun Kit to create a project for my class,
but the delay function seems to not be called.
SoloKhi — November 9, 2025 at 9:41 PM
*/
//the right motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 13; //control pin 1 on the motor driver for the right motor
const int AIN2 = 12; //control pin 2 on the motor driver for the right motor
const int PWMA = 11; //speed control pin on the motor driver for the right motor
const int POT_PIN = A0;
const int NUM_SWITCHES = 2;
const int SW_PINS[] = {7, 6};
int swState[NUM_SWITCHES];
int oldSwState[NUM_SWITCHES] = {1, 1};
int checkSwitches() {
int swNumber = 0;
// check each switch
for (int i = 0; i < NUM_SWITCHES; i++) {
swState[i] = digitalRead(SW_PINS[i]);
if (swState[i] != oldSwState[i]) { // if it changed
oldSwState[i] = swState[i]; // remember state for next time
swNumber = i + 1;
Serial.print("Switch ");
Serial.print(swNumber);
if (swState[i] == LOW) { // was just pressed
Serial.println(" closed.");
} else { // was just released
Serial.println(" opened.");
swNumber = -1;
}
delay(20); // debounce
}
}
return swNumber;
}
/********************************************************************************/
void setup()
{
Serial.begin(115200);
pinMode(SW_PINS[0], INPUT_PULLUP); //set this as a pullup to sense whether the switch is flipped
pinMode(SW_PINS[1], INPUT_PULLUP); //set this as a pullup to sense whether the switch2 is flipped
//set the motor control pins as outputs
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(PWMA, OUTPUT);
}
/********************************************************************************/
void loop() {
//int speed = map(analogRead(POT_PIN), 0, 1023, 0, 255);
int switchNum = checkSwitches();
if (switchNum > 0) {
if (switchNum == 1) {
//dir = 0;
rightMotor(100);
delay(2000);
rightMotor(0);
} else if (switchNum == 2) {
//dir = 1;
rightMotor(-100);
delay(2000);
rightMotor(0);
}
//rightMotor(dir, speed);
}
}
/********************************************************************************/
void rightMotor(int motorSpeed) //function for driving the right motor
{
if (motorSpeed > 0) //if the motor should drive forward (positive speed)
{
digitalWrite(AIN1, HIGH); //set pin 1 to high
digitalWrite(AIN2, LOW); //set pin 2 to low
}
else if (motorSpeed < 0) //if the motor should drive backward (negative speed)
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, HIGH); //set pin 2 to high
}
else //if the motor should stop
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, LOW); //set pin 2 to low
}
analogWrite(PWMA, abs(motorSpeed)); //now that the motor direction is set, drive it at the entered speed
}
IN1
IN2
ENA
CW
CCW
Speed