Skip to content

Instantly share code, notes, and snippets.

@greed9
Created June 23, 2025 19:00
Show Gist options
  • Save greed9/8cb57dc942fd69b5190e4a437ceacd10 to your computer and use it in GitHub Desktop.
Save greed9/8cb57dc942fd69b5190e4a437ceacd10 to your computer and use it in GitHub Desktop.
Incomplete sketch to control DC motor speed via H-Bridge and potentiometer
// hacked from: https://lastminuteengineers.com/drv8833-arduino-tutorial/
// Define the control inputs
#define MOT_A1_PIN 6
#define MOT_A2_PIN 5
void setup(void)
{
// Set all the motor control inputs to OUTPUT
pinMode(MOT_A1_PIN, OUTPUT);
pinMode(MOT_A2_PIN, OUTPUT);
// Turn off motors - Initial state
digitalWrite(MOT_A1_PIN, LOW);
digitalWrite(MOT_A2_PIN, LOW);
// Initialize the serial UART at 9600 baud
Serial.begin(9600);
// Just to know which program is running on my Arduino
Serial.println(F("START " __FILE__ " from " __DATE__ "\r\n" ));
Serial.println("Min:0,Max:1023"); //Initial min/max for the plot
}
void loop( )
{
// ************************
// **** YOUR CODE HERE ****
// ************************
//
// Instructions
//
// declare an int variable, say pwm_value to hold the calculated vale for speed (0-255)
// declare another variable to hold the value you read from the pot via analogReda() - an int
// Use map() to force the range of the analogRead variable into 0 to 255 for analogWrite()
// call set_motor_pwm( ) to the calculated pwm value from map()
delay(100) ;
}
/// Set the current on a motor channel using PWM and directional logic.
///
/// \param pwm PWM duty cycle ranging from -255 full reverse to 255 full forward
/// \param IN1_PIN pin number xIN1 for the given channel
/// \param IN2_PIN pin number xIN2 for the given channel
void set_motor_pwm(int pwm, int IN1_PIN, int IN2_PIN)
{
if (pwm < 0) { // reverse speeds
analogWrite(IN1_PIN, -pwm);
digitalWrite(IN2_PIN, LOW);
} else { // stop or forward
digitalWrite(IN1_PIN, LOW);
analogWrite(IN2_PIN, pwm);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment