In: Computer Science
Write the following in C language for Arduino: Write a program that increases the LED brightness in five steps with each press of the button. Remember you are going to using a digital input and the "digitalRead" command. You are going to need to use a PWM pin and use the "analogWrite" command. The maximum value for our Arduino R3 boards is 255 and you need five steps (25%, 50%, 75%, 100%, and 0%) so you will need to determine the values for each step.
Source Code:
const int buttonPin = 2;           // number of the button pin
const int ledPin = 9;              // number of the LED pin
float brightness = 0;              // brightness of LED starts at 0
int fadeAmount = 51;               // fadeAmount is equal to 20% of 255(max LED brightness)
float buttonPressedCounter = 0.0;  // timer set to 0 whe depressing button
int buttonState = 0;
void setup() {
 // set button as input
 pinMode(buttonPin, INPUT);
 // set LED as output
 pinMode(ledPin, OUTPUT);
 // init serialize communication at 9600 bits per second
 Serial.begin(9600);
}
void loop() {
 // activate when button is being held down
 if (buttonState == HIGH) {
   // on press, when counter is greater than 33, assume button is being held down
   if (buttonPressedCounter > 33) {
     // button was held down for longer than 33
     if (brightness < 255) {
       Serial.print("increasing brightness: ");
       Serial.println(brightness);
       brightness = brightness + 5;
       analogWrite(ledPin, brightness);
     }
   } else {
     buttonPressedCounter ++;
     Serial.print("holding: ");
     Serial.println(buttonPressedCounter);
   }
 } else if (buttonState == LOW) {
   // on release if button pressed counter was less than 33, assume it was a short press
   if ((buttonPressedCounter < 33) & (buttonPressedCounter != 0)) {
     Serial.print("lower LED: ");
     if (brightness - fadeAmount < 0.0) {
       brightness = 0;
     } else {
       brightness = brightness - fadeAmount;
     }
     Serial.println(brightness);
     analogWrite(ledPin, brightness);
   }
   buttonPressedCounter = 0;
 }
}
Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! ===========================================================================