Сейчас поддерживается только 8-битная ШИМ. Для 16-битных таймеров устанавливается режим 8-битной ШИМ.
Это портированная на Java простая демострация из avr-libc (WinAVR). В программе используется таймер 1, который должен иметь ШИМ. Для не ATmega8 выберите любой таймер с ШИМ, подключив светодиод к выходу ШИМ.
Яркость свечения светодиода плавно меняется с помощью ШИМ. После каждого периода ШИМ значение увеличивается или уменьшается. Анод светодиода присоеденен к +5В через резистор 330 Ом, катод - к выходу ШИМ OC1A (PB1 для ATmega8).
import mcujavasource.mcu.*;
/** Учебник 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);
}
}
}