0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

digispark タイマー割り込みとUSB通信の組み合わせ

Posted at

目的

digisparkで,タイマー割り込みを用いつつ,USB通信でモニターを行う。

たたき台ソースコード

# include <DigiUSB.h>

# include <avr/io.h>
# include <avr/interrupt.h>

int ledPin1 = 1;
boolean s = false;

volatile int i;

ISR(TIM0_COMPA_vect) {
  // 16.5 Mhz / (256*256) = 251.77 Hz
  i++;
}

void setup() {
  DigiUSB.begin();
  DigiUSB.refresh();
  DigiUSB.delay(10);
  DigiUSB.println("Booted digispark.");

    pinMode(ledPin1, OUTPUT);

  cli();

  //initialize the timer0
  TCCR0A  = (1<<WGM01);      // Put timer0 in CTC mode and clear other bits
  TCCR0B  = (1<<CS02) ;      // Timer0 prescaling 256 and clearing other bits
  TIMSK  |= (1<<OCIE0A);     // enable timer1 compare interrupt

  //set the timer0 count
  OCR0A = 255; // Count 255 cycles before calling ISR interrupt
  PORTB |= (1<<PINB1); // Set PortB Pin1 high to turn on LED

  //initialize global interrupts before beginning loop
  sei();

  digitalWrite(ledPin1, 0);

}

void loop() {
  DigiUSB.refresh();
  DigiUSB.delay(10);
  if (DigiUSB.available()) {
    do {
      DigiUSB.refresh();
      DigiUSB.delay(10);
    } while (DigiUSB.read() != '\n' );
    DigiUSB.print("millis()/1000:");
    DigiUSB.println(millis() / 1000);
  }
    cli();
  if (i > 252) { // 16.5 MHz / (256*256) / 252 ~= 1 Hz
    i = 0;
    s = !s;
  }
  sei();

  digitalWrite(ledPin1, s);
}

スケッチを書き込むと,1秒間隔でLEDが点滅します。(blink)
digiterm等を起動し,何か文字を書き込んで[return]すると,millis()/1000を表示します。

DigiUSBの動作安定のために,しつこいぐらいにDigiUSB.refreshDigiUSB.delayが挿入されています。
当初,これがなくて,digitermで認識されなくて悩みました。

参考URL

https://nekosan0.bake-neko.net/warehouse_digispark.html
https://brown.ap.teacup.com/nekosan0/3457.html
https://qiita.com/RAWSEQ/items/bf917c8eec2b51b9abc2

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?