2014年8月25日 星期一

Arduino 滑鼠滾輪編碼器/旋轉編碼器

滑鼠拆下來的滾輪編碼器

時序為
                     → CW
A  -----------          -------------    HIGH
               ----------                  LOW

                     ← CCW
B  --------          ----------------    HIGH
            ----------                     LOW

A B

1  1↓CW
1  0
0  0
0  1

1  1
1  0
0  0
0  1↑CCW

程式碼參考底下網址來源修改而來


#define ENCODER_A_PIN 2
#define ENCODER_B_PIN 3
 
unsigned long time = 0;
long position = 0;
long num = 0;
 
void setup()
{
  pinMode(ENCODER_A_PIN,INPUT);
  pinMode(ENCODER_B_PIN,INPUT);
 
  attachInterrupt(0, RotaryEncoder, LOW);
  Serial.begin(9600);
  time = millis();
}
 
void loop()
{
  while (num != position)
  {
    num = position;
    Serial.println(num);
  }
}
 
 
void RotaryEncoder(){  
  int temp =digitalRead(ENCODER_B_PIN);
  if ((millis() - time) > 3) {
      if ( temp == LOW)
      {
        position++;
      }else{
      if ( temp == HIGH)
        position--;
      }
  }
  time = millis();
}

沒中斷版本

int trigger=0;
void RotaryEncoder(){  
  int tempA =digitalRead(ENCODER_A_PIN);
  int tempB =digitalRead(ENCODER_B_PIN);

  
  if ((millis() - time) > 3) {
    if(tempA==LOW && trigger==HIGH){
      if ( tempB == LOW)
      {
        position++;
      }else{
      if ( tempB == HIGH)
        position--;
      }
    }
    trigger=tempA;
    time = millis();
  }
}

參考來源:
http://www.arduino.cn/thread-2423-1-1.html
http://www.geek-workshop.com/thread-373-1-1.html


2015/05/24 更新



恩..多一顆按鈕
CLK 當作A
DT 當B

    #define ENCODER_A_PIN 2
    #define ENCODER_B_PIN 3
    #define SW_PIN 4
    
    unsigned long time = 0;
    volatile long position = 0;
    volatile long num = 0;
     
    void setup()
    {
      pinMode(ENCODER_A_PIN,INPUT_PULLUP);
      pinMode(ENCODER_B_PIN,INPUT_PULLUP);
      pinMode(SW_PIN, INPUT_PULLUP); // 輸入模式並啟用內建上拉電阻
      
      attachInterrupt(0, RotaryEncoder, LOW);
      Serial.begin(9600);
      time = millis();
    }
     
    void loop()
    {
       if(digitalRead(SW_PIN) == LOW){ // 按下開關,歸零
         position = 0; 
         Serial.println("count reset to 0");
         delay(300);
      }
      while (num != position)
      {
        num = position;
        Serial.println(num);
      }
    }
     
     
    void RotaryEncoder(){  
      int temp =digitalRead(ENCODER_B_PIN);
      if ((millis() - time) > 3) {
          if ( temp == LOW)
          {
            position++;
          }else{
          if ( temp == HIGH)
            position--;
          }
      }
      time = millis();
    }

沒有留言:

張貼留言

預測2031/1/1可能 TWCA 憑證 IOS會出現不信任

緣由: TWCA CYBER Root CA 有兩張、兩個效期 (2030、2047年到期) 推測TWCA 預計 2030年12月會停用: TWCA CYBER Root CA (2030 年到期) TWCA Global Root CA 改用啟用: TWCA CYBER ...