German English
Basics

Toggle LEDs using Threads

This example shows how to toggle all 4 LEDs from the Preon32Shuttle developer board with different frequencies. Each LED has a own toggle frequency which are derived from a 1000 ms master interval. This examples creates 4 Threads, one for each LED, which run independently.
/*
 * Copyright (c) 2011., Virtenio GmbH
 * All rights reserved.
 */

package com.virtenio.webdemo;

import com.virtenio.drivers.led.NativeLED;
import com.virtenio.platform.Platform;

import java.io.IOException;

public class ThreadLED {

    public static void main() throws InterruptedException {

        long time = 1000;  // [ms]

        Thread[] threads = new Thread[]{
                createThreadBlinker(Platform.LED_AMBER, time / 8),     //  125 [ms]
                createThreadBlinker(Platform.LED_RED, time / 4),       //  250 [ms]
                createThreadBlinker(Platform.LED_YELLOW, time / 2),    //  500 [ms]
                createThreadBlinker(Platform.LED_GREEN, time / 1)      // 1000 [ms]
        };
        for (Thread t : threads) {
            t.start();
        }

        while (true) {
            Thread.sleep(1000);
        }

    }

    private static Thread createThreadBlinker(final int led, final long speed) {
        return new Thread() {
            public void run() {
                while (true) {
                    try {
                        NativeLED.getInstance(led).on();    // on
                        Thread.sleep(speed);
                        NativeLED.getInstance(led).off();
                        Thread.sleep(speed);                // off
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

}