Tutorial 3
PWM

PWM support in MCU Java Source

Now only 8-bit PWM is supported. For 16-bit timer 8-bit PWM mode is set. All modes of MCU are present.

Program with PWM

This is Java port of the simple demo project from avr-libc (WinAVR). Program uses Timer 1, which must have output compare unit with PWM. For MCU other than ATmega8, select any timer with PWM.

import mcujavasource.mcu.*;

/** Tutorial 3: PWM, fast mode.
 * The brightness of the LED is changed with the PWM.
 * After each period of the PWM, the PWM value is incremented or decremented.
 * LED's anode is connected to +5V through 330 Ohm resistor,
 * cathode - to MCU output compare pin OC1A (PB1 for ATmega8).
 */
public class Tutorial3 extends Microcontroller
{
  private Timer timer;
  private TimerCompare timerCompare;
  
  private int counter = 0;
  private boolean countingUp = true;
  
  public void init()
  { //register initialization on startup
    getHardware().setAllPortsDirection(Pin.IN);
    getHardware().setAllPortsPullUp(true);
    //timer 1 for ATmega8, change for other MCU
    timer = getHardware().getTimer("1");
    timer.setMode(TimerMode.FAST); //8 bit fast PWM
    timer.setPrescaling(8); //for 1 MHz clock, for 8 MHz change to 64
    timer.setEnabled(true);
    BrightnessChanger bc = new BrightnessChanger();
    timer.addTimerListener(bc);
    timer.setTimerOverflowedFired(true);
    //timer compare
    timerCompare = timer.getOutputCompare("A");
    timerCompare.setPinMode(TimerCompare.PinMode.CLEAR_ON_COMPARE_MATCH);
    // setting OC1A direction to output
    timerCompare.getPin().setDirection(Pin.OUT);
    timerCompare.setValue(0);
  }
  
  public void start()
  { //main program
    getHardware().setInterruptsEnabled(true);
  }
  
  private class BrightnessChanger implements TimerListener
  {
    public void timerOverflowed()
    { if(countingUp)
      { counter++;
        if(counter >= 255) countingUp = false;
      }
      else
      { counter--;
        if(counter <= 0) countingUp = true;
      }
      timerCompare.setValue(counter);
    }
    
  }
  
}

Download java source file