Challenge

Project 1 - Controlling a DC motor using PWM and monitoring its Running status

#include

// Define L293 motor driver connections
const int motorPin1 = 2; // Input 1 of L293 (Motor 1)
const int motorPin2 = 3; // Input 2 of L293 (Motor 1)
const int enablePin1 = 9; // Enable pin of L293 (Motor 1)
const int motorPin3 = 4; // Input 1 of L293 (Motor 2)
const int motorPin4 = 5; // Input 2 of L293 (Motor 2)
const int enablePin2 = 10; // Enable pin of L293 (Motor 2)

// Define LCD connections
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address, number of columns, number of rows

void setup() {
// Motor pins as outputs
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(enablePin1, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
pinMode(enablePin2, OUTPUT);

// Initialize LCD
lcd.begin(16, 2);
lcd.print("DC Motor Control");
}

void loop() {
// Read PWM value from potentiometer
int pwmValue = analogRead(A0);

// Map the PWM value to the range 0-255 (for analogWrite)
int motorSpeed = map(pwmValue, 0, 1023, 0, 255);

// Control motor direction and speed based on PWM value
if (motorSpeed > 0) {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
analogWrite(enablePin1, motorSpeed);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
analogWrite(enablePin2, motorSpeed);

// Display running status on LCD
lcd.setCursor(0, 1);
lcd.print("Motor: Forward ");
} else if (motorSpeed < 0) {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
analogWrite(enablePin1, -motorSpeed);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
analogWrite(enablePin2, -motorSpeed);

// Display running status on LCD
lcd.setCursor(0, 1);
lcd.print("Motor: Reverse ");
} else {
// Stop the motor
analogWrite(enablePin1, 0);
analogWrite(enablePin2, 0);

// Display running status on LCD
lcd.setCursor(0, 1);
lcd.print("Motor: Stopped ");
}
}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.