2
votes
`const int ledPin = 9;      // the pin that the LED is attached to

 void setup() 
  {
   // initialize the serial communication:
  Serial.begin(9600);
  // initialize the ledPin as an output:
  pinMode(ledPin, OUTPUT);  
   }

 void loop() {
 byte brightness;

  // check if data has been sent from the computer:
  if (Serial.available()) {
  // read the most recent byte (which will be from 0 to 255):
   brightness = Serial.read();

   Serial.println(brightness);
   // set the brightness of the LED:
   analogWrite(ledPin, brightness);
   }
   }`

i tried the above code with my board

that code takes values from serial monitor and adjusts the brightness of the LED. but instead, the LED stucks at the HIGH state and brightness doesnt change with the input

also the value of brightness i print on serial monitor by Serial.println(brightness); it shows some garbage characters and symbols which are not readable. what should i do?

2

2 Answers

0
votes

I think the problem is that you want to send ASCII data from your computer to the arduino, but you are reading just a single byte. Instead of Serial.read(), use Serial.readString() (and set a timeout with Serial.setTimeout() before). Then convert the number string to an int value using atoi(). Then check if the result value is between 0 and 255 (clamp it). This write this value to the output using PWM (i.e. using analogWrite()).

Looking to the documentation of the Serial class of the arduino: there is a function parseInt() that does the magic :-) Here is the documentation: https://www.arduino.cc/en/Serial/ParseInt

0
votes

Although i am not an expert, i sorted the issue as follows:

const int ledPin = 12;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int brightness;
  if (Serial.available()) {
    analogWrite(ledPin, Serial.parseInt());
  }
}

Note: the code is NOT made by me, its a tweak of the pre-existing example in the arduino IDE

The change i did was to replace Serial.read(); with Serial.parseInt();

Also keep in mind that LED's have a certain forward voltage, so depending on the LED you are using and the overall setup, dimming varies. In my case the smallest value was 140 using a straw hat 0.5W LED.

Good luck!