Project 1 - Controlling a DC motor using PWM and monitoring its Running status
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
#include "lcd.h"
#define PWM_PIN 5
#define DIR_PIN1 2
#define DIR_PIN2 3
int main(void) {
// Initialize PWM pin
DDRD |= (1 << PWM_PIN);
TCCR0A |= (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);
TCCR0B |= (1 << CS01);
// Initialize direction pins
DDRD |= (1 << DIR_PIN1) | (1 << DIR_PIN2);
// Initialize LCD screen
lcd_init(LCD_DISP_ON);
// Main loop
while (1) {
// Read analog input and map to PWM duty cycle
uint16_t pot_value = adc_read(0);
uint8_t duty_cycle = map(pot_value, 0, 1023, 0, 255);
// Set PWM duty cycle
OCR0A = duty_cycle;
// Determine motor direction based on duty cycle
if (duty_cycle > 0) {
PORTD |= (1 << DIR_PIN1);
PORTD &= ~(1 << DIR_PIN2);
lcd_puts("Motor: Forward ");
} else if (duty_cycle < 0) {
PORTD &= ~(1 << DIR_PIN1);
PORTD |= (1 << DIR_PIN2);
lcd_puts("Motor: Backward ");
} else {
PORTD &= ~(1 << DIR_PIN1);
PORTD &= ~(1 << DIR_PIN2);
lcd_puts("Motor: Stopped ");
}
// Delay for stability and update LCD screen
_delay_ms(50);
lcd_clrscr();
}
return 0;
}