Project 1 - Controlling a DC motor using PWM and monitoring its Running status
#include
#define F_CPU 16000000L
#include "avr/interrupt.h"
#include
#define sw_dir (PIND & (1<<1)) // TXD pin in atmega32 pd1
#define sw_dspd (PIND & (1<<2)) //INT0 pin for interrupt
#define pw (PINC & (1<<3)) // this pin for power on and off
#define lcd_port PORTB // PORTB for LCD
#define RS_high PORTD |= (1<<5)
#define RS_low PORTD &=~(1<<5)
#define EN_high PORTD |= (1<<6)
#define EN_low PORTD &=~ (1<<6)
unsigned char i;
void lcd_cmd(char cmd){ // giving the command for lcd display
lcd_port = (cmd & 0xf0); // last 4 bits for lcd mode
RS_low;
EN_low;
_delay_ms(1);
EN_high;
lcd_port = ((cmd<<4)&(0xf0));
RS_low;
EN_low;
_delay_ms(1);
EN_high;
}
void lcd_data(char data){ // sending the data to lcd
lcd_port = (data & 0xf0);
RS_high;
EN_low;
_delay_ms(1);
EN_high;
lcd_port = ((data << 4)& (0xf0));
RS_high;
EN_low;
_delay_ms(1);
EN_high;
}
void lcd_init(){ // diff modes for lcd working
lcd_cmd(0x38);
_delay_ms(5);
lcd_cmd(0x02);
_delay_ms(5);
lcd_cmd(0x01);
_delay_ms(5);
lcd_cmd(0x0C);
_delay_ms(5);
lcd_cmd(0x06);
_delay_ms(5);
lcd_cmd(0x80);
_delay_ms(5);
}
void cursorpos(char x,char y){ // x for row y for columns
if((x<1 || x>2) || (y>16 || y<1 )){
x=1;
y=1;
}
if(x==1){
lcd_cmd(0x7F+y);
}
else{ lcd_cmd(0xBF+y);
}
}
void lcd_out(char x,char y, char *str){ cursorpos(x,y);
while(*str){ lcd_data(*str);
str++;
}
}
int adc_read( char channel){ // configuring the adc value
unsigned int a,result;
ADMUX = channel; //channel we need to select in mux here using 2 bit
ADCSRA = 0x80; //control & status register
ADCH = 0;
ADCL = 0;
ADCSRA |= (1<<6);
while((ADCSRA & 0x40) != 0);
a= ADCL;
result=ADCH;
result = result<<8;
result = result | a;
return result;
}
int main(void)
{
DDRB = 0xFF;
DDRA |= ((1<<0)|(1<<1));
DDRD &=~ (1<<1);
DDRD &=~ (1<<2);
DDRD |=(1<<6);
DDRC &=~ (1<<3);
PORTD |= (1<<2);
PORTC |= (1<<3);
i=64; //running the motor with 25% duty cycle.
TCCR0=0x61;
GICR=(1<
sei(); //Enable global interrupt
lcd_init();
while(1){
while(pw==0){ //continue till the push button is released.
if(sw_dir == 0){ //if the direction control push button is released.
PORTA = 0b00000001;
lcd_out(1,1,"motor ON - cl"); //Running clock wise direction
}
else {
PORTA = 0b00000010; // 1 0 to respective 1A 2A pins to rotate in AntiClockwise direction.
lcd_out(1,1,"motor ON - acl");
}
OCR0=i; // increases in ISR, the corresponding value is to be loaded into
OCR0.
}
PORTA = 0X00;
lcd_out(1,1,"motor is turnoff");
}
}
ISR(INT0_vect){ //interrupt service routine
i=i+20;
)

