我目前正在使用Raspberry Pi进行练习。
我在面包板上使用以下内容:
我的以下代码应该如下工作:
使用第一个按钮可以选择下一个LED,使用第二个按钮可以打开/关闭所选LED。当你在最后一个LED时,它会给出一个真或假(开或关)以下输出:
Circuits 我没有看到我的代码出了什么问题:
//const variables
const int leds[] = {3, 5, 6, 9, 11};
const int buttons[] = {12, 13};
//variables that will change
int buttonState[] = {false, false};
int lastButtonState[] = {false, false};
int values[] = {false, false, false, false};
void setup() {
//init LEDs
for(int i = 0; i < sizeof(leds); i++){
pinMode(leds[i], OUTPUT);
}
//init buttons
for(int i = 0; i < sizeof(buttons); i++){
pinMode(buttons[i], INPUT);
}
}
void loop() {
//fade when game starts
fade();
//start game
start();
//output of game
output();
}
void output(){
bool t1 = !values[0];
bool t2 = t1 && values[1];
bool t3 = values[2] || values[3];
bool Q = !(t2 || t3);
if(!Q){
digitalWrite(leds[4], true);
}else{
digitalWrite(leds[4], false);
}
}
void start(){
//total of leds
int j = 0;
//check if user is not at 5th led
while(j < 4){
//loop through buttons
for(int i = 0; i < 2; i++){
// Read button
buttonState[i] = digitalRead(buttons[i]);
// check button state
if (buttonState[i] != lastButtonState[i]) {
// if the state has changed
if (buttonState[i] == HIGH) {
//check if button 1
if(i == 0){
//select next LED
j++;
}
//else button 2
else{
// if the current state of the 2nd button is HIGH
while(i == 1){
//if current value of led is false, put it true
if(values[j] == false){
//put led on
digitalWrite(leds[j], true);
values[j] = true;
delay(50);
}else{
//put led off
digitalWrite(leds[j], false);
delay(50);
values[j] = false;
}
//go back to button 1?
i = 0;
}
}
//go back to button 1?
i = 0;
}
}
// save the current state as the last state,
// for next time through the loop
lastButtonState[i] = buttonState[i];
// wait a little
delay(50);
}
}
}
void fade(){
//put every led on half-on
for(int i = 0; i < sizeof(leds); i++){
analogWrite(leds[i], 100);
}
}
答案 0 :(得分:1)
在C和C ++中,如果要比较两个值以检查它们是否相等,则必须使用==
(比较运算符)而不是=
(赋值运算符)。你在这里意外地使用了错误的操作员:
while(i = 1){
在这里:
if(values[j] = false){
将这些更改为==
。