Read analog pins and return values over serial

I'm trying to receive serial signals and toggle as well as dim LEDs on that pin. I've got the pin toggling but the I'm not getting the correct values in the serial monitor. The values come out in a constant scroll and report numbers in the range of 280 - 296, it doesn't matter of the LED is on or off the the serialprints are relatively constant.

How can I change the state of the pin and return it's analog value?

int ledPin = 12; // the pin that the LED is attached to
int incomingByte;      // a variable to read incoming serial data into

void setup() {
  // initialize serial communication:
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);

void loop() {
  // see if there's incoming serial data:
  int pinState = analogRead(ledPin);
  if (Serial1.available() > 0) 
    // read the oldest byte in the serial buffer:
    incomingByte =;
    // if it's a capital H (ASCII 72), turn on the LED:
    if (incomingByte == 'H') {
      analogWrite(ledPin, 1023);             
    // if it's an L (ASCII 76) turn off the LED:
    if (incomingByte == 'L') {
      analogWrite(ledPin, 0);

I am not sure what you are trying to do but pin 12 is not a PWM enabled pin and even if it were PWM output does not vary the voltage on the pin, rather it switches between 0 and 5V with a varying duty cycle so the voltage will always be either 0 or 5V.

I'm using a Mega where 12 is a PWM pin.

This is unexplored territory for me. I'm trying to get the value of that pin. I guess it would be between 0 - 255 and or 0 - 1024.

Use digitalRead on digital pin 12
HIGH or LOW depending when you read it.



I'm using a Mega where 12 is a PWM pin.

OK (you might have said), but the point about the voltage being either 0 or 5V at any instant still stands. I note, however, that the pin is set as an output and you are reading from it and the LED and its resistor may have an effect depending on how they are wired. I am not sure what to expect under those circumstances.

Look up duty cycle on Wikipedia, that is what is going on with analogWrite(). Zero is off and 255 is full on, values between 0 and 255 act like reduced voltage.

The analogRead() function reads the analog inputs, A0..A15. You are reading A12 which is floating as it has nothing attached to it.


Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks... Tom... :slight_smile:
Have you tried making a counter function in the code that increases then decreases values cyclically at a count per second or smaller.
This way you can see if that part of the code works, don't look for serial input, just provide serial output telling you the count and LED state.

Tom... :slight_smile: