7セグタイマープログラム

 #include <Arduino.h>

#include <TM1637Display.h>
#define LED_PIN   23
#define BUTTON_PIN 18
#define CLK 17
#define DIO 16



hw_timer_t * timer = NULL;
volatile SemaphoreHandle_t timerSemaphore;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

volatile uint32_t isrCounter = 0;
volatile uint32_t lastIsrAt = 0;
uint32_t resetTime = 0;

// put function declarations here:

void ARDUINO_ISR_ATTR onTimer(){
  // Increment the counter and set the time of ISR
  portENTER_CRITICAL_ISR(&timerMux);
  isrCounter++;
  lastIsrAt = millis();
  portEXIT_CRITICAL_ISR(&timerMux);
  // Give a semaphore that we can check in the loop
  xSemaphoreGiveFromISR(timerSemaphore, NULL);
  // It is safe to use digitalRead/Write here if you want to toggle an output
}

TM1637Display display(CLK, DIO);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(100);
  Serial.printf("%s - run\n",__func__);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  // Create semaphore to inform us when the timer has fired
  timerSemaphore = xSemaphoreCreateBinary();

  // Use 1st timer of 4 (counted from zero).
  // Set 80 divider for prescaler (see ESP32 Technical Reference Manual for more
  // info).
  timer = timerBegin(0, 80, true);

  // Attach onTimer function to our timer.
  timerAttachInterrupt(timer, &onTimer, true);

  // Set alarm to call onTimer function every second (value in microseconds).
  // Repeat the alarm (third parameter)
  timerAlarmWrite(timer, 1000000, true);

  // Start an alarm
  timerAlarmEnable(timer);

  display.setBrightness(0x0f);


}

void loop() {
  // put your main code here, to run repeatedly:

  uint32_t countsec;
  uint32_t countmin;
  uint32_t counthour;
  uint8_t sec;
  uint8_t min;
  uint8_t hour;
 

  if (xSemaphoreTake(timerSemaphore, 0) == pdTRUE){
    uint32_t isrCount = 0, isrTime = 0;
    // Read the interrupt count and time
    portENTER_CRITICAL(&timerMux);
    isrCount = isrCounter;
    isrTime = lastIsrAt;
    portEXIT_CRITICAL(&timerMux);

    countsec = (isrTime - resetTime) / 1000;
    sec = countsec % 60;
    countmin = (countsec - sec) /60;
    min = countmin % 60;
    counthour = (countmin-min)/60;
    hour = counthour % 24;

    display.showNumberDecEx((hour*100)+min, (0x80 >> 1), true); //Hour:Min
    //display.showNumberDecEx((min*100)+sec, (0x80 >> 1), true); //Min:Sec
    digitalWrite(LED_PIN, HIGH);
    delay(200);
    digitalWrite(LED_PIN, LOW);
  }

  if (digitalRead(BUTTON_PIN) == LOW) { // 23番ピンがLoの場合
    resetTime = millis();
  }

 
}

// put function definitions here:

コメント