Can you help with an example Arduino code where you can adjust the motor speed with a potentiometer using Arduino Uno and L298N motor driver board?
You need to have a go at this yourself as it’s homework , otherwise it’s cheating !
If stuck people will help you with your code .
There are examples for analog read in the IDE and the motor boards have examples in their respective libraries .
then let me ask
is this code correct?
const int ENA = 10;
const int IN1 = 9;
const int IN2 = 8;
const int potentiometerPin = A0;
void setup() {
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
Serial.begin(9600);
}
void loop() {
int potValue = analogRead(potentiometerPin);
int motorSpeed = map(potValue, 0, 1023, 0, 255);
Serial.print("Motor Speed: ");
Serial.println(motorSpeed);
analogWrite(ENA, motorSpeed);
if (potValue > 512) {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
} else {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
}
delay(100); // Adjust the delay as per your requirement
}
When you tried the code, did it fail?
I have no means to test it, I just need to write code. Is useful?
then it doesn't matter if it correct or not
but i will score according to the code working
so you need to test it.
Please understand that it is YOUR homework
2 Likes
Yes, the code is useful.
const byte
ENA = 10,
IN1 = 9,
IN2 = 8,
potentiometerPin = A0
;
void setup ()
{
pinMode ( ENA, OUTPUT );
pinMode ( IN1, OUTPUT );
pinMode ( IN2, OUTPUT );
Serial.begin ( 115200 );
}
void loop ()
{
int motorSpeed = map ( analogRead ( potentiometerPin ), 0, 1023, -255, 255 );
Serial.print ( "Motor Speed: " );
Serial.print ( motorSpeed );
analogWrite ( ENA, abs ( motorSpeed ) );
if ( motorSpeed > 0 )
{
digitalWrite ( IN1, HIGH );
digitalWrite ( IN2, LOW );
Serial.println ( " CW" );
}
else
{
digitalWrite ( IN1, LOW );
digitalWrite ( IN2, HIGH );
Serial.println ( " CCW" );
}
delay ( 100 ); // Adjust the delay as per your requirement
}
What if it is zero?
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.