Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have my code for arduino, I am working on making my LED turn its brightness up

ID: 3743671 • Letter: I

Question

I have my code for arduino, I am working on making my LED turn its brightness up or down based on the user input from the serial monitor. So what i need to do is, if i input 1, the LED light will turn on only 1%. If i input the number 60, then the LED will turn on 60% etc... I can only input numbers from 0 to 100. 0 being off completely, and 100 being the brightest. This is what i have so far: It turns off when i input 2 and turns on when i input 1. Not sure how to write what i want it to do.

String inData;

void setup() {
// initialize serial:
Serial.begin(115200);
pinMode(D2, OUTPUT);

// reserve 200 bytes for the inputString:
}

void loop() {
while (Serial.available() > 0)
{
char recieved = Serial.read();
inData += recieved;

// Process message when new line character is recieved
if (recieved == ' ')
{
Serial.print("Message Received: ");
Serial.print(inData);

int x = inData.toInt();
if(x == 2){
digitalWrite(D2, LOW); // turn the LED on (HIGH is the voltage level)
}
else if (x == 1){
digitalWrite(D2, HIGH); // turn the LED off
}

inData = ""; // Clear recieved buffer
}
}
}

Explanation / Answer

I believe you will be needing PWM (Pulse width modulation) concept in Arduino and have to use analogWrite() function for the same. analogWrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly with different ratio between on and off, to create a fading effect. In the absence of circuit, its quite unclear to say what's going wrong.

Though your are ecouraged to refer to the following topics on ardunio website:

1) Arduino - Fade

2) Arduino - ReadAnalogVoltage