0% found this document useful (0 votes)
82 views

Arduino DC Motor Control

This Arduino code controls a DC motor using an L298N H-bridge motor driver and allows changing the motor's direction of rotation by pressing a button. It defines the pins used for motor control and a button, initializes the motor direction on startup, reads the button and potentiometer in a loop to control motor speed and change direction when the button is pressed.

Uploaded by

Yassvind 99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Arduino DC Motor Control

This Arduino code controls a DC motor using an L298N H-bridge motor driver and allows changing the motor's direction of rotation by pressing a button. It defines the pins used for motor control and a button, initializes the motor direction on startup, reads the button and potentiometer in a loop to control motor speed and change direction when the button is pressed.

Uploaded by

Yassvind 99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

1.

/* Arduino DC Motor Control - PWM | H-Bridge | L298N - Example 01


2.
3. by Dejan Nedelkovski, www.HowToMechatronics.com
4. */
5.
6. #define enA 9
7. #define in1 6
8. #define in2 7
9. #define button 4
10.
11. int rotDirection = 0;
12. int pressed = false;
13.
14. void setup() {
15. pinMode(enA, OUTPUT);
16. pinMode(in1, OUTPUT);
17. pinMode(in2, OUTPUT);
18. pinMode(button, INPUT);
19. // Set initial rotation direction
20. digitalWrite(in1, LOW);
21. digitalWrite(in2, HIGH);
22. }
23.
24. void loop() {
25. int potValue = analogRead(A0); // Read potentiometer value
26. int pwmOutput = map(potValue, 0, 1023, 0 , 255); // Map the potentiometer value from 0 to 255
27. analogWrite(enA, pwmOutput); // Send PWM signal to L298N Enable pin
28.
29. // Read button - Debounce
30. if (digitalRead(button) == true) {
31. pressed = !pressed;
32. }
33. while (digitalRead(button) == true);
34. delay(20);
35.
36. // If button is pressed - change rotation direction
37. if (pressed == true & rotDirection == 0) {
38. digitalWrite(in1, HIGH);
39. digitalWrite(in2, LOW);
40. rotDirection = 1;
41. delay(20);
42. }
43. // If button is pressed - change rotation direction
44. if (pressed == false & rotDirection == 1) {
45. digitalWrite(in1, LOW);
46. digitalWrite(in2, HIGH);
47. rotDirection = 0;
48. delay(20);
49. }
50. }

You might also like