我正在使用 Arduino Uno 并尝试将学校项目的两个部分一起编写。两个部分分别工作正常,但结合起来,只有第 1 部分有效。第 1 部分:涉及 1 个按钮开关,2 个 LED,其中一个保持亮起,一个保持关闭,按钮改变是打开还是关闭。第二部分:电位器控制的伺服
我已经确定伺服只有在按下按钮时才会工作,这不应该发生,电位计/伺服代码不应该依赖于 LED 的代码。我绝对是这方面的初学者,并且不了解代码在做什么,所以请原谅我的任何冗余。任何帮助深表感谢。
#include <Servo.h>
Servo myServo;
int const potPin = A0;
int potVal;
int angle;
int switchState;
int lastSwitchState = 0;
const int bluePin = 3;
const int yellowPin = 4;
const int button = 2;
int bluelight = LOW;
int yellowlight = HIGH;
void setup(){
pinMode(bluePin, OUTPUT); //blue LED
pinMode(yellowPin, OUTPUT); //yellow LED
pinMode(button, INPUT); //switch
myServo.attach(9);
Serial.begin(9600);
}
void loop(){
// PART 1 - this is the only part that seems to be working now?
switchState = digitalRead(button);
while (digitalRead(button)==LOW);
if (digitalRead(button)==LOW){
bluelight=!bluelight;
digitalWrite(bluePin, bluelight);
digitalWrite(yellowPin, yellowlight);
}
else{
if (switchState=!lastSwitchState) {
yellowlight=!yellowlight;
bluelight=!bluelight;
digitalWrite(yellowPin, yellowlight);
digitalWrite(bluePin, bluelight);
}
}
// PART 2 - Only works when button is pressed?
potVal = analogRead(potPin);
Serial.print("potVal: ");
Serial.print(potVal);
angle = map(potVal, 0, 1023, 0, 179);
Serial.print(", angle: ");
Serial.println(angle);
myServo.write(angle);
delay(250); //wait for a quarter second
}