Untitled
Servo motor control with atmega32subratasarkar20
c_cpp
5 months ago
1.2 kB
4
Indexable
#define F_CPU 1000000UL #include <avr/io.h> #include <util/delay.h> void setupPWM() { // Set Fast PWM mode with ICR1 as TOP (Mode 14: WGM13:WGM10 = 14) TCCR1A = (1 << WGM11); TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10); // Prescaler = 64 // Set non-inverting mode on OC1A (Clear OC1A on compare match, set at BOTTOM) TCCR1A |= (1 << COM1A1); // Set TOP value for 50Hz (ICR1 = 311) ICR1 = 311; // Set PD5 (OC1A) as output DDRD |= (1 << PD5); } void setServoPosition(int pulseWidth) { // Set the OCR1A register for the specified pulse width OCR1A = pulseWidth; } int main() { setupPWM(); // Initialize PWM while(1) { // Sweep from 0° (1ms) to 180° (2ms) for (int pulseWidth = 16; pulseWidth <= 31; pulseWidth++) { setServoPosition(pulseWidth); // Move servo to current position _delay_ms(50); // Delay to control the speed of movement } // Sweep from 180° (2ms) back to 0° (1ms) for (int pulseWidth = 31; pulseWidth >= 16; pulseWidth--) { setServoPosition(pulseWidth); // Move servo to current position _delay_ms(50); // Delay to control the speed of movement } } }
Editor is loading...
Leave a Comment