The main problem is you have to reset brightness to 0 when the switch is LOW. Btw, I did not test the sketch, only compiled it.
int led = 9;
int brightness = 5;
int fadeAmount = 5;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
int val = digitalRead(2);
Serial.println(val);
if (val==HIGH){
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount; }
delay(100);
}
else{
digitalWrite(9, LOW);
brightness = 0; // Restart with brightness 0
}
}
Some other improvements result in:
#define LED_PIN 9
#define DELAY_TIME 100
int brightness = 5;
int fadeAmount = 5;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int switchButton = digitalRead(2);
Serial.println(switchButton);
if (switchButton == HIGH) {
analogWrite(LED_PIN, brightness);
brightness += fadeAmount;
if ((brightness <= 0) || (brightness >= 255)) {
fadeAmount = -fadeAmount;
}
delay(DELAY_TIME );
}
else {
digitalWrite(LED_PIN, LOW);
brightness = 0; // Restart with brightness 0
}
}
Explanation
- Always indent your code (so that { and } are clear, notice each new { increases the indentation by two spaces, each } decreases the indentation by two spaces.
- For values that do not change use a #define. This prevents (in this case) a few bytes not be stored in valuable memory space. Especially if you would use arrays this is important.
- You used 9 in
digitalWrite(9, LOW); which was probably a mistake, always use defines wherever possible. I also would use #define DELAY_TIME 100 instead of the hardcoded 100 value.
- I addes some spaces before/after values (like
switchButton == HIGH). It doesn't matter if you do or not, but be consequent.
- Use good variable names (
switchButton is more clear than val.
- Use
brightness += fadeAmount; instead of brightness = brightness + fadeAmount;; this is the normal way of increasing (or decreasing/multiplying/whatever) the value of a variable.
- Use ( and ) in non trivial if statements like
if ((brightness <= 0) || (brightness >= 255)), this could save you hours of searching in case you ever make a mistake (in this case there is no functional change).
Good luck with your project.