/*
* Lab4_a.c
*
* Created: 10/13/2017 5:03:07 PM
* Author : SPHAM
* Two leds are connected to uc over PIN PD6
*/
#define dtime 23
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
/*
we have to generate pwm
using on and off circle
-----------------------
function _delay_n_ms will generate n*delay(constant) because
delay doesn't take variable. The code is based on an example on avrfreak forum
*/
void _delay_n_ms(uint8_t n){
while(n--)
_delay_ms(1);
}
void on_off_cycle(uint8_t t){
PORTD &= ~(1<<PORTD6);//off time increasing as t decreasing and vice versa
_delay_n_ms(dtime-t);
PORTD |= 1<<PORTD6; //on time
_delay_n_ms(t);
}
int main(void)
{
/*Initialize DDR, PORT, and PIN*/
DDRD |= (1<<DDRD6);
PORTD &= ~(1<<PORTD6);
/*Using the on-board button B7*/
DDRB &= ~(1<<DDRB7);
PINB |= (1<<PINB7);
/*MAIN LOOP*/
while (1){
int t;
for (t = 0; (!(PINB & (1<<PINB7))) && t < dtime; t++){
on_off_cycle(t);
}
while(!(PINB & (1<<PINB7))) PORTD |= (1<<PORTD6);
//t=20;
while((PINB & (1<<PINB7)) && (t > 0)){
on_off_cycle(t);
t--;
}
while(PINB & (1<<PINB7)) PORTD &= ~(1<<PORTD6);
}
}