ClapMeasure
import lejos.nxt.*;
 
/**
 * The locomotions of a LEGO 9797 car is controlled by sound detected through a
 * microphone on port 1.
 * 
 * @author Ole Caprani
 * @version 23.08.07
 */
public class ClapMeasure implements ButtonListener {
    private static int loudSoundThreshold = 85,
                        lowSoundThreshold = 50;
    private static SoundSensor sound = new SoundSensor(SensorPort.S1);
    private static boolean running;
 
    public ClapMeasure() {
        Button.ESCAPE.addButtonListener(this);
    }
 
    private static boolean waitForLoudSound() throws Exception {
        int soundLevel;
        int counter = 0;
        int counterMax = 25;
 
        while (running && counter <= counterMax) {
            counter++;
            soundLevel = sound.readValue();
            if (soundLevel >= loudSoundThreshold) {
                return true;
            }
            Thread.sleep(1);
        }
        return false;
    }
 
    private static boolean waitForLowSound() throws Exception {
        int soundLevel;
        int counter = 0;
        int counterMax = 250;
 
        while (running && counter <= counterMax) {
            counter++;
            soundLevel = sound.readValue();
            if (soundLevel < lowSoundThreshold) {
                return true;
            }
            Thread.sleep(1);
        }
        return false;
    }
 
    public static void main(String[] args) throws Exception {
        ClapMeasure cm = new ClapMeasure();
        running = true;
        LCD.refresh();
        int counter = 0;
 
        while (running) {
 
            if (detectClap()) 
            {
                counter++;
            }
            LCD.drawString("Claps " + counter, 0, 0);
        }
        LCD.clear();
        LCD.drawString("Program stopped", 0, 0);
        Thread.sleep(2000);
    }
 
    public static boolean detectClap() throws Exception {
        while (sound.readValue() > 50 && running) {
            Thread.sleep(5);
        }
        LCD.drawString("Low ", 0, 1);
 
        if (waitForLoudSound()) {
            LCD.drawString("Loud ", 0, 1);
        } else {
            return false;
        }
 
        if (waitForLowSound()) {
            LCD.drawString("Low ", 0, 1);
            return true;
        }
 
        return false;
    }
 
    @Override
    public void buttonPressed(Button arg0) {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void buttonReleased(Button arg0) {
        running = false;
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License