Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //If you found my video helpful, please SUBSCRIBE: https://www.youtube.com/channel/UCKp1MzuAceJnDqAvsZl_46g
- //The code belongs to this tutorial video: https://youtu.be/8a5k_q0Bu7M
- /*
- * Controlling a DC motor with a potmeter
- * Starting the program and stopping the program with Serial
- * Use 24V power supply at max; control power with potmeter for PWM
- * Connect arduino GND to L298N GND -> Motor will stall otherwise
- *
- */
- /*
- You can also support me by buying the parts using the following links:
- L298N Dual H-bridge DC Motor Driver: https://www.banggood.com/custlink/vmmv0oOv4O
- DC Motor with Planetary Gear: https://www.banggood.com/custlink/KmD34jOG4A
- DC Motor 3500-9000 RPM: https://www.banggood.com/custlink/Dm3DBoO3gf
- Arduino UNO: https://www.banggood.com/custlink/33KKF85c3i
- Variable Power Supply: https://www.banggood.com/custlink/DGKvSpwFvQ
- Linear Slide Potentiometer:https://www.banggood.com/custlink/Gm3DiDNLtk
- */
- 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment