I'm trying to test my analog signal before I send it to an actual analog device. I've written some code and considering the analog square I have expected to see a digital ON or OFF during a single duty cycle but I'm either seeing all OFF for analog values 0-127 and all ON for values 128-255.

My expectation is that I would see 51 ON and 49 OFF thus getting a value closer to 128 of 255.

What am I missing? Is this even possible?

int OUTPUT_PIN = 2; // digital 2 (PWM)
int INPUT_PIN = A0; // analog 0

void setup() {
  pinMode(INPUT_PIN, INPUT);


void loop() {

  analogWrite(OUTPUT_PIN, 128);

  float j = 0;
  for(int i = 0; i < 100; ++i) { // get 100 reads per duty cycle
    float v;
    v = digitalRead( INPUT_PIN );
    if(v >= 1) Serial.println("ON");
    if(v <= 0) Serial.println("OFF");
    j += v;

    delay(12); // trying to match the duty cycle
  j /= 100; // average out the 100 reads



1 Answer 1


Seeing all on for 128+ and all off for 127- is indicative that you are using a pin that can't do PWM.

If you use a non-PWM pin with analogWrite it goes "Is this less than 128? Yes? Then I will turn it off. Otherwise I will turn it on.".

    if (val < 128) {
        digitalWrite(pin, LOW);
    } else {
        digitalWrite(pin, HIGH);

Since you don't mention what board you are using I can only assume that you have picked a pin that can't do PWM. Change to a pin that can do PWM and you should get a PWM signal.

  • I tried on both Mega 2560 and Uno. I see now on the uno that some digital pins have a ~ in front of the number. Coincidentally these are the only pins which send a PWM signal. Moving from outpin pin 2 to 3 solved the issue.
    – Jacksonkr
    Jul 9, 2016 at 19:28
  • That's not coincidental. The ~ is used to denote which pins can do PWM. Like it says on the board: DIGITAL (PWM ~)
    – Majenko
    Jul 9, 2016 at 19:30
  • You are completely right. You've certainly made me very aware of my rookie mistake. Thanks for your time in helping me track down my issue.
    – Jacksonkr
    Jul 9, 2016 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.