Project 1 - Controlling a DC motor using PWM and monitoring its Running status
CODE:
#include <avr/io.h> // for using I/O registers of avr
#define F_CPU 16000000L //defining frequency
#include <util/delay.h> //delay function
#include "avr/interrupt.h" //external interrupts pin
#define lcd_port PORTB //port b pins are used for lcd data
#define rs_high PORTD|=(1<<0) //d0 pin is used for rs..set d5 as rs
#define rs_low PORTD&=~(1<<0) //clear d0 as rs
#define en_high PORTD|=(1<<1) //d1 is set as en..d6 is set as enable
#define en_low PORTD&=~(1<<1) //clear d1 as enable
int a;
void lcd_cmd(char cmd); // cmd register of lcd
void lcd_data(char data); // data register of lcd
void lcd_init(); // lcd initaliaztion
void cursorpos(char x, char y); // cursor postion of lcd
void lcd_out(char x, char y, char *str); // printing output on display
int main(void)
{
DDRB=0xFF; //port b all pins are used as output...here lcd is connect
DDRD |=(1<<5); //d0 pin is used as output which is connect to L293 as input enable..12EN
DDRC |=(1<<0); //c0 pin is used as output which is connect to L293 as input..2A
DDRC |=(1<<1); //c1 pin is used as output which is connect to L293 as input..1A
sei(); //enable global interrupts..setting the interrupt
GICR=(1<<7)|(1<<6); //we have as external interrupts..7th and 6th pin is used..INT0 and INT1..push button is interrupt
PORTD=(1<<2)|(1<<3); //push button as input
lcd_init();
while(1)
{
if(a==1)
{
lcd_out(1,1,"Motor Clockwise");
}
else
{
lcd_out(1,1,"Motor Anticlockwise");
}
}
}
ISR(INT0_vect) //interrupt service routine..when interrupt occurs this is executed first
{ //motor rotate clockwise
PORTC|=(1<<0);
PORTC&=~(1<<1);
a=1;
lcd_cmd(0x01);_delay_ms(5);
}
ISR(INT1_vect)
{ //motor rotate anticlockwise
PORTC|=~(1<<0);
PORTC&=(1<<1);
a=2;
lcd_cmd(0x01);_delay_ms(5);
}
void lcd_cmd(char cmd)
{
lcd_port=cmd;
rs_low; //rs-low, en-low to high...syntax for cmd
en_low;
_delay_ms(5);
en_high;
}
void lcd_data(char data)
{
lcd_port=data;
rs_high; //rs-high, en-low to high..syntax for data
en_low;
_delay_ms(5);
en_high;
}
void lcd_init()
{
lcd_cmd(0x38);_delay_ms(5); //2 lines 5x7 matrix
lcd_cmd(0x02);_delay_ms(5); // return 0
lcd_cmd(0x01);_delay_ms(5); //clear screen
lcd_cmd(0x0C);_delay_ms(5); //display on, cursor off
lcd_cmd(0x06);_delay_ms(5); //increment cursor
lcd_cmd(0x80);_delay_ms(5); //force cursor begin 1st line
lcd_cmd(0xC0);;_delay_ms(5); //force cursor begin 2nd line
}
void cursorpos(char x, char y) //for making cursor understand its position
{
if ((x<1||x>2)||(y>16||y<1)) //x is row..y is column so 2 row 16 column
{
x=1;
y=1;
}
if(x==1) //cursor at begining at first line(1,1)
{
lcd_cmd(0x7F+y); //this indicates first row..80..forcing cursor at begining of first line
}
else
{
lcd_cmd(0xBF+y); //this indicates second row..C0..forcing cursor at begining of second line
}
}
void lcd_out(char x, char y, char *str)
{
cursorpos(x,y);
while(*str)
{
lcd_data(*str);
str++;
}
}
OUTPUT:

