2017年12月11日 星期一

Week13 是賴小沫的

✎旋轉編碼器

👀參考他人的程式碼,並測試其結果

Arduino

#define SERIAL_BAUDRATE 115200
#define CLK_PIN 2 // 定義連接腳位
#define DT_PIN 3
#define SW_PIN 4
#define interruptA 0 // UNO腳位2是interrupt 0,其他板子請見官方網頁
volatile long count = 0;
unsigned long t = 0;
void setup() {
  Serial.begin(SERIAL_BAUDRATE);
  // 當狀態下降時,代表旋轉編碼器被轉動了
  attachInterrupt(interruptA, rotaryEncoderChanged, FALLING);
  pinMode(CLK_PIN, INPUT_PULLUP); // 輸入模式並啟用內建上拉電阻
  pinMode(DT_PIN, INPUT_PULLUP);
  pinMode(SW_PIN, INPUT_PULLUP);
}
void loop(){
  if(digitalRead(SW_PIN) == LOW){ // 按下開關,歸零
    count = 0; 
    Serial.println("count reset to 0");
    delay(300);
 }
}
void rotaryEncoderChanged(){ // when CLK_PIN is FALLING
  unsigned long temp = millis();
  if(temp - t < 200) // 去彈跳
    return;
  t = temp;
  // DT_PIN的狀態代表正轉或逆轉
  count += digitalRead(DT_PIN) == HIGH ? 1 : -1;
  Serial.println(count);
}

將程式上傳至開發板,並觀看其執行結果

👀如何連接UNO與旋轉編碼器

參考此網站,並連接UNO與旋轉編碼器

示意圖
實際組裝

✎旋轉編碼器連結processing

👀processing程式碼

import processing.serial.*;
Serial myPort;
void setup(){
  size(500,500);
  myPort = new Serial(this,"COM7",115200);
}
int x=0;
int lf=10; //line feed,new line
void draw(){
  background(0);
  if(myPort.available()>0){
    String now = myPort.readStringUntil(lf);
    x=int(split(now,'\r')[0]);
    println(x+" "+now);
  }
  ellipse(width/2+x*20,height/2,100,100);
}

按下左上角的三角形Ctrl+R,即可執行看結果

✎knob馬達

👀組裝

示意圖
實際組裝

👀程式碼-開啟範例檔Knob


將程式上傳至開發版,觀察操作結果

執行結果如下

沒有留言:

張貼留言