Mission 14 - Rotary Encoder
 DuinoKit Essentials - View Only. See new "Mission Manual" forum for manual and code   Started by Daniel Alich   2017-06-27 21:28:44 -04:00   Comments: 1    Viewed: 853

  1. Daniel Alich
    Daniel Alich Member Staff Member
    252_1511883342_Mission 14 – Rotary Enc

    /* Rotary encoder read example */
    #define ENC_A 8
    #define ENC_B 9
    #define ENC_PORT PINB

    void setup()
    {
    /* Setup encoder pins as inputs */
    pinMode(ENC_A, INPUT);
    digitalWrite(ENC_A, HIGH);
    pinMode(ENC_B, INPUT);
    digitalWrite(ENC_B, HIGH);
    Serial.begin (9600);
    Serial.println("Start");
    }

    void loop()
    {
    static uint8_t counter = 0; //this variable will be changed by encoder input
    int8_t tmpdata;

    tmpdata = read_encoder();
    int MapValue;
    if( tmpdata ) {
    Serial.print("Counter value: ");
    Serial.print(counter, DEC);
    Serial.print(" value: ");
    MapValue=map(counter,0,255,0,50);
    Serial.println(MapValue, DEC);
    counter += tmpdata;
    }
    }
    /* returns change in encoder state (-1,0,1) */
    int8_t read_encoder()
    {
    static int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
    static uint8_t old_AB = 0;

    old_AB <<=2 ; //remember previous state
    old_AB |= ( ENC_PORT & 0x03 ); //add current state
    return ( enc_states[( old_AB & 0x0f )]);

    }
    Daniel Alich, 2017-06-27 21:28:44 -04:00
  2. (You must log in or sign up to post here)

Report Post

Write your reason

Log in | Sign up
Terms & Conditions!
Help!