Arduino DC Motor Speed Control with L298N and Potentiometer | English Subtitle
ฝัง
- เผยแพร่เมื่อ 20 ก.ย. 2024
- Arduino DC Motor Speed Control with L298N and Potentiometer | English Subtitle
Code : code is on the comment below.
Facebook : / doit20-104218935882053
Please Subscribe my Channel. ThankYou!
// Define pins
const int motorIn1 = 2;
const int motorIn2 = 3;
const int enableA = 9; // for speed control
const int buttonPin = 4;
const int potPin = A0; // potentiometer connected to analog pin A0
// Variables to store button state and motor state
int buttonState = 0;
int lastButtonState = 0;
bool motorRunning = false;
void setup() {
// Set motor control pins as outputs
pinMode(motorIn1, OUTPUT);
pinMode(motorIn2, OUTPUT);
pinMode(enableA, OUTPUT);
// Set button pin as input
pinMode(buttonPin, INPUT);
// Start with motor off
digitalWrite(motorIn1, LOW);
digitalWrite(motorIn2, LOW);
analogWrite(enableA, 0); // Speed 0
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Check if the button has been pressed (transition from LOW to HIGH)
if (buttonState == HIGH && lastButtonState == LOW) {
// Toggle motor state
motorRunning = !motorRunning;
// Debounce delay
delay(50);
}
// Save the current button state as the last state
lastButtonState = buttonState;
// Read the potentiometer value and map it to the PWM range (0-255)
int potValue = analogRead(potPin);
int speed = map(potValue, 0, 1023, 0, 255);
if (motorRunning) {
// If motor is running, set the motor speed based on the potentiometer value
digitalWrite(motorIn1, HIGH);
digitalWrite(motorIn2, LOW);
analogWrite(enableA, speed); // Set speed based on potentiometer value
} else {
// If motor is not running, stop the motor
digitalWrite(motorIn1, LOW);
digitalWrite(motorIn2, LOW);
analogWrite(enableA, 0); // Speed 0
}
}