Project 1 - Controlling a DC motor using PWM and monitoring its Running status
Code:-
#include <avr/io.h>
#define F_CPU 16000000L
#include<util/delay.h>
#include "avr/interrupt.h"
#define lcdport PORTB //declared the PORT B for the LCD
#define rs_high PORTD|=(1<<0); //D0 is used for the Register Select(RS) for HIGH (1)
#define rs_low PORTD&=~(1<<0); //D0 is used for the Register Select(RS) for LOW (0)
#define en_high PORTD|=(1<<1); //D1 is used for the Enable(EN) for HIGH (1)
#define en_low PORTD&=~(1<<1); //D1 is used for the Enable(EN) for LOW (0)
int a;
void lcd_cmd(unsigned char cmd);
void lcd_data(unsigned char data);
void lcd_init();
void cursorpos(char x, char y);
void lcd_print(char row, char column, unsigned int value, int digits);
void lcd_out(char x, char y, char *str);
int adc_read(char channel);
void lcd_cmd(unsigned char cmd) //Send the command to LCD
{
lcdport= cmd;
rs_low;
en_low;
_delay_ms(1);
en_high; //Enable LCD
}
void lcd_data(unsigned char data) //Send the data to LCD
{
lcdport=data;
rs_high;
en_low;
_delay_ms(1);
en_high; //Enable LCD
}
void lcd_init() //LCD Initialization
{
lcd_cmd(0x38);_delay_ms(5); //used for 8 bits lcd mode
lcd_cmd(0x02);_delay_ms(5); //return the cursor to home
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 to begin 1st line
lcd_cmd(0xC0);_delay_ms(5); //display ON cursor ON
}
void cursorpos(char x, char y) //here checking cursor position
{
if((x<1||x>2)||(y<1||y>16)) //Here check the 2 rows and 16 columns
{
x=1; //X= Rows
y=1; //Y= Columns
}
if(x==1)
lcd_cmd(0x7F+y); //80-1=7f for starting the 1st line hex decimal value(80)...we need to start from that column...
else
lcd_cmd(0xbf+y); //2nd line 2nd row
}
void lcd_out(char x, char y, char *str) //Here checking in which position we want to print
{
cursorpos(x,y);
while(*str)
{
lcd_data(*str);
str++;
}
}
int main(void) // main function
{
DDRB =0xff; //clock config for timer, prescaler set to 1, PWM 8 bit
DDRD |=(1<<5);
DDRC |=(1<<0);
DDRC |=(1<<1);
sei(); //enabling interrupt
GICR=(1<<7)|(1<<6);
PORTD=(1<<2)|(1<<3); //setting push button pins PORTD 2&3
lcd_init();
TCCR1A=0x81;
TCCR1B=0x01; //waveform generation bit setting, PWM mode
TCNT1L=0;
TCNT1H=0;
while(1)
{
if(a==1)
{
lcd_out(1,1,"Motor AntiClockwise");
}
else
{
lcd_out(1,1,"Motor Clockwise");
}
}
}
ISR(INT0_vect) //ISR interrupt function
{
PORTC|=(1<<0);
PORTC&=~(1<<1);
a=1;
lcd_cmd(0x01);
_delay_ms(5);
}
ISR(INT1_vect)
{
PORTC|=(1<<1);
PORTC&=~(1<<0);
a=2;
lcd_cmd(0x01);
_delay_ms(5);
}