Project 1 - Controlling a DC motor using PWM and monitoring its Running status
#define F_CPU 16000000L //header files
#include <avr/io.h>
#include <util/delay.h>
#include "avr/interrupt.h"
#define rs_high() PORTC |= (1 << 7);
#define rs_low() PORTC &= ~(1 << 7);
#define en_high() PORTC |= (1 << 6);
#define en_low() PORTC &= ~(1 << 6);
#define lcdport PORTA //defining PORT A as lcdport
#define direction (PIND & (1 << 0))
#define speed (PIND & (1 << 2))
#define power_switch (PIND & (1 << 6))
unsigned char a; //variable declaration
void lcd_command(unsigned char cmd) //lcd command function
{
lcdport = cmd;
rs_low();
en_high();
_delay_ms(1);
en_low();
}
void lcd_data(unsigned char dat) //lcd data function
{
lcdport = dat;
rs_high();
en_high();
_delay_ms(1);
en_low();
}
void lcd_init() //lcd initialization function
{
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) //cursor position function
{
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) //lcd printing function
{
cursorpos(x,y);
while(*str)
{
lcd_data(*str);
str++;
}
}
int main(void)
{
DDRA = 0xFF; //declaring all pins of port A as output
DDRB = 0xFF; //declaring all pins of port B as output
PORTB = 0xFF;
DDRC |=(1<<1)|(1<<0); //setting Pin 1 and Pin 0 as output to L293
DDRD &=~(1<<6); //setting as inputs
DDRD &=~(1<<2);
DDRD &=~(1<<0);
DDRC |=(1<<7)|(1<<6); //setting as output to RS and EN
PORTD|=(1<<0); //Enabling internal pull up resistors
PORTD|=(1<<2);
PORTD|=(1<<6);
a=64; //assigning value to variable for 25% duty cycle
TCCR0 = 0x61; //non inverting mode,phase corrected and no prescaler
GICR |=(1<<7);
MCUCR = 0x02;
sei(); //enabling global interrupt
/* Replace with your application code */
lcd_init();
while (1)
{
while(power_switch==0) //if power switch is closed
{
if(direction==0)
{
PORTC=0x02; //motor rotates in clockwise direction
lcd_out(1,1,"Motor is ON - CW");
}
else
{
PORTC=0x01; //motor rotates in Anticlockwise direction
lcd_out(1,1,"Motor is ON - ACW");
}
OCR0=a; //assigning value of a to OCR0
}
PORTC=0x00; //motor is turned off
lcd_out(1,1,"Motor is TURNOFF");
}
}
ISR(INT0_vect) //interrupt service routine
{
a=a+10; //duty cycle is incremented
}