ステッパーモーター / ただ回してみる

今度はSN754410を使ってただ回してみる。
f:id:ti-nspire:20191123075215p:plain:h250

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

int main(){

    const uint8_t Phases[] = { // 必要な励磁状態を定義しておく。フルステップ。
        (1 << PB0) | (1 << PB2),
        (1 << PB0) | (1 << PB3),
        (1 << PB1) | (1 << PB3),
        (1 << PB1) | (1 << PB2),
    };
    const uint8_t MaxIndex = sizeof(Phases)/sizeof(uint8_t) - 1;

    uint8_t whichPhase = 0; // どの励磁状態にあるのかを覚えておく。
    uint8_t incre = 1;

    DDRB = 0x0F; // (1 << PB0) | (1 << PB1) | (1 << PB2) | (1 << PB3)

    int StepsPerRevolution = 200;                              // 360度/200ステップのステッパーを回す。
    int HowManySteps       = 400;                              // 何ステップ回すかを指定する。
    int RPM                = 120;                              // 回転速度(rpm)を指定する。
    //int Delay_ms = round(1e3/(StepsPerRevolution * RPM/60.0)); // その回転速度に必要な遅延ミリ秒数を計算する。
    int Delay_us = round(1e6/(StepsPerRevolution * RPM/60.0)); // その回転速度に必要な遅延マイクロ秒数を計算する。

    while(1){

        for(int i=0; i<HowManySteps; i++){
            PORTB = Phases[whichPhase];                   // 励磁する。
            whichPhase = (whichPhase + incre) & MaxIndex; // 次の励磁に備える。インクリメントし続けてもオーバーフローしないようにしておく。
            //_delay_ms(Delay_ms);
            _delay_us(Delay_us);
        }

        _delay_ms(500);
        incre = -incre; // 向きを逆にして繰り返す。

    }

    return 0;
}

(※)PORTB = Phases[whichPhase];whichPhase = (whichPhase + incre) & MaxIndex;とは順番を逆にすべきであった。そうしないと、向きを反転した直後の1ステップだけ、指定の向きと逆に回る。