DC Motor PWM control with a potentiometer and L298N

In this video I show you a simple example of controlling a DC motor by using an Arduino and a L298N dual H-bridge circuit. By transforming the values of the potentiometer to values on the PWM output you can control the speed of you DC motor.



Wiring diagram

The L298N is used only in 1 direction mode in this particular example. The demo only shows the PWM control through reading the value of a potentiometer.

The L298N is used only in 1 direction mode in this particular example. The demo only shows the PWM control through reading the value of a potentiometer.



Arduino source code

int potPin = 0;                    // select the input pin for the potentiometer (A0)
int val = 0;                       // variable to store the value coming from the sensor
char receivedCommand;              // character for controlling the serial program
//---------------Motor
const int pinA = 8;               //Enable (Power)
const int enA = 5;                //Enable (PWM) '~'
//-------------------
bool runningEnabled = false;
bool newData = false;
 
 
void setup()
{
  pinMode(pinA, OUTPUT);
  pinMode(enA, OUTPUT);
  Serial.begin(9600);  
  Serial.println("DC-MOT-POT");
}
 
void loop()
{
readSerialPort();  
readPotmeter();
}
 
void readSerialPort()
{
  if (Serial.available() > 0) //is there a data on the serial?
     {
        receivedCommand = Serial.read();
        newData = true; //if we received a new command we set this bool to true
     }
     
     if (newData == true)
     {
          if(receivedCommand == 's') //Start
            {
              runningEnabled = true; //start = enable running
            }
         
          if(receivedCommand == 'n')//Stop
            {
              runningEnabled = false; //shut down everything
              digitalWrite(pinA, LOW);
            }
      }
        newData = false;  //reset newData to false so we can receive new command
 
}
 
void readPotmeter()
{
  if(runningEnabled == true) //is running is enabled?
  {
    val = analogRead(potPin);    // read the value from the pot (A0)
    val = map(val, 0, 1023, 0, 255); //map 0-1023 to 0-255 ; |-----------| ---> |------|
    analogWrite(enA, val); //write PWM (pin ~5)
    digitalWrite(pinA, HIGH); //enable power
    Serial.println(val); //print on serial
  }
  else
  { //do nothing, disable power if it was enabled previously
    runningEnabled = false;
    digitalWrite(pinA, LOW);
  }
}

Previous
Previous

Failure of a piece of steel under tensile loading

Next
Next

Tensile testing of different specimens