import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import lejos.nxt.Button; import lejos.nxt.LCD; import lejos.nxt.SensorPort; import lejos.nxt.Sound; import lejos.nxt.SoundSensor; public class ClapDetector { private final static int SAMPLING_RATE = 25; private final static int CLAP_THRESHOLD = 60; private final static int SILENCE_THRESHOLD = 40; private final static boolean STRICT_CLAP = false; public static void main(String[] args) throws Exception { SoundSensor sound = new SoundSensor(SensorPort.S4); File f = new File("recording.txt"); if (!f.exists()) { if (!f.createNewFile()) { LCD.drawString("File creation problem", 0, 0); LCD.refresh(); while (!Button.ENTER.isPressed()) ; } } FileOutputStream fs = new FileOutputStream(f); DataOutputStream dos = new DataOutputStream(fs); LCD.drawString("Loudness: ", 0, 0); int value; int clapState = -1; String equalizeSymbol = "="; String clearSymbol = " "; String separatorSymbol = ","; String eolSymbol = "\r\n"; int startTime = (int) System.currentTimeMillis(); try { while (!Button.ESCAPE.isPressed()) { value = sound.readValue(); LCD.drawInt(value, 4, 10, 0); LCD.refresh(); writeString(Integer.toString((int)System.currentTimeMillis() - startTime), dos); writeString(separatorSymbol, dos); writeString(Integer.toString(value), dos); writeString(eolSymbol, dos); for (int i = 0; i < 17; i++) LCD.drawString((value / 10 < i) ? clearSymbol : equalizeSymbol, i, 3); LCD.drawInt(0, clapState + 1, 5); LCD.drawInt((int) (Runtime.getRuntime().freeMemory()), 0, 7); LCD.refresh(); if (clapState == -1) { if (value > CLAP_THRESHOLD) clapState = 10; } else if (clapState == 0) { // Sound.buzz(); LCD.clear(); LCD.refresh(); clapState = -1; } else { if ((STRICT_CLAP) && (value > SILENCE_THRESHOLD)) clapState = -1; else clapState--; } Thread.sleep(SAMPLING_RATE); } } catch (IOException e) { } finally { dos.flush(); dos.close(); } LCD.clear(); LCD.drawString("Program stopped", 0, 0); LCD.refresh(); } private static void writeString(String str, DataOutputStream output) throws IOException { for (int i = 0; i < str.length(); i++) output.write(str.charAt(i) + 0); } }