Robofun 機器人論壇
標題:
新手求助:用解碼器加一個按鍵控制2個LED
[打印本頁]
作者:
noob
時間:
2014-9-19 06:18
標題:
新手求助:用解碼器加一個按鍵控制2個LED
不好意思第一次在此發問,我在試作Arduino用解碼器加一個按鍵來控制2個LED,
目前程式2個led只會跟1個val變數跑,led0的val變數會帶給led1,這不是我要的結果,
請問有辦法把一組val變成兩組獨立變數嗎?例如val0,val1.可能是陣列或MAP類似概念.
或是判斷何時為val新值,舊值,運算並套用各自LED.這些部份我真的是不會.
我想讓encoder"單獨"控制led0Pin跟led1Pin.比方說,轉encoder調整led0Pin亮度,
按下按鍵控制切換到led1Pin,轉encoder調整led1Pin亮度,再按按鍵回到led0Pin.如此類推.
請各位幫忙.感謝.
#include <RotaryEncoder.h> // 從這來的. https://code.google.com/p/arduino-rotary-encoder-with-velocity/
int val =0;
int x=0;
RotaryEncoder encoder(A2,A3,5,6,3000); //解碼器腳位 A_A2,B_A3
const int buttonPin = 2;
const int switch_ledPin = 13;
int led0Pin = 5;
int led1Pin = 6;
int button_state = HIGH;
unsigned long int previous_time = 0;
void switch_led_state() {
if(digitalRead(switch_ledPin) == LOW) digitalWrite(switch_ledPin, HIGH);
else digitalWrite(switch_ledPin, LOW);
Serial.print(String("Switching after ") + (millis() - previous_time) + String(" milliseconds\n"));
previous_time = millis();
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(switch_ledPin, OUTPUT);
pinMode(led0Pin, OUTPUT);
pinMode(led1Pin, OUTPUT);
digitalWrite(switch_ledPin, LOW);
Serial.begin(9600) ;
}
void loop() {
if(digitalRead(buttonPin) == LOW) {
if(button_state != LOW) switch_led_state();
button_state = LOW;
} else button_state = HIGH;
int enc = encoder.readEncoder();
int changevalue = 1;
if(enc != 0) {
val = val + (enc);
val = min(val,255);
val = max(val,0);
Serial.println(val);
}
delayMicroseconds(5);
if (digitalRead (switch_ledPin)==LOW)
x=1;
if (digitalRead (switch_ledPin)==HIGH)
x=2;
switch (x){
case 1:
analogWrite(led0Pin,(val));
break;
case 2:
analogWrite(led1Pin,(val));
break;
}
}
複製代碼
歡迎光臨 Robofun 機器人論壇 (https://robofun.net/forum/)
Powered by Discuz! X3.2