#include <Wire.
h>
#include <hd44780.h>
#include <hd44780ioClass/hd44780_I2Cexp.h>
hd44780_I2Cexp lcd;
#define PRESET A0
#define MOTOR_FORWARD A1
#define MOTOR_STOP A2
#define MOTOR_BACK A3
#define MOTOR_ENB 11
#define MOTOR_IN4 10
#define MOTOR_IN3 9
int analogInputValue = 0;
int pwmSpeedValue = 0;
int displaySpeedValue = 0;
int motorState = 0;
void initializePins();
void initializeDisplay();
void displayWelcomeMessage();
void readPresetValue();
void calculateSpeedValues();
void applyMotorSpeed();
void readMotorDirectionButtons();
void updateDisplay();
void executeMotorControl();
void stopMotor();
void runMotorForward();
void runMotorBackward();
void setup()
{
[Link](9600);
initializePins();
initializeDisplay();
displayWelcomeMessage();
}
void loop()
{
readPresetValue();
calculateSpeedValues();
applyMotorSpeed();
readMotorDirectionButtons();
updateDisplay();
executeMotorControl();
delay(50);
}
void initializePins()
{
pinMode(PRESET, INPUT);
pinMode(MOTOR_FORWARD, INPUT_PULLUP);
pinMode(MOTOR_STOP, INPUT_PULLUP);
pinMode(MOTOR_BACK, INPUT_PULLUP);
pinMode(MOTOR_ENB, OUTPUT);
pinMode(MOTOR_IN4, OUTPUT);
pinMode(MOTOR_IN3, OUTPUT);
}
void initializeDisplay()
{
[Link](16, 2);
[Link]();
[Link]();
}
void displayWelcomeMessage()
{
[Link](0, 0);
[Link](" Speed Control ");
[Link](0, 1);
[Link](" DC Motor ");
delay(2000);
[Link]();
}
void readPresetValue()
{
analogInputValue = analogRead(PRESET);
}
void calculateSpeedValues()
{
pwmSpeedValue = map(analogInputValue, 0, 670, 0, 250);
displaySpeedValue = map(analogInputValue, 0, 670, 0, 100);
if (pwmSpeedValue < 0)
{
pwmSpeedValue = 0;
}
if (pwmSpeedValue > 250)
{
pwmSpeedValue = 250;
}
if (displaySpeedValue < 0)
{
displaySpeedValue = 0;
}
if (displaySpeedValue > 100)
{
displaySpeedValue = 100;
}
}
void applyMotorSpeed()
{
analogWrite(MOTOR_ENB, pwmSpeedValue);
}
void readMotorDirectionButtons()
{
if (digitalRead(MOTOR_FORWARD) == LOW)
{
motorState = 1;
}
if (digitalRead(MOTOR_STOP) == LOW)
{
motorState = 0;
}
if (digitalRead(MOTOR_BACK) == LOW)
{
motorState = 2;
}
}
void updateDisplay()
{
[Link](0, 0);
[Link]("Speed: ");
[Link](displaySpeedValue);
[Link]("% ");
[Link](0, 1);
if (motorState == 0)
{
[Link](" Stop ");
}
else if (motorState == 1)
{
[Link](" Anticlockwise ");
}
else if (motorState == 2)
{
[Link](" Clockwise ");
}
else
{
[Link](" Unknown ");
}
}
void executeMotorControl()
{
if (motorState == 0)
{
stopMotor();
}
else if (motorState == 1)
{
runMotorForward();
}
else if (motorState == 2)
{
runMotorBackward();
}
else
{
stopMotor();
}
}
void stopMotor()
{
digitalWrite(MOTOR_IN4, LOW);
digitalWrite(MOTOR_IN3, LOW);
}
void runMotorForward()
{
digitalWrite(MOTOR_IN4, HIGH);
digitalWrite(MOTOR_IN3, LOW);
}
void runMotorBackward()
{
digitalWrite(MOTOR_IN4, LOW);
digitalWrite(MOTOR_IN3, HIGH);
}