-
Notifications
You must be signed in to change notification settings - Fork 0
/
Motor on
48 lines (39 loc) · 1.98 KB
/
Motor on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Pin configuration
const int potPin = A0; // Analog pin connected to the potentiometer
const int motorPWM = 9; // PWM output pin connected to the H-bridge for motor speed control
const int motorDir1 = 7; // Digital pin connected to H-bridge for motor direction control (direction 1)
const int motorDir2 = 8; // Digital pin connected to H-bridge for motor direction control (direction 2)
const int buttonPin = 2; // Digital pin connected to the push button
void setup() {
// Set up the pin modes
pinMode(motorPWM, OUTPUT); // Set PWM pin as output
pinMode(motorDir1, OUTPUT); // Set direction control pin 1 as output
pinMode(motorDir2, OUTPUT); // Set direction control pin 2 as output
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with an internal pull-up resistor
// Initialize the serial monitor for debugging
Serial.begin(9600);
// Initial motor state (stopped)
analogWrite(motorPWM, 0); // Ensure the motor is not running at the start
}
void loop() {
// Read the potentiometer value to determine motor speed
int potValue = analogRead(potPin); // Read the raw value (0 to 1023)
int motorSpeed = map(potValue, 0, 1023, 0, 255); // Map the raw value to PWM range (0 to 255)
// Check if the button is pressed (LOW when pressed due to internal pull-up)
if (digitalRead(buttonPin) == LOW) {
// Set the motor direction (e.g., forward)
digitalWrite(motorDir1, HIGH);
digitalWrite(motorDir2, LOW);
// Write the PWM value to the motor control pin to set speed
analogWrite(motorPWM, motorSpeed);
// Print the current motor status for debugging
Serial.println("Motor is ON");
} else {
// Stop the motor when the button is not pressed
analogWrite(motorPWM, 0);
// Print the current motor status for debugging
Serial.println("Motor is OFF");
}
// Small delay to allow the system to stabilize
delay(10);
}