Arduino uses solid state relay power control for H-bridge.


Arduino H-Bridge Motor Control Program with LCD Display

by Lewis Loflin

This program differs from Arduino SSR Power Enable Program program by pressing S1 or S2 and this stays on until pressed again. If one switch is enabled while one attempts to enable the other, the first is shut off.

If either DP9 or DP10 are HIGH pulse-width modulation output is enabled from DP11 both enabling motor power and acting as a speed control. The speed can be adjusted while the motor is on.

The sketch includes using a LCD display.

LCD display.


Arduino I2C LCD connections.



/*
Motor ON-OFF 
ON-OFF LCD display
PWM ON when LED1 or LED2 ON
*/

#define SW1 2
#define SW2 3
#define LED1 9
#define LED2 10
#define LED3 11
#define pot 0

// HIGH = 1 and LOW = 0
#define ON 1
#define OFF 0

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
// set the LCD address to 0x27

void setup() {
  // put your setup code here, to run once:
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(SW1, INPUT);
  digitalWrite(SW1, HIGH); // pull up on
  pinMode(SW2, INPUT);
  digitalWrite(SW2, HIGH); // pull up on
  Wire.begin(); // join i2c bus (address optional for master)
  lcd.init(); // initialize the lcd
  lcd.backlight();
  lcd.clear();
  lcd.home();
  lcd.print("S1 = 0 S2 = 0");
  lcd.setCursor(0, 1); // pos 0 line 1
  lcd.print("POT =    ");
  POT();
}

void loop() {
  delay(100);
  
  if ( S1() )   {
    digitalWrite(LED2, OFF);
    delay(100);
    byte temp = !digitalRead(LED1);
    digitalWrite(LED1, temp);
    // wait for switch open
    while ( S1() ) { }
  } // end if

  if ( S2() )   {
    digitalWrite(LED1, OFF);
    delay(100);
    byte temp = !digitalRead(LED2);
    digitalWrite(LED2, temp);
    // wait for switch open
    while ( S2() ) { }
  } // end if

  // this line acts as motor speed control
  // enable only when LED1 OR LED2 ON
  if (digitalRead(LED1) || digitalRead(LED2)) 
    analogWrite(LED3, POT() / 4);
  else analogWrite(LED3, OFF);

  POT(); // update LCD// end loop

byte  S1(void)   {
  if (digitalRead(SW1) != 1)   {
    lcd.setCursor(5, 0); // pos 5 line 0
    lcd.print("1");
    return 1;
  }
  else   {
    lcd.setCursor(5, 0); // pos 5 line 0
    lcd.print("0");
    return 0;
  }
}

byte  S2(void)   {
  if (digitalRead(SW2) != 1)   {
    lcd.setCursor(12, 0); // pos 12 line 0
    lcd.print("1");
    return 1;
  }
  else   {
    lcd.setCursor(12, 0); // pos 12 line 0
    lcd.print("0");
    return 0;
  }
}

// return value analog 0
int   POT(void)   {
  int num = analogRead(0);
  lcd.setCursor(6, 1); // pos 7 line 1
  lcd.print(num);
  lcd.print("   ");
  return num;
}