Project 1 - Controlling a DC motor using PWM and monitoring its Running status
/*
* AVR_Project1.c
*
* Created: 01-10-2022 18:30:24
* Author : SANDEEP
*/
//header files
#include <avr/io.h>
#define F_CPU 16000000L//Macro
#include <util/delay.h>
#include "avr/interrupt.h"
//Function Prototypes
void lcd_cmd (unsigned char cmd);
void lcd_data (unsigned char data);
void lcd_init(void);
void lcd_out(char x, char y, char *str);
void cursor_pos(char x, char y);
#define lcdport PORTC //portC as LCD Macro
#define rs_high PORTD |= (1<<5);//RS enable high
#define rs_low PORTD &= ~(1<<5);//RS enable low
#define en_high PORTD |= (1<<6);//enable high
#define en_low PORTD &= ~(1<<6);//enable low
#define dr (PIND&(1<<1)) //Macros
#define sp (PIND&(1<<2))
#define pw (PIND&(1<<0))
unsigned char var;
void lcd_cmd (unsigned char cmd)
{
lcdport=cmd;
rs_low;
en_high;
_delay_ms(1);
en_low;
}
void lcd_data (unsigned char data)
{
lcdport = data;
rs_high;
en_high;
_delay_ms(1);
en_low;
}
void lcd_init()
{
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);
}
//function definition for cursor position
void cursor_pos(char x, char y)//x-row,y-col
{
if((x<1||x>2)||(y<1||y>16))//any typo mistakes
{
x=1;
y=1;
}
if (x==1) //0x80 -1,1 1,2-0x81 1,3-0x82.....
{
lcd_cmd(0x7F+y);//7F+2
}
else //0xC0
{
lcd_cmd(0xBF+y);//BF+5=C4
}
}
//function to access the given strings
void lcd_out(char x, char y, char *str)
{
cursor_pos(x,y);//2,5
while(*str)
{
lcd_data(*str);
str++;
}
}
int main(void)
{
DDRC = 0xFF;//port B configured as outputs
DDRA |= ((1<<0)|(1<<1));//configuring port A 0th PIN and 1st PIN as motor output
DDRD &= ~(1<<1);//ip configuration of direction
DDRD &= ~(1<<2);//ip configuration of power
DDRD |= (1<<5);//configuring port D 5th PIN as RS output
DDRD |= (1<<6);//configuring port D 6th PIN as En output
DDRD &= ~(1<<0);//ip configuration power
PORTD |=(1<<2);//enabling pullup register for interrupt
PORTD |=(1<<0);//enabling pullup register for power
var=64;
TCCR0 |= 0x61;//enabling phase corrected PWM,Non inverting mode,no prescalar
GICR=(1<<INT0);// enable interrupts INI0
MCUCR=0x02;//negative edge
sei();//Global Interrupt Enable
lcd_init();// calling initialization of lcd
while (1)
{
while(pw==0)
{
if(dr==0)
{
PORTA = 0b00000001;//to drive motor in clockwise
lcd_out(1,1,"Motor is running");
lcd_out(2,1,"clockwise");
}
else
{
PORTA =0b00000010;//anti clockwise
lcd_out(1,1,"Motor is running");
lcd_out(2,1,"Anticlockwise");
}
OCR0=var;
}
PORTA=0x00;//stop condition of motor
lcd_out(1,1,"Motor is off");
lcd_out(2,1,"Caution!!!");
}
}
ISR(INT0_vect)//interrupt service routine
{
var=var+10;
}