Skip to content

Instantly share code, notes, and snippets.

@psychemist
Created December 16, 2025 15:34
Show Gist options
  • Select an option

  • Save psychemist/a9c073f2f7e4ef63d3474fc56667b5bb to your computer and use it in GitHub Desktop.

Select an option

Save psychemist/a9c073f2f7e4ef63d3474fc56667b5bb to your computer and use it in GitHub Desktop.
Arduino Starter Project 10
const int controlPin1 = 2;
const int controlPin2 = 3;
const int enablePin = 9;
const int directionSwitchPin = 4;
const int onOffSwitchStateSwitchPin = 5;
const int potentialPin = A0;
// create variables for recording program state
int onOffSwitchState = 0;
int previousOnOffSwitchState = 0;
int directionSwitchState = 0;
int previousDirectionSwitchState = 0;
// create variables for motor control
int motorEnabled = 0;
int motorSpeed = 0;
int motorDirection = 0;
void setup() {
// declare digital pins as input annd outputs
pinMode(directionSwitchPin, INPUT);
pinMode(onOffSwitchStateSwitchPin, INPUT);
pinMode(controlPin1, OUTPUT);
pinMode(controlPin2, OUTPUT);
pinMode(enablePin, OUTPUT);
// turn motor off
digitalWrite(enablePin, LOW);
}
void loop() {
// read sensor information
onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
delay(1);
directionSwitchState = digitalRead(directionSwitchPin);
motorSpeed = analogRead(potentialPin) / 4;
// check if on/off sensor has changed and toggle motor state
if ( onOffSwitchState != previousOnOffSwitchState ) {
if ( onOffSwitchState == HIGH ) {
motorEnabled = !motorEnabled;
}
}
// check if direction has changed and toggle state
if ( directionSwitchState != previousDirectionSwitchState ) {
if ( directionSwitchState == HIGH ) {
motorDirection = !motorDirection;
}
}
// change the pins to turn the motor in the right direction
if ( motorDirection == 1 ) {
digitalWrite(controlPin1, HIGH);
digitalWrite(controlPin2, LOW);
}
else {
digitalWrite(controlPin1, LOW);
digitalWrite(controlPin2, HIGH);
}
// PWM the motor if it is enabled
if ( motorEnabled == 1 ) {
analogWrite(enablePin, motorSpeed);
}
else {
analogWrite(enablePin, 0);
}
// save the current state of the switches for next loop
previousDirectionSwitchState = directionSwitchState;
previousOnOffSwitchState = onOffSwitchState;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment