Serial.read Problems

Hello everyone,

I modified an example program for RGB LED Fading that Shutting all LEDs down and wait for Serial Data to change the brightness of the Red LED.

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3


void setup (){
  
  Serial.begin (9600);
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  int r = 255;
  int g = 255;
  int b = 255;
  analogWrite (REDPIN,r);
  analogWrite (BLUEPIN,b);
  analogWrite (GREENPIN,g);
}
void loop (){
  while (Serial.available() == 0);
  int r = Serial.read() - '0';
  Serial.println (r);
  Serial.flush();
  analogWrite (REDPIN,r);
  
}

As you can see in the code, i read the variable r and directly print it out to the computer to see why it isn't working before i analogWrite the data to the REDPIN.

As you can see in my following example where i write the numbers from 0-10 what i get in response

"1 -35 2 -35 3 -35 4 -35 5 -35 6 -35 7 -35 8 -35 9 -35"

Does anyone know why i get -35, too? I can't get rid of it?

And does anyone know how i can directly send a digit number via Serial to use the full range of the analog Output from 000-255?

Does anyone know why i get -35, too?

What do you suppose that - ‘0’ equals?

If you are using the Serial Monitor to send data, what option have you selected to have it append data to what is sent? In your case, it should be the nothing choice.

And does anyone know how i can directly send a digit number via Serial to use the full range of the analog Output from 000-255?

You are sending strings from the Serial Monitor application, not numbers. When that sinks in, it should be obvious what you need to do (and then, the nothing option will no longer be appropriate).

What is this doing and why is it written like this?

while (Serial.available() == 0);

What is this doing

Waiting for serial data to arrive.

and why is it written like this?

Because OP doesn't know any better.

PaulS:

What is this doing

Waiting for serial data to arrive.

and why is it written like this?

Because OP doesn't know any better.

Is there any negative consequence to blocking for long periods inside loop()?

@PaulS

I wanted the OP to answer that.