// Servo Sweep example for STM32 Nucleo-C031C6
// Using Manual PWM control
#define dcservoPin D9
//const int dcservoPin = 9; // Pin D9 on STM32 Nucleo
// can be #define servoPIN D9
// It gives you the benefit of type safety.
// Since it's defined as an integer,
// the compiler knows to expect an integer value and will give you an error
// if you try to assign a non-integer value to it.
// You can also use it in expressions or calculations if needed.
const int minPulseWidth = 500; // Minimum pulse width (in microseconds)
const int maxPulseWidth = 2400; // Maximum pulse width (in microseconds)
// 500 µs to 2400 µs is the standard pulse width range
//used by most standard hobby servos to control the position of the motor.
//=====================================================================
void setup() {
pinMode(dcservoPin, OUTPUT); // Set the dcservoPin as an output
}
void loop() {
// Move to 0 degrees
servoAngle(0);
delay(1000);
// Move to 45 degrees
servoAngle(45);
delay(1000);
// Move to 90 degrees
servoAngle(90);
delay(1000);
// Move to 135 degrees
servoAngle(135);
delay(1000);
// Move to 180 degrees
servoAngle(180);
delay(1000);
// Move back to 0 degrees
servoAngle(0);
delay(500);
}
// Function to generate a PWM pulse for the servo motor
void servoAngle(int angle) {
// Calculate the pulse width for the given angle
int pulseWidth = map(angle, 0, 180, minPulseWidth, maxPulseWidth);
//map() is a built-in function in Arduino environment.
//It maps a number from one range to another.
// Generate the PWM signal (1 ms to 2.4 ms pulse width)
digitalWrite(dcservoPin, HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(dcservoPin, LOW);
delay(20 - pulseWidth / 1000); // Rest of the 20ms period
}
// NOTE:
//The pulse width (500 to 2400 microseconds)
//is a small portion of the 20ms total period.
// IN SHORT:
// The 500 and 2400 microseconds
// are the time the signal stays HIGH,
// controlling the servo's position.
// 20ms is the total time for one cycle,
// where the HIGH time is the active portion
// and the LOW time is the idle portion.