Collection of ME 8 Embedded code snippets:
- Using java.util.TimerTask and Timer – for scheduling periodic tasks (reading a sensor, checking a status etc eg
MyTimerTask myTimerTask = new MyTimerTask();
Timer timer = new Timer();
timer.schedule(myTimerTask, millisBeforeStarting, millisBetweenExecution);
this.pin = PeripheralManager.open(this.pinId);
this.pin.setValue(true); // true = on, false = off
- Adding an EventListener to a switch:
GPIOPinConfig config = new GPIOPinConfig(this.portId, this.pinId,
GPIOPinConfig.DIR_INPUT_ONLY, PeripheralConfig.DEFAULT,
GPIOPinConfig.TRIGGER_BOTH_EDGES,
this.pin = PeripheralManager.open(config);
this.pin.setInputListener(this);
… where this implements PinListener and valueChanged() method:
public void valueChanged(PinEvent event) {
GPIOPin eventPin = event.getPeripheral();
...
}
- Opening an I2C device for input/output:
I2CDeviceConfig config = new I2CDeviceConfig(i2cBus, address, addressSizeBits, serialClock);
myDevice = PeripheralManager.open(config);
this.uart = PeripheralManager.open(UART_DEVICE_ID);
this.uart.setBaudRate(9600);
InputStream is = Channels.newInputStream(uart);
this.serialBufferedReader = new BufferedReader(new InputStreamReader(is));
- Read using Generic Connection Framework:
CommConnection conn = (CommConnection)Connector.open("comm:/dev/ttyAMA0;baudrate=9600");
InputStream inputStream = conn.openInputStream();
this.serialBufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
- Open and write to a record store:
this.store = RecordStore.openRecordStore(storeName, true);
byte[] dataBytes = data.getBytes();
recordNum = store.addRecord(dataBytes, 0, dataBytes.length);