analogWrite - Look How it Works


As we all know computers only work with one's and zero's - nothing in between. But this values can change very fast. Inside an ATmega328 there are three timers, and each of them can control two pins differently. You can check it all by using the Serial plotter.

Using analogWrite with a low value the pin will be zero most of the time, only for a short while it will be one:

Setting analogWrite(128) the on- and off times will be equal:

Setting it to something near 255 it will look like this:

Now, here is the full program:

/*
   understanding PWM:
   PWM out: Pin-9 (connected internally to TIMER-1)
   read back: Pin-8
   you have toconnect: Pin-8 and Pin-9 to the anode of an LED.
   Ground to cathode of LED (don't forget the resistor)
   Start the Serial plotter and set the baud rate to 115200. 
*/

void setup() {
  Serial.begin(115200);
}

byte pwm;

void loop() {
  // Serial plotter always shows 500 samples:
  int N = 500; 
  byte a[N];
  analogWrite(9, pwm++);
  // TIMER1 has to start from zero 
  // to give a stable picture
  TCNT1 = 0; 
  // read 500 samples fast:
  for (int i = 0; i < N; i++) {
    // read pin-8:
    a[i] = PINB & 1; 
    delayMicroseconds(25);
  }
  // plot the samples and the ground line
  for (int i = 0; i < N; i++) {
    Serial.print("0 ");
    Serial.println(a[i]);
  }
  delay(300);
}




contact: nji(at)gmx.de