你好,这是我第一次接触arduino。我希望有人告诉我为什么我的LED和Motor无法正常运作。我将万分感激!欢迎任何形式的帮助!也告诉我可以参考哪些教程或者视频。
我试图用两个button和capacitive touch sensor有效控制led和motor。以及用rotary encoder来改变led亮度。
我预期的效果:
- 当我按下按钮或者旋转encoder后,led和motor能马上做出改变。
- 只按住button1时,led可以保持关闭。
- 当顺时针旋转encoder, led变暗。 反之亦然。
现在我的code的效果:
- led和motor随意工作着。比如有时候我按下按钮,他们依然按照原来的状态运作着,没有任何该改变。或者有时要等个10秒左右才有反应。(我猜可能是if()太长了?但没道理啊按理说它其实不是很长)motor现在转的很随机。有时候我从头到尾啥都没干,它也会自己变速度和方向。
- 按住button1的时候,有时led会不停闪烁,有时候led就一直亮着没有改变。
- encoder 不完全在工作。有时候一往左就关,一往右就亮。有时候啥也没发生。
这是我的代码:
//Include the Arduino Stepper.h library
#include <Stepper.h>
//Include the encoder library
#include <Encoder.h>
Encoder myEnc(6, 5); //define encoder pin; (OutA, OutB)
//define the pin
const int buttonPin = 2; //button 1
const int ledPin = 3; //12V led
const int touchPin = 4; //capacitive touch sensor
const int wakePin = 12; //button 2
const int stepsPerRevolution = 2048;
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11); //stepper motor
//variables will change
int buttonState = 0;
int touchState = 0;
int wakeState = 0;
long int oldPosition = -999; //encoder old position
long int newPosition; //encoder new position
int positionDifference = 0;
int ledBrightness = 0;
//setup
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(touchPin, INPUT);
pinMode(wakePin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
Serial.begin(12500);
} //end of setup()
//loop
void loop() {
//read the state of the parts
buttonState = digitalRead(buttonPin);
touchState = digitalRead(touchPin);
wakeState = digitalRead(wakePin);
//use encoder to change the brightness
newPosition = myEnc.read();
if (newPosition != oldPosition) {
positionDifference = newPosition - oldPosition;
oldPosition = newPosition;
} //end of if newposition
ledBrightness = ledBrightness + positionDifference;
ledBrightness = constrain(ledBrightness, 0, 30); // maximum led brightness
analogWrite(ledPin, ledBrightness);
//use two buttons and sensor to control the motor and led
if (buttonState == LOW) {
if (touchState == HIGH) { //Serial.println("counterclockwise_superfast_OpenLight_ButtonPressed");
myStepper.setSpeed(15); //set the speed to 15 rpm
myStepper.step(stepsPerRevolution); //counterclockwise
} else {
if (wakeState == LOW) { //Serial.println("clockwise_slow_Wakeup_ButtonPressedWakePressed");
myStepper.setSpeed(5); //set the speed to 5 rpm
myStepper.step(-stepsPerRevolution); //clockwise
} else { //Serial.println("stopEverything"); button pressed, sensor untouched, wake unpressed
digitalWrite(ledPin, LOW); //led LOW
}//end of wakeState LOW
} //end of touchState HIGH
} else {
if (touchState == HIGH) { //Serial.println("clockwise_fast_CloseLight_ButtonUnpressed");
myStepper.setSpeed(10); //set the speed to 10 rpm
myStepper.step(stepsPerRevolution); //clockwise
} else { //Serial.println("counterclockwise_superslow_WhenSleep_ButtonUnpressed");
myStepper.setSpeed(2);
myStepper.step(-stepsPerRevolution);
} //end of touchState HIGH
} //end of buttonState LOW
} //end of loop()
这是我的手绘线路图: