Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. /*
  2.  * Lab4_a.c
  3.  *
  4.  * Created: 10/13/2017 5:03:07 PM
  5.  * Author : SPHAM
  6.  * Two leds are connected to uc over PIN PD6
  7.  */
  8. #define dtime 23
  9. #define F_CPU 16000000UL
  10. #include <avr/io.h>
  11. #include <util/delay.h>
  12. #include <stdio.h>
  13.  
  14. /*
  15.     we have to generate pwm
  16.     using on and off circle
  17.     -----------------------
  18.     function _delay_n_ms will generate n*delay(constant) because
  19.     delay doesn't take variable. The code is based on an example on avrfreak forum
  20. */
  21. void _delay_n_ms(uint8_t n){
  22.     while(n--)
  23.         _delay_ms(1);
  24. }
  25. void on_off_cycle(uint8_t t){
  26.     PORTD &= ~(1<<PORTD6);//off time increasing as t decreasing and vice versa
  27.     _delay_n_ms(dtime-t);
  28.     PORTD |= 1<<PORTD6; //on time
  29.     _delay_n_ms(t);
  30. }
  31.  
  32. int main(void)
  33. {
  34.     /*Initialize DDR, PORT, and PIN*/
  35.     DDRD |= (1<<DDRD6);
  36.     PORTD &= ~(1<<PORTD6);
  37.     /*Using the on-board button B7*/
  38.     DDRB &= ~(1<<DDRB7);
  39.     PINB |= (1<<PINB7);
  40.     /*MAIN LOOP*/
  41.     while (1){
  42.         int t;
  43.         for (t = 0; (!(PINB & (1<<PINB7))) && t < dtime; t++){
  44.                 on_off_cycle(t);
  45.         }
  46.         while(!(PINB & (1<<PINB7))) PORTD |= (1<<PORTD6);
  47.         //t=20;
  48.         while((PINB & (1<<PINB7)) && (t > 0)){
  49.                 on_off_cycle(t);
  50.                 t--;
  51.         }
  52.         while(PINB & (1<<PINB7))    PORTD &= ~(1<<PORTD6);
  53.     }
  54. }