Tutorial 2
Listeners (Interrupts)

Program with interrupt

Here is simple program that uses timer overflow interrupt.

import mcujavasource.mcu.*;

/** Tutorial 2: program with timer interrupts.
 * Three LEDs flash one after another.
 * Default 8-bit timer and its overflow interrupt is used for delay.
 * LED's anode is connected to +5V through 330 Ohm resistor,
 * cathode - to MCU port.
 */
public class Tutorial2 extends Microcontroller
{
  /** Pin of the first LED, PB1 */
  private final Pin led1 = getHardware().getPort("B").getPin(1);
  
  /** Pin of the second LED, PB0 */
  private final Pin led2 = getHardware().getPort("B").getPin(0);
  
  /** Pin of the third LED, PB2 */
  private final Pin led3 = getHardware().getPort("B").getPin(2);
  
  private Timer timer;
  
  private volatile int currentLed = 0;
  
  public void init()
  { //register initialization on startup
    getHardware().setAllPortsDirection(Pin.IN);
    getHardware().setAllPortsPullUp(true);
    led1.setDirection(Pin.OUT);
    // led1 is initially turned on
    led1.setOutput(Pin.LOW);
    led2.setDirection(Pin.OUT);
    led2.setOutput(Pin.HIGH);
    led3.setDirection(Pin.OUT);
    led3.setOutput(Pin.HIGH);
    // getting default 8-bit timer
    timer = getHardware().getDefaultTimer(8);
    timer.setMode(TimerMode.NORMAL);
    // prescaling 1024
    timer.setPrescaling(1024);
    timer.setEnabled(true);
    LedSwitcher ledSwitcher = new LedSwitcher();
    timer.addTimerListener(ledSwitcher);
    timer.setTimerOverflowedFired(true); //this enables interrupt
  }
  
  public void start()
  { //main program
    getHardware().setInterruptsEnabled(true);
  }
  
  private class LedSwitcher implements TimerListener
  {
    public void timerOverflowed()
    { currentLed++;
      if(currentLed >= 3) currentLed = 0;
      switch(currentLed)
      { case 0:
          led3.setOutput(Pin.HIGH); //turn off led3
          led1.setOutput(Pin.LOW); //turn on led1
          break;
        case 1:
          led1.setOutput(Pin.HIGH);
          led2.setOutput(Pin.LOW);
          break;
        case 2:
          led2.setOutput(Pin.HIGH);
          led3.setOutput(Pin.LOW);
          break;
      }
    }
    
  }
  
}

Download java source file

Don't forget to activate the listeners! For examples, timer.setTimerOverflowedFired(true); activates TimerListener (in order, this enables interrupt). Listeners cannot be removed in MCU Java source, but can be activated and deactivated.