When send any value other than 0,the LED glows at some brightness and after that for any value sent, the brightness does not change.
So,How do I control the brightness using serial ?
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();
// set the brightness of the LED:
analogWrite(ledPin, brightness);
}
}
It looks OK to me. You're not sending actual NUMBERS like "255" via the serial monitor, are you? If you enter "255" in the serial monitor and hit enter, you'll be sending at least three characters with values 50, 53, and 53, which are 1) probably not the values you were expecting, 2) very close together, value-wise, so probably not distinguishable in brightness. 3) Sent very close together time-wise, so you probably wouldn't have a chance to notice brightness differences anyway. 4) might be followed by some sort of line ending that would override it anyway.
You should be able to see a brightness difference between " " (space = 32) and "~" (tilde = 176) if there's no line ending set, and you send them one at a time.
See the thing on "Serial Input Basics" for info on reading integers from the serial port.
So,What should I do to make it work ?
Here are the options what I can :-
Use hypertqerminal ?(WinXPsp3)
Use HC05 and phone as serial ?
I blew the 16U2 on my UNO and MEGA some while ago,I am using a Pro Micro(sparkfun) to communicate. I may grab a MAX232 and a DB9 connector and try on a serial port.
westfw:
See the thing on "Serial Input Basics" for info on reading integers from the serial port.
tl;dr & too heavy, I'll need some hrs to grasp that all
Can you explain how to read integers through serial ?
Easier than that. Replace "Serial.read" with "Serial.parseInt"
(You should still read the Serial Basics posts, to understand why Serial.parseInt is less than desirable.)
Dimmer.ino: In function 'void loop()':
Dimmer.ino:40:16: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'byte {aka unsigned char}'
Error compiling.
When I change the " byte brightness " to " int brightness "
Dimmer.ino: In function 'void loop()':
Dimmer.ino:40:16: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'
Error compiling.
if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
brightness = Serial.parseInt();
// set the brightness of the LED:
analogWrite(ledPin, brightness);
}
That would be the non-numeric termination character, causing available() to return positive, and the next attempt at parseInt to time out. Getting rid of it is left as an exercise for the student.