-
Notifications
You must be signed in to change notification settings - Fork 0
/
following_sine_curve
57 lines (46 loc) · 2.24 KB
/
following_sine_curve
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
49
50
51
52
53
54
55
56
57
#include <math.h> // Include the math library for the sin() function
// Pin configuration
const int motorPWM = 9; // PWM output pin connected to the H-bridge for motor speed control
const int motorDir1 = 7; // Digital pin for motor direction control (direction 1)
const int motorDir2 = 8; // Digital pin for motor direction control (direction 2)
const int buttonPin = 2; // Digital pin connected to the push button
// Variables for sine wave generation
float angle = 0.0; // Angle for the sine function
const float increment = 0.1; // Angle increment for smoother transitions
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() {
// 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);
// Generate a sine wave pattern for the motor speed
int motorSpeed = (sin(angle) * 127.5) + 127.5; // Scale sine (-1 to 1) to (0 to 255)
analogWrite(motorPWM, motorSpeed); // Write the PWM value to the motor
// Print the current motor status and speed for debugging
Serial.print("Motor is ON, Speed: ");
Serial.println(motorSpeed);
// Increment the angle for the next loop iteration
angle += increment;
if (angle >= 2 * PI) {
angle -= 2 * PI; // Keep the angle within 0 to 2*PI range
}
} 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 for smoother transitions (adjust as needed)
delay(20);
}