Challenge

Project 1 - Controlling a DC motor using PWM and monitoring its Running status

Here is the code

#define F_CPU 16000000L
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#define lcdport PORTB
#define rs_high PORTD |= (1<<0);
#define rs_low PORTD &= ~(1<<0);
#define en_high PORTD |= (1<<1);
#define en_low PORTD &= ~(1<<1);
#define direction PORTC |=(1<<3);
#define speed PORTD |=(1<<2);
#define power PIND & (0x08);

unsigned char var;
unsigned char motor_on = 0;
volatile uint8_t duty_cycle = 50;

ISR(INT0_vect) // external interrupt service routine
{
	_delay_ms(50); // debounce delay
	if (!(PIND & (1 << PD2))) // check if button is pressed
	{
		// update duty cycle
		if (duty_cycle == 50)
		duty_cycle = 75;
		else if (duty_cycle == 75)
		duty_cycle = 100;
		else if (duty_cycle == 100)
		duty_cycle = 50;
	}
}

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);
}

void lcd_print(char *str)
{
	unsigned char i=0;
	while (str[i]!=0)
	{
		lcd_data(str[i]);
		i++;
	}
}

void delay(){
	TCNT0=0xCE;
	TCCR0=0x1;
	while((TIFR&(1<<TOV0))==0);
	TCCR0=0;
	TIFR=0x01;
}

void change_direction()
{
	PORTC ^= (1 << PC1) | (1 << PC2);
}


int main(void)
{
	DDRB = 0xFF;
	DDRD |= (1<<0);
	DDRD |= (1<<2);
	DDRC |= (1 << PC0) | (1 << PC1) | (1 << PC2);
	DDRD &= ~(1<<3);
	DDRC &= ~(1<<3);
	sei();
	GICR|=(1<<6); 
	
	
	while (1)
	{
		PORTC ^= (1<<PC0);
		delay();
		
		if ((PINC & (1<<PINC3)) && !motor_on)
		{
			motor_on = 1;
			PORTC |= (1<<PC2);
			lcd_init();
			lcd_print("Motor Rotating");
		}
		else if (!(PINC & (1<<PINC3)) && motor_on)
		{
			motor_on = 0;
			PORTC &= ~(1<<PC2);
			lcd_init();
			lcd_print("Motor Stopped");
		}
		
		else if ((PINC & (1<<PINC3)) & (PIND & (1<<PIND3)))
		{
			change_direction();
			while ((PIND & (1 << PD3)));
			lcd_init();
			lcd_print("Changed Direction");
		}
	}
}
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.