ZRE0412

Arduino-HomeWork-01-traffic light

Apr 20th, 2021 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #define HR_LED _BV(2)
  2. #define HY_LED _BV(3)
  3. #define HG_LED _BV(4)
  4. #define VR_LED _BV(5)
  5. #define VY_LED _BV(6)
  6. #define VG_LED _BV(7)
  7.  
  8. #define SW1 _BV(1)
  9. #define SW2 _BV(2)
  10. #define SW3 _BV(3)
  11.  
  12. int timer=0;
  13. byte mode;
  14.  
  15. void setup()
  16. {
  17.   DDRD |= (HR_LED | HY_LED | HG_LED | VR_LED | VY_LED | VG_LED);
  18.  
  19.   DDRB &= ~(SW1 | SW2 | SW3);
  20.  
  21.   //ALL LED OFF
  22.   PORTD = 0;
  23. }
  24.  
  25. void run(const byte LEDR, const byte LEDY, const byte LEDG, const int t){
  26.   int ct = timer-t;
  27.   if(ct==1){
  28.     PORTD &= ~LEDR;
  29.     PORTD |= LEDG;
  30.   }
  31.   else if(ct==8250){
  32.     PORTD |= LEDG;
  33.   }
  34.   else if(ct==8500){
  35.     PORTD &= ~LEDG;
  36.   }
  37.   else if(ct==8750){
  38.     PORTD |= LEDG;
  39.   }
  40.   else if(ct==9000){
  41.     PORTD &= ~LEDG;
  42.   }
  43.   else if(ct>9250 && ct<12500){
  44.     PORTD |= LEDY;
  45.   }
  46.   else if(ct==12500){
  47.     PORTD &= ~LEDY;
  48.     PORTD |= LEDR;
  49.   }
  50. }
  51.  
  52. void flash(const byte LEDA, const byte LEDB){
  53.   if(timer==0){
  54.     PORTD |= LEDA;
  55.     PORTD |= LEDB;
  56.   }
  57.   else if(timer==500){
  58.     PORTD &= ~LEDA;
  59.     PORTD &= ~LEDB;
  60.   }
  61. }
  62.  
  63. void loop()
  64. {
  65.   // 0 0 0
  66.   if(!(PINB & SW1) && !(PINB & SW2) && !(PINB & SW3)){
  67.     if(mode != 0){
  68.       mode = 0;
  69.       timer = 0;
  70.       PORTD = 0;
  71.     }
  72.     mode = 0;
  73.     if(timer==0){
  74.       PORTD |= VR_LED;
  75.     }
  76.     else if(timer<=12500){
  77.       run(HR_LED, HY_LED, HG_LED, 0);
  78.     }
  79.     else if(timer>12500 && timer<=25000){
  80.       run(VR_LED, VY_LED, VG_LED, 12500);
  81.     }
  82.     else if(timer>25000){
  83.       timer = 0;
  84.     }
  85.   }
  86.   // 1 0 0
  87.   else if((PINB & SW1) && !(PINB & SW2) && !(PINB & SW3)){
  88.     if(mode != 1){
  89.       mode = 1;
  90.       timer = 0;
  91.       PORTD = 0;
  92.     }
  93.     if(timer==1000){
  94.       timer = 0;
  95.     }
  96.     flash(HR_LED, VY_LED);
  97.   }
  98.   // 1 1 0
  99.   else if((PINB & SW1) && (PINB & SW2) && !(PINB & SW3)){
  100.     if(mode != 2){
  101.       mode = 2;
  102.       timer = 0;
  103.     }
  104.     PORTD = HG_LED | VR_LED;
  105.   }
  106.   // 1 1 1
  107.   else if((PINB & SW1) && (PINB & SW2) && (PINB & SW3)){
  108.     if(mode != 3){
  109.       mode = 3;
  110.       timer = 0;
  111.     }
  112.     PORTD = VG_LED | HR_LED;
  113.   }
  114.   else{
  115.     mode = -1;
  116.     PORTD = 0;
  117.   }
  118.   delay(1);
  119.   timer++;
  120. }
Add Comment
Please, Sign In to add comment