Advertisement
Guest User

Untitled

a guest
Jan 21st, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.45 KB | None | 0 0
  1. #include "STM32L1xx.h"
  2.  
  3. #define PA1 0x02 // Second bit
  4. #define PA2 0x04 // Fourth bit
  5. #define SWITCH1 PA1
  6. #define SWITCH2 PA2
  7.  
  8. #define PC0 0x01
  9. #define PC1 0x02
  10. #define PC2 0x04
  11. #define PC3 0x08
  12. #define OUTPUT_PINS (PC0 | PC1 | PC2 | PC3)
  13.  
  14.  
  15. void switch_setup() {
  16.     RCC->AHBENR |= 0x01; // Enable GPIOA
  17.    
  18.     GPIOA->MODER &= ~(GPIO_MODER_MODER1 | GPIO_MODER_MODER2); // set PA[1:2] to inputs
  19. }
  20.  
  21. void output_setup() {
  22.     RCC->AHBENR |= 0x04;
  23.    
  24.     GPIOC->MODER &= ~(GPIO_MODER_MODER0 | GPIO_MODER_MODER1 | GPIO_MODER_MODER2 | GPIO_MODER_MODER3); // clear PC[0:3] modes
  25.     GPIOC->MODER |= GPIO_MODER_MODER0_0 | GPIO_MODER_MODER1_0 | GPIO_MODER_MODER2_0 | GPIO_MODER_MODER3_0; // set PC[0:3] to outputs
  26. }
  27.  
  28. void set_output(uint8_t count) {
  29.     GPIOC->ODR = (GPIOC->ODR & ~OUTPUT_PINS) | (count & OUTPUT_PINS); // Set PC[0:3] to count
  30. }
  31.  
  32. uint8_t read_switch1() {
  33.     return GPIOA->IDR & SWITCH1;
  34. }
  35.  
  36. uint8_t read_switch2() {
  37.     return GPIOA->IDR & SWITCH2;
  38. }
  39.  
  40. void delay() {
  41.     // delay for roughly 500 ms
  42.     for (int i = 0; i < 20; i++) {
  43.         for (int j = 0; j < 10000; j++) {
  44.             __nop();
  45.         }
  46.     }
  47. }
  48.  
  49. static uint8_t count = 0;
  50.  
  51. int main() {
  52.     switch_setup();
  53.     output_setup();
  54.    
  55.     count = 0;
  56.    
  57.     while (1) {
  58.         if (read_switch1()) {
  59.             // counter is enabled
  60.            
  61.             if (read_switch2()) {
  62.                 // counting down if value is 1
  63.                
  64.                 count--;
  65.             } else {
  66.                 // counting up otherwise
  67.                
  68.                 count++;
  69.             }
  70.         }
  71.        
  72.         set_output(count);
  73.         delay();
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement