feierfrosch

EncoderTimer, der Anfang

Dec 28th, 2021 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Arduino.h>
  2.  
  3. #define EncPin1 19
  4. #define EncPin2 23
  5.  
  6. volatile int8_t interruptCounter;
  7. long int EncoderCounter;
  8.  
  9. hw_timer_t *timer = NULL;
  10. portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
  11.  
  12. const int8_t table[16] PROGMEM = {0,0,-1,0,0,0,0,1,1,0,0,0,0,-1,0,0};
  13.  
  14. void IRAM_ATTR Encoder();
  15. int8_t encode_read();
  16.  
  17. void setup()
  18. {
  19.  
  20.   Serial.begin(115200);
  21.  
  22.   pinMode(EncPin1, INPUT_PULLUP);
  23.   pinMode(EncPin2, INPUT_PULLUP);
  24.  
  25.   timer = timerBegin(0, 80, true);
  26.   timerAttachInterrupt(timer, &Encoder, true);
  27.   timerAlarmWrite(timer, 3000000, true);
  28.   timerAlarmEnable(timer);
  29. }
  30.  
  31. void loop()
  32. {
  33.   EncoderCounter += encode_read();
  34. }
  35.  
  36. void IRAM_ATTR Encoder()
  37. {
  38.   static int8_t last = 0;
  39.   int8_t EncVal1 = digitalRead(EncPin1);
  40.   int8_t EncVal2 = digitalRead(EncPin2);
  41.   last = (last << 2) & 0x0F;
  42.   if (EncVal1 == HIGH)
  43.     last |= 1;
  44.   if (EncVal2 == HIGH)
  45.     last |= 2;
  46.  
  47.   interruptCounter += pgm_read_byte(&table[last]);
  48.   Serial.println(last, BIN);
  49.   Serial.println(EncoderCounter);
  50. }
  51.  
  52. int8_t encode_read(void)
  53. { // Encoder auslesen
  54.   int8_t val;
  55.  
  56.   // atomarer Variablenzugriff
  57.   cli();
  58.   val = interruptCounter;
  59.   interruptCounter = 0;
  60.   sei();
  61.   return val;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment