#include <Adafruit_NeoPixel.h>
const int PIN = 4;
const int NUMPIXELS = 10;
const int BUTTONPIN = 6;
int buttonState = 0;
int PINState = 0;
int level = 1;
int dt = 100;
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
pixels.begin();
pinMode(BUTTONPIN, INPUT);
Serial.begin(9600);
}
void loop(void) {
Serial.println(buttonState);
buttonState = digitalRead(BUTTONPIN);
if (digitalRead(BUTTONPIN) == HIGH) {
if (buttonState == 0) {
buttonState = 1;
} else {
buttonState = 0;
}
}
if (buttonState == 1) {
opdracht(level);
}
else {
if (level >= 10) {
level++;
} else {
level = 1;
}
pixels.clear();
}
}
//level 1
//void opdracht1() {
// pixels.setPixelColor(0, pixels.Color(150, 0, 0));
// pixels.setPixelColor(5, pixels.Color(0, 0, 150));
// pixels.show();
//}
void opdracht(int x) {
if (x == 1) { //level 1
pixels.setPixelColor(0, pixels.Color(150, 0, 0));
pixels.setPixelColor(5, pixels.Color(0, 0, 150));
pixels.show();
}
if (x == 2) { //level 2
pixels.setPixelColor(8, pixels.Color(150, 0, 0));
pixels.setPixelColor(6, pixels.Color(150, 0, 0));
pixels.setPixelColor(1, pixels.Color(0, 0, 150));
pixels.show();
}
1 Answer
You forgot to ask a question. So I will assume the intended question is “Why does this code always show level 1?” and I will try to answer that.
The variable level
is defined here:
int level = 1;
Its initial value is 1. Then it is updated here:
if (level >= 10) {
level++;
} else {
level = 1;
}
The first time this section of code runs, level
has its initial value,
namely 1. The condition in the if
evaluates to false, then the
statement
level = 1;
is executed, which assigns the value 1 to level
(which has no effect,
as that was already its value anyway).
The next time that section of code runs, level
has still the vale 1,
and the effect is the same as the previous time.
-
oow i understand it thank you!! what do i have to change to change the value? Oct 23, 2020 at 11:32
-
1@louisemoons: Under what condition do you want
level
to be incremented? Can you complete the sentence “level
should be incremented if ...”? Oct 23, 2020 at 11:57 -
Another, stronger hint. Your current code says "if level is greater than or equal to 10, increment it." It starts at 1, and no other code changes it, so that if statement will never be true. Don't you want to increment it if it is less than 10?– Duncan COct 23, 2020 at 12:25
-
if (level >= 10) {
should beif (level < 10) {
?buttonState
for three different purposes. Hint: usebuttonState
for the current state of the button; use something likeoldButtonState
for the state of the button in the last loop; and use something likebuttonPressed
to indicate when the button is first pressed down (which you then use to increment thelevel
)