Sign in Join
Wiki copytemporary

AVR Embedded Tutorial - Analog Write

Deutsch · English

PWM Analog Write

An Atmega328 is used in this example.

Delay

A simple delay function used to slowly increase and decrease the brightness of the LEDs.

pascal
procedure sleep;
  var
    i : Int16;
  begin
    for i := 0 to 1999 do 
      asm// No operation instruction to waste clock cycles 
        Nop  // No operation instruction to waste clock cycles
      END;
  end;

Example

In this example, the PWM frequency is set to be very slow, so that you can see the brightening and darkening of the LEDs. You can see that the analog output is actually modulated.

The following must be set:

pascal
  var
   i : integer;  // Loop counter
 begin
   // Configure PD5 and PD6 as outputs
   DDRD := %01100000;

   // Configure PD5 and PD6 in PWM mode
   TCCR0A := (%10 shl COM0A) or (%10 shl COM0B) or (1 shl WGM0);

   // Enable timer 0, clock / 1024
   TCCR0B := TCCR0B or %101;

   // Main loop that continuously makes the LEDs brighter and darker
   repeat
     for i := 0 to 255 do 
       begin
         OCR0A := i;
         OCR0B := 255 - i;
         sleep;
     end;

     for i := 0 to 255 do 
       begin
         OCR0A := 255 - i;
         OCR0B := i;
         sleep;
       end;
   until False;
 end.

Pitfalls

Note: Since PWM is controlled by a timer, there may be overlaps with the timer functions.

For information on the timer functions, see the Timer, Counter tutorial.

See also


From the Free Pascal wiki, page "AVR Embedded Tutorial - Analog Write", as it stood on 2020-10-19 after a change by Mathias, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.