マニュアルクロックを作る

マニュアルクロックもATmega328Pで生成することにする。

#define F_CPU 8000000UL

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

volatile uint8_t switch_changed = 0;
ISR(INT0_vect){
    switch_changed = 1;
}

int main(){
    DDRD |= (1 << PD5);   // PD5からマニュアルクロックを出力することにする。
    PORTD &= ~(1 << PD5); // 最初はLを出力しておく。

    DDRD &= ~(1 << PD2); // PD2をスイッチ入力にすることにする。
    PORTD |= (1 << PD2); // PD2を内部プルアップしておく。

    EICRA |= (1 << ISC00); // INT0 (PD2)が変化したときに割り込み要求を出すことにする。
    EIMSK |= (1 << INT0);  // INT0割り込みを有効化する。
    sei();  

    while(1){
        if(switch_changed){                              // スイッチが変化したら、
            switch_changed = 0;
            _delay_ms(5);                                // バウンスの収まるまで待ってから、
            if(PIND & (1 << PD2)){PORTD &= ~(1 << PD5);} // スイッチが放されていたらLを出力し、
            else                 {PORTD |=  (1 << PD5);} // そうでなければHを出力する。
        }
    }

    return 0;
}

黄色がスイッチ入力。緑がディバウンス後のクロック出力。
f:id:ti-nspire:20201018094600p:plain:h280 f:id:ti-nspire:20201018094608p:plain:h280

f:id:ti-nspire:20201018095234p:plain:h300 f:id:ti-nspire:20201018095258j:plain:h300