跳到主要內容

選修分組-專題 / OLD / TinkerCAD時間中斷

1

1

 

1

 

/*  CC-BY-SA - diegoCode - 2020 */
 
#define outPin 4
#define ledPin 13
 
#define T_LED 100   // blink period (ms)
 
int countLed = T_LED;
 
void setup() {
  // configure pins 
  pinMode(outPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
 
  // set up timer interrupt 
  setTimerInterrupt(1500); // int @1ms (1000 us)
}
 
void loop() { 
  if (countLed == 0) {
    togglePin(ledPin);
    countLed = T_LED;    
  }
}
 
 
// timer compare ISR
ISR(TIMER1_COMPA_vect) {
  togglePin(outPin);   
  
  if (countLed) --countLed;
}
 
// toggle pin
void togglePin(long pin){
  digitalWrite(pin, digitalRead(pin) ^ 1);
}
 
// set up timer1 - 
// compare interrupt @ uSecs microseconds
void setTimerInterrupt(long uSecs) {
  noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  // compare match register 16MHz/256 * t(s) - 1
  OCR1A = (16e6 / 256L * uSecs) / 1e6 - 1;            
 
  TCCR1B |= (1 << WGM12);   // CTC mode
  TCCR1B |= (1 << CS12);    // 256 prescaler 
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt
 
  interrupts();             // enable all interrupts
}

 

時間類別單位標題發佈點閱
跳至網頁頂部