Project 1 - Controlling a DC motor using PWM and monitoring its Running status
/*
* DCMOTOR_PROJECT1.c
*
* Created: 28-08-2022 09:31:45
* Author : cheru
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#define rs_high() PORTD |=(1<<5);
#define rs_low() PORTD &= ~(1<<5);
#define en_high() PORTD |= (1<<6);
#define en_low() PORTD &= ~(1<<6);
#define lcdport PORTC
void lcd_command(unsigned char cmd)
{
lcdport = cmd;
rs_low();
en_high();
_delay_ms(1);
en_low();
}
void lcd_data(unsigned char dat)
{
lcdport = dat;
rs_high();
en_high();
_delay_ms(1);
en_low();
}
void lcd_init()
{
lcd_command(0x38);_delay_ms(5);
lcd_command(0x02);_delay_ms(5);
lcd_command(0x01);_delay_ms(5);
lcd_command(0x0c);_delay_ms(5);
lcd_command(0x06);_delay_ms(5);
lcd_command(0x80);_delay_ms(5);
}
void cursorpos(char x, char y)
{
if( (x < 1 || x > 2) || (y < 1 || y > 16) )
{
x = 1;
y = 1;
}
if(x == 1)
lcd_command(0x7F+y);
else
lcd_command(0xBF+y);
}
void lcd_out(char x,char y,char *str)
{
cursorpos(x,y);
while(*str)
{
lcd_data(*str);
str++;
}
}
void PWM_init()
{
/*set fast PWM mode with non-inverted output*/
TCCR0 = (1<<WGM00) | (1<<WGM01) | (1<<COM01) | (1<<CS00);
DDRB|=(1<<PB3); /*set OC0 pin as output*/
DDRA |= 0xff; // setting all pins of port a as output
DDRD &= ~(1<<2); // setting pin 2 of port D as input
PORTD |= (1<<2); // setting as pull up for assigning push button
DDRC = 0xff; // for lcd display
DDRD|=(1<<5);
DDRD|=(1<<6);
}
int main ()
{
unsigned char duty=127; // Approx 50 %duty cycle is taken for representation
PWM_init(); // calling the function for setting registers
lcd_init(); // calling for lcd output
while (1)
{
OCR0=duty; // generating pulse width Modulation signal with 50% duty cycle and no prescaler
if(PIND & (1<<2)) // if pin d2 is high i.e button is pressed..
{
PORTA = 1; // setting 1 and 0 to the L293 IC for direction of rotation of motor
lcd_out(1,1,"MOTOR Spinning");
lcd_out(2,3,"Clockwise");
}
else
{
PORTA = 2; // setting 0 and 1 to the L293 IC for opposite rotation of motor
lcd_out(2,3,"AntiClock");
}
}
}

/*When toggled*/
