/
Exercise 3 Solution

Exercise 3 Solution

Task 1 Solution

C++

Blocks

C++

Blocks

int LEDPin = 11; void setup() { pinMode(LEDPin, OUTPUT); Serial.begin(9600); // just to print out the light reading. Not really necessary } void loop() { int delayValue; int lightReading = analogRead(A0); //read the analog value if(lightReading>512) { delayValue = 500; } else { delayValue = 100; } Serial.println(lightReading); digitalWrite(LEDPin, HIGH); delay(delayValue); digitalWrite(LEDPin, LOW); delay(delayValue); }
image2020-1-21_18-31-1.png

Note : The Blocks design shown above is without the Serial print option used in the C++ code on the left

Task 2 Solution

C++

Blocks

C++

Blocks

int delayValue = 0; int lightReading = 0; int brightness = 0; int buttonState = 0; int LEDPin = 11; int lightThreshold = 512; void setup() { pinMode(2, INPUT); pinMode(A0, INPUT); pinMode(LEDPin, OUTPUT); Serial.begin(9600); } void loop() { buttonState = digitalRead(2); if (buttonState == HIGH) { lightReading = analogRead(A0); if (lightReading > lightThreshold) { delayValue = 10; } else { delayValue = 5; } for (brightness = 0; brightness <= 255; brightness += 1) { analogWrite(LEDPin, brightness); delay(delayValue); } Serial.println("ON"); // this will be printed when brightness = 255 for (brightness = 255; brightness >= 0; brightness -= 1) { analogWrite(LEDPin, brightness); delay(delayValue); } } else { Serial.println("OFF"); delay(1000); // printed once every second // analogWrite(LEDPin, 0); is not needed here. Why? } }

 

image2020-1-23_0-2-34.png