From 40ca4be66832a55b55c659613811c4a22da5bdc8 Mon Sep 17 00:00:00 2001 From: Tom Aarts Date: Wed, 27 Nov 2024 19:36:33 -0600 Subject: [PATCH] add checkstyle phase in CI, Fixed the errors --- config/checkstyle/checkstyle.xml | 29 + pom.xml | 22 + .../com/pi4j/devices/ads1256/ADS1256.java | 397 ++++++----- .../com/pi4j/devices/ads1256/ADS1256App.java | 306 ++++---- .../devices/ads1256/ADS1256_Declares.java | 72 +- .../java/com/pi4j/devices/ads1256/README.md | 120 ++-- .../pi4j/devices/appConfig/AppConfigTest.java | 26 +- .../devices/appConfig/AppConfigUtilities.java | 597 ++++++++-------- .../pi4j/devices/appConfig/ChipNameMap.java | 197 +++-- .../com/pi4j/devices/appConfig/GpioToApp.java | 256 ++++--- .../com/pi4j/devices/appConfig/PiPinMap.java | 47 +- .../devices/appConfig/ReadProperties.java | 27 +- .../com/pi4j/devices/at24c512/AT24C512.java | 68 +- .../pi4j/devices/at24c512/AT24C512_App.java | 91 +-- .../java/com/pi4j/devices/at24c512/README.md | 25 +- .../pi4j/devices/base_i2c/BasicI2cDevice.java | 67 +- .../pi4j/devices/base_i2c/I2cSimpleRead.java | 10 +- .../devices/base_i2c/MutableI2cDevice.java | 15 +- .../java/com/pi4j/devices/base_i2c/README.md | 5 +- .../base_util/ffdc/FfdcLoggingModule.java | 8 +- .../base_util/ffdc/FfdcLoggingSystem.java | 4 +- .../pi4j/devices/base_util/ffdc/FfdcUtil.java | 8 +- .../devices/base_util/gpio/BaseGpioInOut.java | 19 +- .../devices/base_util/gpio/GpioBasics.java | 42 +- .../base_util/gpio/GpioPinCfgData.java | 8 +- .../devices/base_util/mapUtil/MapUtil.java | 68 +- .../pi4j/devices/bme280/BME280DeviceI2C.java | 62 +- .../pi4j/devices/bme280/BME280DeviceSPI.java | 115 ++- .../java/com/pi4j/devices/bme280/README.md | 27 +- .../com/pi4j/devices/bmp280/BMP280Device.java | 33 +- .../pi4j/devices/bmp280/BMP280DeviceI2C.java | 75 +- .../pi4j/devices/bmp280/BMP280DeviceSPI.java | 46 +- .../pi4j/devices/bmp280/BMP280I2cExample.java | 24 +- .../pi4j/devices/bmp280/BMP280Interface.java | 19 +- .../pi4j/devices/bmp280/BMP280SpiExample.java | 35 +- .../java/com/pi4j/devices/bmp280/README.md | 60 +- .../com/pi4j/devices/cp2102n/CP2102N.java | 39 +- .../com/pi4j/devices/cp2102n/CP2102N_App.java | 31 +- .../java/com/pi4j/devices/cp2102n/README.md | 118 +-- .../com/pi4j/devices/dac8552/DAC8552.java | 63 +- .../com/pi4j/devices/dac8552/DAC8552App.java | 8 +- .../devices/dac8552/DAC8552_Declares.java | 8 +- .../java/com/pi4j/devices/dac8552/README.md | 15 +- .../java/com/pi4j/devices/dht22/DHT22.java | 8 +- .../com/pi4j/devices/dht22/DHT22_App.java | 15 - .../java/com/pi4j/devices/dht22/README.md | 9 +- .../java/com/pi4j/devices/hcsr04/HCSR04.java | 8 +- .../java/com/pi4j/devices/hcsr04/README.md | 65 +- .../HD44780U_App_LCD1602A.java | 42 +- .../HD44780U_Declares_LCD1602A.java | 4 +- .../HD44780U_Interface_LCD1602A.java | 5 - .../hd44780u_lcd1602a/HD44780U_LCD1602A.java | 95 ++- .../pi4j/devices/hd44780u_lcd1602a/README.md | 78 +- .../devices/is31Fl37Matrix/ControlLeds.java | 127 ++-- .../is31Fl37Matrix/CreateInterrupt.java | 39 +- .../devices/is31Fl37Matrix/DisplayLED.java | 306 ++++---- .../devices/is31Fl37Matrix/DisplayTemp.java | 16 +- .../is31Fl37Matrix/InterruptDetails.java | 34 +- .../is31Fl37Matrix/Is31Fl37Matrix.java | 198 +++--- .../is31Fl37Matrix/Is31Fl37_matrix_app.java | 132 ++-- .../is31Fl37Matrix/Is31Fl37_matrix_test.java | 671 +++++++++--------- .../is31Fl37Matrix/MonitorInterrupt.java | 30 +- .../com/pi4j/devices/is31Fl37Matrix/README.md | 80 +-- .../com/pi4j/devices/lcd1602a/LCD1602A.java | 22 +- .../devices/lcd1602a/LCD1602A_Declares.java | 88 +-- .../com/pi4j/devices/mcp23008/Mcp23008.java | 39 +- .../pi4j/devices/mcp23008/Mcp23008App.java | 41 +- .../java/com/pi4j/devices/mcp23008/README.md | 147 ++-- .../com/pi4j/devices/mcp23017/Mcp23017.java | 41 +- .../pi4j/devices/mcp23017/Mcp23017App.java | 18 - .../java/com/pi4j/devices/mcp23017/README.md | 155 ++-- .../mcp23017_lcd1602a/MCP23017_LCD1602A.java | 324 ++++----- .../MCP23017_LCD1602A_App.java | 23 +- .../MCP23017_LCD1602A_Declares.java | 28 +- .../pi4j/devices/mcp23017_lcd1602a/README.md | 142 ++-- .../Mcp23008PinMonitor.java | 32 +- .../Mcp23017PinMonitor.java | 36 +- .../Mcp23xxxAppProcessParms.java | 47 +- .../mcp23xxxApplication/Mcp23xxxParms.java | 17 +- .../Mcp23xxxPinMonitorIntf.java | 56 +- .../PinInterruptActionIntf.java | 8 +- .../mcp23xxxApplication/PinInterruptBase.java | 11 +- .../PinInterruptDefault.java | 38 +- .../mcp23xxxApplication/PinInterruptLED.java | 67 +- .../devices/mcp23xxxApplication/README.md | 398 +++++------ .../devices/mcp23xxxCommon/Mcp23xxxUtil.java | 152 ++-- .../pi4j/devices/mcp23xxxCommon/McpBase.java | 255 ++++--- .../devices/mcp23xxxCommon/McpConfigData.java | 17 +- .../com/pi4j/devices/mcp3008/MCP3008.java | 44 +- .../com/pi4j/devices/mcp3008/MCP3008App.java | 18 +- .../java/com/pi4j/devices/mcp3008/README.md | 35 +- .../com/pi4j/devices/mcp4725/MCP4725.java | 71 +- .../com/pi4j/devices/mcp4725/MCP4725_App.java | 78 +- .../devices/mcp4725/MCP4725_Declares.java | 36 +- .../java/com/pi4j/devices/mcp4725/README.md | 53 +- .../com/pi4j/devices/mpl3115a2/MPL3115A2.java | 320 ++++----- .../pi4j/devices/mpl3115a2/MPL3115A2_App.java | 80 +-- .../devices/mpl3115a2/MPL3115A2_Declares.java | 188 +++-- .../java/com/pi4j/devices/mpl3115a2/README.md | 145 ++-- .../pi4j/devices/neopixel94v/NeoPixel94V.java | 24 +- .../devices/neopixel94v/NeoPixel94V_App.java | 42 +- .../com/pi4j/devices/neopixel94v/README.md | 125 ++-- .../PCF8574A_App_LCD1602A.java | 18 +- .../PCF8574A_Declares_LCD1602A.java | 31 +- .../pcf8574a_lcd1602a/PCF8574A_LCD1602A.java | 123 ++-- .../pi4j/devices/pcf8574a_lcd1602a/README.md | 34 +- .../com/pi4j/devices/rotary_encoder/README.md | 104 ++- .../RotaryEncoderId5880I2C.java | 16 - .../java/com/pi4j/devices/sn74hc595/README.md | 14 +- .../com/pi4j/devices/sn74hc595/SN74HC595.java | 131 ++-- .../pi4j/devices/sn74hc595/SN74HC595App.java | 26 +- .../com/pi4j/devices/ssd1306/SSD1306.java | 12 +- .../ssd1306/SSD1306Sample128X64IMAGE.java | 128 ++-- .../pi4j/devices/ssd1306/SSD1306_Example.java | 22 +- .../java/com/pi4j/devices/tca9548/README.md | 42 +- .../devices/tca9548/SampleTca9548App.java | 33 +- .../com/pi4j/devices/tca9548/Tca9548.java | 69 +- .../devices/tca9548/Tca9548ConfigData.java | 2 +- .../java/com/pi4j/devices/vl53L0X/README.md | 7 +- .../com/pi4j/devices/vl53L0X/VL53L0X_App.java | 24 +- .../pi4j/devices/vl53L0X/VL53L0X_Device.java | 78 +- 121 files changed, 4619 insertions(+), 5030 deletions(-) create mode 100644 config/checkstyle/checkstyle.xml diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000..5131867 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index d874d55..4faf63b 100644 --- a/pom.xml +++ b/pom.xml @@ -60,6 +60,7 @@ 5.1.9 3.3.2 3.1.0 + 3.6.0 @@ -421,6 +422,27 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven-checkstyle-plugin.version} + + + checkstyle-check + + check + + validate + + + + true + config/checkstyle/checkstyle.xml + **/module-info.java + plain + true + + diff --git a/src/main/java/com/pi4j/devices/ads1256/ADS1256.java b/src/main/java/com/pi4j/devices/ads1256/ADS1256.java index 6877955..dc24373 100644 --- a/src/main/java/com/pi4j/devices/ads1256/ADS1256.java +++ b/src/main/java/com/pi4j/devices/ads1256/ADS1256.java @@ -64,15 +64,14 @@ enum MuxValue { AINCOM } - enum ADS1256_GAIN - { - ADS1256_GAIN_1, //= 0, /* GAIN 1 */ - ADS1256_GAIN_2, // = 1, /*GAIN 2 */ - ADS1256_GAIN_4, // = 2, /*GAIN 4 */ - ADS1256_GAIN_8, // = 3, /*GAIN 8 */ - ADS1256_GAIN_16, // = 4, /* GAIN 16 */ - ADS1256_GAIN_32, // = 5, /*GAIN 32 */ - ADS1256_GAIN_64, // = 6, /*GAIN 64 */ + enum ADS1256_GAIN { + ADS1256_GAIN_1, //= 0, /* GAIN 1 */ + ADS1256_GAIN_2, // = 1, /*GAIN 2 */ + ADS1256_GAIN_4, // = 2, /*GAIN 4 */ + ADS1256_GAIN_8, // = 3, /*GAIN 8 */ + ADS1256_GAIN_16, // = 4, /* GAIN 16 */ + ADS1256_GAIN_32, // = 5, /*GAIN 32 */ + ADS1256_GAIN_64, // = 6, /*GAIN 64 */ } enum ADS1256_DRATE { @@ -97,8 +96,8 @@ enum ADS1256_DRATE { static final int[] ADS1256_DRATE_E = - { - 0xF0, /*reset the default values */ + { + 0xF0, /*reset the default values */ 0xE0, 0xD0, 0xC0, @@ -114,10 +113,11 @@ enum ADS1256_DRATE { 0x23, 0x13, 0x03 - }; + }; /** - * See ADS1256App.java help text to explain these parms + * See ADS1256App.java help text to explain these parms + * * @param pi4j * @param spiBus * @param chipSelect @@ -133,7 +133,7 @@ enum ADS1256_DRATE { * @param vref * @throws InterruptedException */ - public ADS1256(Context pi4j, SpiBus spiBus, SpiChipSelect chipSelect, boolean reset, int drdyPin, int csPin, int rstPin, boolean crtRstGpio, int pdwnPin,boolean crtPdwnGpio, Console console, String traceLevel, double vref) throws InterruptedException { + public ADS1256(Context pi4j, SpiBus spiBus, SpiChipSelect chipSelect, boolean reset, int drdyPin, int csPin, int rstPin, boolean crtRstGpio, int pdwnPin, boolean crtPdwnGpio, Console console, String traceLevel, double vref) throws InterruptedException { super(); this.console = console; this.pi4j = pi4j; @@ -159,30 +159,31 @@ public ADS1256(Context pi4j, SpiBus spiBus, SpiChipSelect chipSelect, boolean r } /** - * Creates the SPI and requested GPIOs. - * Do reset if so requested by app - * Configure chip Gain and speed. + * Creates the SPI and requested GPIOs. + * Do reset if so requested by app + * Configure chip Gain and speed. + * * @throws InterruptedException */ private void init() throws InterruptedException { var spiConfig = Spi.newConfigBuilder(pi4j) - .id("SPI" + this.spiBus + " " + this.chipSelect) - .name("A/D converter") - .bus(this.spiBus) - .chipSelect(this.chipSelect) - .flags(0b0000000000000011100001L) // Ux CE not used, MM mode 1 - .baud(976563) //Spi.DEFAULT_BAUD) - .mode(SpiMode.MODE_1) - .provider("pigpio-spi") - .build(); + .id("SPI" + this.spiBus + " " + this.chipSelect) + .name("A/D converter") + .bus(this.spiBus) + .chipSelect(this.chipSelect) + .flags(0b0000000000000011100001L) // Ux CE not used, MM mode 1 + .baud(976563) //Spi.DEFAULT_BAUD) + .mode(SpiMode.MODE_1) + .provider("pigpio-spi") + .build(); this.spi = this.pi4j.create(spiConfig); - // required all configs + // required all configs var inputConfig1 = DigitalInput.newConfigBuilder(pi4j) - .id("DRDY_pin") - .name("DRDY") - .address(this.drdyPinNum) - .provider("gpiod-digital-input"); // .pull(PullResistance.PULL_UP) + .id("DRDY_pin") + .name("DRDY") + .address(this.drdyPinNum) + .provider("gpiod-digital-input"); // .pull(PullResistance.PULL_UP) try { this.drdyGpio = pi4j.create(inputConfig1); } catch (Exception e) { @@ -192,12 +193,12 @@ private void init() throws InterruptedException { } // required all configs var outputConfig2 = DigitalOutput.newConfigBuilder(pi4j) - .id("CS_pin") - .name("CS") - .address(this.csPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("CS_pin") + .name("CS") + .address(this.csPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { this.csGpio = pi4j.create(outputConfig2); } catch (Exception e) { @@ -206,14 +207,14 @@ private void init() throws InterruptedException { System.exit(202); } // not always required, see README - if(this.crtRstGpio) { + if (this.crtRstGpio) { var outputConfig3 = DigitalOutput.newConfigBuilder(pi4j) - .id("RST_pin") - .name("RESET") - .address(this.rstPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("RST_pin") + .name("RESET") + .address(this.rstPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { this.rstGpio = pi4j.create(outputConfig3); } catch (Exception e) { @@ -221,32 +222,32 @@ private void init() throws InterruptedException { console.println("create DigOut RESET failed"); System.exit(203); } - }else{ + } else { this.logger.trace("RESET Gpio not requested/created"); } // not always required, see README - if(this.crtPdwnGpio) { - var outputConfig4 = DigitalOutput.newConfigBuilder(pi4j) + if (this.crtPdwnGpio) { + var outputConfig4 = DigitalOutput.newConfigBuilder(pi4j) .id("PDWN_pin") .name("PDWN") .address(this.pdwnPinNum) .shutdown(DigitalState.HIGH) .initial(DigitalState.HIGH) .provider("gpiod-digital-output"); - try { - this.pdwnGpio = pi4j.create(outputConfig4); - } catch (Exception e) { - e.printStackTrace(); - console.println("create DigOut PDWN failed"); - System.exit(203); - } - }else{ + try { + this.pdwnGpio = pi4j.create(outputConfig4); + } catch (Exception e) { + e.printStackTrace(); + console.println("create DigOut PDWN failed"); + System.exit(203); + } + } else { this.logger.trace("PDWN Gpio not requested/created"); } - if(this.resetChip){ + if (this.resetChip) { this.doReset(); } @@ -258,6 +259,7 @@ private void init() throws InterruptedException { /** * Validate chip ID = 3, if not program will exist + * * @return chip ID * @throws InterruptedException */ @@ -268,53 +270,54 @@ public int validateChipID() throws InterruptedException { console.title("<-- The Pi4J Project -->", "SPI test program using ADS1256 AtoD Chip"); this.waitForDrdyLow(); id = this.readRegData(ADS1256_Declares.REG_STATUS) >> 4; - if (id != ADS1256_Declares.CHIP_ID){ + if (id != ADS1256_Declares.CHIP_ID) { console.println("Incorrect chip ID : " + id); System.exit(301); } this.logger.trace("<<< Exit displayProgramID : " + id); - return(id); + return (id); } /** - * Set chip Gain and speed + * Set chip Gain and speed + * * @param gain * @param drate * @throws InterruptedException */ - private void ADS1256_ConfigADC(String gain, String drate) throws InterruptedException { + private void ADS1256_ConfigADC(String gain, String drate) throws InterruptedException { this.waitForDrdyLow(); byte status = this.readRegData(ADS1256_Declares.REG_STATUS); - int buf[] = {0,0,0,0}; + int[] buf = {0, 0, 0, 0}; // preserve DRDY bit state and set ACAL bit - buf[0] = (status & ADS1256_Declares.STATUS_DRDY_MASK)|ADS1256_Declares.STATUS_ACAL; //STATUS_REG - buf[1] = (byte) (0b00000000 | (((0 & 0xf) << 4)) | 8); // MUX_REG initial: AIN0/AINCOM - buf[2] = (0<<5) | (0<<3) | (this.mapGainString(gain)<<0); // ADCON_REG CLK/SENSOR off + buf[0] = (status & ADS1256_Declares.STATUS_DRDY_MASK) | ADS1256_Declares.STATUS_ACAL; //STATUS_REG + buf[1] = (byte) (0b00000000 | (((0 & 0xf) << 4)) | 8); // MUX_REG initial: AIN0/AINCOM + buf[2] = (0 << 5) | (0 << 3) | (this.mapGainString(gain) << 0); // ADCON_REG CLK/SENSOR off buf[3] = this.mapDrateString(drate); // DRATE_REG this.csGpio.low(); - this.busyWaitMS(2); + busyWaitMS(2); this.spi.write(ADS1256_Declares.WREG | 0); - this.busyWaitMS(2); + busyWaitMS(2); this.spi.write(0x03); // writing 4 bytes data - this.busyWaitMS(2); + busyWaitMS(2); this.spi.write(buf[0]); - this.busyWaitMS(2); + busyWaitMS(2); this.spi.write(buf[1]); - this.busyWaitMS(2); + busyWaitMS(2); this.spi.write(buf[2]); - this.busyWaitMS(2); + busyWaitMS(2); this.spi.write(buf[3]); - this.busyWaitMS(2); + busyWaitMS(2); this.csGpio.high(); - this.busyWaitMS(1); + busyWaitMS(1); } /** * Debug usage, display state of DRDY InputGpio */ private void showDrdyState() { - this.logger.trace("showDrdyState " ); + this.logger.trace("showDrdyState "); if (this.drdyGpio.state() == DigitalState.HIGH) { this.logger.trace("DRDY state HIGH"); } else if (this.drdyGpio.state() == DigitalState.LOW) { @@ -326,19 +329,20 @@ private void showDrdyState() { /** * If the RESET Gpio was configured reset dhip via Gpio, else use commands + * * @throws InterruptedException */ public void doReset() throws InterruptedException { this.logger.trace(">>> Enter doReset"); - if(this.rstGpio != null) { + if (this.rstGpio != null) { this.rstGpio.high(); - this.busyWaitMS(200); + busyWaitMS(200); this.rstGpio.low(); - this.busyWaitMS(200); + busyWaitMS(200); this.rstGpio.high(); - }else{ + } else { this.writeCmd(ADS1256_Declares.RESET); - this.busyWaitMS(200); + busyWaitMS(200); } this.logger.trace("<<< Exit doReset"); } @@ -346,75 +350,73 @@ public void doReset() throws InterruptedException { private void writeCmd(int cmd) { this.logger.trace(">>> Enter writeCmd cmd " + cmd); this.csGpio.low(); - this.busyWaitMS(2); + busyWaitMS(2); this.spi.write(cmd); - this.busyWaitMS(2); + busyWaitMS(2); this.csGpio.high(); this.logger.trace("<<< Exit writeCmd"); } private void writeReg(int reg, int data) { - this.logger.trace(">>> Enter writeReg reg : " + reg + " data " + String.format("0X%02x: ", data&0xff)); + this.logger.trace(">>> Enter writeReg reg : " + reg + " data " + String.format("0X%02x: ", data & 0xff)); this.csGpio.low(); - this.busyWaitMS(2); - byte buf[] = {0,0,0}; + busyWaitMS(2); + byte[] buf = {0, 0, 0}; buf[0] = (byte) (ADS1256_Declares.WREG | reg); - buf[1] = 0x00; + buf[1] = 0x00; buf[2] = (byte) data; this.spi.write(buf); - this.busyWaitMS(2); + busyWaitMS(2); this.csGpio.high(); this.logger.trace("<<< Exit writeReg"); } private byte readRegData(int reg) { - this.logger.trace(">>> Enter readReg register# : " + reg); + this.logger.trace(">>> Enter readReg register# : " + reg); byte rval = 42; this.csGpio.low(); - this.busyWaitMS(2); - byte buf[] = {0,0,0}; + busyWaitMS(2); + byte[] buf = {0, 0, 0}; buf[0] = (byte) (ADS1256_Declares.RREG | reg); - buf[1] = 0x00; + buf[1] = 0x00; this.spi.write(buf); - this.busyWaitMS(2); + busyWaitMS(2); rval = this.spi.readByte(); - this.busyWaitMS(2); + busyWaitMS(2); this.csGpio.high(); - this.busyWaitMS(200); // let chip quiet - this.logger.trace("<<< Exit readReg : " + String.format("0X%02x: ", rval&0xff)); + busyWaitMS(200); // let chip quiet + this.logger.trace("<<< Exit readReg : " + String.format("0X%02x: ", rval & 0xff)); return (byte) (rval & 0xff); } private static void busyWaitNano(long nanos) { long waitUntil = System.nanoTime() + (nanos); while (waitUntil > System.nanoTime()) { - ; } } private static void busyWaitMicros(long micros) { long waitUntil = System.nanoTime() + (micros * 1000); while (waitUntil > System.nanoTime()) { - ; } } private static void busyWaitMS(long ms) { long waitUntil = System.nanoTime() + (ms * 1000000); while (waitUntil > System.nanoTime()) { - ; } } /** * Name(s) supplied by app. These are mapped to integer values + * * @param name * @return */ private short mapMuxString(String name) { - MuxValue muxMap[] = MuxValue.values(); + MuxValue[] muxMap = MuxValue.values(); int posPin = 0xff; for (MuxValue col : muxMap) { // Calling ordinal() to find index @@ -430,6 +432,7 @@ private short mapMuxString(String name) { /** * Name pairs pChannel and nChannel written into chips MUX register + * * @param pChannel * @param nChannel * @throws IOException @@ -440,13 +443,13 @@ private void mapMux(short pChannel, short nChannel) throws IOException, Interrup // create a data buffer and initialize a conversion request payload - byte muxData[] = new byte[]{(byte) ADS1256_Declares.WREG | ADS1256_Declares.REG_MUX, // 5H/register offset - (byte) (0b00000000), // number regs to write -1 - (byte) (0b00000000 | (((pChannel & 0xf) << 4)) | nChannel), // channel +, channel AINCOM + byte[] muxData = new byte[]{(byte) ADS1256_Declares.WREG | ADS1256_Declares.REG_MUX, // 5H/register offset + (byte) (0b00000000), // number regs to write -1 + (byte) (0b00000000 | (((pChannel & 0xf) << 4)) | nChannel), // channel +, channel AINCOM }; Thread.sleep(2000); - byte muxValue[] = new byte[4]; - this.writeReg( ADS1256_Declares.REG_MUX,(((pChannel & 0xf) << 4) | nChannel) ); + byte[] muxValue = new byte[4]; + this.writeReg(ADS1256_Declares.REG_MUX, (((pChannel & 0xf) << 4) | nChannel)); this.logger.trace("<<< Exit mapMux "); } @@ -454,6 +457,7 @@ private void mapMux(short pChannel, short nChannel) throws IOException, Interrup /** * One-shot get the RDATA for ppName and pnName, then return the value + * * @param ppName * @param pnName * @return @@ -467,13 +471,14 @@ public double getADS1256State(String ppName, String pnName) throws InterruptedEx // allow for user to exit program using CTRL-C this.logger.trace(">>> Enter getADS1256State channel : " + pChannel + "/" + nChannel); // continue running program until user exits using CTRL-C - double rval = read(pChannel, nChannel); + double rval = read(pChannel, nChannel); this.logger.trace("<<< Exit getADS1256State: channel :" + pChannel + "/" + nChannel + " value :" + rval); - return(rval); + return (rval); } /** * Will repeatedly get the RDATA for ppName and pnName, until user ctrl-C + * * @param ppName * @param pnName * @throws InterruptedException @@ -508,28 +513,29 @@ public double read(short pChannel, short nChannel) throws IOException, Interrupt this.logger.trace(" |\r"); this.logger.trace("<<< Exit read"); - return(conversion_value); + return (conversion_value); } /** * Polling for controlled number of times testing for * DRDY Gpio being DigitalState.LOW, return true, else false + * * @return * @throws InterruptedException */ private boolean waitForDrdyLow() throws InterruptedException { boolean rval = false; long i = 0; - for(i=0;i<4000000;i++){ - if(this.drdyGpio.state() == DigitalState.LOW) { + for (i = 0; i < 4000000; i++) { + if (this.drdyGpio.state() == DigitalState.LOW) { rval = true; break; - }else{ - this.logger.trace("Not desired State counter " + i); + } else { + this.logger.trace("Not desired State counter " + i); } } - if(i >= 4000000){ + if (i >= 4000000) { this.logger.trace("waitForDrdyLow Time Out ...\r\n"); } //this.logger.trace(" waitForDrdyLow " + rval); @@ -537,7 +543,6 @@ private boolean waitForDrdyLow() throws InterruptedException { } - /** * Communicate to the ADC chip via SPI to get single-ended conversion value * for a specified channel. @@ -554,62 +559,63 @@ public int getConversionValue(short pChannel, short nChannel) throws IOException this.mapMux(pChannel, nChannel); - this.busyWaitMS(2); + busyWaitMS(2); this.writeCmd(ADS1256_Declares.SYNC); - this.busyWaitMS(2); + busyWaitMS(2); this.writeCmd(ADS1256_Declares.WAKEUP); - this.busyWaitMS(2); + busyWaitMS(2); int value = this.doRDATA(); - this.busyWaitMS(2); + busyWaitMS(2); - this.logger.info("Channel :" + pChannel + "/" + nChannel + " value :" + value ); //String.format(" | %06f", value)); // print + this.logger.info("Channel :" + pChannel + "/" + nChannel + " value :" + value); //String.format(" | %06f", value)); // print if (this.vref > 0) { this.logger.info("A/D read input voltage : " + ((value * this.vref) / 0x7fffff + " \n")); } this.logger.trace("<<< Exit getConversionValue "); - return value; + return value; } /** * REtrieve RDATA from chip + * * @return * @throws InterruptedException */ private int doRDATA() throws InterruptedException { - this.logger.trace(">>> Enter doRDATA "); - - int read = 0; - int buf[] = {0,0,0}; - - this.waitForDrdyLow(); - this.busyWaitMS(1); - - this.csGpio.low(); - this.busyWaitMS(2); - this.spi.write(ADS1256_Declares.RDATA); - this.busyWaitMS(1); - buf[0] = this.spi.readByte(); - buf[1] = this.spi.readByte(); - buf[2] = this.spi.readByte(); - this.csGpio.high(); - read = (buf[0] << 16) & 0x00FF0000; - read |= (buf[1] << 8) & 0x0000FF00; - read |= buf[2] & 0x000000FF; - read &= 0x00ffffff; - //printf("%d %d %d \r\n",buf[0],buf[1],buf[2]); - if (read >= 0x800000) { - read -= 0x1000000; // negative value - } - this.logger.trace("<<< Exit doRDATA "); - return read; + this.logger.trace(">>> Enter doRDATA "); -} + int read = 0; + int[] buf = {0, 0, 0}; + + this.waitForDrdyLow(); + busyWaitMS(1); + + this.csGpio.low(); + busyWaitMS(2); + this.spi.write(ADS1256_Declares.RDATA); + busyWaitMS(1); + buf[0] = this.spi.readByte(); + buf[1] = this.spi.readByte(); + buf[2] = this.spi.readByte(); + this.csGpio.high(); + read = (buf[0] << 16) & 0x00FF0000; + read |= (buf[1] << 8) & 0x0000FF00; + read |= buf[2] & 0x000000FF; + read &= 0x00ffffff; + //printf("%d %d %d \r\n",buf[0],buf[1],buf[2]); + if (read >= 0x800000) { + read -= 0x1000000; // negative value + } + this.logger.trace("<<< Exit doRDATA "); + return read; + + } private short mapDrateString(String name) { - ADS1256_DRATE drateMap[] = ADS1256_DRATE.values(); + ADS1256_DRATE[] drateMap = ADS1256_DRATE.values(); int posPin = 0xff; for (ADS1256_DRATE col : drateMap) { // Calling ordinal() to find index @@ -620,11 +626,11 @@ private short mapDrateString(String name) { break; } } - return (short) ( ADS1256_DRATE_E[posPin] & 0xff); + return (short) (ADS1256_DRATE_E[posPin] & 0xff); } private short mapGainString(String name) { - ADS1256_GAIN drateMap[] = ADS1256_GAIN.values(); + ADS1256_GAIN[] drateMap = ADS1256_GAIN.values(); int posPin = 0xff; for (ADS1256_GAIN col : drateMap) { // Calling ordinal() to find index @@ -638,95 +644,98 @@ private short mapGainString(String name) { return (short) (posPin & 0xff); } - public DigitalState readGpio(int pin){ - this.logger.trace(">>> Enter readGpio pin " + pin); + public DigitalState readGpio(int pin) { + this.logger.trace(">>> Enter readGpio pin " + pin); DigitalState rval = DigitalState.UNKNOWN; byte regVal = this.readRegData(ADS1256_Declares.REG_IO); - if(this.isPinInput(pin, regVal)){ + if (this.isPinInput(pin, regVal)) { rval = this.getPinState(pin, regVal); } - this.logger.trace("<<< Exit readGpio State" + rval); + this.logger.trace("<<< Exit readGpio State" + rval); return (rval); } - public boolean setGpioDirOut(int pin){ - this.logger.trace(">>> Enter setGpioDirOut pin " + pin); + public boolean setGpioDirOut(int pin) { + this.logger.trace(">>> Enter setGpioDirOut pin " + pin); boolean rval = false; - // this.logger.trace("ADCON" + this.readRegData(ADS1256_Declares.REG_ADCON)); + // this.logger.trace("ADCON" + this.readRegData(ADS1256_Declares.REG_ADCON)); byte regVal = this.readRegData(ADS1256_Declares.REG_IO); - regVal &= ~(0x10<< pin) & 0xff; + regVal &= ~(0x10 << pin) & 0xff; this.writeReg(ADS1256_Declares.REG_IO, regVal); rval = true; - this.logger.trace("<<< Exit setGpioDirOut " + rval); + this.logger.trace("<<< Exit setGpioDirOut " + rval); return (rval); } - public boolean setGpioDirIn(int pin){ - this.logger.trace(">>> Enter setGpioDirIn pin " + pin); + public boolean setGpioDirIn(int pin) { + this.logger.trace(">>> Enter setGpioDirIn pin " + pin); boolean rval = false; byte regVal = this.readRegData(ADS1256_Declares.REG_IO); - regVal |= (0x10<< pin) & 0xff; + regVal |= (0x10 << pin) & 0xff; this.writeReg(ADS1256_Declares.REG_IO, regVal); - this.logger.trace("<<< Exit setGpioDirIn State" + rval); + this.logger.trace("<<< Exit setGpioDirIn State" + rval); rval = true; return (rval); } - private DigitalState getPinState(int pin, byte registerVal){ + private DigitalState getPinState(int pin, byte registerVal) { DigitalState rval = DigitalState.UNKNOWN; - this.logger.trace(">>> Enter isPinInput pin: " +pin); - if((registerVal & (0x01 << pin)) == 0){ + this.logger.trace(">>> Enter isPinInput pin: " + pin); + if ((registerVal & (0x01 << pin)) == 0) { rval = DigitalState.LOW; - }else{ + } else { rval = DigitalState.HIGH; } this.logger.trace(" Exit isPinInput "); - return(rval); + return (rval); } - public boolean setGpio(int pin, DigitalState newState){ - this.logger.trace(">>> Enter setGpio pin " + pin + " state : "+ newState); + + public boolean setGpio(int pin, DigitalState newState) { + this.logger.trace(">>> Enter setGpio pin " + pin + " state : " + newState); boolean rval = false; byte regVal = this.readRegData(ADS1256_Declares.REG_IO); - if(this.isPinOutput(pin, regVal)){ + if (this.isPinOutput(pin, regVal)) { rval = this.setPinState(pin, newState, regVal); - }else { + } else { this.logger.trace("Pin " + pin + " not configured for output"); } - this.logger.trace("<<< Exit setGpio " + rval); + this.logger.trace("<<< Exit setGpio " + rval); return (rval); } - private boolean setPinState(int pin, DigitalState newState, byte registerVal){ + private boolean setPinState(int pin, DigitalState newState, byte registerVal) { boolean rval = false; - this.logger.trace(">>> Enter setPinState pin: " +pin + " state: " + newState); - if(newState == DigitalState.HIGH){ - registerVal |= (1<< pin); - rval = true; - }else{ - registerVal &= ~(1<< pin); + this.logger.trace(">>> Enter setPinState pin: " + pin + " state: " + newState); + if (newState == DigitalState.HIGH) { + registerVal |= (1 << pin); + rval = true; + } else { + registerVal &= ~(1 << pin); rval = true; } this.writeReg(ADS1256_Declares.REG_IO, registerVal); this.logger.trace(" Exit setPinState " + rval); - return(rval); + return (rval); } - private boolean isPinInput(int pin, byte registerVal){ + + private boolean isPinInput(int pin, byte registerVal) { boolean rval = false; - this.logger.trace(">>> Enter isPinInput pin: " +pin); - if((registerVal & (0x10 << pin)) >0){ + this.logger.trace(">>> Enter isPinInput pin: " + pin); + if ((registerVal & (0x10 << pin)) > 0) { rval = true; } - this.logger.trace(" Exit isPinInput " + rval); - return(rval); + this.logger.trace(" Exit isPinInput " + rval); + return (rval); } - private boolean isPinOutput(int pin, byte registerVal){ + + private boolean isPinOutput(int pin, byte registerVal) { boolean rval = false; - this.logger.trace(">>> Enter isPinOutput pin: " +pin); - if((registerVal & (0x10 << pin)) == 0){ + this.logger.trace(">>> Enter isPinOutput pin: " + pin); + if ((registerVal & (0x10 << pin)) == 0) { rval = true; } - this.logger.trace(" Exit isPinOutput " + rval); - return(rval); + this.logger.trace(" Exit isPinOutput " + rval); + return (rval); } @@ -736,7 +745,7 @@ private boolean isPinOutput(int pin, byte registerVal){ // ADC channel count // file private Spi spi; - private Console console; + private final Console console; private final String traceLevel; private final Logger logger; @@ -744,20 +753,20 @@ private boolean isPinOutput(int pin, byte registerVal){ private final SpiChipSelect chipSelect; private final SpiBus spiBus; - private Context pi4j; + private final Context pi4j; private boolean resetChip = false; private DigitalInput drdyGpio; - private int drdyPinNum; // 17 + private final int drdyPinNum; // 17 private DigitalOutput csGpio; - private int csPinNum; // 22 + private final int csPinNum; // 22 private DigitalOutput rstGpio; - private int rstPinNum; // 18 + private final int rstPinNum; // 18 private boolean crtRstGpio = false; private DigitalOutput pdwnGpio; - private int pdwnPinNum; // 27 + private final int pdwnPinNum; // 27 private boolean crtPdwnGpio = false; } diff --git a/src/main/java/com/pi4j/devices/ads1256/ADS1256App.java b/src/main/java/com/pi4j/devices/ads1256/ADS1256App.java index 21af318..9817dcd 100644 --- a/src/main/java/com/pi4j/devices/ads1256/ADS1256App.java +++ b/src/main/java/com/pi4j/devices/ads1256/ADS1256App.java @@ -46,158 +46,158 @@ public class ADS1256App { - public static void main(String[] args) throws InterruptedException, IOException { - var console = new Console(); - Context pi4j = Pi4J.newAutoContext(); - - double vref = 0; - String ppName = "AINCOM"; - String pnName = "AINCOM"; - - boolean crtRestart = false; - boolean crtPdwn = false; - int drdyPin = 42; - int csPin = 42; - int rsrtPin = 42; - int pdwnPin = 42; - boolean resetChip = false; - SpiChipSelect chipSelect = SpiChipSelect.CS_0; - SpiBus spiBus = SpiBus.BUS_0; - DigitalState newState = DigitalState.UNKNOWN; - boolean setPinState = false; - boolean readPin = false; - - int gpiopPin = 42; - - console.title("<-- The Pi4J V2 Project Extension -->", "MCP3008App"); - String helpString = " parms: -vref decimal reference voltage \n" + - "-rst resetPin -cs chipSelectPin -drdy drdyPin -pdwn syn/pwrdPin \n" + - " -pp -pn AIN0 AIN1 AIN2 AIN3 AIN4 AIN5 AIN6 AIN7 AINCOM -x reset \n" + - " -p gpio pin number -rp read \"-p\" -sp set state \"-p\" HIGH/LOW \n" + - " -s HEX value SPI # -t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; - - String traceLevel = "info"; - for (int i = 0; i < args.length; i++) { - String o = args[i]; - if (o.contentEquals("-vref")) { // reference voltage - String a = args[i + 1]; - i++; - vref = Float.parseFloat(a); - } else if (o.contentEquals("-p")) { // pin number - String a = args[i + 1]; - i++; - gpiopPin = Integer.parseInt(a); - if (gpiopPin > 3) { - console.println("Invalid GPIO pin number : " + gpiopPin); - System.exit(45); - } - } else if (o.contentEquals("-rp")) { // read -p - readPin = true; - } else if (o.contentEquals("-sp")) { // set state of -p - String a = args[i + 1]; - i++; - if (a.contentEquals("HIGH")) { - newState = DigitalState.HIGH; - setPinState = true; - } else if (a.contentEquals("LOW")) { - newState = DigitalState.LOW; - setPinState = true; - } else { - console.println("Seting pin state invalid : " + a); - System.exit(44); - } - } else if (o.contentEquals("-rst")) { // device address - String a = args[i + 1]; - i++; - rsrtPin = Integer.parseInt(a); - crtRestart = true; - } else if (o.contentEquals("-cs")) { // device address - String a = args[i + 1]; - i++; - csPin = Integer.parseInt(a); - } else if (o.contentEquals("-drdy")) { // device address - String a = args[i + 1]; - i++; - drdyPin = Integer.parseInt(a); - } else if (o.contentEquals("-pdwn")) { // device address - String a = args[i + 1]; - i++; - pdwnPin = Integer.parseInt(a); - crtPdwn = true; - } else if (o.contentEquals("-cNotUsed")) { - String a = args[i + 1]; - chipSelect = SpiChipSelect.getByNumber(Short.parseShort(a.substring(2), 16)); - i++; - } else if (o.contentEquals("-x")) { - resetChip = true; - } else if (o.contentEquals("-s")) { - String a = args[i + 1]; - spiBus = SpiBus.getByNumber(Short.parseShort(a.substring(2), 16)); - i++; - } else if (o.contentEquals("-t")) { // device address - String a = args[i + 1]; - i++; - traceLevel = a; - if (a.contentEquals("trace") | a.contentEquals("debug") | a.contentEquals("info") | a.contentEquals("warn") | a.contentEquals("error") | a.contentEquals("off")) { - console.println("Changing trace level to : " + traceLevel); - } else { - console.println("Changing trace level invalid : " + traceLevel); - System.exit(41); - } - } else if (o.contentEquals("-pp")) { // pin positive - String a = args[i + 1]; - i++; - ppName = a; - if (a.contentEquals("AIN0") | a.contentEquals("AIN1") | a.contentEquals("AIN2") | a.contentEquals("AIN3") | a.contentEquals("AIN4") | a.contentEquals("AIN5") | a.contentEquals("AIN6") | a.contentEquals("AIN7") | a.contentEquals("AINCOM")) { - } else { - console.println("-pp invalid : " + ppName); - System.exit(42); - } - } else if (o.contentEquals("-pn")) { // pin positive - String a = args[i + 1]; - i++; - pnName = a; - if (a.contentEquals("AIN0") | a.contentEquals("AIN1") | a.contentEquals("AIN2") | a.contentEquals("AIN3") | a.contentEquals("AIN4") | a.contentEquals("AIN5") | a.contentEquals("AIN6") | a.contentEquals("AIN7") | a.contentEquals("AINCOM")) { - } else { - console.println("-pn invalid : " + pnName); - System.exit(43); - } - } else if (o.contentEquals("-h")) { - console.println(helpString); - System.exit(44); - } else { - console.println(" !!! Invalid Parm " + o); - console.println(helpString); - System.exit(45); - } - } - - - short pinCount = 8; - console.println("----------------------------------------------------------"); - console.println("PI4J PROVIDERS"); - console.println("----------------------------------------------------------"); - pi4j.providers().describe().print(System.out); - System.out.println("----------------------------------------------------------"); - - ADS1256 spiCls = new ADS1256(pi4j, spiBus, chipSelect, resetChip, drdyPin, csPin, rsrtPin, crtRestart, pdwnPin, crtPdwn, console, traceLevel, vref); - - - spiCls.validateChipID(); - - if (readPin) { - spiCls.setGpioDirIn(gpiopPin); - console.println(" pin " + gpiopPin + " state : " +spiCls.readGpio(gpiopPin)); - } else if (setPinState) { - spiCls.setGpioDirOut(gpiopPin); - console.println(" pin " + gpiopPin + " rval " + spiCls.setGpio(gpiopPin, newState)); - } else { - double rtn = spiCls.getADS1256State(ppName, pnName); - System.out.println("getMCP3008State returned : channel :" + ppName + "/" + pnName + " value :" + rtn); - - spiCls.displayADS1256State(ppName, pnName); - } - } + public static void main(String[] args) throws InterruptedException, IOException { + var console = new Console(); + Context pi4j = Pi4J.newAutoContext(); + + double vref = 0; + String ppName = "AINCOM"; + String pnName = "AINCOM"; + + boolean crtRestart = false; + boolean crtPdwn = false; + int drdyPin = 42; + int csPin = 42; + int rsrtPin = 42; + int pdwnPin = 42; + boolean resetChip = false; + SpiChipSelect chipSelect = SpiChipSelect.CS_0; + SpiBus spiBus = SpiBus.BUS_0; + DigitalState newState = DigitalState.UNKNOWN; + boolean setPinState = false; + boolean readPin = false; + + int gpiopPin = 42; + + console.title("<-- The Pi4J V2 Project Extension -->", "MCP3008App"); + String helpString = " parms: -vref decimal reference voltage \n" + + "-rst resetPin -cs chipSelectPin -drdy drdyPin -pdwn syn/pwrdPin \n" + + " -pp -pn AIN0 AIN1 AIN2 AIN3 AIN4 AIN5 AIN6 AIN7 AINCOM -x reset \n" + + " -p gpio pin number -rp read \"-p\" -sp set state \"-p\" HIGH/LOW \n" + + " -s HEX value SPI # -t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; + + String traceLevel = "info"; + for (int i = 0; i < args.length; i++) { + String o = args[i]; + if (o.contentEquals("-vref")) { // reference voltage + String a = args[i + 1]; + i++; + vref = Float.parseFloat(a); + } else if (o.contentEquals("-p")) { // pin number + String a = args[i + 1]; + i++; + gpiopPin = Integer.parseInt(a); + if (gpiopPin > 3) { + console.println("Invalid GPIO pin number : " + gpiopPin); + System.exit(45); + } + } else if (o.contentEquals("-rp")) { // read -p + readPin = true; + } else if (o.contentEquals("-sp")) { // set state of -p + String a = args[i + 1]; + i++; + if (a.contentEquals("HIGH")) { + newState = DigitalState.HIGH; + setPinState = true; + } else if (a.contentEquals("LOW")) { + newState = DigitalState.LOW; + setPinState = true; + } else { + console.println("Seting pin state invalid : " + a); + System.exit(44); + } + } else if (o.contentEquals("-rst")) { // device address + String a = args[i + 1]; + i++; + rsrtPin = Integer.parseInt(a); + crtRestart = true; + } else if (o.contentEquals("-cs")) { // device address + String a = args[i + 1]; + i++; + csPin = Integer.parseInt(a); + } else if (o.contentEquals("-drdy")) { // device address + String a = args[i + 1]; + i++; + drdyPin = Integer.parseInt(a); + } else if (o.contentEquals("-pdwn")) { // device address + String a = args[i + 1]; + i++; + pdwnPin = Integer.parseInt(a); + crtPdwn = true; + } else if (o.contentEquals("-cNotUsed")) { + String a = args[i + 1]; + chipSelect = SpiChipSelect.getByNumber(Short.parseShort(a.substring(2), 16)); + i++; + } else if (o.contentEquals("-x")) { + resetChip = true; + } else if (o.contentEquals("-s")) { + String a = args[i + 1]; + spiBus = SpiBus.getByNumber(Short.parseShort(a.substring(2), 16)); + i++; + } else if (o.contentEquals("-t")) { // device address + String a = args[i + 1]; + i++; + traceLevel = a; + if (a.contentEquals("trace") | a.contentEquals("debug") | a.contentEquals("info") | a.contentEquals("warn") | a.contentEquals("error") | a.contentEquals("off")) { + console.println("Changing trace level to : " + traceLevel); + } else { + console.println("Changing trace level invalid : " + traceLevel); + System.exit(41); + } + } else if (o.contentEquals("-pp")) { // pin positive + String a = args[i + 1]; + i++; + ppName = a; + if (a.contentEquals("AIN0") | a.contentEquals("AIN1") | a.contentEquals("AIN2") | a.contentEquals("AIN3") | a.contentEquals("AIN4") | a.contentEquals("AIN5") | a.contentEquals("AIN6") | a.contentEquals("AIN7") | a.contentEquals("AINCOM")) { + } else { + console.println("-pp invalid : " + ppName); + System.exit(42); + } + } else if (o.contentEquals("-pn")) { // pin positive + String a = args[i + 1]; + i++; + pnName = a; + if (a.contentEquals("AIN0") | a.contentEquals("AIN1") | a.contentEquals("AIN2") | a.contentEquals("AIN3") | a.contentEquals("AIN4") | a.contentEquals("AIN5") | a.contentEquals("AIN6") | a.contentEquals("AIN7") | a.contentEquals("AINCOM")) { + } else { + console.println("-pn invalid : " + pnName); + System.exit(43); + } + } else if (o.contentEquals("-h")) { + console.println(helpString); + System.exit(44); + } else { + console.println(" !!! Invalid Parm " + o); + console.println(helpString); + System.exit(45); + } + } + + + short pinCount = 8; + console.println("----------------------------------------------------------"); + console.println("PI4J PROVIDERS"); + console.println("----------------------------------------------------------"); + pi4j.providers().describe().print(System.out); + System.out.println("----------------------------------------------------------"); + + ADS1256 spiCls = new ADS1256(pi4j, spiBus, chipSelect, resetChip, drdyPin, csPin, rsrtPin, crtRestart, pdwnPin, crtPdwn, console, traceLevel, vref); + + + spiCls.validateChipID(); + + if (readPin) { + spiCls.setGpioDirIn(gpiopPin); + console.println(" pin " + gpiopPin + " state : " + spiCls.readGpio(gpiopPin)); + } else if (setPinState) { + spiCls.setGpioDirOut(gpiopPin); + console.println(" pin " + gpiopPin + " rval " + spiCls.setGpio(gpiopPin, newState)); + } else { + double rtn = spiCls.getADS1256State(ppName, pnName); + System.out.println("getMCP3008State returned : channel :" + ppName + "/" + pnName + " value :" + rtn); + + spiCls.displayADS1256State(ppName, pnName); + } + } } \ No newline at end of file diff --git a/src/main/java/com/pi4j/devices/ads1256/ADS1256_Declares.java b/src/main/java/com/pi4j/devices/ads1256/ADS1256_Declares.java index 173cfbd..97fff02 100644 --- a/src/main/java/com/pi4j/devices/ads1256/ADS1256_Declares.java +++ b/src/main/java/com/pi4j/devices/ads1256/ADS1256_Declares.java @@ -39,51 +39,51 @@ public class ADS1256_Declares { - protected final static int WAKEUP = 0b00000000; // wakeup/exist standby - protected final static int RDATA = 0b00000001; // read conversion data - protected final static int RDDATC = 0b00000011; // read conv data continuously - protected final static int SDATAC = 0b00001111; // stop read continuously - protected final static int RREG = 0b00010000; // read register(s) - protected final static int WREG = 0b01010000; // write register(s) - protected final static int SELFCAL = 0b11110000; // offset/gain self calibration - protected final static int SELFOCAL = 0b11110001; // offset self calibration - protected final static int SELFGCAL = 0b11110010; // gain self calibration - protected final static int SYSOCAL = 0b11110011; //system offset calibration - protected final static int SYSGCAL = 0b11110100; // system gain calibration - protected final static int SYNC = 0b11111100; // sync A/D converstion - protected final static int STANDBY = 0b11111101; // begin standby - protected final static int RESET = 0b11111110; // reset chip - protected final static int WAKEUPb = 0b11111111; // wakeup/exist standby + protected final static int WAKEUP = 0b00000000; // wakeup/exist standby + protected final static int RDATA = 0b00000001; // read conversion data + protected final static int RDDATC = 0b00000011; // read conv data continuously + protected final static int SDATAC = 0b00001111; // stop read continuously + protected final static int RREG = 0b00010000; // read register(s) + protected final static int WREG = 0b01010000; // write register(s) + protected final static int SELFCAL = 0b11110000; // offset/gain self calibration + protected final static int SELFOCAL = 0b11110001; // offset self calibration + protected final static int SELFGCAL = 0b11110010; // gain self calibration + protected final static int SYSOCAL = 0b11110011; //system offset calibration + protected final static int SYSGCAL = 0b11110100; // system gain calibration + protected final static int SYNC = 0b11111100; // sync A/D converstion + protected final static int STANDBY = 0b11111101; // begin standby + protected final static int RESET = 0b11111110; // reset chip + protected final static int WAKEUPb = 0b11111111; // wakeup/exist standby - protected final static int GPIO_0_IS_IN = 0b00010000; // cfg for input - protected final static int GPIO_1_IS_IN = 0b00100000; // cfg for input - protected final static int GPIO_2_IS_IN = 0b01000000; // cfg for input - protected final static int GPIO_3_IS_IN = 0b10000000; // cfg for input + protected final static int GPIO_0_IS_IN = 0b00010000; // cfg for input + protected final static int GPIO_1_IS_IN = 0b00100000; // cfg for input + protected final static int GPIO_2_IS_IN = 0b01000000; // cfg for input + protected final static int GPIO_3_IS_IN = 0b10000000; // cfg for input - protected final static int GPIO_0_MASK = 0b00000001; // bit mask - protected final static int GPIO_1_MASK = 0b00000010; // bit mask - protected final static int GPIO_2_MASK = 0b00000100; // bit mask - protected final static int GPIO_3_MASK = 0b00001000; // bit mask + protected final static int GPIO_0_MASK = 0b00000001; // bit mask + protected final static int GPIO_1_MASK = 0b00000010; // bit mask + protected final static int GPIO_2_MASK = 0b00000100; // bit mask + protected final static int GPIO_3_MASK = 0b00001000; // bit mask - protected final static int STATUS_ACAL = 0b00000100; // enable auto calibrate + protected final static int STATUS_ACAL = 0b00000100; // enable auto calibrate protected final static int STATUS_DRDY_MASK = 0b00000001; // Mask off DRDY status bit - protected final static int REG_STATUS = 0x00; - protected final static int REG_MUX = 0x01; - protected final static int REG_ADCON = 0x02; - protected final static int REG_DRATE = 0x03; - protected final static int REG_IO = 0x04; - protected final static int REG_OFC0 = 0x05; - protected final static int REG_OFC1 = 0x06; - protected final static int REG_OFC2 = 0x07; - protected final static int REG_FSC0 = 0x08; - protected final static int REG_FSC1 = 0x09; - protected final static int REG_FSC2 = 0x0A; + protected final static int REG_STATUS = 0x00; + protected final static int REG_MUX = 0x01; + protected final static int REG_ADCON = 0x02; + protected final static int REG_DRATE = 0x03; + protected final static int REG_IO = 0x04; + protected final static int REG_OFC0 = 0x05; + protected final static int REG_OFC1 = 0x06; + protected final static int REG_OFC2 = 0x07; + protected final static int REG_FSC0 = 0x08; + protected final static int REG_FSC1 = 0x09; + protected final static int REG_FSC2 = 0x0A; - protected final static int CHIP_ID = 0x03; + protected final static int CHIP_ID = 0x03; } diff --git a/src/main/java/com/pi4j/devices/ads1256/README.md b/src/main/java/com/pi4j/devices/ads1256/README.md index b06f3f2..db5b3fa 100644 --- a/src/main/java/com/pi4j/devices/ads1256/README.md +++ b/src/main/java/com/pi4j/devices/ads1256/README.md @@ -1,28 +1,24 @@ - -# Pi4J_V2-ADS1256 +# Pi4J_V2-ADS1256 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runADS1256.sh -Note_0 Within the code of this application, The use of -rp or -sp and -all AD/DA parms will be ignored - +Note_0 Within the code of this application, The use of -rp or -sp and +all AD/DA parms will be ignored -Tested -ADS1256 module mounted. The chip I have has no vref input pin and no labeling +Tested +ADS1256 module mounted. The chip I have has no vref input pin and no labeling nor documentation. Used a VOM to map lines from the ADS1256 to external pins -It appears the DVdd 5V is used as the V-reference. - - +It appears the DVdd 5V is used as the V-reference. --Connections --Chip connected to SPI0 -Pi----------------Module pin number----------------------Pi ---3.3V-----------AIN0 ch0----------P1 Syn/PwrD--------------3.3V tie high ---5v------------ AIN1 ch1----------P2 CS-----------------GPIO22 Chip select +--3.3V-----------AIN0 ch0----------P1 Syn/PwrD--------------3.3V tie high +--5v------------ AIN1 ch1----------P2 CS-----------------GPIO22 Chip select -----------------AIN2 ch2----------P3 DRDY----------------PIO17 ------------------AIN3 ch3----------P4 Dout---------------GPIO9 MISO +-----------------AIN3 ch3----------P4 Dout---------------GPIO9 MISO -----------------AIN4 ch4----------P5 Din----------------GPIO10 MOSI -----------------AIN5 ch5----------P6 Sclk----------------GPIO11 SCLK -----------------AIN6 ch6----------P7 Agnd----------------Gnd @@ -30,100 +26,82 @@ It appears the DVdd 5V is used as the V-reference. -----------------D0 -----------------D1 -----------------D2 ------------------D3 +-----------------D3 -The Syn/PwrD is tied high. The program does not use the Sync pin to initiate -a conversion, rather the issue the SYNC and WAKEUP commands. -This module does not expose the RESET line. +The Syn/PwrD is tied high. The program does not use the Sync pin to initiate +a conversion, rather the issue the SYNC and WAKEUP commands. +This module does not expose the RESET line. Also note, the ChipSelect 'CS' uses GPIO22, not the Pi normal CS0 or CS1 associated with SPI0. Required as operations span more than a single SPI function and the chip must remain selected. -cs and -drdy required for this chip configuration. --rst and -pdwn should not be used +-rst and -pdwn should not be used -sudo ./runADS1256.sh -pp AIN0 -pn AIN1 -cs 22 -drdy 17 -t trace -x - -No reset pin and no powerDown pin omitt -rst 18 -pdwn 27 +sudo ./runADS1256.sh -pp AIN0 -pn AIN1 -cs 22 -drdy 17 -t trace -x +No reset pin and no powerDown pin omitt -rst 18 -pdwn 27 sudo ./runADS1256.sh -pp AIN1 -pn AINCOM -cs 22 -drdy 17 -t trace -x -vref 5.0 -TRACE com.pi4j.devices.ads1256.ADS1256 Channel :1/8 value :8388607 -INFO com.pi4j.devices.ads1256.ADS1256 - A/D read input voltage : 5.0 - +TRACE com.pi4j.devices.ads1256.ADS1256 Channel :1/8 value :8388607 +INFO com.pi4j.devices.ads1256.ADS1256 - A/D read input voltage : 5.0 -sudo ./runADS1256.sh -pp AIN1 -pn AINCOM -cs 22 -drdy 17 -t trace -x -vref 5.0 +sudo ./runADS1256.sh -pp AIN1 -pn AINCOM -cs 22 -drdy 17 -t trace -x -vref 5.0 -TRACE com.pi4j.devices.ads1256.ADS1256 Channel :0/8 value :5441076 +TRACE com.pi4j.devices.ads1256.ADS1256 Channel :0/8 value :5441076 INFO com.pi4j.devices.ads1256.ADS1256 - A/D read input voltage : 3.243134408370782 +sudo ./runADS1256.sh -pp AIN1 -pn AIN0 -cs 22 -drdy 17 -t trace -x -vref 5.0 +TRACE com.pi4j.devices.ads1256.ADS1256 - Channel :1/0 value :3031976 +INFO com.pi4j.devices.ads1256.ADS1256 - A/D read input voltage : 1.8071987399099756 -sudo ./runADS1256.sh -pp AIN1 -pn AIN0 -cs 22 -drdy 17 -t trace -x -vref 5.0 -TRACE com.pi4j.devices.ads1256.ADS1256 - Channel :1/0 value :3031976 -INFO com.pi4j.devices.ads1256.ADS1256 - A/D read input voltage : 1.8071987399099756 - - - - --vref option: if > 0, feature will display calculated Channel input voltage. - - +-vref option: if > 0, feature will display calculated Channel input voltage. - - - - - - -ADS1256 module mounted within Waveshare AD/DA board +ADS1256 module mounted within Waveshare AD/DA board Chip connected to SPI0 Pi---------------AD/DA---BOARD---------------------------Pi -10K-pot-5V------ch0----------P13----Syn/PwrD------------GPIO 27 --LDR-------------ch1----------P15----CS------------------GPIO22 Chip select +-LDR-------------ch1----------P15----CS------------------GPIO22 Chip select -----------------ch2----------P11----DRDY----------------GPIO17 ------------------ch3----------P21----Dout----------------GPIO9 MISO +-----------------ch3----------P21----Dout----------------GPIO9 MISO -----------------ch4----------P19----Din-----------------GPIO10 MOSI -----------------ch5----------P23----Sclk----------------GPIO11 SCLK -----------------ch6----------P6-----Agnd----------------Gnd ------------------ch7----------P2-----DVdd----------------5V See Note_1 +-----------------ch7----------P2-----DVdd----------------5V See Note_1 -GPIO26----------D0-----------P12----RESET---------------GPIO18 -GPIO19----------D1 -GPIO13----------D2 --GPIO6-----------D3 +-GPIO6-----------D3 -The Syn/PwrD is configured as HIGH under all conditions. The program does not -use the Sync pin to initiate a conversion, rather to issue the -SYNC and WAKEUP commands. +The Syn/PwrD is configured as HIGH under all conditions. The program does not +use the Sync pin to initiate a conversion, rather to issue the +SYNC and WAKEUP commands. -Also note, the ChipSelect 'CS' uses GPIO22, not the Pi normal CS0 or CS1 -associated with SPI0. Required as operations span more than a single SPI +Also note, the ChipSelect 'CS' uses GPIO22, not the Pi normal CS0 or CS1 +associated with SPI0. Required as operations span more than a single SPI function and the chip must remain selected. --cs -drdy -rst and -pdwn required for this chip configuration. - -sudo ./runADS1256.sh -pp AIN1 -pn AINCOM -cs 22 -drdy 17 -rst 18 -pdwn 27 -t trace -x -vref 5.0 - - --vref option: if > 0, feature will display calculated Channel input voltage. +-cs -drdy -rst and -pdwn required for this chip configuration. +sudo ./runADS1256.sh -pp AIN1 -pn AINCOM -cs 22 -drdy 17 -rst 18 -pdwn 27 -t trace -x -vref 5.0 +-vref option: if > 0, feature will display calculated Channel input voltage. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -NOTE_1 !!!!!! ADS1256 must operate with Vcc 3.3v. Needed to be compatible with Pi logic voltage +NOTE_1 !!!!!! ADS1256 must operate with Vcc 3.3v. Needed to be compatible with Pi logic voltage !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -!!!!! WARNING: WHen the AD/DA bard is strapped VCC-3.3, the Pi4 may not power on. Seems the drag -on the 3.3v prevents the Pi boot. - +!!!!! WARNING: WHen the AD/DA bard is strapped VCC-3.3, the Pi4 may not power on. Seems the drag +on the 3.3v prevents the Pi boot. -DRDY low ->> data conversion complete, RDATA 24 bits. +DRDY low ->> data conversion complete, RDATA 24 bits. ->>>>Single shot -WREG set channel -STANDBY cmd -WAKEUP -delay 33 microSeconds -DRDY low -RDATA -STANDBY +> > > > Single shot +> > > > WREG set channel +> > > > STANDBY cmd +> > > > WAKEUP +> > > > delay 33 microSeconds +> > > > DRDY low +> > > > RDATA +> > > > STANDBY diff --git a/src/main/java/com/pi4j/devices/appConfig/AppConfigTest.java b/src/main/java/com/pi4j/devices/appConfig/AppConfigTest.java index acb393f..c59b130 100644 --- a/src/main/java/com/pi4j/devices/appConfig/AppConfigTest.java +++ b/src/main/java/com/pi4j/devices/appConfig/AppConfigTest.java @@ -21,7 +21,7 @@ /** * Testcase */ -public class AppConfigTest extends AppConfigUtilities{ +public class AppConfigTest extends AppConfigUtilities { /** * CTOR. @@ -37,19 +37,19 @@ public class AppConfigTest extends AppConfigUtilities{ *

* PostCond: Class methods are now accessable */ - public AppConfigTest(Context pi4j, FfdcUtil ffdc, BaseGpioInOut gUtil, Console console) { - super(pi4j, ffdc,gUtil, console); + public AppConfigTest(Context pi4j, FfdcUtil ffdc, BaseGpioInOut gUtil, Console console) { + super(pi4j, ffdc, gUtil, console); } /** * usage Display help text for using this program *

- * PreCond: AppConfigUtilities instance initialized. See CTOR + * PreCond: AppConfigUtilities instance initialized. See CTOR */ public void usage() { System.out.println("options -h 'help', -b bus, -a address, -z mainChip " + "-c chipName -p pinName " - + " -x reset-chip -n reset GPIO -f ffdcLvl -g gpiodict -m mcp23xx_pin_onfig -s log"); + + " -x reset-chip -n reset GPIO -f ffdcLvl -g gpiodict -m mcp23xx_pin_onfig -s log"); } @@ -78,7 +78,7 @@ public static void main(String[] args) { gUtil.dumpHashMap(); MapUtil mapUtils = new MapUtil(ffdc, gUtil); - AppConfigTest cfgU = new AppConfigTest(pi4j, ffdc, gUtil, console); + AppConfigTest cfgU = new AppConfigTest(pi4j, ffdc, gUtil, console); // later in this function, the device address and bus number will be properly set boolean returned = false; @@ -144,10 +144,7 @@ public static void main(String[] args) { String chipBus = chipD.get("busNum"); String chipAddr = chipD.get("address"); - boolean isBanked = false; - if (banked.equalsIgnoreCase("y")) { - isBanked = true; - } + boolean isBanked = banked.equalsIgnoreCase("y"); int chipAddrInt = Integer.parseInt(chipAddr.substring(2), 16); McpConfigData mcpcfgD = new McpConfigData(cfgU.ffdc); Mcp23xxxParms parmsObj = Mcp23xxxAppProcessParms.processMain(pi4j, args, true, dioPinData, console); @@ -160,7 +157,7 @@ public static void main(String[] args) { } Mcp23xxxUtil mcpUtil = new Mcp23xxxUtil(pi4j, cfgU.ffdc, Integer.parseInt(initialChipBus.substring(2), 16), - chipAddrInt, mcpcfgD, mcpObj, console); + chipAddrInt, mcpcfgD, mcpObj, console); if (cfgU.hasFullKeyedData) { cfgU.ffdc.ffdcDebugEntry("Start of hasFullKeyedData"); HashMap> outerMap = cfgU.mapUtils.createFullMap(cfgU.fullKeyedData); @@ -280,10 +277,7 @@ public static void main(String[] args) { String chipBus2 = chipD2.get("busNum"); String chipAddr2 = chipD2.get("address"); - boolean isBanked2 = false; - if (banked2.equalsIgnoreCase("y")) { - isBanked2 = true; - } + boolean isBanked2 = banked2.equalsIgnoreCase("y"); if (isBanked2) { console.println("Drive pin15 high"); mcpUtil.drivePin(15, true); @@ -318,7 +312,7 @@ public static void main(String[] args) { cfgU.disableBus(7, mainBus, mainChip); // - if (isBanked == false) { + if (!isBanked) { boolean eChip = cfgU.enableChipPath("matrix#1"); console.println("matrix#1 bus 7"); cfgU.displayEnableReg(mainBus, mainChip); diff --git a/src/main/java/com/pi4j/devices/appConfig/AppConfigUtilities.java b/src/main/java/com/pi4j/devices/appConfig/AppConfigUtilities.java index 6df7557..bbc459b 100644 --- a/src/main/java/com/pi4j/devices/appConfig/AppConfigUtilities.java +++ b/src/main/java/com/pi4j/devices/appConfig/AppConfigUtilities.java @@ -35,42 +35,39 @@ package com.pi4j.devices.appConfig; -import java.io.BufferedReader; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashMap; -import java.util.logging.LogManager; - -import com.pi4j.devices.base_util.gpio.BaseGpioInOut; -import com.pi4j.devices.base_util.mapUtil.MapUtil; - import com.pi4j.context.Context; import com.pi4j.devices.base_util.ffdc.FfdcUtil; +import com.pi4j.devices.base_util.gpio.BaseGpioInOut; import com.pi4j.devices.base_util.gpio.GpioPinCfgData; +import com.pi4j.devices.base_util.mapUtil.MapUtil; import com.pi4j.devices.tca9548.Tca9548; import com.pi4j.devices.tca9548.Tca9548ConfigData; import com.pi4j.util.Console; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.logging.LogManager; + /** *

AppConfigUtilities

Utilities for the configuration of an I2C chip. * Provides details such as: The location of a chip, is it connected directly * to the Pi, or behind a mux/switch. If behind a mux/switch, id for that * mux/switch and what bus on the mux/switch. - * + *

* Also implements various methods that enable the path from the pi bus * the chip. So if the pin/chip that is required is in the configuration files * the path from the proper Pi I2C bus will be connected including any required * mux/switch being configured. - * + *

* Supports i2c access to the register(s). Individual methods support enable and * disabling individual buses. In addition a method support the performing a chip reset. *

* The code is written with use of the datasheet available on the WEB. * TCA9548A Low-Voltage 8-Channel I2C Switch with Reset datasheet (Rev. G) - * */ public class AppConfigUtilities { @@ -89,33 +86,33 @@ public class AppConfigUtilities { *

* PostCond: Class methods are now accessable */ - public AppConfigUtilities(Context pi4j, FfdcUtil ffdc, BaseGpioInOut gUtil, Console console) { - LogManager lm = LogManager.getLogManager(); - this.busNumTemp = 0xff; - this.addressTemp = 0xff; - this.console = console; - this.pi4j = pi4j; - this.ffdc = ffdc; - this.hasFullKeyedData = false; - this.hasFullPinKeyedData = false; - this.mapUtils = new MapUtil( ffdc, gUtil); - this.dioPinData = gUtil.pinDict; - ChipNameMap cMap = new ChipNameMap(); - String chips = cMap.readProperties(); - this.chipMap = this.mapUtils.createFullMap(chips); - - GpioToApp gMap = new GpioToApp(); - String pins = gMap.readProperties(); - this.pinMap = this.mapUtils.createXtraFullMap(pins); - - PiPinMap pMap = new PiPinMap(); - String piPins = pMap.readProperties(); - this.piPinMap = this.mapUtils.createFullMap(piPins); - - - this.init(); + public AppConfigUtilities(Context pi4j, FfdcUtil ffdc, BaseGpioInOut gUtil, Console console) { + LogManager lm = LogManager.getLogManager(); + this.busNumTemp = 0xff; + this.addressTemp = 0xff; + this.console = console; + this.pi4j = pi4j; + this.ffdc = ffdc; + this.hasFullKeyedData = false; + this.hasFullPinKeyedData = false; + this.mapUtils = new MapUtil(ffdc, gUtil); + this.dioPinData = gUtil.pinDict; + ChipNameMap cMap = new ChipNameMap(); + String chips = cMap.readProperties(); + this.chipMap = this.mapUtils.createFullMap(chips); + + GpioToApp gMap = new GpioToApp(); + String pins = gMap.readProperties(); + this.pinMap = this.mapUtils.createXtraFullMap(pins); + + PiPinMap pMap = new PiPinMap(); + String piPins = pMap.readProperties(); + this.piPinMap = this.mapUtils.createFullMap(piPins); + + + this.init(); - } + } /** * init. @@ -125,9 +122,9 @@ public AppConfigUtilities(Context pi4j, FfdcUtil ffdc, BaseGpioInOut gUtil, Con *

* PostCond: AppConfigUtilities state set */ - private void init(){ - this.deviceMap = new HashMap>(); - } + private void init() { + this.deviceMap = new HashMap>(); + } /** @@ -136,40 +133,40 @@ private void init(){ * PreCond: AppConfigUtilities instance initialized. See CTOR * * - *

- * PostCond: If successful return true, else false. - *

- *

- * Note: register contents for disableBusNumber are effected, all other register - * contents are NOT modified. - *

+ *

+ * PostCond: If successful return true, else false. + *

+ *

+ * Note: register contents for disableBusNumber are effected, all other register + * contents are NOT modified. + *

*/ public void dumpDicts() { - ffdc.ffdcMethodEntry("dumpDicts"); - ffdc.ffdcDebugEntry("chipMap: " + this.chipMap); - ffdc.ffdcDebugEntry("pinMap: " + this.pinMap); - ffdc.ffdcDebugEntry("piPinMap: " + this.piPinMap); - ffdc.ffdcMethodExit("dumpDicts"); - } - + ffdc.ffdcMethodEntry("dumpDicts"); + ffdc.ffdcDebugEntry("chipMap: " + this.chipMap); + ffdc.ffdcDebugEntry("pinMap: " + this.pinMap); + ffdc.ffdcDebugEntry("piPinMap: " + this.piPinMap); + ffdc.ffdcMethodExit("dumpDicts"); + } /** * chipMapDetails Look up dictionary details for a chip *

* PreCond: AppConfigUtilities instance initialized. See CTOR + * * @param chipName String name of target chip *

* Will search the chipMap for this entry *

- * @return Dictionary of details for the 'key' chipName + * @return Dictionary of details for the 'key' chipName */ public HashMap chipMapDetails(String chipName) { this.ffdc.ffdcMethodEntry("getMapDetails Chip " + chipName); HashMap details = this.chipMap.get(chipName); this.ffdc.ffdcDebugEntry("chipMapDetails :" + details); this.ffdc.ffdcMethodExit("getMapDetails rval " + details); - return(details); + return (details); } @@ -178,40 +175,42 @@ public HashMap chipMapDetails(String chipName) { * on a particular chip chip *

* PreCond: AppConfigUtilities instance initialized. See CTOR + * * @param chipName String name of target chip - * @param pinName String name of target pin + * @param pinName String name of target pin *

* Will search the chipMap for the target chip - * the search the pinMap for the pin + * the search the pinMap for the pin *

- * @return Dictionary of details for the 'key' pin + * @return Dictionary of details for the 'key' pin */ public HashMap getPinMapDetails(String chipName, String pinName) { - this.ffdc.ffdcMethodEntry("getPinMapDetails Chip " + chipName + " pin " + pinName); - HashMap rval = null; - if (this.pinMap.containsKey(chipName)) { - HashMap> chipDetails = this.pinMap.get(chipName); - if (chipDetails.containsKey(pinName)) { - rval = chipDetails.get(pinName); - } + this.ffdc.ffdcMethodEntry("getPinMapDetails Chip " + chipName + " pin " + pinName); + HashMap rval = null; + if (this.pinMap.containsKey(chipName)) { + HashMap> chipDetails = this.pinMap.get(chipName); + if (chipDetails.containsKey(pinName)) { + rval = chipDetails.get(pinName); } - this.ffdc.ffdcMethodExit("getPinMapDetails rval " + rval); - return (rval); } + this.ffdc.ffdcMethodExit("getPinMapDetails rval " + rval); + return (rval); + } /** * buildTca9548 Create instance of Tca9548. Use class state. *

* PreCond: AppConfigUtilities instance initialized. See CTOR - * @return Tca9548 instantiated + * + * @return Tca9548 instantiated */ private Tca9548 buildTca9548() { - this.ffdc.ffdcMethodEntry("buildTca9548 "); - Tca9548 tcaObj = new Tca9548(this.pi4j,this.ffdc, this.busNumTemp, this.addressTemp, console); - this.ffdc.ffdcMethodExit("buildTca9548 : " + tcaObj); + this.ffdc.ffdcMethodEntry("buildTca9548 "); + Tca9548 tcaObj = new Tca9548(this.pi4j, this.ffdc, this.busNumTemp, this.addressTemp, console); + this.ffdc.ffdcMethodExit("buildTca9548 : " + tcaObj); - return (tcaObj); - } + return (tcaObj); + } /** * mapBus Using the param data, test if this chip is directly @@ -220,98 +219,98 @@ private Tca9548 buildTca9548() { * target chip is accessable *

* PreCond: AppConfigUtilities instance initialized. See CTOR - * @param target Dictionary entry defining the target. - * @return boolean to indicate success true, else false * + * @param target Dictionary entry defining the target. + * @return boolean to indicate success true, else false */ public boolean mapBus(HashMap target) { - this.ffdc.ffdcMethodEntry("mapBus target : " + target); - boolean rval = false; - if (this.chipMap.containsKey(target.get("chipName")) == false) { - this.ffdc.ffdcConfigWarningEntry("chipMap missing key : " + target.get("chipName")); - this.ffdc.ffdcErrorExit("",2006); - } else { - rval = true; - HashMap chipDetail = this.chipMap.get(target.get("chipName")); - - if (chipDetail.containsKey("behindMux")) { - String muxDev = chipDetail.get("behindMux"); - HashMap muxDetail = this.chipMap.get(muxDev); - String muxBus = muxDetail.get("busNum"); - String muxAddr = muxDetail.get("address"); - String chipBus = chipDetail.get("busNum"); - int muxAddrI = Integer.parseInt(muxAddr.substring(2), 16); - this.addressTemp = muxAddrI; - int muxBusI = Integer.parseInt(muxBus.substring(2), 16); - this.busNumTemp = muxBusI; - this.ffdc.ffdcDebugEntry("muxDev : " + muxDev + " muxBus :" + muxBus + " chipBus :" + chipBus); - if (muxDetail.get("pca").equals("9548")) { - // enable the bus - // I2cBase i2cDevice = null; - - Tca9548 tcaObj = this.prime9548(chipDetail); - this.ffdc.ffdcDebugEntry("tcaObj : " + tcaObj); - tcaObj.enableBus(Integer.parseInt(chipBus.substring(2), 16)); - } else { - rval = false; - this.ffdc.ffdcConfigWarningEntry("BehindMux device not supported " + muxDetail.get("pca")); - } - - } else { // just talk to the bus. - this.ffdc.ffdcDebugEntry("Not behind mux"); + this.ffdc.ffdcMethodEntry("mapBus target : " + target); + boolean rval = false; + if (!this.chipMap.containsKey(target.get("chipName"))) { + this.ffdc.ffdcConfigWarningEntry("chipMap missing key : " + target.get("chipName")); + this.ffdc.ffdcErrorExit("", 2006); + } else { + rval = true; + HashMap chipDetail = this.chipMap.get(target.get("chipName")); + + if (chipDetail.containsKey("behindMux")) { + String muxDev = chipDetail.get("behindMux"); + HashMap muxDetail = this.chipMap.get(muxDev); + String muxBus = muxDetail.get("busNum"); + String muxAddr = muxDetail.get("address"); + String chipBus = chipDetail.get("busNum"); + int muxAddrI = Integer.parseInt(muxAddr.substring(2), 16); + this.addressTemp = muxAddrI; + int muxBusI = Integer.parseInt(muxBus.substring(2), 16); + this.busNumTemp = muxBusI; + this.ffdc.ffdcDebugEntry("muxDev : " + muxDev + " muxBus :" + muxBus + " chipBus :" + chipBus); + if (muxDetail.get("pca").equals("9548")) { + // enable the bus + // I2cBase i2cDevice = null; + + Tca9548 tcaObj = this.prime9548(chipDetail); + this.ffdc.ffdcDebugEntry("tcaObj : " + tcaObj); + tcaObj.enableBus(Integer.parseInt(chipBus.substring(2), 16)); + } else { + rval = false; + this.ffdc.ffdcConfigWarningEntry("BehindMux device not supported " + muxDetail.get("pca")); } + + } else { // just talk to the bus. + this.ffdc.ffdcDebugEntry("Not behind mux"); } - this.ffdc.ffdcMethodExit("mapBus "); - return (rval); } + this.ffdc.ffdcMethodExit("mapBus "); + return (rval); + } /** * enableGpioPath Using the param data, get the data that describes * the chip. Ensure the bus associated with that chip is connected * to the Pi. * * PreCond: AppConfigUtilities instance initialized. See CTOR - * @param gpio Pin number. - * @param chip Chip containing the gpio - * @return boolean to indicate success true, else false * + * @param gpio Pin number. + * @param chip Chip containing the gpio + * @return boolean to indicate success true, else false */ public boolean enableGpioPath(String gpio, String chip) { - this.ffdc.ffdcMethodEntry("enableGpioPath gpio : " + gpio + " chip : " + chip); - boolean rval = false; - if (this.pinMap.containsKey(chip)) { - HashMap> chipDetails = this.pinMap.get(chip); - if (chipDetails.containsKey(gpio)) { - HashMap target = chipDetails.get(gpio); - rval = this.mapBus(target); - } else { - this.ffdc.ffdcConfigWarningEntry( - " enableGpioPath gpio : " + gpio + " chip : " + chip + " not contained in pinMap entry"); - } + this.ffdc.ffdcMethodEntry("enableGpioPath gpio : " + gpio + " chip : " + chip); + boolean rval = false; + if (this.pinMap.containsKey(chip)) { + HashMap> chipDetails = this.pinMap.get(chip); + if (chipDetails.containsKey(gpio)) { + HashMap target = chipDetails.get(gpio); + rval = this.mapBus(target); + } else { + this.ffdc.ffdcConfigWarningEntry( + " enableGpioPath gpio : " + gpio + " chip : " + chip + " not contained in pinMap entry"); } - this.ffdc.ffdcMethodExit("enableGpioPath gpio : " + gpio + " chip : " + chip + " rval : " + rval); - return (rval); } + this.ffdc.ffdcMethodExit("enableGpioPath gpio : " + gpio + " chip : " + chip + " rval : " + rval); + return (rval); + } /** * enableChipPath Using the param data, get the data that describes * the chip. Ensure the bus associated with that chip is connected * to the Pi. * * PreCond: AppConfigUtilities instance initialized. See CTOR - * @param chip Chip containing the gpio - * @return boolean to indicate success true, else false * + * @param chip Chip containing the gpio + * @return boolean to indicate success true, else false */ public boolean enableChipPath(String chip) { - this.ffdc.ffdcMethodEntry("enableChipPath chip : " + chip); - boolean rval = false; - HashMap chipDetails = this.getChipMapRec(chip); - if (chipDetails != null) { - rval = this.mapBus(chipDetails); - } - this.ffdc.ffdcMethodExit("enableChipPath chip : " + chip); - - return (rval); + this.ffdc.ffdcMethodEntry("enableChipPath chip : " + chip); + boolean rval = false; + HashMap chipDetails = this.getChipMapRec(chip); + if (chipDetails != null) { + rval = this.mapBus(chipDetails); } + this.ffdc.ffdcMethodExit("enableChipPath chip : " + chip); + + return (rval); + } /** * prime9548 Using the param data, get the required device address @@ -321,221 +320,225 @@ public boolean enableChipPath(String chip) { * else create a new TCA9548 instance. If a new instance is created * update the deviceMap. * * PreCond: AppConfigUtilities instance initialized. See CTOR - * @param chipDetails Chip details for the required TCA9548 - * @return Tca9548 * + * @param chipDetails Chip details for the required TCA9548 + * @return Tca9548 */ public Tca9548 prime9548(HashMap chipDetails) { - Tca9548 rObj = null; - this.ffdc.ffdcMethodEntry("prime9548 with " + chipDetails); - - String muxBus = chipDetails.get("busNum"); - String muxAddr = chipDetails.get("address"); - int muxAddrI = Integer.parseInt(muxAddr.substring(2), 16); // replace("0x", - // ""); - int muxBusI = Integer.parseInt(muxBus.substring(2), 16); // .replace("0x", - this.ffdc.ffdcDebugEntry("muxDev : " + muxAddr + " muxBus :" + muxBus); - // enable the bus - // I2cBase i2cDevice = null; - // test if instance already created - HashMap busDetails; - if(this.deviceMap.containsKey(muxBus)) { - busDetails = deviceMap.get(muxBus); - if (busDetails.containsKey(muxAddr)) { - Object mux = busDetails.get(muxAddr); - if (mux.getClass() == Tca9548.class) { - rObj = (Tca9548) mux; - this.ffdc.ffdcDebugEntry("tcaObj already exist :" + rObj); - } + Tca9548 rObj = null; + this.ffdc.ffdcMethodEntry("prime9548 with " + chipDetails); + + String muxBus = chipDetails.get("busNum"); + String muxAddr = chipDetails.get("address"); + int muxAddrI = Integer.parseInt(muxAddr.substring(2), 16); // replace("0x", + // ""); + int muxBusI = Integer.parseInt(muxBus.substring(2), 16); // .replace("0x", + this.ffdc.ffdcDebugEntry("muxDev : " + muxAddr + " muxBus :" + muxBus); + // enable the bus + // I2cBase i2cDevice = null; + // test if instance already created + HashMap busDetails; + if (this.deviceMap.containsKey(muxBus)) { + busDetails = deviceMap.get(muxBus); + if (busDetails.containsKey(muxAddr)) { + Object mux = busDetails.get(muxAddr); + if (mux.getClass() == Tca9548.class) { + rObj = (Tca9548) mux; + this.ffdc.ffdcDebugEntry("tcaObj already exist :" + rObj); } } - if(rObj == null) { - this.ffdc.ffdcDebugEntry("tcaObj must be created"); - rObj = this.buildTca9548(); - // create entry into the devceMap entry - HashMap + } + if (rObj == null) { + this.ffdc.ffdcDebugEntry("tcaObj must be created"); + rObj = this.buildTca9548(); + // create entry into the devceMap entry + HashMap innerMap = new HashMap(); - innerMap.put(muxAddr, rObj); - this.deviceMap.put(muxBus, innerMap); + innerMap.put(muxAddr, rObj); + this.deviceMap.put(muxBus, innerMap); - } - this.ffdc.ffdcDebugEntry("tcaObj : " + rObj); - // ""); - this.ffdc.ffdcMethodExit("prime9548 with " + chipDetails + " intp obj : " + rObj); - return rObj; } + this.ffdc.ffdcDebugEntry("tcaObj : " + rObj); + // ""); + this.ffdc.ffdcMethodExit("prime9548 with " + chipDetails + " intp obj : " + rObj); + return rObj; + } /** * displayEnableReg Using the param data bus and chip, get the * chip details from the chipMap. If chip is a TCA9548, get a reference * to that instance and call the method to display the bus enablement details. *

- * PreCond: AppConfigUtilities instance initialized. See CTOR - * @param bus bus number for the chip - * @param chip subject chip - * @return boolean If successful true, else false + * PreCond: AppConfigUtilities instance initialized. See CTOR + * + * @param bus bus number for the chip + * @param chip subject chip + * @return boolean If successful true, else false */ public boolean displayEnableReg(int bus, String chip) { - this.ffdc.ffdcMethodEntry("displayEnableReg in " + bus + "/" + chip); - boolean rval = false; - HashMap chipDetails = this.getChipMapRec(chip); - // make sure the chip is mapped onto the pi bus - if (chipDetails != null) { - this.mapBus(chipDetails); - if (chipDetails.get("pca").equals("9548")) { - // switch on chipType - Tca9548 tcaObj = this.prime9548(chipDetails); - tcaObj.displayBusEnable(); - rval = true; - } - } else { - this.ffdc.ffdcDebugEntry("No details for chip : " + chip); + this.ffdc.ffdcMethodEntry("displayEnableReg in " + bus + "/" + chip); + boolean rval = false; + HashMap chipDetails = this.getChipMapRec(chip); + // make sure the chip is mapped onto the pi bus + if (chipDetails != null) { + this.mapBus(chipDetails); + if (chipDetails.get("pca").equals("9548")) { + // switch on chipType + Tca9548 tcaObj = this.prime9548(chipDetails); + tcaObj.displayBusEnable(); + rval = true; } - this.ffdc.ffdcMethodExit("displayEnableReg "); - return (rval); + } else { + this.ffdc.ffdcDebugEntry("No details for chip : " + chip); } + this.ffdc.ffdcMethodExit("displayEnableReg "); + return (rval); + } /** * disableBus Using the param data bus and chip, get the * chip details from the chipMap. If chip is a TCA9548, get a reference * to that instance and call the method to disable bus disableBusNum *

- * PreCond: AppConfigUtilities instance initialized. See CTOR - * @param disableBusNum Bus to disable - * @param bus bus number for the chip - * @param chip subject chip - * @return boolean If successful true, else false + * PreCond: AppConfigUtilities instance initialized. See CTOR + * + * @param disableBusNum Bus to disable + * @param bus bus number for the chip + * @param chip subject chip + * @return boolean If successful true, else false */ public boolean disableBus(int disableBusNum, int bus, String chip) { - this.ffdc.ffdcMethodEntry("disableBus number " + disableBusNum + " in chip " + chip); - boolean rval = false; - HashMap chipDetails = this.getChipMapRec(chip); - if (chipDetails != null) { + this.ffdc.ffdcMethodEntry("disableBus number " + disableBusNum + " in chip " + chip); + boolean rval = false; + HashMap chipDetails = this.getChipMapRec(chip); + if (chipDetails != null) { + // switch on chipType + this.mapBus(chipDetails); + if (chipDetails.get("pca").equals("9548")) { // switch on chipType - this.mapBus(chipDetails); - if (chipDetails.get("pca").equals("9548")) { - // switch on chipType - Tca9548 tcaObj = this.prime9548(chipDetails); - this.ffdc.ffdcMethodEntry("tcaObj : " + tcaObj); - tcaObj.disableBus(disableBusNum); - rval = true; - } - } else { - this.ffdc.ffdcConfigWarningEntry("invalid bus/chip lookup " + bus + "/ " + chip); + Tca9548 tcaObj = this.prime9548(chipDetails); + this.ffdc.ffdcMethodEntry("tcaObj : " + tcaObj); + tcaObj.disableBus(disableBusNum); + rval = true; } - this.ffdc.ffdcMethodExit("disableBus " + rval); - return (rval); + } else { + this.ffdc.ffdcConfigWarningEntry("invalid bus/chip lookup " + bus + "/ " + chip); } + this.ffdc.ffdcMethodExit("disableBus " + rval); + return (rval); + } /** * enableBus Using the param data bus and chip, get the * chip details from the chipMap. If chip is a TCA9548, get a reference * to that instance and call the method to enable bus enableBusNum *

- * PreCond: AppConfigUtilities instance initialized. See CTOR - * @param enableBusNum Bus to enable - * @param bus bus number for the chip - * @param chip subject chip - * @return boolean If successful true, else false + * PreCond: AppConfigUtilities instance initialized. See CTOR + * + * @param enableBusNum Bus to enable + * @param bus bus number for the chip + * @param chip subject chip + * @return boolean If successful true, else false */ - public boolean enableBus(int enableBusNum, int bus, String chip) { - this.ffdc.ffdcMethodEntry("enableBus number " + enableBusNum + " in chip " + chip); - boolean rval = false; - HashMap chipDetails = this.getChipMapRec(chip); - if (chipDetails != null) { + public boolean enableBus(int enableBusNum, int bus, String chip) { + this.ffdc.ffdcMethodEntry("enableBus number " + enableBusNum + " in chip " + chip); + boolean rval = false; + HashMap chipDetails = this.getChipMapRec(chip); + if (chipDetails != null) { + // switch on chipType + this.mapBus(chipDetails); + if (chipDetails.get("pca").equals("9548")) { // switch on chipType - this.mapBus(chipDetails); - if (chipDetails.get("pca").equals("9548")) { - // switch on chipType - Tca9548 tcaObj = this.prime9548(chipDetails); - tcaObj.enableBus(enableBusNum); - rval = true; - } - } else { - this.ffdc.ffdcConfigWarningEntry("invalid bus/chip lookup " + bus + "/ " + chip); + Tca9548 tcaObj = this.prime9548(chipDetails); + tcaObj.enableBus(enableBusNum); + rval = true; } - this.ffdc.ffdcMethodExit("disableBus " + rval); - return (rval); + } else { + this.ffdc.ffdcConfigWarningEntry("invalid bus/chip lookup " + bus + "/ " + chip); } + this.ffdc.ffdcMethodExit("disableBus " + rval); + return (rval); + } /** * getChipMapRec Using the param data chip, get the * chip details from the chipMap. *

- * PreCond: AppConfigUtilities instance initialized. See CTOR - * @param chip subject chip - * @return chipeDetail dictionary + * PreCond: AppConfigUtilities instance initialized. See CTOR + * + * @param chip subject chip + * @return chipeDetail dictionary */ public HashMap getChipMapRec(String chip) { - this.ffdc.ffdcMethodEntry("getChipMapRec " + chip); - HashMap rval = null; - if (this.chipMap.containsKey(chip) == false) { - this.ffdc.ffdcErrorExit("chipMap missing key : " + chip, 2020); - } else { - rval = this.chipMap.get(chip); - // HashMap chipD = this.getChipMapRec(chip); - } - this.ffdc.ffdcMethodExit("getChipMapRec " + rval); - return (rval); + this.ffdc.ffdcMethodEntry("getChipMapRec " + chip); + HashMap rval = null; + if (!this.chipMap.containsKey(chip)) { + this.ffdc.ffdcErrorExit("chipMap missing key : " + chip, 2020); + } else { + rval = this.chipMap.get(chip); + // HashMap chipD = this.getChipMapRec(chip); } + this.ffdc.ffdcMethodExit("getChipMapRec " + rval); + return (rval); + } /** - * runCli Execute and display results of the i2cdetect CLI + * runCli Execute and display results of the i2cdetect CLI *

- * PreCond: AppConfigUtilities instance initialized. See CTOR + * PreCond: AppConfigUtilities instance initialized. See CTOR */ public void runCli() { - // build my command as a list of strings - ProcessBuilder processBuilder = new ProcessBuilder(); - - processBuilder.command("i2cdetect", "-y", "1"); - Process p = null; - try { - p = processBuilder.start(); - } catch (IOException e) { - e.printStackTrace(); - this.ffdc.ffdcErrorEntry("runCli failed"); - } + // build my command as a list of strings + ProcessBuilder processBuilder = new ProcessBuilder(); + + processBuilder.command("i2cdetect", "-y", "1"); + Process p = null; + try { + p = processBuilder.start(); + } catch (IOException e) { + e.printStackTrace(); + this.ffdc.ffdcErrorEntry("runCli failed"); + } - InputStream is = p.getInputStream(); - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - int line ; - try { - while ((line = br.read()) == -1) { - ffdc.ffdcConfigWarningEntry(is.toString()); - } - } catch (java.io.IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - this.ffdc.ffdcErrorEntry("runCli failed"); + InputStream is = p.getInputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + int line; + try { + while ((line = br.read()) == -1) { + ffdc.ffdcConfigWarningEntry(is.toString()); } + } catch (java.io.IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + this.ffdc.ffdcErrorEntry("runCli failed"); } + } - private final Context pi4j; - protected int busNumTemp; - protected int addressTemp; - private Console console; - HashMap>> pinMap; - HashMap> chipMap; - HashMap> piPinMap; - FfdcUtil ffdc; - String priChipName; - String pinName; - boolean hasFullKeyedData; - String fullKeyedData; - boolean hasFullPinKeyedData; - String fullPinKeyedData; - public BaseGpioInOut gpio; - public HashMap dioPinData; - public Tca9548ConfigData ConfigData; + private final Context pi4j; + protected int busNumTemp; + protected int addressTemp; + private final Console console; + HashMap>> pinMap; + HashMap> chipMap; + HashMap> piPinMap; + FfdcUtil ffdc; + String priChipName; + String pinName; + boolean hasFullKeyedData; + String fullKeyedData; + boolean hasFullPinKeyedData; + String fullPinKeyedData; + public BaseGpioInOut gpio; + public HashMap dioPinData; + public Tca9548ConfigData ConfigData; - public MapUtil mapUtils; + public MapUtil mapUtils; - // bUS0x? address0x?? 'someInstance - HashMap> deviceMap; + // bUS0x? address0x?? 'someInstance + HashMap> deviceMap; - } +} diff --git a/src/main/java/com/pi4j/devices/appConfig/ChipNameMap.java b/src/main/java/com/pi4j/devices/appConfig/ChipNameMap.java index 815ff4e..2bbd8f9 100644 --- a/src/main/java/com/pi4j/devices/appConfig/ChipNameMap.java +++ b/src/main/java/com/pi4j/devices/appConfig/ChipNameMap.java @@ -34,34 +34,25 @@ package com.pi4j.devices.appConfig; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; +import java.io.*; import java.util.Properties; /** *

ChipNameMap

- *

- * Defines each chip in the system. Characteristics like Pi bus number, - * Device address, Speed, if behind a mux/switch.... - * These details are used by the Application configuration code. - *

- *

- * The structure is defined and must be followed, or code updates be completed. - *

- *

- * The application must ensure the 'set_properties()' method has been called. - * See com.pi4j.devices.appConfig.SetProperties as an example. - *

- * - * -*/ - public class ChipNameMap { + *

+ * Defines each chip in the system. Characteristics like Pi bus number, + * Device address, Speed, if behind a mux/switch.... + * These details are used by the Application configuration code. + *

+ *

+ * The structure is defined and must be followed, or code updates be completed. + *

+ *

+ * The application must ensure the 'set_properties()' method has been called. + * See com.pi4j.devices.appConfig.SetProperties as an example. + *

+ */ +public class ChipNameMap { /** * setProperties *

@@ -69,69 +60,68 @@ public class ChipNameMap { * *

* PostCond: File config_chipMap.properties contains the class data chip_map - * - * */ + */ public void setProperties() { - Properties prop = new Properties(); - OutputStream output = null; - String fName = "config_chipMap.properties"; - this.createNewFile(fName); - - try { - - output = new FileOutputStream(fName); - - prop.setProperty("chip_map", - "{ {'23008#1':{'busNum':'0x0','address':'0x20','banked':'n','behindMux':'9548#1','pca':'23008','chipName':'23008#1'}}," - + "{'23017#1':{'busNum':0x1','address':'0x22','banked':'n','behindMux':'9548#1','pca':'23017','chipName':'23017#1'}}," - + "{'23017#2':{'busNum':0x6','address':'0x22','banked':'n','behindMux':'9548#1','pca':'23017','chipName':'23017#1'}}," - + "{'23017#3':{'busNum':'0X4','banked':'y','address':'0x20','behindMux':'9548#3','pca':'23017','chipName':'23017#3'}}," - + "{'9548#1':{'busType':'i2c','busNum':'0X1','address':'0x70','pca':'9548','chipName':'9548#1'}}," - + "{'9548#2':{'busType':'i2c','busNum':'0X1','address':'0x70','pca':'9548','chipName':'9548#2'}}," - + "{'9548#3':{'busType':'i2c','busNum':'0X1','address':'0x76','pca':'9548','chipName':'9548#3'}}," - + "{'3008#2':{'busType':'spi','channel':'0X0','speed':'1000000','mode':'0','pca':'3008','chipName':'3008#2'}}," - + "{'matrix#1':{'busNum':0x7','address':'0x74','behindMux':'9548#1','pca':'i31fl3731','chipName':'matrix#1'}}," - + "{'BMP#1':{'busNum':0x7','address':'0x77','behindMux':'9548#1','pca':'BMP180','chipName':'BMP#1'}}," - + "{'pi3B':{'busType':'i2c','busNum':'X','pca':'ARM','chipName':'pi3B'}}," - + " {'pi4B':{'busNum':'XXXX','pca':'ARM','chipName':'pi4B'}}}"); - // MODE_0(0), MODE_1(1), MODE_2(2), MODE_3(3); - // save properties to project root folder - prop.store(output, null); - - } catch (IOException io) { - io.printStackTrace(); - } finally { - if (output != null) { - try { - output.close(); - } catch (IOException e) { - e.printStackTrace(); - } + Properties prop = new Properties(); + OutputStream output = null; + String fName = "config_chipMap.properties"; + this.createNewFile(fName); + + try { + + output = new FileOutputStream(fName); + + prop.setProperty("chip_map", + "{ {'23008#1':{'busNum':'0x0','address':'0x20','banked':'n','behindMux':'9548#1','pca':'23008','chipName':'23008#1'}}," + + "{'23017#1':{'busNum':0x1','address':'0x22','banked':'n','behindMux':'9548#1','pca':'23017','chipName':'23017#1'}}," + + "{'23017#2':{'busNum':0x6','address':'0x22','banked':'n','behindMux':'9548#1','pca':'23017','chipName':'23017#1'}}," + + "{'23017#3':{'busNum':'0X4','banked':'y','address':'0x20','behindMux':'9548#3','pca':'23017','chipName':'23017#3'}}," + + "{'9548#1':{'busType':'i2c','busNum':'0X1','address':'0x70','pca':'9548','chipName':'9548#1'}}," + + "{'9548#2':{'busType':'i2c','busNum':'0X1','address':'0x70','pca':'9548','chipName':'9548#2'}}," + + "{'9548#3':{'busType':'i2c','busNum':'0X1','address':'0x76','pca':'9548','chipName':'9548#3'}}," + + "{'3008#2':{'busType':'spi','channel':'0X0','speed':'1000000','mode':'0','pca':'3008','chipName':'3008#2'}}," + + "{'matrix#1':{'busNum':0x7','address':'0x74','behindMux':'9548#1','pca':'i31fl3731','chipName':'matrix#1'}}," + + "{'BMP#1':{'busNum':0x7','address':'0x77','behindMux':'9548#1','pca':'BMP180','chipName':'BMP#1'}}," + + "{'pi3B':{'busType':'i2c','busNum':'X','pca':'ARM','chipName':'pi3B'}}," + + " {'pi4B':{'busNum':'XXXX','pca':'ARM','chipName':'pi4B'}}}"); + // MODE_0(0), MODE_1(1), MODE_2(2), MODE_3(3); + // save properties to project root folder + prop.store(output, null); + + } catch (IOException io) { + io.printStackTrace(); + } finally { + if (output != null) { + try { + output.close(); + } catch (IOException e) { + e.printStackTrace(); } - } - } - public void createNewFile(String fName) { - - try { - PrintWriter writer = null; - File f = new File(fName); - if (f.exists() && !f.isDirectory()) { - System.out.println("file exists "); - writer = new PrintWriter(new FileWriter(fName)); - } else { - System.out.println("file does not exist"); - writer = new PrintWriter(fName); - } - writer.close(); + } + } - } catch (Exception e) { - // Print out the exception that occurred - System.out.println("Unable to create new file " + e.getMessage()); + public void createNewFile(String fName) { + + try { + PrintWriter writer = null; + File f = new File(fName); + if (f.exists() && !f.isDirectory()) { + System.out.println("file exists "); + writer = new PrintWriter(new FileWriter(fName)); + } else { + System.out.println("file does not exist"); + writer = new PrintWriter(fName); } + writer.close(); + + } catch (Exception e) { + // Print out the exception that occurred + System.out.println("Unable to create new file " + e.getMessage()); } + } /** * readProperties @@ -143,35 +133,34 @@ public void createNewFile(String fName) { * PostCond: File config_chipMap.properties read. * * @return String containing value for key chip_map - * - * */ + */ public String readProperties() { - Properties prop = new Properties(); - InputStream input = null; - String rval = ""; - ReadProperties readProp = new ReadProperties(); - try { - input = new FileInputStream("config_chipMap.properties"); - // load a properties file - prop.load(input); - // System.out.println(prop.getProperty("chip_map")); - - rval = prop.getProperty("chip_map"); - - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - e.printStackTrace(); - } + Properties prop = new Properties(); + InputStream input = null; + String rval = ""; + ReadProperties readProp = new ReadProperties(); + try { + input = new FileInputStream("config_chipMap.properties"); + // load a properties file + prop.load(input); + // System.out.println(prop.getProperty("chip_map")); + + rval = prop.getProperty("chip_map"); + + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); } } - return (rval); - } + return (rval); } +} + diff --git a/src/main/java/com/pi4j/devices/appConfig/GpioToApp.java b/src/main/java/com/pi4j/devices/appConfig/GpioToApp.java index f5e9c31..9a9564b 100644 --- a/src/main/java/com/pi4j/devices/appConfig/GpioToApp.java +++ b/src/main/java/com/pi4j/devices/appConfig/GpioToApp.java @@ -35,157 +35,145 @@ package com.pi4j.devices.appConfig; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; +import java.io.*; import java.util.Properties; /** *

GpioToApp

- *

- * Defines each chip, defines pins available on that chip. - * Included detail, mux/switch name if located behind a mux/chip, - * action details when an interrupt pertains to this pin. - * *

- *

- * The structure is defined and must be followed, or code updates be completed. - *

- *

- * The application must ensure the 'set_properties()' method has been called. - * See com.pi4j.devices.appConfig.SetProperties as an example. - *

- * - * + *

+ * Defines each chip, defines pins available on that chip. + * Included detail, mux/switch name if located behind a mux/chip, + * action details when an interrupt pertains to this pin. + * *

+ *

+ * The structure is defined and must be followed, or code updates be completed. + *

+ *

+ * The application must ensure the 'set_properties()' method has been called. + * See com.pi4j.devices.appConfig.SetProperties as an example. + *

*/ - public class GpioToApp { - - - /** - * setProperties - *

- * PreCond: GpioToApp instance initialized. - * - *

- * PostCond: File config_pin_map.properties contains the class data pin_map - * - * */ - public void setProperties() { - Properties prop = new Properties(); - OutputStream output = null; - String fName = "config_pin_map.properties"; - this.createNewFile(fName); - - try { - output = new FileOutputStream(fName); - prop.setProperty("pin_map", - "{ {'23008#1':{{'pin7':{'appName':'input','action':'hilow','chipName':'23008#1','gpioNumLED':'dio12'}}," - + "{'pin14':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin15','pinChip':'23008#1'}}," - + "{'pin15':{'appName':'LED','action':'reflect','chipName':'23008#1'}}," - + "{'pin2':{'appName':'LED','action':'reflect','chipName':'23008#1'}}," - + "{'pin0':{'appName':'LED','action':'reflect','chipName':'23008#1'}}," - + "{'pin3':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}}," - + "{'pin4':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}} } }," - + "{'23017#1':{{'pin7':{'appName':'input','action':'hilow','chipName':'23017#1','gpioNumLED':'dio12'}}," - + "{'pin15':{'appName':'input','action':'reflect','chipName':'23017#2','pin':'pin0','pinChip':'23017#1'}}," - + "{'pin4':{'appName':'input','action':'hilow','chipName':'23017#1','pin':'pin14','pinChip':'23017#1'}}," - + "{'pin14':{'appName':'LED','action':'reflect','chipName':'23017#1'}}," - + "{'pin0':{'appName':'LED','action':'reflect','chipName':'23017#1'}}," - + "{'pin15':{'appName':'LED','action':'reflect','chipName':'23017#1'}}," - + "{'pin15':{'appName':'input','action':'reflect','chipName':'23017#1','pin':'pin0','pinChip':'23017#1'}}," - + "{'pin2':{'appName':'LED','action':'reflect','chipName':'23017#1'}} } }, " - + "{'23017#2':{{'pin7':{'appName':'input','action':'hilow','chipName':'23017#2','gpioNumLED':'dio12'}}," - + "{'pin14':{'appName':'input','action':'reflect','chipName':'23017#2','pin':'pin15','pinChip':'23017#2'}}," - + "{'pin9':{'appName':'output','action':'reflect','chipName':'23017#2'}}," - + "{'pin4':{'appName':'LED','action':'reflect','chipName':'23017#2'}}," - + "{'pin0':{'appName':'LED','action':'reflect','chipName':'23017#2'}}," - + "{'pin15':{'appName':'LED','action':'reflect','chipName':'23017#2'}}," - + "{'pin2':{'appName':'LED','action':'reflect','chipName':'23017#2'}} } }, " - + "{'23017#3':{{'pin15':{'appName':'LED','action':'reflect','chipName':'23017#3'}} }} }"); - - // save properties to project root folder - prop.store(output, null); - - } catch (IOException io) { - io.printStackTrace(); - } finally { - if (output != null) { - try { - output.close(); - } catch (IOException e) { - e.printStackTrace(); - } +public class GpioToApp { + + + /** + * setProperties + *

+ * PreCond: GpioToApp instance initialized. + * + *

+ * PostCond: File config_pin_map.properties contains the class data pin_map + */ + public void setProperties() { + Properties prop = new Properties(); + OutputStream output = null; + String fName = "config_pin_map.properties"; + this.createNewFile(fName); + + try { + output = new FileOutputStream(fName); + prop.setProperty("pin_map", + "{ {'23008#1':{{'pin7':{'appName':'input','action':'hilow','chipName':'23008#1','gpioNumLED':'dio12'}}," + + "{'pin14':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin15','pinChip':'23008#1'}}," + + "{'pin15':{'appName':'LED','action':'reflect','chipName':'23008#1'}}," + + "{'pin2':{'appName':'LED','action':'reflect','chipName':'23008#1'}}," + + "{'pin0':{'appName':'LED','action':'reflect','chipName':'23008#1'}}," + + "{'pin3':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}}," + + "{'pin4':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}} } }," + + "{'23017#1':{{'pin7':{'appName':'input','action':'hilow','chipName':'23017#1','gpioNumLED':'dio12'}}," + + "{'pin15':{'appName':'input','action':'reflect','chipName':'23017#2','pin':'pin0','pinChip':'23017#1'}}," + + "{'pin4':{'appName':'input','action':'hilow','chipName':'23017#1','pin':'pin14','pinChip':'23017#1'}}," + + "{'pin14':{'appName':'LED','action':'reflect','chipName':'23017#1'}}," + + "{'pin0':{'appName':'LED','action':'reflect','chipName':'23017#1'}}," + + "{'pin15':{'appName':'LED','action':'reflect','chipName':'23017#1'}}," + + "{'pin15':{'appName':'input','action':'reflect','chipName':'23017#1','pin':'pin0','pinChip':'23017#1'}}," + + "{'pin2':{'appName':'LED','action':'reflect','chipName':'23017#1'}} } }, " + + "{'23017#2':{{'pin7':{'appName':'input','action':'hilow','chipName':'23017#2','gpioNumLED':'dio12'}}," + + "{'pin14':{'appName':'input','action':'reflect','chipName':'23017#2','pin':'pin15','pinChip':'23017#2'}}," + + "{'pin9':{'appName':'output','action':'reflect','chipName':'23017#2'}}," + + "{'pin4':{'appName':'LED','action':'reflect','chipName':'23017#2'}}," + + "{'pin0':{'appName':'LED','action':'reflect','chipName':'23017#2'}}," + + "{'pin15':{'appName':'LED','action':'reflect','chipName':'23017#2'}}," + + "{'pin2':{'appName':'LED','action':'reflect','chipName':'23017#2'}} } }, " + + "{'23017#3':{{'pin15':{'appName':'LED','action':'reflect','chipName':'23017#3'}} }} }"); + + // save properties to project root folder + prop.store(output, null); + + } catch (IOException io) { + io.printStackTrace(); + } finally { + if (output != null) { + try { + output.close(); + } catch (IOException e) { + e.printStackTrace(); } - } - } - public void createNewFile(String fName) { - - try { - PrintWriter writer = null; - File f = new File(fName); - if (f.exists() && !f.isDirectory()) { - System.out.println("file exists "); - writer = new PrintWriter(new FileWriter(fName)); - } else { - System.out.println("file does not exist"); - writer = new PrintWriter(fName); - } - writer.close(); + } + } - } catch (Exception e) { - // Print out the exception that occurred - System.out.println("Unable to create new file " + e.getMessage()); + public void createNewFile(String fName) { + + try { + PrintWriter writer = null; + File f = new File(fName); + if (f.exists() && !f.isDirectory()) { + System.out.println("file exists "); + writer = new PrintWriter(new FileWriter(fName)); + } else { + System.out.println("file does not exist"); + writer = new PrintWriter(fName); } + writer.close(); + + } catch (Exception e) { + // Print out the exception that occurred + System.out.println("Unable to create new file " + e.getMessage()); } + } - /** - * readProperties - *

- * PreCond: GpioToApp instance initialized. set_properties was called. - * - * - *

- * PostCond: File config_pin_map.properties read. - * - * @return String containing value for key pin_map - * - * */ - public String readProperties() { - Properties prop = new Properties(); - InputStream input = null; - String rval = ""; - ReadProperties readProp = new ReadProperties(); - try { - input = new FileInputStream("config_pin_map.properties"); - // load a properties file - prop.load(input); - // System.out.println(prop.getProperty("pin_map")); - rval = prop.getProperty("pin_map"); - - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - e.printStackTrace(); - } + /** + * readProperties + *

+ * PreCond: GpioToApp instance initialized. set_properties was called. + * + * + *

+ * PostCond: File config_pin_map.properties read. + * + * @return String containing value for key pin_map + */ + public String readProperties() { + Properties prop = new Properties(); + InputStream input = null; + String rval = ""; + ReadProperties readProp = new ReadProperties(); + try { + input = new FileInputStream("config_pin_map.properties"); + // load a properties file + prop.load(input); + // System.out.println(prop.getProperty("pin_map")); + rval = prop.getProperty("pin_map"); + + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); } } - return (rval); - } - + return (rval); } +} + + diff --git a/src/main/java/com/pi4j/devices/appConfig/PiPinMap.java b/src/main/java/com/pi4j/devices/appConfig/PiPinMap.java index 9cb0400..f25de0d 100644 --- a/src/main/java/com/pi4j/devices/appConfig/PiPinMap.java +++ b/src/main/java/com/pi4j/devices/appConfig/PiPinMap.java @@ -35,32 +35,23 @@ package com.pi4j.devices.appConfig; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; +import java.io.*; import java.util.Properties; // Map Pi3B and Pi4B gpio mapping /** *

PiPinMap

- *

- * Defines each GPIO pins on the Pi BCM. Numbering follows the BCM numbering. - * Included detail action details when an interrupt pertains to this pin. - *

- *

- * The structure is defined and must be followed, or code updates be completed. - *

- *

- * The application must ensure the 'set_properties()' method has been called. - * See com.pi4j.devices.appConfig.SetProperties as an example. - *

- * - * + *

+ * Defines each GPIO pins on the Pi BCM. Numbering follows the BCM numbering. + * Included detail action details when an interrupt pertains to this pin. + *

+ *

+ * The structure is defined and must be followed, or code updates be completed. + *

+ *

+ * The application must ensure the 'set_properties()' method has been called. + * See com.pi4j.devices.appConfig.SetProperties as an example. + *

*/ public class PiPinMap { @@ -72,8 +63,7 @@ public class PiPinMap { * *

* PostCond: File config_pi_pins.properties contains the class data pi_pin_map - * - * */ + */ public void setProperties() { Properties prop = new Properties(); OutputStream output = null; @@ -84,10 +74,10 @@ public void setProperties() { output = new FileOutputStream(fName); prop.setProperty("pi_pin_map", - "{{'dio13':{'appName':'output','action':'hilow','chipName':'pi4B'}}," - + "{'dio12':{'appName':'LED','action':'reflect','chipName':'pi4B'}}," - + "{'dio18':{'appName':'LED','action':'reflect','chipName':'pi4B'}}," - + "{'dio26':{'appName':'hilow','action':'reflect','chipName':'pi4B'}}}"); + "{{'dio13':{'appName':'output','action':'hilow','chipName':'pi4B'}}," + + "{'dio12':{'appName':'LED','action':'reflect','chipName':'pi4B'}}," + + "{'dio18':{'appName':'LED','action':'reflect','chipName':'pi4B'}}," + + "{'dio26':{'appName':'hilow','action':'reflect','chipName':'pi4B'}}}"); // save properties to project root folder prop.store(output, null); @@ -136,8 +126,7 @@ public void createNewFile(String fName) { * PostCond: File config_pi_pins.properties read. * * @return String containing value for key pi_pin_map - * - * */ + */ public String readProperties() { Properties prop = new Properties(); diff --git a/src/main/java/com/pi4j/devices/appConfig/ReadProperties.java b/src/main/java/com/pi4j/devices/appConfig/ReadProperties.java index 8b9431d..6678c0d 100644 --- a/src/main/java/com/pi4j/devices/appConfig/ReadProperties.java +++ b/src/main/java/com/pi4j/devices/appConfig/ReadProperties.java @@ -36,24 +36,23 @@ /** *

ReadProperties

- *

- * Single class that calls read_properties on the various - * classes within the appConfig package - *

- * - * + *

+ * Single class that calls read_properties on the various + * classes within the appConfig package + *

*/ public class ReadProperties { /** * CTOR */ - public ReadProperties(){} + public ReadProperties() { + } /** * Work Print the values in all three properties. */ - public void work(){ + public void work() { ChipNameMap cMap = new ChipNameMap(); String chips = cMap.readProperties(); @@ -73,9 +72,10 @@ public void work(){ } + /** * main - * + *

* Classes within the appConfig package have their readProperties method called. *

* PreCond: None @@ -83,13 +83,12 @@ public void work(){ * *

* PostCond: Each file read and printed to the screen. - *

- * - * */ + *

+ */ public static void main(String[] args) { ReadProperties read = new ReadProperties(); read.work(); - } + } - } +} diff --git a/src/main/java/com/pi4j/devices/at24c512/AT24C512.java b/src/main/java/com/pi4j/devices/at24c512/AT24C512.java index 8edb5e0..bb7dbf6 100644 --- a/src/main/java/com/pi4j/devices/at24c512/AT24C512.java +++ b/src/main/java/com/pi4j/devices/at24c512/AT24C512.java @@ -37,7 +37,6 @@ package com.pi4j.devices.at24c512; import com.pi4j.context.Context; -import com.pi4j.devices.bmp280.BMP280Declares; import com.pi4j.io.i2c.I2C; import com.pi4j.io.i2c.I2CConfig; import com.pi4j.util.Console; @@ -67,8 +66,6 @@ public class AT24C512 { public static final String I2C_PROVIDER_ID = ID + "-i2c"; - - private final Logger logger; private final String traceLevel; @@ -82,8 +79,8 @@ public class AT24C512 { protected Console console = null; - protected int busNum ; - protected int address ; + protected int busNum; + protected int address; /** * @param console Context instance used accross application @@ -92,9 +89,9 @@ public class AT24C512 { */ /** - * @param console Context instance used across application - * @param bus Pi bus - * @param address Device address + * @param console Context instance used across application + * @param bus Pi bus + * @param address Device address * @param traceLevel for Logger */ public AT24C512(Context pi4j, Console console, int bus, int address, String traceLevel) { @@ -130,6 +127,7 @@ public AT24C512(Context pi4j, Console console, int bus, int address, Logger logg this.logger = logger; this.createI2cDevice(); // will set start this.i2c } + /** * @param device Set i2c state */ @@ -164,11 +162,11 @@ private void createI2cDevice() { String id = String.format("Bus: 0X%02x: ", bus); String name = String.format("Address: 0X%02x: ", address); var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .name(name) - .provider("linuxfs-i2c") /* "linuxfs-i2c") "linuxfs-i2c") */ - .build(); + .bus(bus) + .device(address) + .name(name) + .provider("linuxfs-i2c") /* "linuxfs-i2c") "linuxfs-i2c") */ + .build(); this.config = i2cDeviceConfig; this.i2c = this.pi4j.create(i2cDeviceConfig); @@ -186,10 +184,9 @@ public String i2cDetail() { } - - public byte[] readCurrentAddrEEPROM(int numBytes){ + public byte[] readCurrentAddrEEPROM(int numBytes) { this.logger.trace(">>> enter: readCurrentAddrEEPROM numByte : " + numBytes); - byte rData[] = new byte[numBytes]; + byte[] rData = new byte[numBytes]; int rc = 0; String details = "\n 0 1 2 3 4 5 6 7 8 9 a b c d e f \n"; details = details + String.format(" %02x: ", 0); @@ -197,8 +194,8 @@ public byte[] readCurrentAddrEEPROM(int numBytes){ for (int i = 0; i < numBytes; i++) { rData[i] = (byte) this.i2c.read();// .readRegister((int) register); - details = details + String.format("%02x ", rData[i]) + " "; - if (((i > 0) && ((i + 1) % 16) == 0) || (i == 15)){ + details = details + String.format("%02x ", rData[i]) + " "; + if (((i > 0) && ((i + 1) % 16) == 0) || (i == 15)) { details = details + "\n"; details = details + String.format(" %02x: ", i + 1); } @@ -206,22 +203,22 @@ public byte[] readCurrentAddrEEPROM(int numBytes){ rc = rData.length; this.logger.trace("read data :" + details - + "\n rc: "+ String.format("0X%02x: ",rc ) + "\n" ); + + "\n rc: " + String.format("0X%02x: ", rc) + "\n"); - this.logger.trace("<<< Exit: readCurrentAddrEEPROM numByte read : " + rc ); - return(rData); + this.logger.trace("<<< Exit: readCurrentAddrEEPROM numByte read : " + rc); + return (rData); } - public byte[] readEEPROM(long register, int numBytes){ - this.logger.trace(">>> enter: readEEPROM register " + String.format("%04x ", register) + " numByte : " + numBytes); - byte rData[] = new byte[numBytes]; + public byte[] readEEPROM(long register, int numBytes) { + this.logger.trace(">>> enter: readEEPROM register " + String.format("%04x ", register) + " numByte : " + numBytes); + byte[] rData = new byte[numBytes]; int rc = 0; // int rc = this.i2c.readRegister((int) ((register&0xff00) >> 8),rData, numBytes); String details = "\n 0 1 2 3 4 5 6 7 8 9 a b c d e f \n"; details = details + String.format(" %02x: ", 0); - // rData[i] = this.i2c.readRegisterByte(i); + // rData[i] = this.i2c.readRegisterByte(i); byte[] compVal = new byte[numBytes]; // this one needs to handle multibyte reg value @@ -230,8 +227,8 @@ public byte[] readEEPROM(long register, int numBytes){ regByte[1] = (byte) (register & 0xff); rc = this.i2c.readRegister(regByte, rData); for (int i = 0; i < numBytes; i++) { - details = details + String.format( "%02x ", rData[i]) + " "; - if (((i > 0) && ((i + 1) % 16) == 0) || (i == 15)){ + details = details + String.format("%02x ", rData[i]) + " "; + if (((i > 0) && ((i + 1) % 16) == 0) || (i == 15)) { details = details + "\n"; details = details + String.format(" %02x: ", i + 1); } @@ -239,15 +236,15 @@ public byte[] readEEPROM(long register, int numBytes){ rc = rData.length; // rc = this.i2c.readRegister((int) register, rData, 0, numBytes); this.logger.trace("readRegister data :" + details - + "\n rc: " + String.format("0X%02x: ",rc) + "\n"); + + "\n rc: " + String.format("0X%02x: ", rc) + "\n"); - this.logger.trace("<<< Exit: readEEPROM numByte read : " + rc ); - return(rData); + this.logger.trace("<<< Exit: readEEPROM numByte read : " + rc); + return (rData); } - public int writeEEPROM(long register, int numBytes, byte[] wData){ - this.logger.trace(">>> enter: writeEEPROM register :" + String.format("%04x ", register) + " numBytes " + numBytes); + public int writeEEPROM(long register, int numBytes, byte[] wData) { + this.logger.trace(">>> enter: writeEEPROM register :" + String.format("%04x ", register) + " numBytes " + numBytes); // needs to handle multibyte reg value byte[] regByte = new byte[2]; // This chip is two byte register address @@ -260,18 +257,17 @@ public int writeEEPROM(long register, int numBytes, byte[] wData){ details = details + String.format(" %02x: ", 0); for (int i = 0; i < numBytes; i++) { details = details + String.format("%02x ", wData[i]) + " "; - if( ((i > 0) && ((i + 1) % 16) == 0)|| (i == 15)) { + if (((i > 0) && ((i + 1) % 16) == 0) || (i == 15)) { details = details + "\n"; details = details + String.format(" %02x: ", i + 1); } } this.logger.trace("writeRegister data :" + details - + "\n rc: "+ String.format("0X%02x: ",rc) + "\n" ); + + "\n rc: " + String.format("0X%02x: ", rc) + "\n"); this.logger.trace("<<< Exit: writeEEPROM numBytes written numBytes written regAddr + data :" + rc); - return(rc); + return (rc); } - } diff --git a/src/main/java/com/pi4j/devices/at24c512/AT24C512_App.java b/src/main/java/com/pi4j/devices/at24c512/AT24C512_App.java index f848644..d26881a 100644 --- a/src/main/java/com/pi4j/devices/at24c512/AT24C512_App.java +++ b/src/main/java/com/pi4j/devices/at24c512/AT24C512_App.java @@ -38,27 +38,22 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.devices.bmp280.BMP280Declares; -import com.pi4j.devices.bmp280.BMP280Device; -import com.pi4j.exception.LifecycleException; -import com.pi4j.plugin.linuxfs.provider.i2c.LinuxFsI2CProvider; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; + public class AT24C512_App { - /** - * Sample application using AT24C512 SEEPROM. - * - * @param args an array of {@link java.lang.String} objects. - * Parms are not required. if 'any' parameter value is supplied, - * the example uses the create pattern for device instantiation, - * otherwise provider setup is used - * @throws java.lang.Exception if any. - */ - public static void main(String[] args) throws Exception { + /** + * Sample application using AT24C512 SEEPROM. + * + * @param args an array of {@link java.lang.String} objects. + * Parms are not required. if 'any' parameter value is supplied, + * the example uses the create pattern for device instantiation, + * otherwise provider setup is used + * @throws java.lang.Exception if any. + */ + public static void main(String[] args) throws Exception { int busNum = 0x01; @@ -71,7 +66,7 @@ public static void main(String[] args) throws Exception { String writeData = ""; boolean doWrite = false; int writeDataLen = 0; - + // ------------------------------------------------------------ // Initialize the Pi4J Runtime Context // ------------------------------------------------------------ @@ -95,20 +90,6 @@ public static void main(String[] args) throws Exception { System.out.println("----------------------------------------------------------"); pi4j.providers().describe().print(System.out); System.out.println("----------------------------------------------------------"); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); - final Console console = new Console(); console.print("=============================================================="); @@ -117,9 +98,9 @@ public void handle(Signal sig) { String helpString = " parms: -b hex value bus -a hex value address \n" + - "-n numBytes -r readReg -rr read current addr NoData -w writeReg -d data -t trace\n" + - "-r not permitted with args -d -w, either read data or write data \n " + - " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; + "-n numBytes -r readReg -rr read current addr NoData -w writeReg -d data -t trace\n" + + "-r not permitted with args -d -w, either read data or write data \n " + + " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { String o = args[i]; @@ -131,26 +112,26 @@ public void handle(Signal sig) { String a = args[i + 1]; i++; address = Integer.parseInt(a.substring(2), 16); - }else if (o.contentEquals("-n")) { // device address + } else if (o.contentEquals("-n")) { // device address String a = args[i + 1]; i++; numBytes = Integer.parseInt(a.substring(2), 16); - }else if (o.contentEquals("-rr")) { // current chip pointer used + } else if (o.contentEquals("-rr")) { // current chip pointer used doCurrentRead = true; - }else if (o.contentEquals("-r")) { // read specific reg + } else if (o.contentEquals("-r")) { // read specific reg String a = args[i + 1]; i++; doRead = true; readReg = Long.parseLong(a.substring(2), 16); - }else if (o.contentEquals("-w")) { // write specific reg + } else if (o.contentEquals("-w")) { // write specific reg String a = args[i + 1]; i++; doWrite = true; writeReg = Long.parseLong(a.substring(2), 16); - }else if (o.contentEquals("-d")) { // write reg + } else if (o.contentEquals("-d")) { // write reg String a = args[i + 1]; i++; - writeDataLen = (a.length()-2)/2; // subtract 0X from the string + writeDataLen = (a.length() - 2) / 2; // subtract 0X from the string writeData = a.substring(2); } else if (o.contentEquals("-t")) { // device address String a = args[i + 1]; @@ -172,7 +153,7 @@ public void handle(Signal sig) { } } - if(doRead & doWrite){ + if (doRead & doWrite) { console.println(" !!! Invalid Parms, -r -w mutually exclusive"); console.println(helpString); System.exit(43); @@ -180,7 +161,7 @@ public void handle(Signal sig) { } var seeDev = new AT24C512(pi4j, console, busNum, address, traceLevel); - console.println(" Dev I2C detail " + seeDev.i2cDetail()); + console.println(" Dev I2C detail " + seeDev.i2cDetail()); console.println(" Setup ----------------------------------------------------------"); @@ -188,7 +169,7 @@ public void handle(Signal sig) { byte[] toRead; - if(doWrite) { + if (doWrite) { if (numBytes != writeDataLen) { console.println(" !!! -n NOT equal to length of -d data "); console.println(helpString); @@ -198,31 +179,31 @@ public void handle(Signal sig) { int toOffset = 0; int singleInt = 0; for (int i = 0; i < writeDataLen * 2; i += 2) { - try { + try { singleInt = Integer.parseInt(writeData.substring(i, i + 2), 16); - } catch (NumberFormatException nfe) { - // not a valid hex - console.println("Invalid: parm -d not a valid hex \n"); - System.exit(45); - } - bytesToWrite[toOffset] = (byte) (bytesToWrite[toOffset] | (byte) (singleInt & 0xff)); + } catch (NumberFormatException nfe) { + // not a valid hex + console.println("Invalid: parm -d not a valid hex \n"); + System.exit(45); + } + bytesToWrite[toOffset] = (byte) (bytesToWrite[toOffset] | (byte) (singleInt & 0xff)); toOffset++; } int bWritten = seeDev.writeEEPROM(writeReg, writeDataLen, bytesToWrite); console.println("Wrote " + bWritten + " bytes, expected : " + writeDataLen); - } else if(doRead) { + } else if (doRead) { toRead = seeDev.readEEPROM(readReg, numBytes); var details = "\n 0 1 2 3 4 5 6 7 8 9 a b c d e f \n"; details = details + String.format(" %02x: ", 0); for (int i = 0; i < numBytes; i++) { details = details + String.format("%02x ", toRead[i]) + " "; - if (((i > 0) && ((i + 1) % 16) == 0) || (i == 15) ){ + if (((i > 0) && ((i + 1) % 16) == 0) || (i == 15)) { details = details + "\n"; details = details + String.format(" %02x: ", i + 1); } } - console.println("Read " + numBytes + " bytes " + details); - }else if(doCurrentRead) { + console.println("Read " + numBytes + " bytes " + details); + } else if (doCurrentRead) { toRead = seeDev.readCurrentAddrEEPROM(numBytes); var details = "\n 0 1 2 3 4 5 6 7 8 9 a b c d e f \n"; details = details + String.format(" %02x: ", 0); @@ -233,7 +214,7 @@ public void handle(Signal sig) { details = details + String.format(" %02x: ", i + 1); } } - console.println("Read " + numBytes + " bytes " + details); + console.println("Read " + numBytes + " bytes " + details); } // Shutdown Pi4J pi4j.shutdown(); diff --git a/src/main/java/com/pi4j/devices/at24c512/README.md b/src/main/java/com/pi4j/devices/at24c512/README.md index 43fa186..1829c29 100644 --- a/src/main/java/com/pi4j/devices/at24c512/README.md +++ b/src/main/java/com/pi4j/devices/at24c512/README.md @@ -1,11 +1,7 @@ - -# NOT READY FOR USE. Pi4J limitation prevents this completion.... - - +# NOT READY FOR USE. Pi4J limitation prevents this completion.... # Pi4J_V2-AT24C512 SEEPROM - https://www.alldatasheet.com/datasheet-pdf/pdf/56068/ATMEL/AT24C512.html The example program has the assumption the BMP280 is connected to Pi bus 1, and the device is factory configured to @@ -23,32 +19,25 @@ Use of different bus or device address, use the applicable values in the followi Specific READ Read 2 bytes starting page/address 0x342 -sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x2 -r 0x342 -t trace - +sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x2 -r 0x342 -t trace Specific WRITE Write 2 byte '0x1234 at page/address 0x324 -sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x2 -w 0x0342 -d 0x1234 -t trace - - +sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x2 -w 0x0342 -d 0x1234 -t trace Specific READ Read 1 byte starting page/address 0x342 -sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x1 -r 0x342 -t trace - +sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x1 -r 0x342 -t trace Specific from current page/address Read 1 byte starting page/address 0x343 -sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x1 -rr -t trace - - +sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x1 -rr -t trace - -parms: -b hex value bus -a hex value address -t trace -n numbytes -r readReg -w writeReg -d data -rr read current +parms: -b hex value bus -a hex value address -t trace -n numbytes -r readReg -w writeReg -d data -rr read current -r not permitted with args -d -w, either read data or write data trace values : "trace", "debug", "info", "warn", "error" or "off" Default "info" -sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x11 -w 0x112 -d 0x1122334455667788990011223344556677 -t trace +sudo ./runAT24C512.sh -b 0x01 -b 0x01 -a 0x50 -n 0x11 -w 0x112 -d 0x1122334455667788990011223344556677 -t trace diff --git a/src/main/java/com/pi4j/devices/base_i2c/BasicI2cDevice.java b/src/main/java/com/pi4j/devices/base_i2c/BasicI2cDevice.java index c3c9b6b..19e2029 100644 --- a/src/main/java/com/pi4j/devices/base_i2c/BasicI2cDevice.java +++ b/src/main/java/com/pi4j/devices/base_i2c/BasicI2cDevice.java @@ -34,8 +34,8 @@ package com.pi4j.devices.base_i2c; -import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.context.Context; +import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.exception.Pi4JException; import com.pi4j.io.exception.IOReadException; import com.pi4j.io.i2c.I2C; @@ -43,7 +43,6 @@ import com.pi4j.util.Console; import java.io.IOException; -import java.nio.charset.StandardCharsets; /** * BasicI2cDevice creates and uses i2cDeviceConfig for read and write operations.This class adds @@ -88,22 +87,22 @@ private void init() { String id = String.format("0X%02x: ", this.busNum); String name = String.format("0X%02x: ", this.address); this.i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(this.busNum) - .device(this.address) - .id(id+" "+name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(this.busNum) + .device(this.address) + .id(id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); } catch (Pi4JException e) { String details = String.format("new config create failed bus %s address %s ", String.format("0X%02x: ", this.busNum), String.format("0X%02x: ", this.address)); this.ffdc.ffdcErrorEntry(details); - this.ffdc.ffdcErrorEntry(e.getMessage() + " /n" + e.toString()); + this.ffdc.ffdcErrorEntry(e.getMessage() + " /n" + e); this.ffdc.ffdcErrorExit("i2C NEW CONFIG failed", 105); } try { this.i2cDevice = this.pi4j.create(this.i2cDeviceConfig); } catch (Exception e) { - this.ffdc.ffdcErrorEntry(e.getMessage() + " /n" + e.toString()); + this.ffdc.ffdcErrorEntry(e.getMessage() + " /n" + e); String details = String.format("device create failed bus %s address %s ", String.format("0X%02x: ", this.busNum), String.format("0X%02x: ", this.address)); this.ffdc.ffdcErrorExit(details, 104); //e.printStackTrace(); @@ -118,11 +117,11 @@ private void init() { * @param offset Device register * *

- * PostCond: Register contents returned if successful, else negative value + * PostCond: Register contents returned if successful, else negative value */ protected int readRegister(int offset) { int reg = 0; - this.ffdc.ffdcMethodEntry("readRegister : offset " + String.format("0X%02x: ", offset) + " bus : " + String.format("0X%02x: ",this.busNum) + " device address: " + String.format("0X%02x: ",this.address)); + this.ffdc.ffdcMethodEntry("readRegister : offset " + String.format("0X%02x: ", offset) + " bus : " + String.format("0X%02x: ", this.busNum) + " device address: " + String.format("0X%02x: ", this.address)); reg = this.i2cDevice.readRegister(offset); this.examineReturnRead(reg); this.ffdc.ffdcMethodExit("readRegister data :" + String.format("0X%02x: ", reg)); @@ -139,11 +138,10 @@ protected int readRegister(int offset) { *

* PostCond: Register contents returned if successful, else * exception will surface - * * @throws IOException, IOReadException */ protected byte readRegisterByte(int offset) throws IOException, IOReadException { - this.ffdc.ffdcMethodEntry("readRegisterBye : offset " + String.format("0X%02x: ", offset) + " bus : " + String.format("0X%02x: ",this.busNum) + " device address: " + String.format("0X%02x: ",this.address)); + this.ffdc.ffdcMethodEntry("readRegisterBye : offset " + String.format("0X%02x: ", offset) + " bus : " + String.format("0X%02x: ", this.busNum) + " device address: " + String.format("0X%02x: ", this.address)); byte reg = 0; reg = this.i2cDevice.readRegisterByte(offset); this.ffdc.ffdcMethodExit("readRegisterByte data :" + String.format("0X%02x: ", reg)); @@ -151,8 +149,6 @@ protected byte readRegisterByte(int offset) throws IOException, IOReadException } - - /** * I2C device access,read device register presently referenced in device control register. * @@ -167,7 +163,7 @@ protected byte readRegisterByte(int offset) throws IOException, IOReadException * PostCond: Register contents returned if successful, else negative value */ protected int read() { - this.ffdc.ffdcMethodEntry("read bus : " + String.format("0X%02x: ",this.busNum) + " device address: " + String.format("0X%02x: ",this.address)); + this.ffdc.ffdcMethodEntry("read bus : " + String.format("0X%02x: ", this.busNum) + " device address: " + String.format("0X%02x: ", this.address)); int reg = 0; reg = this.i2cDevice.read(); this.examineReturnRead(reg); @@ -175,6 +171,7 @@ protected int read() { this.ffdc.ffdcMethodExit("read data:" + String.format("0X%02x: ", reg)); return (reg); } + /** * I2C device access,read device register presently referenced in device control register. * @@ -191,7 +188,7 @@ protected int read() { * @throws IOException */ protected byte readByte() throws IOException { - this.ffdc.ffdcMethodEntry("readByte bus : " + String.format("0X%02x: ",this.busNum) + " device address: " + String.format("0X%02x: ",this.address)); + this.ffdc.ffdcMethodEntry("readByte bus : " + String.format("0X%02x: ", this.busNum) + " device address: " + String.format("0X%02x: ", this.address)); byte reg = 0; reg = this.i2cDevice.readByte(); this.ffdc.ffdcDebugEntry("readByte data :" + String.format("0X%02x: ", reg)); @@ -199,16 +196,15 @@ protected byte readByte() throws IOException { } /** - * - * @param register offset into device - * @param buffer storage to contain contents read - * @param bufferOffset offset in buffer to place read data - * @param length length of data to read - * @return number bytes read else negative number + * @param register offset into device + * @param buffer storage to contain contents read + * @param bufferOffset offset in buffer to place read data + * @param length length of data to read + * @return number bytes read else negative number */ - protected int readRegister(int register, byte[] buffer, int bufferOffset, int length){ - this.ffdc.ffdcMethodEntry("readRegister bus : " + String.format("0X%02x: ",this.busNum) + " device address: " + String.format("0X%02x: ",this.address) - + " register: " + String.format("0X%02x: ",bufferOffset)+ " length: " + String.format("0X%02x: ",length)); + protected int readRegister(int register, byte[] buffer, int bufferOffset, int length) { + this.ffdc.ffdcMethodEntry("readRegister bus : " + String.format("0X%02x: ", this.busNum) + " device address: " + String.format("0X%02x: ", this.address) + + " register: " + String.format("0X%02x: ", bufferOffset) + " length: " + String.format("0X%02x: ", length)); int rc = 0; // StandardCharsets.UTF_8, @@ -225,9 +221,9 @@ protected int readRegister(int register, byte[] buffer, int bufferOffset, int l } this.ffdc.ffdcDebugEntry("readRegister data :" + details - + " rc: " + "\n" + String.format("0X%02x: ",rc)); - return(rc); - } + + " rc: " + "\n" + String.format("0X%02x: ", rc)); + return (rc); + } /** * I2C device access, write data to device register presently referenced in device control register. @@ -240,7 +236,7 @@ protected int readRegister(int register, byte[] buffer, int bufferOffset, int l * PostCond: 0 returned if successful, else non-zero */ protected int write(byte data) { - this.ffdc.ffdcMethodEntry("write : data " + String.format("0X%02x: ", data) + " bus : " + String.format("0X%02x: ",this.busNum) + " device address: " + String.format("0X%02x: ",this.address)); + this.ffdc.ffdcMethodEntry("write : data " + String.format("0X%02x: ", data) + " bus : " + String.format("0X%02x: ", this.busNum) + " device address: " + String.format("0X%02x: ", this.address)); int rval = 0; rval = this.i2cDevice.write(data); this.examineReturnWrite(rval); @@ -248,6 +244,7 @@ protected int write(byte data) { this.ffdc.ffdcMethodExit("write rval :" + String.format("0X%02x: ", rval)); return (rval); } + /** * I2C device access, write data to device register to set offset, then write * data byte. @@ -255,13 +252,13 @@ protected int write(byte data) { * PreCond: BasicI2cDevice instance initialized. See CTOR * * @param offset Device Register address - * @param data Register updated with byte data + * @param data Register updated with byte data * - *

- * PostCond: 0 returned if successful, else non-zero + *

+ * PostCond: 0 returned if successful, else non-zero */ protected int writeByte(int offset, byte data) { - this.ffdc.ffdcMethodEntry("writeByte : offset " + String.format("0X%02x: ", offset) + " data : " + String.format("0X%02x: ",data ) + " bus : " + String.format("0X%02x: ",this.busNum) + " device address: " + String.format("0X%02x: ",this.address)); + this.ffdc.ffdcMethodEntry("writeByte : offset " + String.format("0X%02x: ", offset) + " data : " + String.format("0X%02x: ", data) + " bus : " + String.format("0X%02x: ", this.busNum) + " device address: " + String.format("0X%02x: ", this.address)); int rval = 0; rval = this.i2cDevice.writeRegister(offset, data); this.examineReturnWrite(rval); diff --git a/src/main/java/com/pi4j/devices/base_i2c/I2cSimpleRead.java b/src/main/java/com/pi4j/devices/base_i2c/I2cSimpleRead.java index 897a9f8..66f070a 100644 --- a/src/main/java/com/pi4j/devices/base_i2c/I2cSimpleRead.java +++ b/src/main/java/com/pi4j/devices/base_i2c/I2cSimpleRead.java @@ -93,7 +93,7 @@ public void dumpRegs() throws IOException, IOReadException { // Here we will cre var details = "\n 0 1 2 3 4 5 6 7 8 9 a b c d e f \n"; details = details + String.format("%02x: ", 0); byte[] buffer = new byte[this.numBytes]; - if (this.writeRestart == false) { + if (!this.writeRestart) { this.ffdc.ffdcDebugEntry("Read chip from its present offset"); for (int i = 0; i < this.numBytes; i++) { byte data = this.readRegisterByte(i); @@ -118,12 +118,12 @@ public void dumpRegs() throws IOException, IOReadException { // Here we will cre this.ffdc.ffdcDebugEntry(details); this.ffdc.ffdcMethodExit(this.getMethodName()); } + int numBytes = 0; int deviceOffset; boolean writeRestart = false; - /** * Description of parms passed to class main * @@ -132,9 +132,9 @@ public void dumpRegs() throws IOException, IOReadException { // Here we will cre */ protected void usage() { System.out.println( - "options -h 'help', -b bus, -a address, \n" + - " -r deviceRegister, -n number of bytes -f ffdc_lvl -s sysCfg \n" + - "-f :0 < TRACE 1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF "); + "options -h 'help', -b bus, -a address, \n" + + " -r deviceRegister, -n number of bytes -f ffdc_lvl -s sysCfg \n" + + "-f :0 < TRACE 1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF "); } /** diff --git a/src/main/java/com/pi4j/devices/base_i2c/MutableI2cDevice.java b/src/main/java/com/pi4j/devices/base_i2c/MutableI2cDevice.java index c946b37..e18958f 100644 --- a/src/main/java/com/pi4j/devices/base_i2c/MutableI2cDevice.java +++ b/src/main/java/com/pi4j/devices/base_i2c/MutableI2cDevice.java @@ -101,16 +101,16 @@ protected void reinit(String id, String name, int bus, int address) { this.busNum = bus; this.address = address; this.i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(this.busNum) - .device(this.address) - .id(id) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(this.busNum) + .device(this.address) + .id(id) + .name(name) + .provider("linuxfs-i2c") + .build(); } catch (Pi4JException e) { String details = String.format("new config create failed bus %s address %s ", String.format("0X%02x: ", this.busNum), String.format("0X%02x: ", this.address)); this.ffdc.ffdcErrorEntry(details); - this.ffdc.ffdcErrorEntry(e.getMessage() + " /n" + e.toString()); + this.ffdc.ffdcErrorEntry(e.getMessage() + " /n" + e); this.ffdc.ffdcErrorExit("i2C NEW CONFIG failed", 105); } try { @@ -150,7 +150,6 @@ protected int readRegister(int offset) { * *

* PostCond: Register contents returned if successful, else exception will surface - * * @throws IOException, IOReadException */ protected byte readRegisterByte(int offset) throws IOException, IOReadException { diff --git a/src/main/java/com/pi4j/devices/base_i2c/README.md b/src/main/java/com/pi4j/devices/base_i2c/README.md index 7c9161b..4ed76ea 100644 --- a/src/main/java/com/pi4j/devices/base_i2c/README.md +++ b/src/main/java/com/pi4j/devices/base_i2c/README.md @@ -8,9 +8,8 @@ Pi4J :: Java I/O Library for Raspberry Pi :: Device :: Mcp23xxPinMonitor Project by Tom Aarts ========================================================================== -Simple program to execute and I2C read at the specified bus -b, address -a, --o offset, -n number of bytes. Other parms, -f FFDC level, -s dump pi4j sys data - +Simple program to execute and I2C read at the specified bus -b, address -a, +-o offset, -n number of bytes. Other parms, -f FFDC level, -s dump pi4j sys data 1. ./mvnw clean package 2. cd target/distribution diff --git a/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingModule.java b/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingModule.java index 6daadbe..7a01a75 100644 --- a/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingModule.java +++ b/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingModule.java @@ -33,12 +33,12 @@ */ package com.pi4j.devices.base_util.ffdc; + /** * FfdcLoggingModule * Interface declarations for custom logging, the implementing class * can add any desired information to the 'detail'. - * - * */ + */ public interface FfdcLoggingModule { boolean ffdcMethodEntry(String detail); @@ -54,8 +54,8 @@ public interface FfdcLoggingModule { void ffdcErrorExit(String detail, int code); - boolean ffdcClearLogs(String detail); + boolean ffdcClearLogs(String detail); - boolean ffdcFlushShutdown(); + boolean ffdcFlushShutdown(); } diff --git a/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingSystem.java b/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingSystem.java index 5ec8816..ebe1126 100644 --- a/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingSystem.java +++ b/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcLoggingSystem.java @@ -33,12 +33,12 @@ */ package com.pi4j.devices.base_util.ffdc; + /** * FfdcLoggingModule * Interface declarations for custom logging, the implementing class * can add any desired details. - * - * */ + */ public interface FfdcLoggingSystem { void printLoadedPlatforms(); diff --git a/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcUtil.java b/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcUtil.java index f353132..cdc7934 100644 --- a/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcUtil.java +++ b/src/main/java/com/pi4j/devices/base_util/ffdc/FfdcUtil.java @@ -95,7 +95,6 @@ public FfdcUtil(Console console, Context pi4j, int ffdcControlLevel, Class owner } - /** * init */ @@ -107,8 +106,8 @@ private void init() { this.setLevel(this.ffdc); this.logger = LoggerFactory.getLogger(this.owner); - // this.logger = LogManager.getLogger(this.owner); - // this.setLevel(this.ffdc); + // this.logger = LogManager.getLogger(this.owner); + // this.setLevel(this.ffdc); } @@ -313,7 +312,6 @@ public boolean setLevel(int val) { *

  • 5 ERROR *
  • 6 OFF * - * @param newLevel * @return Simple int converted to Log4j value */ private String mapIntToLevel(int newLevel) { @@ -419,7 +417,7 @@ private String mapIntToLevel(int newLevel) { */ @Override public boolean ffdcFlushShutdown() { - // LogManager.shutdown(); + // LogManager.shutdown(); return (true); } diff --git a/src/main/java/com/pi4j/devices/base_util/gpio/BaseGpioInOut.java b/src/main/java/com/pi4j/devices/base_util/gpio/BaseGpioInOut.java index 65d9db8..11bd877 100644 --- a/src/main/java/com/pi4j/devices/base_util/gpio/BaseGpioInOut.java +++ b/src/main/java/com/pi4j/devices/base_util/gpio/BaseGpioInOut.java @@ -35,21 +35,20 @@ package com.pi4j.devices.base_util.gpio; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - +import com.pi4j.context.Context; import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.io.exception.IOException; import com.pi4j.io.gpio.digital.DigitalInput; import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalState; +import com.pi4j.io.gpio.digital.PullResistance; -import static java.util.concurrent.TimeUnit.MICROSECONDS; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; -import com.pi4j.context.Context; -import com.pi4j.io.gpio.digital.PullResistance; +import static java.util.concurrent.TimeUnit.MICROSECONDS; /** * BaseGpioInOut @@ -455,10 +454,10 @@ public boolean createGpioInstance(HashMap> pinCf Set outerSet = outerMap.entrySet(); Iterator>> outerIterator = outerSet.iterator(); while (outerIterator.hasNext()) { - Map.Entry> mentry = (Map.Entry) outerIterator.next(); + Map.Entry> mentry = outerIterator.next(); System.out.println("mentry " + mentry); String pinName = mentry.getKey(); - if (pinName.startsWith("gpio") == false) { + if (!pinName.startsWith("gpio")) { this.ffdc.ffdcErrorExit("illegal name prefix :" + pinName, 1001); } int pinNumber = Integer.parseInt(pinName.substring(4)); diff --git a/src/main/java/com/pi4j/devices/base_util/gpio/GpioBasics.java b/src/main/java/com/pi4j/devices/base_util/gpio/GpioBasics.java index 5a7ddf7..e580d38 100644 --- a/src/main/java/com/pi4j/devices/base_util/gpio/GpioBasics.java +++ b/src/main/java/com/pi4j/devices/base_util/gpio/GpioBasics.java @@ -34,11 +34,11 @@ package com.pi4j.devices.base_util.gpio; +import com.pi4j.context.Context; import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.io.exception.IOException; import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalState; -import com.pi4j.context.Context; /** * GpioBasics is a worker class intended to contain utilities required by various classes @@ -62,42 +62,42 @@ default void sleepMS(int mSecs, FfdcUtil ffdc) { /** * reset_chip *

    - * This method does not use the Pin Dictionary, It creates the - * DigitalOutput instance as needed. + * This method does not use the Pin Dictionary, It creates the + * DigitalOutput instance as needed. *

    *

    * PreCond: GpioBasics instance initialized. See CTOR * - * @param resetGpio Gpio pin number to use - * @param pi4j Context - * @param delay time to wait between driving resetGpio - * @param bar if bar true, the chip reset pin is BAR, reset condition is LOW - * @param ffdc for logging information - *

    - * PostCond: Pin driven and restored to initial state - *

    + * @param resetGpio Gpio pin number to use + * @param pi4j Context + * @param delay time to wait between driving resetGpio + * @param bar if bar true, the chip reset pin is BAR, reset condition is LOW + * @param ffdc for logging information + *

    + * PostCond: Pin driven and restored to initial state + *

    */ default void resetChip(int resetGpio, Context pi4j, int delay, boolean bar, FfdcUtil ffdc) { var ledConfig = DigitalOutput.newConfigBuilder(pi4j) - .id("resetPin") - .name("Chip reset") - .address(resetGpio) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("resetPin") + .name("Chip reset") + .address(resetGpio) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); DigitalOutput resetPin = null; try { resetPin = pi4j.create(ledConfig); } catch (Exception e) { e.printStackTrace(); - ffdc.ffdcErrorExit(String.format("reset_chip %s" ,e.toString()), 600); + ffdc.ffdcErrorExit(String.format("reset_chip %s", e), 600); } try { - if(bar) { // active low + if (bar) { // active low resetPin.low(); this.sleepMS(delay, ffdc); resetPin.high(); - }else{ + } else { resetPin.high(); this.sleepMS(delay, ffdc); resetPin.low(); @@ -105,7 +105,7 @@ default void resetChip(int resetGpio, Context pi4j, int delay, boolean bar, Ffdc } catch (IOException e) { e.printStackTrace(); } - } + } } diff --git a/src/main/java/com/pi4j/devices/base_util/gpio/GpioPinCfgData.java b/src/main/java/com/pi4j/devices/base_util/gpio/GpioPinCfgData.java index ffe0592..e0059e6 100644 --- a/src/main/java/com/pi4j/devices/base_util/gpio/GpioPinCfgData.java +++ b/src/main/java/com/pi4j/devices/base_util/gpio/GpioPinCfgData.java @@ -35,17 +35,13 @@ package com.pi4j.devices.base_util.gpio; -import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalInput; - -import com.pi4j.io.gpio.digital.PullResistance; - -import com.pi4j.io.gpio.digital.DigitalState; +import com.pi4j.io.gpio.digital.DigitalOutput; /** * GpioPinCfgData *

    - * Definitions used by the gpio package + * Definitions used by the gpio package *

    */ diff --git a/src/main/java/com/pi4j/devices/base_util/mapUtil/MapUtil.java b/src/main/java/com/pi4j/devices/base_util/mapUtil/MapUtil.java index ffcc134..d968460 100644 --- a/src/main/java/com/pi4j/devices/base_util/mapUtil/MapUtil.java +++ b/src/main/java/com/pi4j/devices/base_util/mapUtil/MapUtil.java @@ -34,16 +34,10 @@ package com.pi4j.devices.base_util.mapUtil; -import com.pi4j.io.gpio.digital.DigitalState; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import com.pi4j.devices.base_util.gpio.BaseGpioInOut; -import com.pi4j.devices.base_util.gpio.GpioBasics; import com.pi4j.devices.base_util.ffdc.FfdcUtil; -import com.pi4j.devices.base_util.gpio.GpioPinCfgData; -import com.pi4j.io.gpio.digital.PullResistance; +import com.pi4j.devices.base_util.gpio.BaseGpioInOut; + +import java.util.HashMap; /** @@ -78,12 +72,12 @@ public MapUtil(FfdcUtil ffdc, BaseGpioInOut baseUtil) { /** * createMap - *

    + *

    * PreCond: AppMapUtils instance initialized. See CTOR - * @param pin number for the string data - * @param dataStr String to converted to a dictionary - * @return Dictionary of details for the 'pin' * + * @param pin number for the string data + * @param dataStr String to converted to a dictionary + * @return Dictionary of details for the 'pin' */ public HashMap> createMap(int pin, String dataStr) { this.ffdc.ffdcMethodEntry("mcpConfigure::createMap"); @@ -92,7 +86,7 @@ public HashMap> createMap(int pin, String dataSt HashMap innerMap; outerMap = new HashMap>(); innerMap = new HashMap(); - String result = new String(); + String result = ""; // remove {} result = dataStr.replace("{", ""); result = result.replace("}", ""); @@ -103,7 +97,7 @@ public HashMap> createMap(int pin, String dataSt // split on , result = result.trim(); - String arrayDict[] = result.split(",", 0); + String[] arrayDict = result.split(",", 0); for (String temp1 : arrayDict) { String key = temp1.substring(0, temp1.indexOf(":")); String val = temp1.substring(temp1.indexOf(":") + 1); @@ -116,11 +110,11 @@ public HashMap> createMap(int pin, String dataSt /** * createXtraFullMap - *

    + *

    * PreCond: AppMapUtils instance initialized. See CTOR - * @param fullDataStr String to converted to a dictionary - * @return Dictionary of details for the 'pin' * + * @param fullDataStr String to converted to a dictionary + * @return Dictionary of details for the 'pin' */ public HashMap>> createXtraFullMap(String fullDataStr) { @@ -130,7 +124,7 @@ public HashMap>> createXtraFullM rMap = new HashMap>>(); HashMap> internalDetailMap; internalDetailMap = new HashMap>(); - String result = new String(); + String result = ""; result = fullDataStr.trim(); // remove ' result = result.replace("'", ""); @@ -142,7 +136,7 @@ public HashMap>> createXtraFullM // int cardIdStart = result.indexOf("{{", offset); // int cardIdEnd = result.indexOf(":" , offset) -1 ; // String cardName = result.substring( cardIdStart, cardIdEnd); - String rawText = new String(); + String rawText = ""; // int valueEnd = result.indexOf("}}}", cardIdStart); // end of this // cards @@ -170,11 +164,11 @@ public HashMap>> createXtraFullM /** * createFullMap - *

    + *

    * PreCond: AppMapUtils instance initialized. See CTOR - * @param fullDataStr String to converted to a dictionary - * @return Dictionary of details for the 'pin' * + * @param fullDataStr String to converted to a dictionary + * @return Dictionary of details for the 'pin' */ public HashMap> createFullMap(String fullDataStr) { // public void createFullMap(String FullDataStr) { @@ -184,7 +178,7 @@ public HashMap> createFullMap(String fullDataStr HashMap> tempMap; outerMap = new HashMap>(); innerMap = new HashMap(); - String result = new String(); + String result = ""; result = fullDataStr.trim(); // remove ' result = result.replace("'", ""); @@ -225,7 +219,7 @@ public HashMap> createFullMap(String fullDataStr majorKey = prepend + pinNum; } - String value = new String(); + String value = ""; endOfValue = ((result.indexOf("}", valueStart))); // starting at the inner brace, get all K/V's and the closing brace value = result.substring(result.indexOf("{", valueStart), (endOfValue + 1)); @@ -251,27 +245,27 @@ public HashMap> createFullMap(String fullDataStr /** * createMap - *

    - * Create HashMap using the two strings supplied as params - * pin5 {'dir':'out','int_ena':'no'} + *

    + * Create HashMap using the two strings supplied as params + * pin5 {'dir':'out','int_ena':'no'} * - *

    - *

    + *

    + *

    * PreCond: AppMapUtils instance initialized. See CTOR - *

    - * @param majorKey String to converted to a dictionary key - * @param dataStr String to convert to a HashMap value - * @return Dictionary of details for the majorkey + *

    * + * @param majorKey String to converted to a dictionary key + * @param dataStr String to convert to a HashMap value + * @return Dictionary of details for the majorkey */ - public HashMap> createMap(String majorKey, String dataStr) { + public HashMap> createMap(String majorKey, String dataStr) { this.ffdc.ffdcMethodEntry("mcpConfigure::createMap"); // System.out.println(" dataStr : " + dataStr); HashMap> outerMap; HashMap innerMap; outerMap = new HashMap>(); innerMap = new HashMap(); - String result = new String(); + String result = ""; // remove {} result = dataStr.replace("{", ""); result = result.replace("}", ""); @@ -282,7 +276,7 @@ public HashMap> createMap(String majorKey, Strin // split on , result = result.trim(); - String arrayDict[] = result.split(",", 0); + String[] arrayDict = result.split(",", 0); for (String temp1 : arrayDict) { String key = temp1.substring(0, temp1.indexOf(":")); String val = temp1.substring(temp1.indexOf(":") + 1); diff --git a/src/main/java/com/pi4j/devices/bme280/BME280DeviceI2C.java b/src/main/java/com/pi4j/devices/bme280/BME280DeviceI2C.java index ebbc6c2..d2a32c8 100644 --- a/src/main/java/com/pi4j/devices/bme280/BME280DeviceI2C.java +++ b/src/main/java/com/pi4j/devices/bme280/BME280DeviceI2C.java @@ -36,21 +36,20 @@ */ - import com.pi4j.Pi4J; -import com.pi4j.util.Console; import com.pi4j.io.i2c.I2C; import com.pi4j.io.i2c.I2CConfig; import com.pi4j.io.i2c.I2CProvider; +import com.pi4j.util.Console; import java.text.DecimalFormat; /** * Example code to read the temperature, humidity and pressure from a BME280 sensor, on an Adafruit board via I2C and SPI. - * + *

    * This example can be executed without sudo with: * jbang Pi4JTempHumPressI2C.java - * + *

    * Based on: * *

      @@ -58,7 +57,7 @@ *
    • https://www.adafruit.com/product/2652
    • *
    • https://learn.adafruit.com/adafruit-bme280-humidity-barometric-pressure-temperature-sensor-breakout/pinouts
    • *
    - * + *

    * I2C Wiring * *

      @@ -68,11 +67,11 @@ *
    • SDI to I2C data SDA (pin 3)
    • *
    • CS to 3.3v
    • *
    - * + *

    * Make sure I2C is enabled on the Raspberry Pi. Use `sudo raspi-config' > Interface Options > I2C. - * + *

    * Check that the sensor is detected on address 0x77 with ``. - * + *

    * $ i2cdetect -y 1 * 0 1 2 3 4 5 6 7 8 9 a b c d e f * 00: -- -- -- -- -- -- -- -- @@ -83,7 +82,6 @@ * 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- * 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- * 70: -- -- -- -- -- -- -- 77 - * */ public class BME280DeviceI2C { private static final Console console = new Console(); // Pi4J Logger helper @@ -115,10 +113,10 @@ public static void main(String[] args) throws Exception { console.println("Initializing the sensor via I2C"); I2CProvider i2CProvider = pi4j.provider("linuxfs-i2c"); I2CConfig i2cConfig = I2C.newConfigBuilder(pi4j) - .id("BME280") - .bus(I2C_BUS) - .device(address) - .build(); + .id("BME280") + .bus(I2C_BUS) + .device(address) + .build(); // Read values 10 times try (I2C bme280 = i2CProvider.create(i2cConfig)) { @@ -147,6 +145,7 @@ public static void main(String[] args) throws Exception { * The chip will be reset, forcing the POR (PowerOnReset) * steps to occur. Once completes the chip will be configured * to operate 'forced' mode and single sample. + * * @param device * @throws Exception */ @@ -156,7 +155,7 @@ private static void resetSensor(I2C device) throws Exception { // The sensor needs some time to complete POR steps Thread.sleep(300); int id = device.readRegister(BMP280Declares.chipId); - if(id != BMP280Declares.idValueMskBME) { + if (id != BMP280Declares.idValueMskBME) { console.println("Incorrect chip ID, NOT BME280"); System.exit(42); } @@ -177,7 +176,7 @@ private static void resetSensor(I2C device) throws Exception { ctlReg |= BMP280Declares.ctl_pressSamp1; // Pressure oversample 1 byte[] regVal = new byte[1]; - regVal[0] = (byte)(BMP280Declares.ctrl_meas); + regVal[0] = (byte) (BMP280Declares.ctrl_meas); byte[] ctlVal = new byte[1]; ctlVal[0] = (byte) ctlReg; @@ -188,13 +187,14 @@ private static void resetSensor(I2C device) throws Exception { * Three register sets containing the readings are read, then all factory * compensation registers are read. The compensated reading are calculated and * displayed. + * * @param device */ private static void getMeasurements(I2C device) { byte[] buff = new byte[6]; device.readRegister(BMP280Declares.press_msb, buff); - long adc_T = (long) ((buff[3] & 0xFF) << 12) | (long) ((buff[4] & 0xFF) << 4) | (long) ((buff[5] & 0x0F) >> 4); - long adc_P = (long) ((buff[0] & 0xFF) << 12) | (long) ((buff[1] & 0xFF) << 4) | (long) ((buff[2] & 0x0F)>> 4); + long adc_T = (long) ((buff[3] & 0xFF) << 12) | (long) ((buff[4] & 0xFF) << 4) | (long) ((buff[5] & 0x0F) >> 4); + long adc_P = (long) ((buff[0] & 0xFF) << 12) | (long) ((buff[1] & 0xFF) << 4) | (long) ((buff[2] & 0x0F) >> 4); byte[] buffHum = new byte[2]; device.readRegister(BMP280Declares.hum_msb, buffHum); @@ -218,12 +218,12 @@ private static void getMeasurements(I2C device) { double var1 = (((double) adc_T) / 16384.0 - ((double) dig_t1) / 1024.0) * ((double) dig_t2); double var2 = ((((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0) * - (((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0)) * ((double) dig_t3); + (((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0)) * ((double) dig_t3); double t_fine = (int) (var1 + var2); double temperature = (var1 + var2) / 5120.0; console.println("Temperature: " + df.format(temperature) + " °C"); - console.println("Temperature: " + df.format(temperature* 1.8 + 32) + " °F "); + console.println("Temperature: " + df.format(temperature * 1.8 + 32) + " °F "); // Pressure device.readRegister(BMP280Declares.reg_dig_p1, compVal); @@ -254,8 +254,7 @@ private static void getMeasurements(I2C device) { int dig_p9 = signedInt(compVal); - - var1 = ((double) t_fine / 2.0) - 64000.0; + var1 = (t_fine / 2.0) - 64000.0; var2 = var1 * var1 * ((double) dig_p6) / 32768.0; var2 = var2 + var1 * ((double) dig_p5) * 2.0; var2 = (var2 / 4.0) + (((double) dig_p4) * 65536.0); @@ -286,35 +285,34 @@ private static void getMeasurements(I2C device) { long dig_h1 = castOffSignByte(charVal[0]); device.readRegister(BMP280Declares.reg_dig_h2, compVal); - int dig_h2 = signedInt(compVal); + int dig_h2 = signedInt(compVal); device.readRegister(BMP280Declares.reg_dig_h3, charVal); long dig_h3 = castOffSignByte(charVal[0]); device.readRegister(BMP280Declares.reg_dig_h4, compVal); // get the bits - int dig_h4 = ((compVal[0]&0xff) << 4) | (compVal[1] & 0x0f) ; + int dig_h4 = ((compVal[0] & 0xff) << 4) | (compVal[1] & 0x0f); device.readRegister(BMP280Declares.reg_dig_h5, compVal); // get the bits - int dig_h5 = (compVal[0]&0x0f) | ((compVal[1] & 0xff) << 4); + int dig_h5 = (compVal[0] & 0x0f) | ((compVal[1] & 0xff) << 4); device.readRegister(BMP280Declares.reg_dig_h6, charVal); long dig_h6 = signedByte(charVal); - double humidity = (double)t_fine - 76800.0; - humidity = (adc_H -(((double)dig_h4) * 64.0 + ((double)dig_h5)/16384.0 * humidity)) * (((double)dig_h2)/65536.0 * (1.0 + ((double)dig_h6) /67108864.0 * humidity * (1.0 + ((double)dig_h3)/67108864.0 * humidity))); - humidity = humidity * (1.0 - ((double) dig_h1) * humidity/524288.0); - if(humidity > 100.0){ + double humidity = t_fine - 76800.0; + humidity = (adc_H - (((double) dig_h4) * 64.0 + ((double) dig_h5) / 16384.0 * humidity)) * (((double) dig_h2) / 65536.0 * (1.0 + ((double) dig_h6) / 67108864.0 * humidity * (1.0 + ((double) dig_h3) / 67108864.0 * humidity))); + humidity = humidity * (1.0 - ((double) dig_h1) * humidity / 524288.0); + if (humidity > 100.0) { humidity = 100.0; - }else if(humidity < 0.0){ + } else if (humidity < 0.0) { humidity = 0.0; } console.println("Humidity: " + df.format(humidity) + " %"); - } /** @@ -326,12 +324,11 @@ private static int castOffSignByte(byte read) { } /** - * * @param read 8 bits data * @return signed value */ private static int signedByte(byte[] read) { - return ((int)read[0] ); + return read[0]; } /** @@ -400,7 +397,6 @@ private static class BMP280Declares { static int reg_dig_h6 = 0xE7; // 3:0 11:4 - // register contents static int idValueMskBME = 0x60; // expected chpId value BME280 static int reset_cmd = 0xB6; // written to reset diff --git a/src/main/java/com/pi4j/devices/bme280/BME280DeviceSPI.java b/src/main/java/com/pi4j/devices/bme280/BME280DeviceSPI.java index a68457c..75979e2 100644 --- a/src/main/java/com/pi4j/devices/bme280/BME280DeviceSPI.java +++ b/src/main/java/com/pi4j/devices/bme280/BME280DeviceSPI.java @@ -35,24 +35,25 @@ */ package com.pi4j.devices.bme280; + import com.pi4j.Pi4J; -import com.pi4j.exception.LifecycleException; import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalState; -import com.pi4j.io.spi.*; +import com.pi4j.io.spi.Spi; +import com.pi4j.io.spi.SpiBus; +import com.pi4j.io.spi.SpiChipSelect; +import com.pi4j.io.spi.SpiMode; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; import java.text.DecimalFormat; /** * Example code to read the temperature, humidity and pressure from a BME280 sensor, on an Adafruit board via I2C and SPI. * Make sure to follow the README of this project to learn more about JBang and how to install it. - * + *

    * This example must be executed with sudo as it uses PiGpio with: * sudo `which jbang` Pi4JTempHumPressSpi.java - * + *

    * Based on: * *

      @@ -60,7 +61,7 @@ *
    • https://www.adafruit.com/product/2652
    • *
    • https://learn.adafruit.com/adafruit-bme280-humidity-barometric-pressure-temperature-sensor-breakout/pinouts
    • *
    - * + *

    * SPI Wiring * *

      @@ -71,12 +72,10 @@ *
    • SCK to SCLK (BCM11, pin 23)
    • *
    • CS to BCM21 (pin 40)
    • *
    - * */ public class BME280DeviceSPI { - private static final Console console = new Console(); // Pi4J Logger helper private static final String SPI_PROVIDER_NAME = "BME280 SPI Provider"; @@ -84,8 +83,9 @@ public class BME280DeviceSPI { private static final SpiChipSelect chipSelect = SpiChipSelect.CS_0; private static final SpiBus spiBus = SpiBus.BUS_0; - private static DigitalOutput csGpio; + private static DigitalOutput csGpio; private static Spi spi; + public static void main(String[] args) throws Exception { var pi4j = Pi4J.newAutoContext(); var csPin = 21; // BCM 21 = physical pin 40 @@ -93,20 +93,8 @@ public static void main(String[] args) throws Exception { // Initialize SPI console.println("Initializing the sensor via SPI"); - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); - String helpString = " parms: -csp chipSelectGPIO \n " ; + String helpString = " parms: -csp chipSelectGPIO \n "; for (int i = 0; i < args.length; i++) { String o = args[i]; if (o.contentEquals("-csp")) { // device address @@ -124,23 +112,23 @@ public void handle(Signal sig) { } var csGpioConfig = DigitalOutput.newConfigBuilder(pi4j) - .id("CS_pin") - .name("CS") - .address(csPin) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("CS_pin") + .name("CS") + .address(csPin) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); csGpio = pi4j.create(csGpioConfig); var spiConfig = Spi.newConfigBuilder(pi4j) - .id(SPI_PROVIDER_ID) - .name(SPI_PROVIDER_NAME) - .bus(spiBus) - .chipSelect(chipSelect) - .baud(Spi.DEFAULT_BAUD) - .mode(SpiMode.MODE_0) - .provider("pigpio-spi") - .build(); + .id(SPI_PROVIDER_ID) + .name(SPI_PROVIDER_NAME) + .bus(spiBus) + .chipSelect(chipSelect) + .baud(Spi.DEFAULT_BAUD) + .mode(SpiMode.MODE_0) + .provider("pigpio-spi") + .build(); spi = pi4j.create(spiConfig); // Read values 10 times @@ -168,15 +156,17 @@ public void handle(Signal sig) { * The chip will be reset, forcing the POR (PowerOnReset) * steps to occur. Once completes the chip will be configured * to operate 'forced' mode and single sample. + * * @throws Exception - */ private static void resetSensor() throws Exception { + */ + private static void resetSensor() throws Exception { int rc = writeRegister(BMP280Declares.reset, BMP280Declares.reset_cmd); // The sensor needs some time to complete POR steps Thread.sleep(300); int id = readRegister(BMP280Declares.chipId); - if(id != BMP280Declares.idValueMskBME) { + if (id != BMP280Declares.idValueMskBME) { console.println("Incorrect chip ID, NOT BME280"); System.exit(42); } @@ -195,11 +185,11 @@ public void handle(Signal sig) { ctlReg |= BMP280Declares.ctl_pressSamp1; // Pressure oversample 1 byte[] regVal = new byte[1]; - regVal[0] = (byte)(BMP280Declares.ctrl_meas); + regVal[0] = (byte) (BMP280Declares.ctrl_meas); byte[] ctlVal = new byte[1]; ctlVal[0] = (byte) ctlReg; - writeRegister(BMP280Declares.ctrl_meas,ctlVal[0]); + writeRegister(BMP280Declares.ctrl_meas, ctlVal[0]); } /** @@ -210,8 +200,8 @@ public void handle(Signal sig) { private static void getMeasurements() { byte[] buff = new byte[6]; readRegister(BMP280Declares.press_msb, buff); - long adc_T = (long) ((buff[3] & 0xFF) << 12) | (long) ((buff[4] & 0xFF) << 4) | (long) ((buff[5] & 0x0F) >> 4); - long adc_P = (long) ((buff[0] & 0xFF) << 12) | (long) ((buff[1] & 0xFF) << 4) | (long) ((buff[2] & 0x0F)>> 4); + long adc_T = (long) ((buff[3] & 0xFF) << 12) | (long) ((buff[4] & 0xFF) << 4) | (long) ((buff[5] & 0x0F) >> 4); + long adc_P = (long) ((buff[0] & 0xFF) << 12) | (long) ((buff[1] & 0xFF) << 4) | (long) ((buff[2] & 0x0F) >> 4); byte[] buffHum = new byte[2]; readRegister(BMP280Declares.hum_msb, buffHum); @@ -233,12 +223,12 @@ private static void getMeasurements() { double var1 = (((double) adc_T) / 16384.0 - ((double) dig_t1) / 1024.0) * ((double) dig_t2); double var2 = ((((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0) * - (((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0)) * ((double) dig_t3); + (((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0)) * ((double) dig_t3); double t_fine = (int) (var1 + var2); double temperature = (var1 + var2) / 5120.0; console.println("Temperature: " + df.format(temperature) + " °C"); - console.println("Temperature: " + df.format(temperature* 1.8 + 32) + " °F "); + console.println("Temperature: " + df.format(temperature * 1.8 + 32) + " °F "); // Pressure readRegister(BMP280Declares.reg_dig_p1, compVal); @@ -268,7 +258,7 @@ private static void getMeasurements() { readRegister(BMP280Declares.reg_dig_p9, compVal); int dig_p9 = signedInt(compVal); - var1 = ((double) t_fine / 2.0) - 64000.0; + var1 = (t_fine / 2.0) - 64000.0; var2 = var1 * var1 * ((double) dig_p6) / 32768.0; var2 = var2 + var1 * ((double) dig_p5) * 2.0; var2 = (var2 / 4.0) + (((double) dig_p4) * 65536.0); @@ -297,29 +287,29 @@ private static void getMeasurements() { long dig_h1 = castOffSignByte(charVal[0]); readRegister(BMP280Declares.reg_dig_h2, compVal); - int dig_h2 = signedInt(compVal); + int dig_h2 = signedInt(compVal); readRegister(BMP280Declares.reg_dig_h3, charVal); long dig_h3 = castOffSignByte(charVal[0]); readRegister(BMP280Declares.reg_dig_h4, compVal); // get the bits - int dig_h4 = (compVal[0] << 4) | (compVal[1] & 0x0f) ; + int dig_h4 = (compVal[0] << 4) | (compVal[1] & 0x0f); readRegister(BMP280Declares.reg_dig_h5, compVal); // get the bits - int dig_h5 = (compVal[0]&0x0f) | ((compVal[1] & 0xff) << 4); + int dig_h5 = (compVal[0] & 0x0f) | ((compVal[1] & 0xff) << 4); readRegister(BMP280Declares.reg_dig_h6, charVal); long dig_h6 = signedByte(charVal); - double humidity = (double)t_fine - 76800.0; - humidity = (adc_H -(((double)dig_h4) * 64.0 + ((double)dig_h5)/16384.0 * humidity)) * (((double)dig_h2)/65536.0 * (1.0 + ((double)dig_h6) /67108864.0 * humidity * (1.0 + ((double)dig_h3)/67108864.0 * humidity))); - humidity = humidity * (1.0 - ((double) dig_h1) * humidity/524288.0); - if(humidity > 100.0){ + double humidity = t_fine - 76800.0; + humidity = (adc_H - (((double) dig_h4) * 64.0 + ((double) dig_h5) / 16384.0 * humidity)) * (((double) dig_h2) / 65536.0 * (1.0 + ((double) dig_h6) / 67108864.0 * humidity * (1.0 + ((double) dig_h3) / 67108864.0 * humidity))); + humidity = humidity * (1.0 - ((double) dig_h1) * humidity / 524288.0); + if (humidity > 100.0) { humidity = 100.0; - }else if(humidity < 0.0){ + } else if (humidity < 0.0) { humidity = 0.0; } @@ -335,9 +325,9 @@ private static void getMeasurements() { private static int readRegister(int register) { //console.println(">>> Enter readRegister : " + String.format("0X%02x: ", register)); csGpio.low(); - byte data[] = new byte[]{(byte) (0b10000000 | register)}; + byte[] data = new byte[]{(byte) (0b10000000 | register)}; int bytesWritten = spi.write(data); - byte value[] = new byte[1]; + byte[] value = new byte[1]; byte rval = spi.readByte(); csGpio.high(); //console.println("<<< Exit readRegister : " + String.format("0X%02x: ", rval)); @@ -351,7 +341,7 @@ private static int readRegister(int register) { */ private static int readRegister(int register, byte[] buffer) { //console.println(">>> Enter readRegister : " + String.format("0X%02x: ", register)); - byte data[] = new byte[]{(byte) (0b10000000 | register)}; + byte[] data = new byte[]{(byte) (0b10000000 | register)}; csGpio.low(); int bytesWritten = spi.write(data); int bytesRead = spi.read(buffer); @@ -369,10 +359,10 @@ private static int writeRegister(int register, int data) { // console.println(">>> Enter writeRegister : " + String.format("0X%02x: ", register)); int rval = 0; int byteswritten = -1; - byte buffer[] = new byte[]{(byte) (0b01111111 & register), - (byte) data + byte[] buffer = new byte[]{(byte) (0b01111111 & register), + (byte) data }; - byte dummy[] = new byte[2]; + byte[] dummy = new byte[2]; // send read request to BMP chip via SPI channel csGpio.low(); byteswritten = spi.write(buffer); @@ -410,13 +400,13 @@ private static long castOffSignInt(byte[] read) { temp += (((long) read[1] & 0xff)) << 8; return (temp); } + /** - * * @param read 8 bits data * @return signed value */ private static int signedByte(byte[] read) { - return ((int)read[0] ); + return read[0]; } private static class BMP280Declares { @@ -496,5 +486,4 @@ private static class BMP280Declares { } - } diff --git a/src/main/java/com/pi4j/devices/bme280/README.md b/src/main/java/com/pi4j/devices/bme280/README.md index de11ad6..038ce68 100644 --- a/src/main/java/com/pi4j/devices/bme280/README.md +++ b/src/main/java/com/pi4j/devices/bme280/README.md @@ -1,22 +1,20 @@ - https://pdf1.alldatasheet.com/datasheet-pdf/view/1132060/BOSCH/BME280.html - - - The program uses org.slf4j.simple Class SimpleLogger as suggested by the Pi4j_V2 documentation. Consult that logger class documentation to understand its various logging options. I2C connection path. + 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runBME280I2C.sh -Args if bus and or address must be set + Args if bus and or address must be set -b 0x01 -a 0x77 The SPI example assumes SPI bus 0, ChipSelect GPIO 21. The GPIO is configurable as a program parm option. -The SPI connection per the Datasheet supports MODE0 or MODE3. The spec shows reading a register consists of: +The SPI connection per the Datasheet supports MODE0 or MODE3. The spec shows reading a register consists of: + 1. Chip select driven low 2. Eight clocks pulses to write the register address via the Pi MOSI 3. Multiple eight clock pulses for each byte of data returned thru the Pi MISO @@ -29,23 +27,20 @@ the chips config register be modified. As most chips use 4-wire configuration I GPIO as the CS (chip select) SPI connection path. + 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runBME280SPI.sh -csp 21 - - No parameters are required. However, if 'any' parameter value is to be supplied: parms: -b hex value bus -a hex value address -t trace trace values : "trace", "debug", "info", "warn", "error" or "off" Default "info" - - SPI connection using 4-wire SPI -Pi p19 MOSI BMP SDI Blue -Pi p21 MISO BMP SDO Yellow -Pi p23 SCLK BMP SCK Green -Pi p40 GPIO21 BMP CS Orange -Pi Gnd BMP GND Brown -Pi 3.3 BMP Vin Red \ No newline at end of file +Pi p19 MOSI BMP SDI Blue +Pi p21 MISO BMP SDO Yellow +Pi p23 SCLK BMP SCK Green +Pi p40 GPIO21 BMP CS Orange +Pi Gnd BMP GND Brown +Pi 3.3 BMP Vin Red \ No newline at end of file diff --git a/src/main/java/com/pi4j/devices/bmp280/BMP280Device.java b/src/main/java/com/pi4j/devices/bmp280/BMP280Device.java index 5fd8fc2..70b6c4d 100644 --- a/src/main/java/com/pi4j/devices/bmp280/BMP280Device.java +++ b/src/main/java/com/pi4j/devices/bmp280/BMP280Device.java @@ -32,11 +32,8 @@ import com.pi4j.context.Context; -import com.pi4j.io.i2c.I2C; -import com.pi4j.io.i2c.I2CConfig; import com.pi4j.util.Console; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @@ -64,8 +61,6 @@ public abstract class BMP280Device implements BMP280Interface { public static final String ID = "BMP280"; - - private static final int t1 = 0; private static final int t2 = 1; private static final int t3 = 2; @@ -84,16 +79,14 @@ public abstract class BMP280Device implements BMP280Interface { protected String traceLevel; - protected Context pi4j = null; protected Console console = null; - /** - * @param pi4j Context instance used across application - * @param console + * @param pi4j Context instance used across application + * @param console * @param traceLevel for Logger */ public BMP280Device(Context pi4j, Console console, String traceLevel) { @@ -101,12 +94,9 @@ public BMP280Device(Context pi4j, Console console, String traceLevel) { this.pi4j = pi4j; this.console = console; this.traceLevel = traceLevel; - - } + } - - /** * @param read 8 bits data @@ -146,7 +136,6 @@ private long castOffSignInt(byte[] read) { } - /** * Reset BMP280 chip to remove any previous applications configuration details. *

    @@ -176,9 +165,9 @@ public double[] readBMP280() { ctlVal[0] = (byte) ctlReg; - this.writeRegister(BMP280Declares.ctrl_meas,ctlVal[0]); + this.writeRegister(BMP280Declares.ctrl_meas, ctlVal[0]); - // this.writeRegister(BMP280Declares.ctrl_meas, ctlReg); + // this.writeRegister(BMP280Declares.ctrl_meas, ctlReg); // Next delay for 100 ms to provide chip time to perform measurements @@ -193,9 +182,9 @@ public double[] readBMP280() { byte[] compVal = new byte[2]; - this.readRegister(BMP280Declares.reg_dig_t1, compVal); + this.readRegister(BMP280Declares.reg_dig_t1, compVal); - long dig_t1 = castOffSignInt(compVal); + long dig_t1 = castOffSignInt(compVal); this.readRegister(BMP280Declares.reg_dig_t2, compVal); int dig_t2 = signedInt(compVal); @@ -254,7 +243,7 @@ public double[] readBMP280() { double var1, var2, T, P; var1 = (((double) adc_T) / 16384.0 - ((double) dig_t1) / 1024.0) * ((double) dig_t2); var2 = ((((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0) * - (((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0)) * ((double) dig_t3); + (((double) adc_T) / 131072.0 - ((double) dig_t1) / 8192.0)) * ((double) dig_t3); t_fine = (int) (var1 + var2); T = (var1 + var2) / 5120.0; @@ -350,7 +339,7 @@ public void resetSensor() { } catch (InterruptedException e) { e.printStackTrace(); } - this.logger.trace("exit: resetSensor rc : " + rc); + this.logger.trace("exit: resetSensor rc : " + rc); } @@ -364,9 +353,9 @@ public void initSensor() { this.resetSensor(); // read 0xD0 validate data equal 0x58 or 0x60 int id = this.readRegister(BMP280Declares.chipId); - if((id == BMP280Declares.idValueMskBMP) || (id == BMP280Declares.idValueMskBME)) { + if ((id == BMP280Declares.idValueMskBMP) || (id == BMP280Declares.idValueMskBME)) { this.logger.trace("Correct chip ID read"); - }else{ + } else { System.out.println("Incorrect chip ID read"); System.exit(42); } diff --git a/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceI2C.java b/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceI2C.java index e046dda..97f32e7 100644 --- a/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceI2C.java +++ b/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceI2C.java @@ -43,7 +43,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class BMP280DeviceI2C extends BMP280Device{ +public class BMP280DeviceI2C extends BMP280Device { protected int busNum = BMP280Declares.DEFAULT_BUS; protected int address = BMP280Declares.DEFAULT_ADDRESS; @@ -68,7 +68,7 @@ public BMP280DeviceI2C(Context pi4j, Console console, int bus, int address, Stri this.address = address; this.busNum = bus; this.console = console; - // "trace", "debug", "info", "warn", "error" or "off"). If not specified, defaults to "info" + // "trace", "debug", "info", "warn", "error" or "off"). If not specified, defaults to "info" // must fully qualify logger as others exist and the slf4 code will use the first it // encounters if using the defaultLogLevel System.setProperty("org.slf4j.simpleLogger.log." + BMP280DeviceI2C.class.getName(), traceLevel); @@ -77,19 +77,19 @@ public BMP280DeviceI2C(Context pi4j, Console console, int bus, int address, Stri this.createI2cDevice(); // will set start this.i2c } - /** - * @param console Context instance used across application - * @param bus Pi bus - * @param address Device address - * @param logger Instantiated Logger - */ - public BMP280DeviceI2C(Context pi4j, Console console, int bus, int address, Logger logger) { - super(pi4j, console, "info"); - this.address = address; - this.busNum = bus; - this.logger = logger; - this.createI2cDevice(); // will set start this.i2c - } + /** + * @param console Context instance used across application + * @param bus Pi bus + * @param address Device address + * @param logger Instantiated Logger + */ + public BMP280DeviceI2C(Context pi4j, Console console, int bus, int address, Logger logger) { + super(pi4j, console, "info"); + this.address = address; + this.busNum = bus; + this.logger = logger; + this.createI2cDevice(); // will set start this.i2c + } /** * @param device Set i2c state @@ -125,12 +125,12 @@ private void createI2cDevice() { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id(id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id(id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); this.config = i2cDeviceConfig; this.i2c = this.pi4j.create(i2cDeviceConfig); this.logger.info("Exit:createI2cDevice "); @@ -158,42 +158,37 @@ public I2CConfig config() { } /** - * - * @param register - * @return 8bit value read from register + * @param register + * @return 8bit value read from register */ - public int readRegister(int register){ + public int readRegister(int register) { int rval = 0; - rval =this.i2c.readRegister(register); - return(rval); + rval = this.i2c.readRegister(register); + return (rval); } /** - * - * @param register register address - * @param buffer Buffer to return read data + * @param register register address + * @param buffer Buffer to return read data * @return count number bytes read or fail -1 */ - public int readRegister(int register, byte[] buffer){ + public int readRegister(int register, byte[] buffer) { int rval = 0; - rval =this.i2c.readRegister(register, buffer); - return(rval); + rval = this.i2c.readRegister(register, buffer); + return (rval); } - - /** - * - * @param register register - * @param data byte to write + * @param register register + * @param data byte to write * @return bytes written, else -1 */ - public int writeRegister(int register, int data){ + public int writeRegister(int register, int data) { int rval = 0; rval = this.i2c.writeRegister(register, data); - return(rval); + return (rval); } diff --git a/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceSPI.java b/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceSPI.java index a2733f6..26a3839 100644 --- a/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceSPI.java +++ b/src/main/java/com/pi4j/devices/bmp280/BMP280DeviceSPI.java @@ -104,12 +104,12 @@ private void init() { // required all configs var outputConfig2 = DigitalOutput.newConfigBuilder(pi4j) - .id("CS_pin") - .name("CS") - .address(this.csPin) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("CS_pin") + .name("CS") + .address(this.csPin) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { this.csGpio = pi4j.create(outputConfig2); } catch (Exception e) { @@ -130,17 +130,17 @@ private void init() { private void createSPIDevice() { this.logger.info(">>> Enter:createSPIDevice bus " + this.spiBus + " CS Gpio" + this.csGpio.toString()); var spiConfig = Spi.newConfigBuilder(this.pi4j) - .id("SPI" + this.spiBus + "_BMP280") - .name("D/A converter") - .bus(this.spiBus) - .chipSelect(this.chipSlct) - //1 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 - //b b b b b b R T n n n n W A u2 u1 u0 p2 p1 p0 m m - // .flags(0b0000000000000000100000L) // MODE0, ux GPIO not used for chip select - .baud(Spi.DEFAULT_BAUD) // Max 10MHz - .mode(SpiMode.MODE_0) - .provider("pigpio-spi") - .build(); + .id("SPI" + this.spiBus + "_BMP280") + .name("D/A converter") + .bus(this.spiBus) + .chipSelect(this.chipSlct) + //1 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 + //b b b b b b R T n n n n W A u2 u1 u0 p2 p1 p0 m m + // .flags(0b0000000000000000100000L) // MODE0, ux GPIO not used for chip select + .baud(Spi.DEFAULT_BAUD) // Max 10MHz + .mode(SpiMode.MODE_0) + .provider("pigpio-spi") + .build(); this.spi = this.pi4j.create(spiConfig); this.logger.info("Exit:createSPIDevice "); } @@ -153,9 +153,9 @@ private void createSPIDevice() { public int readRegister(int register) { this.logger.trace(">>> Enter readRegister : " + String.format("0X%02x: ", register)); this.csGpio.low(); - byte data[] = new byte[]{(byte) (0b10000000 | register)}; + byte[] data = new byte[]{(byte) (0b10000000 | register)}; int bytesWritten = this.spi.write(data); - byte value[] = new byte[1]; + byte[] value = new byte[1]; byte rval = this.spi.readByte(); this.csGpio.high(); this.logger.trace("<<< Exit readRegister : " + String.format("0X%02x: ", rval)); @@ -169,7 +169,7 @@ public int readRegister(int register) { */ public int readRegister(int register, byte[] buffer) { this.logger.trace(">>> Enter readRegister : " + String.format("0X%02x: ", register)); - byte data[] = new byte[]{(byte) (0b10000000 | register)}; + byte[] data = new byte[]{(byte) (0b10000000 | register)}; this.csGpio.low(); int bytesWritten = this.spi.write(data); int bytesRead = this.spi.read(buffer); @@ -188,10 +188,10 @@ public int writeRegister(int register, int data) { this.logger.trace(">>> Enter writeRegister : " + String.format("0X%02x: ", register)); int rval = 0; int byteswritten = -1; - byte buffer[] = new byte[]{(byte) (0b01111111 & register), - (byte) data + byte[] buffer = new byte[]{(byte) (0b01111111 & register), + (byte) data }; - byte dummy[] = new byte[2]; + byte[] dummy = new byte[2]; // send read request to BMP chip via SPI channel this.csGpio.low(); byteswritten = this.spi.write(buffer); diff --git a/src/main/java/com/pi4j/devices/bmp280/BMP280I2cExample.java b/src/main/java/com/pi4j/devices/bmp280/BMP280I2cExample.java index c85673e..19c29ec 100644 --- a/src/main/java/com/pi4j/devices/bmp280/BMP280I2cExample.java +++ b/src/main/java/com/pi4j/devices/bmp280/BMP280I2cExample.java @@ -32,13 +32,9 @@ import com.pi4j.Pi4J; - -import com.pi4j.exception.LifecycleException; - import com.pi4j.context.Context; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; + /** * Class to test and demonstrate the BMP280 device. @@ -76,8 +72,7 @@ public static void main(String[] args) throws Exception { // may include 'Platforms' and 'I/O Providers' - - Context pi4j = Pi4J.newAutoContext(); + Context pi4j = Pi4J.newAutoContext(); // print installed providers System.out.println("----------------------------------------------------------"); @@ -85,19 +80,6 @@ public static void main(String[] args) throws Exception { System.out.println("----------------------------------------------------------"); pi4j.providers().describe().print(System.out); System.out.println("----------------------------------------------------------"); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); final Console console = new Console(); @@ -107,7 +89,7 @@ public void handle(Signal sig) { String helpString = " parms: -b hex value bus -a hex value address -t trace \n " + - " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; + " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { String o = args[i]; diff --git a/src/main/java/com/pi4j/devices/bmp280/BMP280Interface.java b/src/main/java/com/pi4j/devices/bmp280/BMP280Interface.java index 96b935d..a7709a1 100644 --- a/src/main/java/com/pi4j/devices/bmp280/BMP280Interface.java +++ b/src/main/java/com/pi4j/devices/bmp280/BMP280Interface.java @@ -80,9 +80,8 @@ public interface BMP280Interface { double pressureMb(); /** - * - * @param register - * @return 8bit value read from register + * @param register + * @return 8bit value read from register */ int readRegister(int register); @@ -92,12 +91,11 @@ public interface BMP280Interface { * @param buffer Buffer to return read data * @return count number bytes read or fail -1 */ - // int readRegister(byte[] register, byte[] buffer); + // int readRegister(byte[] register, byte[] buffer); /** - * - * @param register register address - * @param buffer Buffer to return read data + * @param register register address + * @param buffer Buffer to return read data * @return count number bytes read or fail -1 */ int readRegister(int register, byte[] buffer); @@ -109,13 +107,12 @@ public interface BMP280Interface { * @param dataLength lentgh of data to write * @return bytes written, else -1 */ - // int writeRegister(byte[] register, byte[] data, int dataLength); + // int writeRegister(byte[] register, byte[] data, int dataLength); /** - * - * @param register byte register - * @param data byte data to write + * @param register byte register + * @param data byte data to write * @return bytes written, else -1 */ int writeRegister(int register, int data); diff --git a/src/main/java/com/pi4j/devices/bmp280/BMP280SpiExample.java b/src/main/java/com/pi4j/devices/bmp280/BMP280SpiExample.java index b8e24a1..7733867 100644 --- a/src/main/java/com/pi4j/devices/bmp280/BMP280SpiExample.java +++ b/src/main/java/com/pi4j/devices/bmp280/BMP280SpiExample.java @@ -38,15 +38,12 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; import com.pi4j.io.spi.SpiBus; import com.pi4j.io.spi.SpiChipSelect; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; -public class BMP280SpiExample { +public class BMP280SpiExample { /** @@ -78,7 +75,7 @@ public static void main(String[] args) throws Exception { // extensions found in the application's classpath which // may include 'Platforms' and 'I/O Providers' - Context pi4j = Pi4J.newAutoContext(); + Context pi4j = Pi4J.newAutoContext(); // print installed providers System.out.println("----------------------------------------------------------"); @@ -86,19 +83,6 @@ public static void main(String[] args) throws Exception { System.out.println("----------------------------------------------------------"); pi4j.providers().describe().print(System.out); System.out.println("----------------------------------------------------------"); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); final Console console = new Console(); @@ -108,15 +92,15 @@ public void handle(Signal sig) { String helpString = " parms: -t trace -csp chipSelectGPIO \n " + - " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; + " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { String o = args[i]; if (o.contentEquals("-csp")) { // device address - String a = args[i + 1]; - i++; - csPin = Integer.parseInt(a); - } else if (o.contentEquals("-t")) { // device address + String a = args[i + 1]; + i++; + csPin = Integer.parseInt(a); + } else if (o.contentEquals("-t")) { // device address String a = args[i + 1]; i++; traceLevel = a; @@ -139,15 +123,12 @@ public void handle(Signal sig) { var bmpDev = new BMP280DeviceSPI(pi4j, console, spiBus, chipSelect, csPin, traceLevel); - - - bmpDev.initSensor(); console.println(" Setup ----------------------------------------------------------"); - double reading1 = bmpDev.temperatureC(); + double reading1 = bmpDev.temperatureC(); console.println(" Temperatue C = " + reading1); double reading2 = bmpDev.temperatureF(); diff --git a/src/main/java/com/pi4j/devices/bmp280/README.md b/src/main/java/com/pi4j/devices/bmp280/README.md index ed98343..e8c2959 100644 --- a/src/main/java/com/pi4j/devices/bmp280/README.md +++ b/src/main/java/com/pi4j/devices/bmp280/README.md @@ -8,7 +8,6 @@ The I2C example program has the assumption the BMP280 is connected to Pi bus 1, operate as device address 0x77. If these assumptions are not possible, the bus and device address value can be passed as parms. Or modify the BMP280I2cExample program to use your specific bus and device address. - The SPI example assumes SPI bus 0, ChipSelect GPIO 21. The GPIO is configurable as a program parm option. The program uses org.slf4j.simple Class SimpleLogger as suggested by the Pi4j_V2 documentation. Consult that logger @@ -16,41 +15,35 @@ class documentation to understand its various logging options. The I2C connection functions as written in the Phillips spec. - I2C connection path. + 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runBMP280I2C.sh Args if bus and or address must be set -b 0x01 -a 0x77 +The SPI connection per the Datasheet supports MODE0 or MODE3. The spec shows reading a register consists of: - -The SPI connection per the Datasheet supports MODE0 or MODE3. The spec shows reading a register consists of: -1. Chip select driven low +1. Chip select driven low 2. Eight clocks pulses to write the register address via the Pi MOSI 3. Multiple eight clock pulses for each byte of data returned thru the Pi MISO 4. Chip select driven high In either Mode0 or Mode3 the read data bytes are miss-read and the clock pulses are not signaled for the expected reads. The SPI open flags support configuration of writing a determined number of bytes before continuing the clock pulses -for the expected read data . This however requires the BMP280 chip connect using the 3-wire configuration and -the chips config register be modified. As most chips use 4-wire configuration I use 4-wire, and use a configurable +for the expected read data . This however requires the BMP280 chip connect using the 3-wire configuration and +the chips config register be modified. As most chips use 4-wire configuration I use 4-wire, and use a configurable GPIO as the CS (chip select) - - SPI connection path. + 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runBMP280SPI.sh -csp 21 - - - -Use of different bus or device address, use the applicable values in the following command. -sudo ./runBMP280I2C.sh -b 0x01 -a 0x77 - +Use of different bus or device address, use the applicable values in the following command. +sudo ./runBMP280I2C.sh -b 0x01 -a 0x77 Will create the BMP280 device to create a BMP280Device instance Call the various temperature and pressure methods defined in the interface. The device defaults to Pi Bus 1 and device address 0X77 @@ -61,28 +54,27 @@ trace values : "trace", "debug", "info", "warn", "error" or "off" Default "info The file BMP280.pdf documents a method of connecting an Adafruit BMP280 to a Pi. +I2C connection -I2C connection - -| RPi | Color | Sensor | -| :--- | :--- | :--- | -| Pin1 3.3V | Red | Vin | -| N/C | | 3v | -| Pin6 Gnd | Brown | Gnd | -| Pin5 SCL | Green | SCK | -| N/C | Yellow | SDO | -| Pin3 SDA | Blue | SDI | -| Pin17 3.3v | Orange | CS | +| RPi | Color | Sensor | +|:-----------|:-------|:-------| +| Pin1 3.3V | Red | Vin | +| N/C | | 3v | +| Pin6 Gnd | Brown | Gnd | +| Pin5 SCL | Green | SCK | +| N/C | Yellow | SDO | +| Pin3 SDA | Blue | SDI | +| Pin17 3.3v | Orange | CS | SPI connection using 4-wire SPI -| RPi | Color | Sensor | -| :--- | :--- | :--- | -| Pin19 MOSI | Blue | SDI | -| Pin21 MISO | Yellow | SDO | -| Pin23 SCLK | Green | SCK | -| Pin40 GPIO21| Orange | CS | -| Pin6 Gnd | Brown | GND | -| Pin1 3.3V | Red | Vin | +| RPi | Color | Sensor | +|:-------------|:-------|:-------| +| Pin19 MOSI | Blue | SDI | +| Pin21 MISO | Yellow | SDO | +| Pin23 SCLK | Green | SCK | +| Pin40 GPIO21 | Orange | CS | +| Pin6 Gnd | Brown | GND | +| Pin1 3.3V | Red | Vin | diff --git a/src/main/java/com/pi4j/devices/cp2102n/CP2102N.java b/src/main/java/com/pi4j/devices/cp2102n/CP2102N.java index 6d6ed18..0b3f45d 100644 --- a/src/main/java/com/pi4j/devices/cp2102n/CP2102N.java +++ b/src/main/java/com/pi4j/devices/cp2102n/CP2102N.java @@ -37,8 +37,6 @@ package com.pi4j.devices.cp2102n; import com.pi4j.context.Context; -import com.pi4j.devices.vl53L0X.VL53L0X_Device; -import com.pi4j.io.i2c.I2C; import com.pi4j.io.serial.FlowControl; import com.pi4j.io.serial.Parity; import com.pi4j.io.serial.Serial; @@ -63,23 +61,23 @@ public CP2102N(Context pi4j, String traceLevel) { Serial createSerialDevice() { - String id = String.format("CP2102N"); - String name = String.format("Serial-USB"); - this.logger.info("Enter: createSerialDevice CP2102N" + id + "" + name); + String id = "CP2102N"; + String name = "Serial-USB"; + this.logger.info("Enter: createSerialDevice CP2102N" + id + name); Serial rval = null; - rval =pi4j.create(Serial.newConfigBuilder(pi4j) - .use_9600_N81() - .dataBits_8() - .parity(Parity.NONE) //or ODD or EVEN - .stopBits(StopBits._1) - .flowControl(FlowControl.NONE) - .id(id) - .name(name) - .device("/dev/ttyAMA0") - .provider("linuxfsserial") - .build()); + rval = pi4j.create(Serial.newConfigBuilder(pi4j) + .use_9600_N81() + .dataBits_8() + .parity(Parity.NONE) //or ODD or EVEN + .stopBits(StopBits._1) + .flowControl(FlowControl.NONE) + .id(id) + .name(name) + .device("/dev/ttyAMA0") + .provider("linuxfsserial") + .build()); - this.logger.info("Exit: createSerialDevice CP2102N" + id + "" + name); + this.logger.info("Exit: createSerialDevice CP2102N" + id + name); return (rval); } @@ -92,13 +90,13 @@ void init() { public void sendData(String s) { this.logger.info("Enter:sendData data : " + s); - if(this.device.isOpen() == false){ + if (!this.device.isOpen()) { this.logger.error("Serial device not open"); System.exit(43); } byte[] command = s.getBytes(); for (int c = 0; c < command.length; c++) { - this.logger.trace("Uart send byte " + c + " :" +String.format("%02X ", command[c])); + this.logger.trace("Uart send byte " + c + " :" + String.format("%02X ", command[c])); } this.logger.trace(command.toString()); this.device.write(command); @@ -106,10 +104,9 @@ public void sendData(String s) { } - private final Context pi4j; private final Logger logger; - private Serial device; + private final Serial device; private final String traceLevel; diff --git a/src/main/java/com/pi4j/devices/cp2102n/CP2102N_App.java b/src/main/java/com/pi4j/devices/cp2102n/CP2102N_App.java index 5f04285..c08d521 100644 --- a/src/main/java/com/pi4j/devices/cp2102n/CP2102N_App.java +++ b/src/main/java/com/pi4j/devices/cp2102n/CP2102N_App.java @@ -38,12 +38,8 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.devices.vl53L0X.VL53L0X_Device; -import com.pi4j.devices.vl53L0X.Vl53L0X_Declares; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; + public class CP2102N_App { @@ -55,19 +51,6 @@ public static void main(String[] args) { /* var pi4j = Pi4J.newContextBuilder().add( linuxfs-i2cProvider.newInstance()).build(); */ - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); final Console console = new Console(); @@ -81,14 +64,14 @@ public void handle(Signal sig) { int gpioReset = 0; String helpString = " parms: -t trace \n " + - " -r reset integer value GPIO \n " + - " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; + " -r reset integer value GPIO \n " + + " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { String o = args[i]; - if (o.contentEquals("-t")) { // device address + if (o.contentEquals("-t")) { // device address String a = args[i + 1]; i++; traceLevel = a; @@ -98,7 +81,7 @@ public void handle(Signal sig) { console.println("Changing trace level invalid : " + traceLevel); System.exit(40); } - } else if (o.contentEquals("-r")) { + } else if (o.contentEquals("-r")) { String a = args[i + 1]; doReset = true; gpioReset = Integer.parseInt(a); @@ -112,7 +95,7 @@ public void handle(Signal sig) { System.exit(42); } } - if (doReset ) { + if (doReset) { // TODO //use gpioReset System.exit(43); diff --git a/src/main/java/com/pi4j/devices/cp2102n/README.md b/src/main/java/com/pi4j/devices/cp2102n/README.md index 13f0ebf..d4e4abe 100644 --- a/src/main/java/com/pi4j/devices/cp2102n/README.md +++ b/src/main/java/com/pi4j/devices/cp2102n/README.md @@ -1,43 +1,71 @@ - Pi4J :: Java I/O Library for Raspberry Pi :: Device :: CP2102N serial to USB ========================================================================== ### This repository contains device specific support for various devices. -### This is an example implementation and will need to be adjusted to fit your needs. +### This is an example implementation and will need to be adjusted to fit your needs. Project by Tom Aarts ========================================================================== * -# * - -# * #%L -# * ********************************************************************** -# * ORGANIZATION : Pi4J -# * PROJECT : Pi4J :: EXTENSION -# * FILENAME : README.md -# * -# * This file is part of the Pi4J project. More information about -# * this project can be found here: https://pi4j.com/ -# * ********************************************************************** -# * %% -# * * Copyright (C) 2012 - 2023 Pi4J -# * %% -# * -# * Licensed under the Apache License, Version 2.0 (the "License"); -# * you may not use this file except in compliance with the License. -# * You may obtain a copy of the License at -# * -# * http://www.apache.org/licenses/LICENSE-2.0 -# * -# * Unless required by applicable law or agreed to in writing, software -# * distributed under the License is distributed on an "AS IS" BASIS, -# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# * See the License for the specific language governing permissions and -# * limitations under the License. -# * #L% -# * + +# * - + +# * #%L + +# * ********************************************************************** + +# * ORGANIZATION : Pi4J + +# * PROJECT : Pi4J :: EXTENSION + +# * FILENAME : README.md + +# * + +# * This file is part of the Pi4J project. More information about + +# * this project can be found here: https://pi4j.com/ + +# * ********************************************************************** + +# * %% + +# * * Copyright (C) 2012 - 2023 Pi4J + +# * %% + +# * + +# * Licensed under the Apache License, Version 2.0 (the "License"); + +# * you may not use this file except in compliance with the License. + +# * You may obtain a copy of the License at + +# * + +# * http://www.apache.org/licenses/LICENSE-2.0 + +# * + +# * Unless required by applicable law or agreed to in writing, software + +# * distributed under the License is distributed on an "AS IS" BASIS, + +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +# * See the License for the specific language governing permissions and + +# * limitations under the License. + +# * #L% + +# * + # + # ### This repository contains device specific support for various devices. @@ -47,29 +75,27 @@ Project by Tom Aarts Project by Tom Aarts ========================== - # CP2102N - # Datasheet https://datasheetspdf.com/pdf-file/1260478/SiliconLaboratories/CP2102N/1 _ ______ _______ _______ -|\ /|( ( /|( __ \ ( ____ \( ____ ) -| ) ( || \ ( || ( \ )| ( \/| ( )| -| | | || \ | || | ) || (__ | (____)| -| | | || (\ \) || | | || __) | __) -| | | || | \ || | ) || ( | (\ ( -| (___) || ) \ || (__/ )| (____/\| ) \ \__ -(_______)|/ )_)(______/ (_______/|/ \__/ - _______ _______ _ _______ _________ _______ _______ __________________ _______ _ -( ____ \( ___ )( ( /|( ____ \\__ __/( ____ )|\ /|( ____ \\__ __/\__ __/( ___ )( ( /| -| ( \/| ( ) || \ ( || ( \/ ) ( | ( )|| ) ( || ( \/ ) ( ) ( | ( ) || \ ( | -| | | | | || \ | || (_____ | | | (____)|| | | || | | | | | | | | || \ | | -| | | | | || (\ \) |(_____ ) | | | __)| | | || | | | | | | | | || (\ \) | -| | | | | || | \ | ) | | | | (\ ( | | | || | | | | | | | | || | \ | -| (____/\| (___) || ) \ |/\____) | | | | ) \ \__| (___) || (____/\ | | ___) (___| (___) || ) \ | -(_______/(_______)|/ )_)\_______) )_( |/ \__/(_______)(_______/ )_( \_______/(_______)|/ )_) +|\ /|( ( /|( __ \ ( ____ \( ____ ) +| ) ( || \ ( || ( \ )| ( \/| ( )| +| | | || \ | || | ) || (__ | (____)| +| | | || (\ \) || | | || __) | __) +| | | || | \ || | ) || ( | (\ ( +| (___) || ) \ || (__/ )| (____/\| ) \ \__ +(_______)|/ )_)(______/ (_______/|/ \__/ + _______ _______ _ _______ _________ _______ _______ __________________ _______ _ +( ____ \( ___ )( ( /|( ____ \\__ __/( ____ )|\ /|( ____ \\__ __/\__ __/( ___ )( ( /| +| ( \/| ( ) || \ ( || ( \/ ) ( | ( )|| ) ( || ( \/ ) ( ) ( | ( ) || \ ( | +| | | | | || \ | || (_____ | | | (____)|| | | || | | | | | | | | || \ | | +| | | | | || (\ \) |(_____ ) | | | __)| | | || | | | | | | | | || (\ \) | +| | | | | || | \ | ) | | | | (\ ( | | | || | | | | | | | | || | \ | +| (____/\| (___) || ) \ |/\____) | | | | ) \ \__| (___) || (____/\ | | ___) (___| (___) || ) \ | +(_______/(_______)|/ )_)\_______) )_( |/ \__/(_______)(_______/ )_( \_______/(_______)|/ )_) # integrating this code simply to protect it from loss. \ No newline at end of file diff --git a/src/main/java/com/pi4j/devices/dac8552/DAC8552.java b/src/main/java/com/pi4j/devices/dac8552/DAC8552.java index 36adab0..5fce7b3 100644 --- a/src/main/java/com/pi4j/devices/dac8552/DAC8552.java +++ b/src/main/java/com/pi4j/devices/dac8552/DAC8552.java @@ -66,8 +66,8 @@ public DAC8552(SpiBus spiBus, int csPin, Console console, String traceLevel, Con private void writeByte(byte toWrite) { this.logger.trace(">>> Enter writeByte :" + String.format(" | %04x", toWrite)); - byte value[] = new byte[1]; - byte valueToWrite[] = new byte[1]; + byte[] value = new byte[1]; + byte[] valueToWrite = new byte[1]; valueToWrite[0] = toWrite; int bytesRead = this.spi.transfer(valueToWrite, 0, value, 0, 1); this.logger.trace("<<< Exit writeByte "); @@ -82,12 +82,12 @@ private void writeByte(byte toWrite) { * @param data */ private void Write_DAC8532(int channel, int data) { - this.logger.trace(">>> Enter Write_DAC8532 channel : " + String.format(" | %04x",channel) + " data :" + String.format(" | %04x", data)); + this.logger.trace(">>> Enter Write_DAC8532 channel : " + String.format(" | %04x", channel) + " data :" + String.format(" | %04x", data)); this.csGpio.high(); this.csGpio.low(); this.writeByte((byte) (channel & 0xff)); - this.writeByte((byte) ((data >> 8) & 0xff)); + this.writeByte((byte) ((data >> 8) & 0xff)); this.writeByte((byte) (data & 0xff)); this.csGpio.high(); this.logger.trace("<<< Exit Write_DAC8532 "); @@ -132,9 +132,8 @@ public boolean DAC8532_Out_Voltage(String channel, double voltage) { } /** - * * @param channel - * @return numeric value for this channel, used as input data written to the DAC + * @return numeric value for this channel, used as input data written to the DAC */ private int mapChnl(String channel) { this.logger.trace(">>> Enter mapChnl : " + channel); @@ -147,34 +146,34 @@ private int mapChnl(String channel) { this.logger.error("Invalid channel designation :" + channel); System.exit(300); } - this.logger.trace("<<< Exit mapChnl :"+ String.format(" | %04x", rval)); + this.logger.trace("<<< Exit mapChnl :" + String.format(" | %04x", rval)); return (rval); } private void init() throws InterruptedException { this.logger.trace(">>> Enter init"); var spiConfig = Spi.newConfigBuilder(this.pi4j) - .id("SPI" + this.spiBus + "_DAC8552") - .name("D/A converter") - .bus(this.spiBus) - .chipSelect(SpiChipSelect.CS_0) // not used - // 30D400 - // 0b001100001101010000000000 - .flags(0b0000000000000011100001L) // Ux CE not used, MM mode 1 - .baud(976563) - .mode(SpiMode.MODE_1) - .provider("pigpio-spi") - .build(); + .id("SPI" + this.spiBus + "_DAC8552") + .name("D/A converter") + .bus(this.spiBus) + .chipSelect(SpiChipSelect.CS_0) // not used + // 30D400 + // 0b001100001101010000000000 + .flags(0b0000000000000011100001L) // Ux CE not used, MM mode 1 + .baud(976563) + .mode(SpiMode.MODE_1) + .provider("pigpio-spi") + .build(); this.spi = this.pi4j.create(spiConfig); // required all configs var outputConfig2 = DigitalOutput.newConfigBuilder(pi4j) - .id("CS_pin") - .name("CS") - .address(this.csPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("CS_pin") + .name("CS") + .address(this.csPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { this.csGpio = pi4j.create(outputConfig2); } catch (Exception e) { @@ -188,19 +187,19 @@ private void init() throws InterruptedException { private Spi spi; - private Console console; - private String traceLevel; - private Logger logger; + private final Console console; + private final String traceLevel; + private final Logger logger; - private double vref = DAC8552_Declares.DAC_VREF; - private double voutput = 0; + private final double vref = DAC8552_Declares.DAC_VREF; + private final double voutput = 0; private DigitalOutput csGpio; - private int csPinNum; + private final int csPinNum; - private Context pi4j; + private final Context pi4j; - private SpiBus spiBus; + private final SpiBus spiBus; } diff --git a/src/main/java/com/pi4j/devices/dac8552/DAC8552App.java b/src/main/java/com/pi4j/devices/dac8552/DAC8552App.java index e3896ed..2695cbf 100644 --- a/src/main/java/com/pi4j/devices/dac8552/DAC8552App.java +++ b/src/main/java/com/pi4j/devices/dac8552/DAC8552App.java @@ -47,7 +47,7 @@ public class DAC8552App { public static void main(String[] args) throws InterruptedException, IOException { var console = new Console(); Context pi4j = Pi4J.newAutoContext(); - int csPin = 0; + int csPin = 0; double vref = 0.0; double voutput = 0.0; boolean hasVref = false; @@ -55,9 +55,9 @@ public static void main(String[] args) throws InterruptedException, IOException String channel = ""; console.title("<-- The Pi4J V2 Project Extension -->", "DAC8552App \n"); String helpString = " parms: -cs chip select GPIO -s HEX value SPI # -t trace \n" + - "-chn channel, -vout voltage out -vref reference voltage\n" + - " Tracevalues : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; + "-chn channel, -vout voltage out -vref reference voltage\n" + + " Tracevalues : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { diff --git a/src/main/java/com/pi4j/devices/dac8552/DAC8552_Declares.java b/src/main/java/com/pi4j/devices/dac8552/DAC8552_Declares.java index 2783e95..2341f98 100644 --- a/src/main/java/com/pi4j/devices/dac8552/DAC8552_Declares.java +++ b/src/main/java/com/pi4j/devices/dac8552/DAC8552_Declares.java @@ -39,10 +39,10 @@ public class DAC8552_Declares { - protected final static int channel_A = 0x30; - protected final static int channel_B = 0x34; + protected final static int channel_A = 0x30; + protected final static int channel_B = 0x34; - protected final static int DAC_Value_MAX = 65535; + protected final static int DAC_Value_MAX = 65535; - protected final static double DAC_VREF = 3.3; + protected final static double DAC_VREF = 3.3; } diff --git a/src/main/java/com/pi4j/devices/dac8552/README.md b/src/main/java/com/pi4j/devices/dac8552/README.md index 696baeb..93c1716 100644 --- a/src/main/java/com/pi4j/devices/dac8552/README.md +++ b/src/main/java/com/pi4j/devices/dac8552/README.md @@ -1,4 +1,3 @@ - Pi4J :: Java I/O Library for Raspberry Pi :: Device :: DAC8552 ========================================================================== @@ -14,21 +13,19 @@ Pi------------------DAC---------------------Pi 5V---------------P1-------P8----------------GND 5V---------------P2-------P7----------------MOSI LED-B------------P3-------P6----------------SCLK -LED-A------------P4-------P5----------------GPIO22 +LED-A------------P4-------P5----------------GPIO22 GPIO22 could be any Pi GPIO of your chosing, use its numeric value with -cs +sudo ./runDAC8552.sh -s 0x0 -cs 23 -t trace -vout 2.1 -vref 5.0 -chn channel_A -sudo ./runDAC8552.sh -s 0x0 -cs 23 -t trace -vout 2.1 -vref 5.0 -chn channel_A - -Channel A set to approximately 2.1 V - +Channel A set to approximately 2.1 V -sudo ./runDAC8552.sh -s 0x0 -cs 23 -t trace -vout 5.0 -vref 5.0 -chn channel_B +sudo ./runDAC8552.sh -s 0x0 -cs 23 -t trace -vout 5.0 -vref 5.0 -chn channel_B -Channel B set to approximately 5 V +Channel B set to approximately 5 V -sudo ./runDAC8552.sh -cs 23 -vout 3.0 -chn channel_B +sudo ./runDAC8552.sh -cs 23 -vout 3.0 -chn channel_B Will operate with the default trace_level 'info', SPI0 and -vref 3.3 diff --git a/src/main/java/com/pi4j/devices/dht22/DHT22.java b/src/main/java/com/pi4j/devices/dht22/DHT22.java index 75d622c..a607921 100644 --- a/src/main/java/com/pi4j/devices/dht22/DHT22.java +++ b/src/main/java/com/pi4j/devices/dht22/DHT22.java @@ -61,7 +61,7 @@ public class DHT22 { private final Console console; private final Context pi4j; - private DigitalOutput oeGpio = null; + private final DigitalOutput oeGpio = null; private int dataPinNum = 0xff; private final String traceLevel; private Logger logger; @@ -156,7 +156,8 @@ private void idleInputPin() { } - public void readAndDisplayData() { + public void + readAndDisplayData() { { double temperature, humidity; @@ -211,7 +212,7 @@ private double[] read() { } } this.idleInputPin(); - double rval[] = null; + double[] rval = null; double temperature = 0.0; double humidity = 0.0; //should be 40 but the first few bits are often missed and often equal 0 @@ -250,7 +251,6 @@ private void readAndDisplayDataLL() { this.createOutputPin(); this.dataOut.low(); while (System.nanoTime() - now < 2000000) { - ; } this.dataOut.high(); this.idleOutputPin(); diff --git a/src/main/java/com/pi4j/devices/dht22/DHT22_App.java b/src/main/java/com/pi4j/devices/dht22/DHT22_App.java index 498d620..7f65a33 100644 --- a/src/main/java/com/pi4j/devices/dht22/DHT22_App.java +++ b/src/main/java/com/pi4j/devices/dht22/DHT22_App.java @@ -38,11 +38,8 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; import com.pi4j.io.exception.IOException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; public class DHT22_App { @@ -56,18 +53,6 @@ public static void main(String[] args) throws InterruptedException, IOException " \n -t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + " or \"off\" Default \"info\""; - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - // Thread.dumpStack(); - System.exit(2); - } - }); for (int i = 0; i < args.length; i++) { String o = args[i]; diff --git a/src/main/java/com/pi4j/devices/dht22/README.md b/src/main/java/com/pi4j/devices/dht22/README.md index 59e064f..597bd6f 100644 --- a/src/main/java/com/pi4j/devices/dht22/README.md +++ b/src/main/java/com/pi4j/devices/dht22/README.md @@ -1,6 +1,5 @@ Pi4J :: Java I/O Library for Raspberry Pi :: Device :: DHT22 -Uses SN74HC595 to update D0-D7 of the LCD display module ========================================================================== ### This repository contains device specific support for various devices. @@ -24,10 +23,10 @@ https://www.sparkfun.com/datasheets/Sensors/Temperature/DHT22.pdf Simple usage of the DHT22 Humidity and Temperature sensor. -Pi DHT22 -5+ 1. VDD -GPIO 2. Data -Gnd 3. Ground +Pi DHT22 +5+ 1. VDD +GPIO 2. Data +Gnd 3. Ground 1. ./mvnw clean package 2. cd target/distribution diff --git a/src/main/java/com/pi4j/devices/hcsr04/HCSR04.java b/src/main/java/com/pi4j/devices/hcsr04/HCSR04.java index 2b69760..a3a6002 100644 --- a/src/main/java/com/pi4j/devices/hcsr04/HCSR04.java +++ b/src/main/java/com/pi4j/devices/hcsr04/HCSR04.java @@ -64,7 +64,7 @@ public class HCSR04 { /** * Constructs an HCSR04 object with the specified GPIO pin numbers for trigger and echo. * - * @param pi4jContext the Pi4J context used to initialize GPIO pins + * @param pi4jContext the Pi4J context used to initialize GPIO pins * @param trigPinNumber the GPIO pin number used for the trigger signal * @param echoPinNumber the GPIO pin number used for the echo signal */ @@ -105,7 +105,7 @@ public HCSR04(DigitalOutput trigPin, DigitalInput echoPin) { * on the duration of the echo pulse. * * @return the calculated distance to the object in centimeters, or -1 if the - * measurement is invalid (out of range). + * measurement is invalid (out of range). */ public double measureDistance() { try { @@ -157,9 +157,9 @@ private long waitForEchoSignal(boolean high) { * centimeters and accounts for the round-trip of the signal (to the object and back). * * @param pulseStartTime the start time of the echo pulse in nanoseconds - * @param pulseEndTime the end time of the echo pulse in nanoseconds + * @param pulseEndTime the end time of the echo pulse in nanoseconds * @return the calculated distance to the object in centimeters, or -1 if the - * pulse duration is outside expected bounds (handled in measureDistance). + * pulse duration is outside expected bounds (handled in measureDistance). */ private double calculateDistance(long pulseStartTime, long pulseEndTime) { long pulseDuration = pulseEndTime - pulseStartTime; // Duration in nanoseconds diff --git a/src/main/java/com/pi4j/devices/hcsr04/README.md b/src/main/java/com/pi4j/devices/hcsr04/README.md index d0ce8bd..6a903f9 100644 --- a/src/main/java/com/pi4j/devices/hcsr04/README.md +++ b/src/main/java/com/pi4j/devices/hcsr04/README.md @@ -1,28 +1,32 @@ HC-SR04 Ultrasonic Sensor Example with Pi4J =========================================== -This project demonstrates how to use the HC-SR04 ultrasonic sensor with a Raspberry Pi via the Pi4J library to measure distances in centimeters. The application continuously measures and displays the distance from the sensor to an object every second. +This project demonstrates how to use the HC-SR04 ultrasonic sensor with a Raspberry Pi via the Pi4J library to measure +distances in centimeters. The application continuously measures and displays the distance from the sensor to an object +every second. Requirements ------------ -- Raspberry Pi (any model with GPIO support) -- HC-SR04 Ultrasonic Sensor -- Pi4J library (version compatible with your Pi and Java setup) -- Java 11 or later +- Raspberry Pi (any model with GPIO support) +- HC-SR04 Ultrasonic Sensor +- Pi4J library (version compatible with your Pi and Java setup) +- Java 11 or later Wiring ------ -1. **TRIG** (trigger) pin on the HC-SR04 sensor is connected to GPIO 23 on the Raspberry Pi. -2. **ECHO** (echo) pin on the HC-SR04 sensor is connected to GPIO 24 on the Raspberry Pi. -3. **VCC** pin on the HC-SR04 sensor is connected to the 5V power pin on the Raspberry Pi. -4. **GND** pin on the HC-SR04 sensor is connected to a ground (GND) pin on the Raspberry Pi. +1. **TRIG** (trigger) pin on the HC-SR04 sensor is connected to GPIO 23 on the Raspberry Pi. +2. **ECHO** (echo) pin on the HC-SR04 sensor is connected to GPIO 24 on the Raspberry Pi. +3. **VCC** pin on the HC-SR04 sensor is connected to the 5V power pin on the Raspberry Pi. +4. **GND** pin on the HC-SR04 sensor is connected to a ground (GND) pin on the Raspberry Pi. -**Note**: Some Raspberry Pi models use 3.3V GPIO pins, so if needed, use a voltage divider to lower the ECHO signal voltage. +**Note**: Some Raspberry Pi models use 3.3V GPIO pins, so if needed, use a voltage divider to lower the ECHO signal +voltage. Compile and Run ------ + 1. **Build the project:** ```bash mvn clean install @@ -31,39 +35,44 @@ Compile and Run ```bash cd target/distribution ``` -3. **Run the application with optional GPIO parameters:** +3. **Run the application with optional GPIO parameters:** ```bash sudo ./runHCSR04.sh ``` + #### Example Usage - - **Using Default GPIO Pins (TRIG=23, ECHO=24):** - ```bash - sudo ./runHCSR04.sh - ``` - - **Specifying GPIO Pins (e.g., TRIG=20, ECHO=21):** - ```bash - sudo ./runHCSR04.sh 20 21 - ``` - - **Getting Help Information:** - ```bash - sudo ./runHCSR04.sh -h - ``` + +- **Using Default GPIO Pins (TRIG=23, ECHO=24):** + ```bash + sudo ./runHCSR04.sh + ``` +- **Specifying GPIO Pins (e.g., TRIG=20, ECHO=21):** + ```bash + sudo ./runHCSR04.sh 20 21 + ``` +- **Getting Help Information:** + ```bash + sudo ./runHCSR04.sh -h + ``` + Code Overview ------------- ### HCSR04 Class -The `HCSR04` class configures the GPIO pins to interact with the sensor and provides a `measureDistance` method to calculate and return the distance to an object based on the duration of the ECHO pulse. +The `HCSR04` class configures the GPIO pins to interact with the sensor and provides a `measureDistance` method to +calculate and return the distance to an object based on the duration of the ECHO pulse. Key points: -- **Trigger Signal**: A 10-microsecond pulse on the TRIG pin starts the measurement. -- **Echo Measurement**: The class measures the duration of the ECHO pulse to calculate the distance. -- **Distance Calculation**: Uses the speed of sound to convert pulse duration into centimeters. +- **Trigger Signal**: A 10-microsecond pulse on the TRIG pin starts the measurement. +- **Echo Measurement**: The class measures the duration of the ECHO pulse to calculate the distance. +- **Distance Calculation**: Uses the speed of sound to convert pulse duration into centimeters. ### HCSR04_App Class -The `HCSR04_App` class is a simple application that initializes the Pi4J context and the `HCSR04` sensor instance. It enters a loop to repeatedly measure and print the distance to the console every second. +The `HCSR04_App` class is a simple application that initializes the Pi4J context and the `HCSR04` sensor instance. It +enters a loop to repeatedly measure and print the distance to the console every second. Example Output -------------- diff --git a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_App_LCD1602A.java b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_App_LCD1602A.java index 27fa95e..18e09bb 100644 --- a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_App_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_App_LCD1602A.java @@ -69,12 +69,12 @@ public static void main(String[] args) throws InterruptedException, IOException console.title("<-- The Pi4J V2 Project Extension -->", "HD44780U_App"); String helpString = " parms: HD44780U \n " + - " -rs STCP gpio, -en SHCP gpio, -line1 LcdString,-line1Offset offset ," + - " -line2 LcdString, -line2Offset offset, -shiftL left shift -clearLCD \n" + - " parms : HD44780U_interface \n" + - " -ds HEX DS gpio -oe OE gpio, -st STCP gpio, -sh SHCP gpio, -mr MR gpio " + - "-t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; + " -rs STCP gpio, -en SHCP gpio, -line1 LcdString,-line1Offset offset ," + + " -line2 LcdString, -line2Offset offset, -shiftL left shift -clearLCD \n" + + " parms : HD44780U_interface \n" + + " -ds HEX DS gpio -oe OE gpio, -st STCP gpio, -sh SHCP gpio, -mr MR gpio " + + "-t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { @@ -99,19 +99,19 @@ public static void main(String[] args) throws InterruptedException, IOException String a = args[i + 1]; MRPinNum = Integer.parseInt(a); i++; - } else if (o.contentEquals("-rd")) { + } else if (o.contentEquals("-rd")) { String a = args[i + 1]; i++; registerData = (byte) (Integer.parseInt(a.substring(2), 16) & 0xff); - }else if (o.contentEquals("-rs")) { + } else if (o.contentEquals("-rs")) { String a = args[i + 1]; rsPinNum = Integer.parseInt(a); i++; - } else if (o.contentEquals("-en")) { + } else if (o.contentEquals("-en")) { String a = args[i + 1]; enPinNum = Integer.parseInt(a); i++; - }else if (o.contentEquals("-line1")) { + } else if (o.contentEquals("-line1")) { String a = args[i + 1]; lineOne = a; i++; @@ -119,21 +119,21 @@ public static void main(String[] args) throws InterruptedException, IOException String a = args[i + 1]; lineOneOffset = Integer.parseInt(a); i++; - }else if (o.contentEquals("-line2")) { + } else if (o.contentEquals("-line2")) { String a = args[i + 1]; lineTwo = a; i++; - }else if (o.contentEquals("-line2Offset")) { + } else if (o.contentEquals("-line2Offset")) { String a = args[i + 1]; lineTwoOffset = Integer.parseInt(a); i++; - }else if (o.contentEquals("-shiftL")) { + } else if (o.contentEquals("-shiftL")) { String a = args[i + 1]; shiftLeftCount = Integer.parseInt(a); i++; } else if (o.contentEquals("-clearLCD")) { - clearLCD = true; - }else if (o.contentEquals("-t")) { + clearLCD = true; + } else if (o.contentEquals("-t")) { String a = args[i + 1]; i++; traceLevel = a; @@ -161,17 +161,17 @@ public static void main(String[] args) throws InterruptedException, IOException pi4j.providers().describe().print(System.out); System.out.println("----------------------------------------------------------"); - var d0_d7 = new SN74HC595(pi4j, console, DSPinNum, OEPinNum, STCPPinNum, SHCPPinNum, MRPinNum, registerData, traceLevel); - HD44780U_LCD1602A dispObj = new HD44780U_LCD1602A(pi4j, console, d0_d7, rsPinNum, enPinNum, clearLCD, traceLevel); + var d0_d7 = new SN74HC595(pi4j, console, DSPinNum, OEPinNum, STCPPinNum, SHCPPinNum, MRPinNum, registerData, traceLevel); + HD44780U_LCD1602A dispObj = new HD44780U_LCD1602A(pi4j, console, d0_d7, rsPinNum, enPinNum, clearLCD, traceLevel); - if(lineOne.length() >0) { + if (lineOne.length() > 0) { dispObj.sendStringLineX(lineOne, 1, lineOneOffset); } - if(lineTwo.length() >0) { - dispObj.sendStringLineX(lineTwo, 2, lineTwoOffset); + if (lineTwo.length() > 0) { + dispObj.sendStringLineX(lineTwo, 2, lineTwoOffset); } Thread.sleep(5000); @@ -180,7 +180,7 @@ public static void main(String[] args) throws InterruptedException, IOException Thread.sleep(5000); - if(clearLCD) { + if (clearLCD) { dispObj.clearDisplay(); } } diff --git a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Declares_LCD1602A.java b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Declares_LCD1602A.java index 46b2da2..ca7bcb1 100644 --- a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Declares_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Declares_LCD1602A.java @@ -41,7 +41,7 @@ public class HD44780U_Declares_LCD1602A { - // RS GPIO and RW GPIO. Internal command + // RS GPIO and RW GPIO. Internal command public static final DigitalState RsInternalIr = DigitalState.LOW; public static final DigitalState RwInternalIr = DigitalState.LOW; @@ -50,8 +50,6 @@ public class HD44780U_Declares_LCD1602A { public static final DigitalState RwInternalBf = DigitalState.HIGH; - - // RS GPIO and RW GPIO. Write commands public static final DigitalState RsInternalWrtState = DigitalState.HIGH; public static final DigitalState RwInternalWrtState = DigitalState.LOW; diff --git a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Interface_LCD1602A.java b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Interface_LCD1602A.java index 1fb1ef6..edfe25e 100644 --- a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Interface_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_Interface_LCD1602A.java @@ -41,9 +41,4 @@ public interface HD44780U_Interface_LCD1602A { void sendCommand(int cmd); - - - - - } diff --git a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_LCD1602A.java b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_LCD1602A.java index 6e0467a..c71be6e 100644 --- a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/HD44780U_LCD1602A.java @@ -38,29 +38,29 @@ import com.pi4j.context.Context; +import com.pi4j.devices.lcd1602a.LCD1602A; +import com.pi4j.devices.lcd1602a.LCD1602A_Declares; import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalState; import com.pi4j.util.Console; import org.slf4j.LoggerFactory; -import com.pi4j.devices.lcd1602a.LCD1602A; -import com.pi4j.devices.lcd1602a.LCD1602A_Declares; -public class HD44780U_LCD1602A extends LCD1602A{ +public class HD44780U_LCD1602A extends LCD1602A { private DigitalOutput RsPin = null; private DigitalOutput EnPin = null; // - private int RsPinNum = 0xff; + private int RsPinNum = 0xff; private int EnPinNum = 0xff; - private String traceLevel; + private final String traceLevel; - private HD44780U_Interface_LCD1602A D0_D7; + private final HD44780U_Interface_LCD1602A D0_D7; public HD44780U_LCD1602A(Context pi4j, Console console, HD44780U_Interface_LCD1602A d0_d7, int rsGpio, int enGpio, boolean clearIt, String traceLevel) { - super(pi4j, console, clearIt, traceLevel); + super(pi4j, console, clearIt, traceLevel); this.D0_D7 = d0_d7; this.RsPinNum = rsGpio; this.EnPinNum = enGpio; @@ -79,14 +79,13 @@ public void init() { this.logger.trace("EN Pin " + this.EnPinNum); - var outputConfig1 = DigitalOutput.newConfigBuilder(pi4j) - .id("RS_pin") - .name("Enable") - .address(this.RsPinNum) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); + .id("RS_pin") + .name("Enable") + .address(this.RsPinNum) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { this.RsPin = pi4j.create(outputConfig1); } catch (Exception e) { @@ -96,12 +95,12 @@ public void init() { } var outputConfig3 = DigitalOutput.newConfigBuilder(pi4j) - .id("EN_pin") - .name("EN") - .address(this.EnPinNum) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); + .id("EN_pin") + .name("EN") + .address(this.EnPinNum) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { this.EnPin = pi4j.create(outputConfig3); } catch (Exception e) { @@ -111,19 +110,18 @@ public void init() { } - this.D0_D7.sendCommand(0x00); // ensure all pins are low this.EnPin.low(); this.sleepTimeNanoS(LCD1602A_Declares.postWrtEnableCycleDelay); - // enable LCD with blink - this.sendCommand(LCD1602A_Declares.dispCMD | LCD1602A_Declares.dispOnBit| LCD1602A_Declares.dispBlnkOnBit | LCD1602A_Declares.dispCrsOnBit ); + // enable LCD with blink + this.sendCommand(LCD1602A_Declares.dispCMD | LCD1602A_Declares.dispOnBit | LCD1602A_Declares.dispBlnkOnBit | LCD1602A_Declares.dispCrsOnBit); // entry mode, cursor moves right each character this.sendCommand(LCD1602A_Declares.entryModeCMD | LCD1602A_Declares.entryModeIncCMD); - this.sendCommand(LCD1602A_Declares.funcSetCMD | LCD1602A_Declares.func8BitsBit | LCD1602A_Declares.func5x8TwoBit); - if(this.clearDisplay){ + this.sendCommand(LCD1602A_Declares.funcSetCMD | LCD1602A_Declares.func8BitsBit | LCD1602A_Declares.func5x8TwoBit); + if (this.clearDisplay) { this.logger.trace("Clear Display"); this.clearDisplay(); } @@ -134,17 +132,11 @@ public void init() { } - - - - - - protected void sendChar(char c) { - this.logger.trace(">>> Enter: sendChar : " + c ); + this.logger.trace(">>> Enter: sendChar : " + c); if (this.lcdAvailable()) { this.RsPin.high(); - this.sleepTimeNanoS(LCD1602A_Declares.dataWrtSetupDuration); + this.sleepTimeNanoS(LCD1602A_Declares.dataWrtSetupDuration); this.D0_D7.sendCommand(c); this.sleepTimeNanoS(LCD1602A_Declares.postAddressWrtSetupDelay); this.pulseEnable(); @@ -153,32 +145,31 @@ protected void sendChar(char c) { } this.logger.trace("<<< Exit: sendChar "); } + // do required gpio->LCD_input dance before and after actual LCD pin update - protected void sendCommand(int cmd){ + protected void sendCommand(int cmd) { this.logger.trace(">>> Enter: sendCommand "); - if(this.lcdAvailable()){ - this.RsPin.low(); - this.sleepTimeNanoS(LCD1602A_Declares.dataWrtSetupDuration); - this.D0_D7.sendCommand(cmd); - this.sleepTimeNanoS(LCD1602A_Declares.postAddressWrtSetupDelay); - this.pulseEnable(); - }else { - this.logger.info("LCD in busy state, request not possible"); - } + if (this.lcdAvailable()) { + this.RsPin.low(); + this.sleepTimeNanoS(LCD1602A_Declares.dataWrtSetupDuration); + this.D0_D7.sendCommand(cmd); + this.sleepTimeNanoS(LCD1602A_Declares.postAddressWrtSetupDelay); + this.pulseEnable(); + } else { + this.logger.info("LCD in busy state, request not possible"); + } this.logger.trace("<<< Exit: sendCommand "); } /** - * Value of 0 indicates the device is not performing internal - * operations and will accept commands - * Not possible with the Pi GPIOs. Later if the D0_D7 interface is on an - * MCP230xx, this maybe possible. For present time, use timing values - * documented in datasheet - * @return bit value of DB7 + * Value of 0 indicates the device is not performing internal + * operations and will accept commands + * Not possible with the Pi GPIOs. Later if the D0_D7 interface is on an + * MCP230xx, this maybe possible. For present time, use timing values + * documented in datasheet + * */ - - protected void pulseEnable() { this.logger.trace(">>> Enter: pulseEnable "); this.EnPin.high(); @@ -189,6 +180,4 @@ protected void pulseEnable() { } - - } \ No newline at end of file diff --git a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/README.md b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/README.md index 373043f..0d72602 100644 --- a/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/README.md +++ b/src/main/java/com/pi4j/devices/hd44780u_lcd1602a/README.md @@ -1,7 +1,3 @@ - - - - Pi4J :: Java I/O Library for Raspberry Pi :: Device :: HD44780U LCD Uses SN74HC595 to update D0-D7 of the LCD display module @@ -13,7 +9,7 @@ Uses SN74HC595 to update D0-D7 of the LCD display module Project by Tom Aarts ========================================================================== -2X40 LCD. 1602A +2X40 LCD. 1602A Controlled by Pi GPIOs, data lines controlled by 8 bit shift register. @@ -23,55 +19,47 @@ https://www.sparkfun.com/datasheets/LCD/ADM1602K-NSR-FBS-3.3v.pdf Shift register https://www.ti.com/product/SN74HC595 - - HD44780U details -Pi LCD1602 -Grnd Write always rw -GPIO17 rs -GPIO27 en -NC Not possible on Pi bf -Grnd VSS -5VDC VDD -5VDC V0 -5VDC A -Grnd K - -SN74HC595 LCD1602 -QA D0 -QB D1 -QC D2 -QD D3 -QE D4 -QF D5 -QG D6 -QH D7 - - - - - +Pi LCD1602 +Grnd Write always rw +GPIO17 rs +GPIO27 en +NC Not possible on Pi bf +Grnd VSS +5VDC VDD +5VDC V0 +5VDC A +Grnd K + +SN74HC595 LCD1602 +QA D0 +QB D1 +QC D2 +QD D3 +QE D4 +QF D5 +QG D6 +QH D7 SN74HC595 details - 9 8 gnd +9 8 gnd -gpio13 10 7 QH Red LED -gpio6 11 6 QG -gpio5 12 5 QF -gpio20 13 4 QE -gpio23 14 3 QD -QA 15 2 QC Green LED -Vdd 5v 16 1 QB +gpio13 10 7 QH Red LED +gpio6 11 6 QG +gpio5 12 5 QF +gpio20 13 4 QE +gpio23 14 3 QD +QA 15 2 QC Green LED +Vdd 5v 16 1 QB 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runHD44780U_LCD1602A.sh parms........ - -sudo ./runHD44780U_LCD1602A.sh -rs 17 -en 27 -ds 23 -oe 20 -st 5 -mr 13 -sh 6 -rd 0x84 -t trace -line1 aBc -line2 XyZ +sudo ./runHD44780U_LCD1602A.sh -rs 17 -en 27 -ds 23 -oe 20 -st 5 -mr 13 -sh 6 -rd 0x84 -t trace -line1 aBc -line2 XyZ Clears display, Line1 begins in fourth position, line2 begins in second position -sudo ./runHD44780U_LCD1602A.sh -rs 17 -en 27 -clearLCD -ds 23 -oe 20 -st 5 -mr 13 -sh 6 -rd 0x84 -t trace -line1 aaaaaa -line1Offset 4 -line2 zzzzzz -line2Offset 2 - +sudo ./runHD44780U_LCD1602A.sh -rs 17 -en 27 -clearLCD -ds 23 -oe 20 -st 5 -mr 13 -sh 6 -rd 0x84 -t trace -line1 aaaaaa +-line1Offset 4 -line2 zzzzzz -line2Offset 2 -Param -shiftL 2 shift both lines 2 positions to left +Param -shiftL 2 shift both lines 2 positions to left diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/ControlLeds.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/ControlLeds.java index 8715fbf..503ee7f 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/ControlLeds.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/ControlLeds.java @@ -37,7 +37,7 @@ import org.slf4j.Logger; /** - * Controls the processing abd warning LEDs + * Controls the processing abd warning LEDs */ public class ControlLeds { @@ -45,102 +45,101 @@ public class ControlLeds { private final Logger logger; - public ControlLeds(Context pi4j, Console console, DigitalOutput red_led_pin, DigitalOutput green_led_pin, Is31Fl37Matrix matrix, Logger logger ) { - this.redLED = red_led_pin; - this.greenLED = green_led_pin; - this.matrix = matrix; - this.pi4j = pi4j; - this.console = console; - this.logger = logger; + public ControlLeds(Context pi4j, Console console, DigitalOutput red_led_pin, DigitalOutput green_led_pin, Is31Fl37Matrix matrix, Logger logger) { + this.redLED = red_led_pin; + this.greenLED = green_led_pin; + this.matrix = matrix; + this.pi4j = pi4j; + this.console = console; + this.logger = logger; - this.init(); - } + this.init(); + } - private boolean init() { - // this.gpio = new BaseGpioInOut(this.ffdc, this.dioPinData, - // this.ffdc.logger); + private boolean init() { + // this.gpio = new BaseGpioInOut(this.ffdc, this.dioPinData, + // this.ffdc.logger); /* this..gpio.getCfgData(RaspiBcmPin.GPIO_22).input .addListener(new GpioInterruptListener()); */ - return (true); - } + return (true); + } /** - * * Warning LED will begin flashing. Process LED will be off. LED matrix will have all leds energized + * * @param matrix Is31Fl37Matrix */ - public void flash_alarm_led( Is31Fl37Matrix matrix) { - this.logger.trace("flash_alarm_led "); - this.logger.error("WaitOnInterrupt failed"); + public void flash_alarm_led(Is31Fl37Matrix matrix) { + this.logger.trace("flash_alarm_led "); + this.logger.error("WaitOnInterrupt failed"); - if(this.greenLED != null) { - this.greenLED.low(); - } + if (this.greenLED != null) { + this.greenLED.low(); + } - matrix.blink_write(0); - for (int i = 0; i < 7; i++) { - matrix.fill(7, (byte) 0, 0); - } - if(this.redLED != null) { - while (true) { - this.redLED.toggle(); - matrix.blink_write(0); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - System.exit(20); // logging disabled so use System call - } + matrix.blink_write(0); + for (int i = 0; i < 7; i++) { + matrix.fill(7, (byte) 0, 0); + } + if (this.redLED != null) { + while (true) { + this.redLED.toggle(); + matrix.blink_write(0); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + System.exit(20); // logging disabled so use System call } } - } + } + /** - * - * @param active True, processLED on, Warning LED off, else processLED off, Warning LED on + * @param active True, processLED on, Warning LED off, else processLED off, Warning LED on */ public void toggle_led(boolean active) { - this.logger.trace("toggle_led " + active); - if ((this.greenLED != null) && (this.redLED != null)) { - if (active) { - this.greenLED.high(); - this.redLED.low(); - } else { - this.greenLED.low(); - this.redLED.high(); - } + this.logger.trace("toggle_led " + active); + if ((this.greenLED != null) && (this.redLED != null)) { + if (active) { + this.greenLED.high(); + this.redLED.low(); + } else { + this.greenLED.low(); + this.redLED.high(); } + } - this.logger.trace("toggle_led"); + this.logger.trace("toggle_led"); - } + } /** - * Monitor the matrix controller interrupt to indicate the matrix has completed - * displaying the previously loaded matrix data. + * Monitor the matrix controller interrupt to indicate the matrix has completed + * displaying the previously loaded matrix data. * - * @return Class with success indicator and count of wait loops executed. + * @return Class with success indicator and count of wait loops executed. */ public InterruptDetails wait_for_interrupt() { - this.logger.trace("wait_for_interrupt"); + this.logger.trace("wait_for_interrupt"); - InterruptDetails rval = matrix.waitIntjLoop(); // uses gpio addListener - // InterruptDetails rval = matrix.waitIntpLoop(); // uses polling of GPIO INTB - // signals. + InterruptDetails rval = matrix.waitIntjLoop(); // uses gpio addListener + // InterruptDetails rval = matrix.waitIntpLoop(); // uses polling of GPIO INTB + // signals. - this.logger.trace("wait_for_interrupt " + rval.getSuccessVal() + " counter :" - + String.format("0x%02X", rval.getCounter())); - return (rval); - } + this.logger.trace("wait_for_interrupt " + rval.getSuccessVal() + " counter :" + + String.format("0x%02X", rval.getCounter())); + return (rval); + } - private final Is31Fl37Matrix matrix; + private final Is31Fl37Matrix matrix; private final Context pi4j; private final Console console; @@ -148,4 +147,4 @@ public InterruptDetails wait_for_interrupt() { private DigitalOutput greenLED = null; // considered the normal processing LED - } +} diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/CreateInterrupt.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/CreateInterrupt.java index 5b03495..f645823 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/CreateInterrupt.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/CreateInterrupt.java @@ -1,17 +1,18 @@ package com.pi4j.devices.is31Fl37Matrix; import com.pi4j.Pi4J; -import com.pi4j.io.gpio.digital.*; +import com.pi4j.io.gpio.digital.DigitalOutput; +import com.pi4j.io.gpio.digital.DigitalState; +import com.pi4j.io.gpio.digital.DigitalStateChangeEvent; +import com.pi4j.io.gpio.digital.DigitalStateChangeListener; import com.pi4j.util.Console; -import java.util.Properties; - public class CreateInterrupt { /** *

    Constructor for CreateInterrupt.

    - * + *

    * Sole purpose is unit testing. Pi4 with Pi OS 64bit * missing short duration interrupt. This program allows * controlling the interrupt duration. @@ -61,7 +62,7 @@ public static void main(String[] args) throws Exception { countLoops = Integer.parseInt(a); console.println("Process " + countLoops + " half second loops"); i++; - }else if (o.contentEquals("-m")) { + } else if (o.contentEquals("-m")) { String a = args[i + 1]; milliSecDelay = Integer.parseInt(a); console.println("MilliSecond " + countLoops + " interrupt duration"); @@ -70,11 +71,11 @@ public static void main(String[] args) throws Exception { firstDirection = args[i + 1]; if (firstDirection.contentEquals("HIGH") | firstDirection.contentEquals("LOW")) { i++; - if(firstDirection.contentEquals("LOW")){ - initialState=DigitalState.HIGH; + if (firstDirection.contentEquals("LOW")) { + initialState = DigitalState.HIGH; interruptLevelLow = true; - }else{ - initialState=DigitalState.LOW; + } else { + initialState = DigitalState.LOW; interruptLevelLow = false; } } else { @@ -87,14 +88,13 @@ public static void main(String[] args) throws Exception { } - var interruptConfig = DigitalOutput.newConfigBuilder(pi4j) - .id("Interrupt") - .name("Interrupt") - .address(interruptPinNum) - .shutdown(initialState) - .initial(initialState) - .provider("gpiod-digital-output"); + .id("Interrupt") + .name("Interrupt") + .address(interruptPinNum) + .shutdown(initialState) + .initial(initialState) + .provider("gpiod-digital-output"); try { interruptPin = pi4j.create(interruptConfig); } catch (Exception e) { @@ -105,19 +105,19 @@ public static void main(String[] args) throws Exception { interruptPin.addListener(new MonitorInterrupt.MatrixGpioListener()); - console.println(); + console.println(); console.println("CHANGE OUTPUT STATES VIA I/O HARDWARE AND CHANGE EVENTS WILL BE PRINTED BELOW:"); /*for(int c = 0; c < countLoops; c++){ Thread.sleep(500); }*/ // wait (block) for user to exit program using CTRL-C - if(interruptLevelLow){ + if (interruptLevelLow) { console.println("Interrupt LOW wait " + milliSecDelay + "MS, then HIGH"); interruptPin.low(); Thread.sleep(milliSecDelay); interruptPin.high(); - }else{ + } else { console.println("Interrupt HIGH wait " + milliSecDelay + "MS, then LOW"); interruptPin.high(); Thread.sleep(milliSecDelay); @@ -131,7 +131,6 @@ public static void main(String[] args) throws Exception { } public static class MatrixGpioListener implements DigitalStateChangeListener { - ; public MatrixGpioListener() { Runtime.getRuntime().addShutdownHook(new Thread() { diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayLED.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayLED.java index 3821dbd..f177c6f 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayLED.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayLED.java @@ -39,186 +39,186 @@ */ public class DisplayLED { - + public DisplayLED(Logger logger) { - super(); - this.logger = logger; - } + super(); + this.logger = logger; + } - public void usage() { - System.out.println("option f:func,b:bus,-a:address,-t bmp_address ,-n number,-x:axis,-y:axis,-o:ON"); - System.out.println("python display_led.py -b 1 -a 0X74 -t 0x77 -o ON -t 12:34 -w STEADY -l 1"); - System.out.println("python display_led.py -b 1 -a 0x74 -t 0x77 -x 0 -y 0 -o ON "); - System.out.println("python display_led.py -b 1 -a 0x74 -t 0x77 -n 1 -w BLINK or STEADY"); - } + public void usage() { + System.out.println("option f:func,b:bus,-a:address,-t bmp_address ,-n number,-x:axis,-y:axis,-o:ON"); + System.out.println("python display_led.py -b 1 -a 0X74 -t 0x77 -o ON -t 12:34 -w STEADY -l 1"); + System.out.println("python display_led.py -b 1 -a 0x74 -t 0x77 -x 0 -y 0 -o ON "); + System.out.println("python display_led.py -b 1 -a 0x74 -t 0x77 -n 1 -w BLINK or STEADY"); + } - // pixels for 0 1 2 3 4 5 6 7 8 9 : - // First element is the width in pixels of the displayed number - int[] a; - int[] xy0 = new int[] { 0, 0, 1, 0, 2, 0, 0, 1, 2, 1, 0, 2, 2, 2, 0, 3, 2, 3, 0, 4, 2, 4, 0, 5, 2, 5, 0, 6, 2, 6, 2, - 6, 1, 6 }; - int[] xy1 = new int[] { 0, 1, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 0, 6, 2, 6 }; - int[] xy2 = new int[] { 0, 1, 0, 2, 1, 0, 2, 0, 3, 1, 3, 2, 3, 3, 2, 4, 1, 5, 0, 6, 1, 6, 2, 6, 3, 6 }; - int[] xy3 = new int[] { 0, 1, 1, 0, 2, 0, 3, 1, 3, 2, 2, 3, 3, 4, 3, 5, 0, 5, 1, 6, 2, 6 }; - int[] xy4 = new int[] { 0, 0, 0, 1, 0, 2, 0, 3, 1, 3, 2, 3, 3, 0, 3, 1, 3, 2, 3, 3, 3, 4, 3, 5, 3, 6 }; - int[] xy5 = new int[] { 0, 0, 0, 1, 0, 2, 0, 6, 1, 0, 2, 0, 3, 0, 1, 2, 2, 3, 3, 4, 2, 5, 1, 6, 0, 6 }; - int[] xy6 = new int[] { 1, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 3, 2, 3, 3, 4, 3, 5, 2, 6, 1, 6 }; - int[] xy7 = new int[] { 0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 3, 1, 3, 2, 3, 3, 3, 4, 3, 5, 3, 6 }; - int[] xy8 = new int[] { 0, 1, 0, 2, 1, 0, 2, 0, 3, 1, 3, 2, 1, 3, 2, 3, 0, 4, 0, 5, 1, 6, 2, 6, 3, 4, 3, 5 }; - int[] xy9 = new int[] { 0, 1, 0, 2, 1, 0, 2, 0, 3, 1, 3, 2, 1, 3, 2, 3, 3, 3, 3, 4, 3, 5, 3, 6 }; - int[] xy10 = new int[] { 0, 2, 0, 4 }; - int[][] pixels = new int[][] { xy0, xy1, xy2, xy3, xy4, xy5, xy6, xy7, xy8, xy9, xy10 }; - - int[] width = new int[] { 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 1 }; - - // List>> listOfListsOfLists =new - // ArrayList>>(1); - // list [ list [list,list] ] ] - - /* - * // 0 [ [ - * [3],[[0,0],[1,0],[2,0],[0,1],[2,1],[0,2],[2,2],[0,3],[2,3],[0,4],[2,4] - * ,[0,5],[2,5],[0,6],[2,6],[2,6],[1,6]] ], [ // 1 - * [3],[[0,1],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[0,6],[2,6]] ], // 2 - * [ - * [4],[[0,1],[0,2],[1,0],[2,0],[3,1],[3,2],[3,3],[2,4],[1,5],[0,6],[1,6],[2 - * , 6],[3,6]] ] , // 3 - * [[4],[[0,1],[1,0],[2,0],[3,1],[3,2],[2,3],[3,4],[3,5],[0,5],[1,6],[2,6]]] - * ,// 4 - * [[4],[[0,0],[0,1],[0,2],[0,3],[1,3],[2,3],[3,0],[3,1],[3,2],[3,3],[3,4 - * ],[3,5],[3,6]] ], [ // 5 - * [4],[[0,0],[0,1],[0,2],[0,6],[1,0],[2,0],[3,0],[1,2],[ - * 2,3],[3,4],[2,5],[1,6],[0,6]] ], [ // 6 - * [4],[[1,0],[0,1],[0,2],[0,3],[0,4],[0,5 - * ],[1,3],[2,3],[3,4],[3,5],[2,6],[1,6]] ], [ //7 - * [4],[[0,0],[0,1],[1,0],[2,0],[3,0],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6]] - * ], [ //8 - * [4],[[0,1],[0,2],[1,0],[2,0],[3,1],[3,2],[1,3],[2,3],[0,4],[0,5],[1,6 - * ],[2,6],[3,4],[3,5]] ], [ // 9 - * [4],[[0,1],[0,2],[1,0],[2,0],[3,1],[3,2],[1,3],[ - * 2,3],[3,3],[3,4],[3,5],[3,6]] ], // 10 [ [1],[[0,2],[0,4]] ], ] - */ - private int space_between_symbols = 0; + // pixels for 0 1 2 3 4 5 6 7 8 9 : + // First element is the width in pixels of the displayed number + int[] a; + int[] xy0 = new int[]{0, 0, 1, 0, 2, 0, 0, 1, 2, 1, 0, 2, 2, 2, 0, 3, 2, 3, 0, 4, 2, 4, 0, 5, 2, 5, 0, 6, 2, 6, 2, + 6, 1, 6}; + int[] xy1 = new int[]{0, 1, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 0, 6, 2, 6}; + int[] xy2 = new int[]{0, 1, 0, 2, 1, 0, 2, 0, 3, 1, 3, 2, 3, 3, 2, 4, 1, 5, 0, 6, 1, 6, 2, 6, 3, 6}; + int[] xy3 = new int[]{0, 1, 1, 0, 2, 0, 3, 1, 3, 2, 2, 3, 3, 4, 3, 5, 0, 5, 1, 6, 2, 6}; + int[] xy4 = new int[]{0, 0, 0, 1, 0, 2, 0, 3, 1, 3, 2, 3, 3, 0, 3, 1, 3, 2, 3, 3, 3, 4, 3, 5, 3, 6}; + int[] xy5 = new int[]{0, 0, 0, 1, 0, 2, 0, 6, 1, 0, 2, 0, 3, 0, 1, 2, 2, 3, 3, 4, 2, 5, 1, 6, 0, 6}; + int[] xy6 = new int[]{1, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 3, 2, 3, 3, 4, 3, 5, 2, 6, 1, 6}; + int[] xy7 = new int[]{0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 3, 1, 3, 2, 3, 3, 3, 4, 3, 5, 3, 6}; + int[] xy8 = new int[]{0, 1, 0, 2, 1, 0, 2, 0, 3, 1, 3, 2, 1, 3, 2, 3, 0, 4, 0, 5, 1, 6, 2, 6, 3, 4, 3, 5}; + int[] xy9 = new int[]{0, 1, 0, 2, 1, 0, 2, 0, 3, 1, 3, 2, 1, 3, 2, 3, 3, 3, 3, 4, 3, 5, 3, 6}; + int[] xy10 = new int[]{0, 2, 0, 4}; + int[][] pixels = new int[][]{xy0, xy1, xy2, xy3, xy4, xy5, xy6, xy7, xy8, xy9, xy10}; + + int[] width = new int[]{3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 1}; + + // List>> listOfListsOfLists =new + // ArrayList>>(1); + // list [ list [list,list] ] ] + + /* + * // 0 [ [ + * [3],[[0,0],[1,0],[2,0],[0,1],[2,1],[0,2],[2,2],[0,3],[2,3],[0,4],[2,4] + * ,[0,5],[2,5],[0,6],[2,6],[2,6],[1,6]] ], [ // 1 + * [3],[[0,1],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[0,6],[2,6]] ], // 2 + * [ + * [4],[[0,1],[0,2],[1,0],[2,0],[3,1],[3,2],[3,3],[2,4],[1,5],[0,6],[1,6],[2 + * , 6],[3,6]] ] , // 3 + * [[4],[[0,1],[1,0],[2,0],[3,1],[3,2],[2,3],[3,4],[3,5],[0,5],[1,6],[2,6]]] + * ,// 4 + * [[4],[[0,0],[0,1],[0,2],[0,3],[1,3],[2,3],[3,0],[3,1],[3,2],[3,3],[3,4 + * ],[3,5],[3,6]] ], [ // 5 + * [4],[[0,0],[0,1],[0,2],[0,6],[1,0],[2,0],[3,0],[1,2],[ + * 2,3],[3,4],[2,5],[1,6],[0,6]] ], [ // 6 + * [4],[[1,0],[0,1],[0,2],[0,3],[0,4],[0,5 + * ],[1,3],[2,3],[3,4],[3,5],[2,6],[1,6]] ], [ //7 + * [4],[[0,0],[0,1],[1,0],[2,0],[3,0],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6]] + * ], [ //8 + * [4],[[0,1],[0,2],[1,0],[2,0],[3,1],[3,2],[1,3],[2,3],[0,4],[0,5],[1,6 + * ],[2,6],[3,4],[3,5]] ], [ // 9 + * [4],[[0,1],[0,2],[1,0],[2,0],[3,1],[3,2],[1,3],[ + * 2,3],[3,3],[3,4],[3,5],[3,6]] ], // 10 [ [1],[[0,2],[0,4]] ], ] + */ + private final int space_between_symbols = 0; /** - * Translate 'number' to its LED frame data and load into matrix controller shifted by plus_x columns + * Translate 'number' to its LED frame data and load into matrix controller shifted by plus_x columns + * * @param number * @param digit_count * @param plus_x * @param display_dev * @param led_blink - * @return matrix column offset for next number + * @return matrix column offset for next number */ - public int write_num(int number, int digit_count, int plus_x, Is31Fl37Matrix display_dev, int led_blink) { - this.logger.trace("write_num"); + public int write_num(int number, int digit_count, int plus_x, Is31Fl37Matrix display_dev, int led_blink) { + this.logger.trace("write_num"); - int[] the_list = pixels[number]; - // plus_x used to place items across matrix + int[] the_list = pixels[number]; + // plus_x used to place items across matrix - for (int i = 0; i < the_list.length; i += 2) { - display_dev.pixel(plus_x + (the_list[i]), the_list[i + 1], 10, led_blink, 0); - // Use digit_count and each digit is on a new frams, - // or put them all on the same frame if last parm '0' - } - int next_displace = plus_x + (width[number] + space_between_symbols); - this.logger.trace("write_num"); + for (int i = 0; i < the_list.length; i += 2) { + display_dev.pixel(plus_x + (the_list[i]), the_list[i + 1], 10, led_blink, 0); + // Use digit_count and each digit is on a new frams, + // or put them all on the same frame if last parm '0' + } + int next_displace = plus_x + (width[number] + space_between_symbols); + this.logger.trace("write_num"); - return next_displace; + return next_displace; - } + } /** - * Based on input data, create the LED patterns (frame) to display that data. Then pass that data to the - * matrix controller to perform the actual display - * @param pin_monitor to toggle LEDs - * @param display_dev matrix controller - * @param display_num temperature value - * @param display_asc time value - * @param led_blink intensity - * @param loop_count whether display value is shown more than once - * @param time_mode Whether creating frames of temperature info ot time-of-day info + * Based on input data, create the LED patterns (frame) to display that data. Then pass that data to the + * matrix controller to perform the actual display + * + * @param pin_monitor to toggle LEDs + * @param display_dev matrix controller + * @param display_num temperature value + * @param display_asc time value + * @param led_blink intensity + * @param loop_count whether display value is shown more than once + * @param time_mode Whether creating frames of temperature info ot time-of-day info */ - public void create_led_pattern(ControlLeds pin_monitor, Is31Fl37Matrix display_dev, int display_num, - char[] display_asc, int led_blink, Integer loop_count, boolean time_mode) { - // if verbose: - // print - // "create_led_pattern:display in leds : time_mode %s, display_num %s - // "%(time_mode, - // display_num) - this.logger.trace("create_led_pattern"); - this.logger.trace("parms : display_num : " + String.format("0x%02X", display_num) + " display_ASC : " - + display_asc[0] + " blink : " + String.format("0x%02X", led_blink) + " loop_count : " - + String.format("0x%02X", loop_count) + " time_mode : " + time_mode); - - // # et LEDs to indicate starting matrix operation - pin_monitor.toggle_led(true); - - char[] ascii_num; // = ''; // new char[5]; - String ascii_str; - - if (time_mode) { - ascii_num = display_asc; - } else { - ascii_str = Integer.toString(display_num); - ascii_num = ascii_str.toCharArray(); - } - int num = 0; - int offset = 0; - int placement = 0; // # aded to x axis value in setting the pixels - // # special format when displaying time - if (time_mode) { // # we expect format HH:MM in string format - num = Character.getNumericValue(display_asc[0]); - placement = this.write_num(num, offset, placement, display_dev, led_blink); - offset += 1; - // # - num = Character.getNumericValue(display_asc[1]); - placement = this.write_num(num, offset, placement, display_dev, led_blink); - offset += 1; - // # - num = 10; // # pixel array for base 10, has an eleventh entry for - // the : - display_dev.blink_write(540); - placement = this.write_num(num, offset, placement, display_dev, 1); // #led_blink) - // # - // force - // blinking - offset += 1; - // # - num = Character.getNumericValue(display_asc[3]); - placement = this.write_num(num, offset, placement, display_dev, led_blink); - offset += 1; - // # - num = Character.getNumericValue(display_asc[4]); + public void create_led_pattern(ControlLeds pin_monitor, Is31Fl37Matrix display_dev, int display_num, + char[] display_asc, int led_blink, Integer loop_count, boolean time_mode) { + // if verbose: + // print + // "create_led_pattern:display in leds : time_mode %s, display_num %s + // "%(time_mode, + // display_num) + this.logger.trace("create_led_pattern"); + this.logger.trace("parms : display_num : " + String.format("0x%02X", display_num) + " display_ASC : " + + display_asc[0] + " blink : " + String.format("0x%02X", led_blink) + " loop_count : " + + String.format("0x%02X", loop_count) + " time_mode : " + time_mode); + + // # et LEDs to indicate starting matrix operation + pin_monitor.toggle_led(true); + + char[] ascii_num; // = ''; // new char[5]; + String ascii_str; + + if (time_mode) { + ascii_num = display_asc; + } else { + ascii_str = Integer.toString(display_num); + ascii_num = ascii_str.toCharArray(); + } + int num = 0; + int offset = 0; + int placement = 0; // # aded to x axis value in setting the pixels + // # special format when displaying time + if (time_mode) { // # we expect format HH:MM in string format + num = Character.getNumericValue(display_asc[0]); + placement = this.write_num(num, offset, placement, display_dev, led_blink); + offset += 1; + // # + num = Character.getNumericValue(display_asc[1]); + placement = this.write_num(num, offset, placement, display_dev, led_blink); + offset += 1; + // # + num = 10; // # pixel array for base 10, has an eleventh entry for + // the : + display_dev.blink_write(540); + placement = this.write_num(num, offset, placement, display_dev, 1); // #led_blink) + // # + // force + // blinking + offset += 1; + // # + num = Character.getNumericValue(display_asc[3]); + placement = this.write_num(num, offset, placement, display_dev, led_blink); + offset += 1; + // # + num = Character.getNumericValue(display_asc[4]); + placement = this.write_num(num, offset, placement, display_dev, led_blink); + offset += 1; + } else { + for (int i = 0; i < ascii_num.length; i++) { + num = Character.getNumericValue(ascii_num[i]); placement = this.write_num(num, offset, placement, display_dev, led_blink); offset += 1; } + } - else { - for (int i = 0; i < ascii_num.length; i++) { - num = Character.getNumericValue(ascii_num[i]); - placement = this.write_num(num, offset, placement, display_dev, led_blink); - offset += 1; - } - } + int delay = 693; + int frames = 0; // could use offset + display_dev.autoplay(delay, loop_count, frames);// #offset + // # wait for the autoplay to complete + // #completed = pin_monitor.monitor_intr(verbose) + // # call dbus interface + + // if verbose: + // print "monitor_intr returned ", completed + this.logger.trace("create_led_pattern"); - int delay = 693; - int frames = 0; // could use offset - display_dev.autoplay(delay, loop_count, frames);// #offset - // # wait for the autoplay to complete - // #completed = pin_monitor.monitor_intr(verbose) - // # call dbus interface + } - // if verbose: - // print "monitor_intr returned ", completed - this.logger.trace("create_led_pattern"); - } + private final Logger logger; -private Logger logger; - - - } +} diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayTemp.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayTemp.java index 65d2734..8687605 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayTemp.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/DisplayTemp.java @@ -50,7 +50,7 @@ public class DisplayTemp { * This class includes the state - private BMP280Device bmpDev; This is required as Pi4j_V2 * does not permit repeated instantiations of an I2C device using the same Pi i2c Bus and address. So * this class creates the BMP280 device once and reuses that same instance on subsequent invocation. - * */ + */ public DisplayTemp(Context pi4j, Console console, Is31Fl37Matrix display, Logger logger) { this.display = display; @@ -61,8 +61,8 @@ public DisplayTemp(Context pi4j, Console console, Is31Fl37Matrix display, Logger } /** - * Note, the bmp_bus and bmp_address supplied on the initial call to this method will continue to be used - * on subsequent calls regardless of values supplied. + * Note, the bmp_bus and bmp_address supplied on the initial call to this method will continue to be used + * on subsequent calls regardless of values supplied. */ public void process_bmp_data(ControlLeds pin_monitor, int led_blink, Integer loop_count, Integer bmp_bus, Integer bmp_address) { @@ -71,7 +71,7 @@ public void process_bmp_data(ControlLeds pin_monitor, int led_blink, // bmp = read_BMP180.ReadBmp180() this.logger.trace("process_bmp_data"); this.logger.trace("parms : blink : " + String.format("0x%02X", led_blink) + " loop_count : " - + String.format("0x%02X", loop_count) + " bmp180 address : " + String.format("0x%02X", bmp_address)); + + String.format("0x%02X", loop_count) + " bmp180 address : " + String.format("0x%02X", bmp_address)); // pi4j_V2 does not support creating an instance more than one. if (this.bmpDev == null) { @@ -93,7 +93,7 @@ public void process_bmp_data(ControlLeds pin_monitor, int led_blink, char[] display_asc = new char[5]; DisplayLED disp_worker = new DisplayLED(this.logger); disp_worker.create_led_pattern(pin_monitor, this.display, display_num, display_asc, led_blink, loop_count, - time_mode); + time_mode); /* * System.out.println("sit and spin to see if the java trigger fires"); * try { Thread.sleep(10); } catch (InterruptedException e) { // TODO @@ -118,14 +118,14 @@ public void show_time(ControlLeds pin_monitor, int led_blink, LocalTime thisSec; this.logger.trace("show_time"); this.logger.trace("parms : blink : " + String.format("0x%02X", led_blink) + " loop_count : " - + String.format("0x%02X", loop_count)); + + String.format("0x%02X", loop_count)); thisSec = LocalTime.now(); String string_asc = String.format("%1$02d:%2$02d", thisSec.getHour(), thisSec.getMinute()); char[] display_asc = string_asc.toCharArray(); DisplayLED disp_worker = new DisplayLED(this.logger); disp_worker.create_led_pattern(pin_monitor, this.display, display_num, display_asc, led_blink, loop_count, - time_mode); + time_mode); InterruptDetails completed = pin_monitor.wait_for_interrupt(); if (completed.getSuccessVal()) { @@ -137,7 +137,7 @@ public void show_time(ControlLeds pin_monitor, int led_blink, } - private Is31Fl37Matrix display; + private final Is31Fl37Matrix display; private final Logger logger; private BMP280Device bmpDev; private final Context pi4j; diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/InterruptDetails.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/InterruptDetails.java index 4718728..5f2f7f2 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/InterruptDetails.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/InterruptDetails.java @@ -32,29 +32,29 @@ */ public class InterruptDetails { - public InterruptDetails(){ - this.counter = 0; - this.rval = false; + public InterruptDetails() { + this.counter = 0; + this.rval = false; - } + } - public InterruptDetails(boolean rval, int counter){ - this.counter = counter; - this.rval = rval; + public InterruptDetails(boolean rval, int counter) { + this.counter = counter; + this.rval = rval; - } + } - public boolean getSuccessVal(){ - return (this.rval); - } + public boolean getSuccessVal() { + return (this.rval); + } - public int getCounter(){ - return(this.counter); - } + public int getCounter() { + return (this.counter); + } - private boolean rval; - private int counter; + private final boolean rval; + private final int counter; - } +} diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37Matrix.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37Matrix.java index 5a97868..b908dfc 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37Matrix.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37Matrix.java @@ -34,43 +34,46 @@ */ - import com.pi4j.context.Context; - import com.pi4j.io.gpio.digital.*; - import com.pi4j.io.i2c.I2C; - import org.slf4j.Logger; +import com.pi4j.context.Context; +import com.pi4j.io.gpio.digital.DigitalInput; +import com.pi4j.io.gpio.digital.DigitalState; +import com.pi4j.io.gpio.digital.DigitalStateChangeEvent; +import com.pi4j.io.gpio.digital.DigitalStateChangeListener; +import com.pi4j.io.i2c.I2C; +import org.slf4j.Logger; public class Is31Fl37Matrix { - private int width = 16; - private int height = 9; - private int _MODE_REGISTER = 0x00; - private int _FRAME_REGISTER = 0x01; - private int _AUTOPLAY1_REGISTER = 0x02; - private int _AUTOPLAY2_REGISTER = 0x03; - private int _BLINK_REGISTER = 0x05; - private int _AUDIOSYNC_REGISTER = 0x06; - private int _FRAME_STATE_REGISTER = 0x07; - private int _BREATH1_REGISTER = 0x08; - private int _BREATH2_REGISTER = 0x09; - private int _SHUTDOWN_REGISTER = 0x0a; - private int _GAIN_REGISTER = 0x0b; - private int _ADC_REGISTER = 0x0c; - - private int _CONFIG_BANK = 0x0b; - private int _BANK_ADDRESS = 0xfd; - - private int _PICTURE_MODE = 0x00; - private int _AUTOPLAY_MODE = 0x08; - private int _AUDIOPLAY_MODE = 0x18; - - private int _ENABLE_OFFSET = 0x00; - private int _BLINK_OFFSET = 0x12; - private int _COLOR_OFFSET = 0x24; + private final int width = 16; + private final int height = 9; + private final int _MODE_REGISTER = 0x00; + private final int _FRAME_REGISTER = 0x01; + private final int _AUTOPLAY1_REGISTER = 0x02; + private final int _AUTOPLAY2_REGISTER = 0x03; + private final int _BLINK_REGISTER = 0x05; + private final int _AUDIOSYNC_REGISTER = 0x06; + private final int _FRAME_STATE_REGISTER = 0x07; + private final int _BREATH1_REGISTER = 0x08; + private final int _BREATH2_REGISTER = 0x09; + private final int _SHUTDOWN_REGISTER = 0x0a; + private final int _GAIN_REGISTER = 0x0b; + private final int _ADC_REGISTER = 0x0c; + + private final int _CONFIG_BANK = 0x0b; + private final int _BANK_ADDRESS = 0xfd; + + private final int _PICTURE_MODE = 0x00; + private final int _AUTOPLAY_MODE = 0x08; + private final int _AUDIOPLAY_MODE = 0x18; + + private final int _ENABLE_OFFSET = 0x00; + private final int _BLINK_OFFSET = 0x12; + private final int _COLOR_OFFSET = 0x24; private int _frame = 0; private boolean intrp_occured = false; - private Logger logger; + private final Logger logger; public Is31Fl37Matrix(Integer bus, Integer address, Integer bmp_address, Logger logger, DigitalInput interruptPin, Context pi4j) { @@ -95,17 +98,17 @@ public Is31Fl37Matrix(Integer bus, Integer address, Integer bmp_address, Logger private I2C createI2cDevice(int bus, int address) { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); - this.logger.trace("Enter: createI2cDevice VL53L0X_TOF" + id + "" + name); + this.logger.trace("Enter: createI2cDevice VL53L0X_TOF" + id + name); I2C rval = null; var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id("VL53L0X_TOF " + id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id("VL53L0X_TOF " + id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); rval = this.pi4j.create(i2cDeviceConfig); - this.logger.trace("Exit: createI2cDevice VL53L0X_TOF" + id + "" + name); + this.logger.trace("Exit: createI2cDevice VL53L0X_TOF" + id + name); return (rval); } @@ -164,8 +167,6 @@ private boolean init() { // this.ffdc.logger); - - this.input.addListener(new MatrixGpioListener(this)); this.logger.info("Added listener"); try { @@ -179,8 +180,8 @@ private boolean init() { * GpioSyncStateTrigger( * this.gpio.getCfgData(RaspiBcmPin.GPIO_24).output)); */ - this.audio_sync(0); - this.logger.info("init"); + this.audio_sync(0); + this.logger.info("init"); return (true); } @@ -199,8 +200,8 @@ public void intrp_happened() { /** * Uses the Pi GPIO event listener pattern. When the interrupt occurs the listener class will set * this.intrp_occured true - * @return Class containing completion success and loop count waiting for interrupt. * + * @return Class containing completion success and loop count waiting for interrupt. */ public InterruptDetails waitIntjLoop() { this.logger.info("waitIntjLoop"); @@ -209,7 +210,7 @@ public InterruptDetails waitIntjLoop() { int counter = 0; int MAX = 2000; while (true) { - if (this.intrp_occured == true) { + if (this.intrp_occured) { is_done = true; this.intrp_occured = false; // ystem.out.println("GPIO 20 is LOW"); @@ -231,14 +232,15 @@ public InterruptDetails waitIntjLoop() { } } this.logger.info( - "waitIntjLoop " + is_done + " counter : " + String.format("0x%02X", counter)); + "waitIntjLoop " + is_done + " counter : " + String.format("0x%02X", counter)); return (new InterruptDetails(is_done, counter)); } /** - * Ti avaoid a Pi4J_V2 GPIO interrupt bug, maually check the interrupt GPIO to determine if - * the matrix controller signalled frame display completion via the INTB line - * @return Class containing completion success and loop count waiting for interrupt. + * Ti avaoid a Pi4J_V2 GPIO interrupt bug, maually check the interrupt GPIO to determine if + * the matrix controller signalled frame display completion via the INTB line + * + * @return Class containing completion success and loop count waiting for interrupt. */ public InterruptDetails waitIntpLoop() { boolean is_done = false; @@ -247,11 +249,11 @@ public InterruptDetails waitIntpLoop() { this.logger.trace("waitIntpLoop"); while (true) { - if (this.input.isLow()) { - is_done = true; - this.logger.info(this.input.getDescription() + " is LOW"); - break; - } + if (this.input.isLow()) { + is_done = true; + this.logger.info(this.input.getDescription() + " is LOW"); + break; + } try { Thread.sleep(2); @@ -267,7 +269,7 @@ public InterruptDetails waitIntpLoop() { } } this.logger.trace( - "waitIntpLoop " + is_done + " counter " + String.format("0x%02X", counter)); + "waitIntpLoop " + is_done + " counter " + String.format("0x%02X", counter)); return (new InterruptDetails(is_done, counter)); } @@ -311,22 +313,22 @@ public void dumpRegs() { public String dumpBits(int regOffset, byte[] reg) { String wholeMess = ""; - String reg_name[] = { "_MODE_REGISTER ", "_FRAME_REGISTER ", "_AUTOPLAY1_REGISTER", "_AUTOPLAY2_REGISTER ", - "_BLINK_REGISTER ", "_AUDIOSYNC_REGISTER ", "_FRAME_STATE_REGISTER", "_BREATH1_REGISTER ", - "_BREATH2_REGISTER ", "_SHUTDOWN_REGISTER ", "_GAIN_REGISTER ", "_ADC_REGISTER " }; - - String[][] pin_name = { { "--- --- --- Mode Mode >>> Frame <<<" }, - { "--- --- --- --- --- >>> Frame <<< " }, - { "--- >>> Loops <<< --- >>> Frames <<< " }, - { "--- --- >>>> Frame Delay X 23ms <<<< " }, - { "--- --- IC --- Blink > Time X 0.27s < " }, - { "--- --- --- --- --- --- --- Enable " }, - { "--- --- --- INT --- > Current Frame < " }, - { "--- > Fade out time < --- > Fade in time < " }, - { "--- --- --- Ena --- --- --- ET " }, - { "--- --- --- --- --- --- --- on/normal" }, - { "--- --- --- Mode Ena >>> AGS <<< " }, - { ">>> Audio Sample Rate <<< " }, }; + String[] reg_name = {"_MODE_REGISTER ", "_FRAME_REGISTER ", "_AUTOPLAY1_REGISTER", "_AUTOPLAY2_REGISTER ", + "_BLINK_REGISTER ", "_AUDIOSYNC_REGISTER ", "_FRAME_STATE_REGISTER", "_BREATH1_REGISTER ", + "_BREATH2_REGISTER ", "_SHUTDOWN_REGISTER ", "_GAIN_REGISTER ", "_ADC_REGISTER "}; + + String[][] pin_name = {{"--- --- --- Mode Mode >>> Frame <<<"}, + {"--- --- --- --- --- >>> Frame <<< "}, + {"--- >>> Loops <<< --- >>> Frames <<< "}, + {"--- --- >>>> Frame Delay X 23ms <<<< "}, + {"--- --- IC --- Blink > Time X 0.27s < "}, + {"--- --- --- --- --- --- --- Enable "}, + {"--- --- --- INT --- > Current Frame < "}, + {"--- > Fade out time < --- > Fade in time < "}, + {"--- --- --- Ena --- --- --- ET "}, + {"--- --- --- --- --- --- --- on/normal"}, + {"--- --- --- Mode Ena >>> AGS <<< "}, + {">>> Audio Sample Rate <<< "},}; wholeMess = wholeMess + "Reg " + reg_name[regOffset] + " " + String.format("0x%02X", reg[0]); byte val = reg[0]; @@ -335,8 +337,8 @@ public String dumpBits(int regOffset, byte[] reg) { // System.out.println("pin7 pin6 pin5 pin4 pin3 pin2 pin1 pin0"); wholeMess = wholeMess + "\n" + pin_name[regOffset][0]; wholeMess = wholeMess + "\n" + " " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " - + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"; + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " + + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"; } return (wholeMess); @@ -347,7 +349,6 @@ private void audio_sync(int value) { this._register_write(this._CONFIG_BANK, this._AUDIOSYNC_REGISTER, value); this.logger.trace("audio_sync"); - return; } private void frame_write(int frame, boolean show) { @@ -376,20 +377,20 @@ private void _mode(int mode) { this._register_write(this._CONFIG_BANK, this._MODE_REGISTER, mode); this.logger.trace("_mode"); - } + } private int getInt(byte[] data, int index) { // # return two bytes from data as a signed 16-bit valu this.logger.trace( - "getInt :" + String.format("0x%02X", data) + " index : " + String.format("0x%02X", index)); + "getInt :" + String.format("0x%02X", data) + " index : " + String.format("0x%02X", index)); this.logger.trace( - "get short " + String.format("0x%02X", data[index]) + " " + String.format("0x%02X", data[index + 1])); + "get short " + String.format("0x%02X", data[index]) + " " + String.format("0x%02X", data[index + 1])); this.logger.trace( - "return " + (int) (((data[index] << 16)) + ((data[index + 1] << 8)) + ((data[index + 2]) & 0xff))); + "return " + (((data[index] << 16)) + ((data[index + 1] << 8)) + ((data[index + 2]) & 0xff))); this.logger.trace("getInt : " + String.format("0x%02X", - ((int) (((data[index] << 16)) + ((data[index + 1] << 8)) + ((data[index + 2]) & 0xff))))); - return ((int) (((data[index] << 16)) + ((data[index + 1] << 8)) + ((data[index + 2]) & 0xff))); + ((data[index] << 16)) + ((data[index + 1] << 8)) + ((data[index + 2]) & 0xff))); + return ((data[index] << 16)) + ((data[index + 1] << 8)) + ((data[index + 2]) & 0xff); } private int blink_read() { @@ -419,7 +420,7 @@ int blink_write(int rate) { public byte _bank_read() { this.logger.trace("_bank_read "); byte[] data = new byte[1]; - int rc = this.device.read(data, this._BANK_ADDRESS, 1); + int rc = this.device.read(data, this._BANK_ADDRESS, 1); this.logger.trace("_bank_read :" + String.format("0x%02X", data[0])); return (data[0]); } @@ -436,7 +437,7 @@ private int _bank_write(int bank) { void fill(int color, byte blink, int frame) { this.logger.trace("fill :" + String.format("0x%02X", color) + " blink " - + String.format("0x%02X", blink) + " frame " + String.format("0x%02X", frame)); + + String.format("0x%02X", blink) + " frame " + String.format("0x%02X", frame)); if (frame == 42) { frame = this._frame; } @@ -467,7 +468,7 @@ void fill(int color, byte blink, int frame) { private int _pixel_addr(int x, int y) { this.logger.trace( - "_pixel_addr " + String.format("0x%02X", x) + " " + String.format("0x%02X", y)); + "_pixel_addr " + String.format("0x%02X", x) + " " + String.format("0x%02X", y)); this.logger.trace("_pixel_addr : " + String.format("0x%02X", (x + y * 16))); return (x + y * 16); } @@ -475,8 +476,8 @@ private int _pixel_addr(int x, int y) { int pixel(int x, int y, int color, int blink, int frame) { // System.out.println("pixels "); this.logger.trace("pixel " + String.format("0x%02X", x) + " " + String.format("0x%02X", y) - + " color " + String.format("0x%02X", color) + " blink " + String.format("0x%02X", blink) + " frame " - + String.format("0x%02X", frame)); + + " color " + String.format("0x%02X", color) + " blink " + String.format("0x%02X", blink) + " frame " + + String.format("0x%02X", frame)); int rtn = 0; if ((x < 0) || (x > this.width)) { @@ -506,7 +507,7 @@ int pixel(int x, int y, int color, int blink, int frame) { int addr = pixel / 8; int bit = pixel % 8; byte[] data = this._register_read(frame, this._BLINK_OFFSET + addr); - int bits = (int) data[0]; + int bits = data[0]; if (blink == 1) { bits |= 1 << bit; } else { @@ -519,11 +520,11 @@ int pixel(int x, int y, int color, int blink, int frame) { private byte[] _register_read(int bank, int register) { this.logger.trace("_register_read : " + String.format("0x%02X", bank) + " register " - + String.format("0x%02X", register)); + + String.format("0x%02X", register)); // System.out.println("reg read " + bank + " " + register); this._bank_write(bank); byte[] rtn = new byte[1]; - int bytesRead = this.device.readRegister(register, rtn,1); + int bytesRead = this.device.readRegister(register, rtn, 1); // i2c.read_i2c_block_data(self.address, // register, 1)[0]); /* @@ -537,7 +538,7 @@ private byte[] _register_read(int bank, int register) { private void _register_write(int bank, int register, int value) { this.logger.trace("_register_write : " + String.format("0x%02X", bank) + " register " - + String.format("0x%02X", register) + " value " + String.format("0x%02X", value)); + + String.format("0x%02X", register) + " value " + String.format("0x%02X", value)); // System.out.println("reg write " + bank + " " + register + " " + // value); @@ -563,7 +564,7 @@ private void _mode_write(int mode) { void autoplay(int delay, int loops, int frames) { this.logger.trace("autoplay " + String.format("0x%02X", delay) + " loops " - + String.format("0x%02X", loops) + " frames" + String.format("0x%02X", frames)); + + String.format("0x%02X", loops) + " frames" + String.format("0x%02X", frames)); if (delay == 0) { this._mode_write(this._PICTURE_MODE); this.logger.trace("delay zero, picture mode"); @@ -591,16 +592,16 @@ void autoplay(int delay, int loops, int frames) { } - private int address; - private int bmp_address; - private int bus_num; - private I2C device; - private DigitalInput input; + private final int address; + private final int bmp_address; + private final int bus_num; + private final I2C device; + private final DigitalInput input; - private Context pi4j; + private final Context pi4j; + + private class MatrixGpioListener implements DigitalStateChangeListener { - private class MatrixGpioListener implements DigitalStateChangeListener { - ; public MatrixGpioListener(Is31Fl37Matrix chip) { this.chip = chip; Runtime.getRuntime().addShutdownHook(new Thread() { @@ -623,7 +624,8 @@ public void onDigitalStateChange(DigitalStateChangeEvent event) { this.chip.intrp_happened(); } } - private Is31Fl37Matrix chip; + + private final Is31Fl37Matrix chip; } diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_app.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_app.java index c64c932..65d5e77 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_app.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_app.java @@ -46,18 +46,16 @@ //import com.pi4j.io.gpio.Pin; - - public class Is31Fl37_matrix_app { - private DigitalOutput processGPIO; - private DigitalOutput warnGPIO; + private DigitalOutput processGPIO; + private DigitalOutput warnGPIO; private Context pi4j = null; private int address; private int bmp_address; private int bus_num; private int bmp_bus; - private boolean verbose = false; + private final boolean verbose = false; private int loop_count = 0; private int repeat_count; private int led_blink = 0; @@ -70,7 +68,6 @@ public class Is31Fl37_matrix_app { //GpioUtil gpioUtil; - public Is31Fl37_matrix_app() { System.out.println(" default ctor"); @@ -113,15 +110,15 @@ public void print_state() { * this.led_blink); */ this.logger.info(" print_state() Matrix address: " + String.format("0x%02X", this.address) + " Matrix bus_num: " - + this.bus_num + " BMP address: " + String.format("0x%02X", this.bmp_address) + " BMP bus_num: " - + this.bmp_bus +" traceLevel: " + this.traceLevel + " loop_count: " + this.loop_count - + " repeat_count: " + this.repeat_count + " led_blink: " + this.led_blink); + + this.bus_num + " BMP address: " + String.format("0x%02X", this.bmp_address) + " BMP bus_num: " + + this.bmp_bus + " traceLevel: " + this.traceLevel + " loop_count: " + this.loop_count + + " repeat_count: " + this.repeat_count + " led_blink: " + this.led_blink); } public void clearGpioCfg() { - // final GpioController gpio = GpioFactory.getInstance(); - // gpio.shutdown(); + // final GpioController gpio = GpioFactory.getInstance(); + // gpio.shutdown(); } public static void main(String[] args) throws IOException, InterruptedException { @@ -156,12 +153,11 @@ public static void main(String[] args) throws IOException, InterruptedException String mainChip = null; boolean doReset = false; - + final Console console = new Console(); Context pi4j = Pi4J.newAutoContext(); - console.println("Is31fl37_matrix_app entered : "); String badParm = ""; for (int i = 0; i < args.length; i++) { @@ -178,10 +174,10 @@ public static void main(String[] args) throws IOException, InterruptedException } } else if (o.contentEquals("-h")) { console.println( - " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31fl37_matrix_app -b 0x1 -a 0x74 " + - " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + - "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + - "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\"" ); + " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31fl37_matrix_app -b 0x1 -a 0x74 " + + " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + + "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + + "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""); System.exit(0); } else if (o.contentEquals("-r")) { String a = args[i + 1]; @@ -194,15 +190,15 @@ public static void main(String[] args) throws IOException, InterruptedException monitorPinNum = Integer.parseInt(a); console.println("monitorPin " + monitorPinNum); i++; - } else if (o.contentEquals("-b")) { + } else if (o.contentEquals("-b")) { String a = args[i + 1]; bus_num = Integer.parseInt(a.substring(2), 16); i++; - } else if (o.contentEquals("-bmpB")) { + } else if (o.contentEquals("-bmpB")) { String a = args[i + 1]; bmp_bus = Integer.parseInt(a.substring(2), 16); i++; - }else if (o.contentEquals("-l")) { + } else if (o.contentEquals("-l")) { String a = args[i + 1]; i++; int num = Integer.parseInt(a); @@ -229,7 +225,7 @@ public static void main(String[] args) throws IOException, InterruptedException i++; address = Integer.parseInt(a.substring(2), 16); // display_app.address = Integer.parseInt(a, 16); - }else if (o.contentEquals("-bmpA")) { + } else if (o.contentEquals("-bmpA")) { String a = args[i + 1]; i++; bmp_address = Integer.parseInt(a.substring(2), 16); @@ -244,10 +240,10 @@ public static void main(String[] args) throws IOException, InterruptedException console.println("Changing trace level invalid : " + traceLevel); System.exit(41); } - } else if (o.contentEquals("-c")) { + } else if (o.contentEquals("-c")) { String a = args[i + 1]; i++; - repeat_count = Integer.parseInt(a.substring(0)); + repeat_count = Integer.parseInt(a); } else if (o.contentEquals("-s")) { tmpFileUse = true; @@ -256,7 +252,7 @@ public static void main(String[] args) throws IOException, InterruptedException // >>>tcaObj.bus_num = Integer.parseInt(a.substring(2), 16); i++; - }else if (o.contentEquals("-g")) { + } else if (o.contentEquals("-g")) { String a = args[i + 1]; createProcessPin = true; processGPIO = Integer.parseInt(a); @@ -268,23 +264,21 @@ public static void main(String[] args) throws IOException, InterruptedException warnGPIO = Integer.parseInt(a); console.println("warnLED pin " + warnGPIO); i++; - } else { + } else { badParm = o; parmsOk = false; } } - - // create the required GPIOs var ledConfigIntr = DigitalInput.newConfigBuilder(pi4j) - .id("MatrixInterrupt") - .name("MatrixInterrupt") - .address(monitorPinNum) - .pull(PullResistance.PULL_UP) - .debounce(4000L) - .provider("gpiod-digital-input"); + .id("MatrixInterrupt") + .name("MatrixInterrupt") + .address(monitorPinNum) + .pull(PullResistance.PULL_UP) + .debounce(4000L) + .provider("gpiod-digital-input"); try { monitorPin = pi4j.create(ledConfigIntr); } catch (Exception e) { @@ -293,12 +287,12 @@ public static void main(String[] args) throws IOException, InterruptedException System.exit(200); } var ledConfigReset = DigitalOutput.newConfigBuilder(pi4j) - .id("MatrixReset") - .name("MatrixReset") - .address(resetPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("MatrixReset") + .name("MatrixReset") + .address(resetPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { resetPin = pi4j.create(ledConfigReset); } catch (Exception e) { @@ -307,14 +301,14 @@ public static void main(String[] args) throws IOException, InterruptedException System.exit(201); } - if(createProcessPin) { + if (createProcessPin) { var ledConfigGreen = DigitalOutput.newConfigBuilder(pi4j) - .id("ProcessLED") - .name("ProcessLED") - .address(processGPIO) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); + .id("ProcessLED") + .name("ProcessLED") + .address(processGPIO) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { processPin = pi4j.create(ledConfigGreen); } catch (Exception e) { @@ -324,14 +318,14 @@ public static void main(String[] args) throws IOException, InterruptedException } } - if(createWarnPin) { + if (createWarnPin) { var ledConfigRed = DigitalOutput.newConfigBuilder(pi4j) - .id("WarnLED") - .name("WarnLED") - .address(warnGPIO) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); + .id("WarnLED") + .name("WarnLED") + .address(warnGPIO) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { warnPin = pi4j.create(ledConfigRed); } catch (Exception e) { @@ -341,23 +335,23 @@ public static void main(String[] args) throws IOException, InterruptedException } } - if(doReset){ + if (doReset) { console.println("Do chip reset"); resetPin.low(); Thread.sleep(600); resetPin.high(); } - Is31Fl37_matrix_app display_app = new Is31Fl37_matrix_app(pi4j,console, bus_num, address, bmp_bus, bmp_address, loop_count, - repeat_count, led_blink, traceLevel, resetPin, monitorPin, warnPin, processPin); + Is31Fl37_matrix_app display_app = new Is31Fl37_matrix_app(pi4j, console, bus_num, address, bmp_bus, bmp_address, loop_count, + repeat_count, led_blink, traceLevel, resetPin, monitorPin, warnPin, processPin); - if (parmsOk == false) { + if (!parmsOk) { console.println("Invalid parm : " + badParm); console.println( - " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31fl37_matrix_app -b 0x1 -a 0x74 " + - " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + - "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + - "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\"" ); + " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31fl37_matrix_app -b 0x1 -a 0x74 " + + " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + + "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + + "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""); System.exit(0x42); } @@ -368,9 +362,9 @@ public static void main(String[] args) throws IOException, InterruptedException try { Is31Fl37Matrix matrix = new Is31Fl37Matrix(display_app.bus_num, display_app.address, - display_app.bmp_address, display_app.logger, display_app.monitorPin, display_app.pi4j); + display_app.bmp_address, display_app.logger, display_app.monitorPin, display_app.pi4j); DisplayTemp display = new DisplayTemp(display_app.pi4j, display_app.console, matrix, display_app.logger); - ControlLeds pin_monitor = new ControlLeds(display_app.pi4j, display_app.console,display_app.warnGPIO, display_app.processGPIO, matrix, display_app.logger); + ControlLeds pin_monitor = new ControlLeds(display_app.pi4j, display_app.console, display_app.warnGPIO, display_app.processGPIO, matrix, display_app.logger); try { Thread.sleep(2000); } catch (InterruptedException e) { @@ -388,7 +382,7 @@ public static void main(String[] args) throws IOException, InterruptedException // cfgU.runCli(); display.process_bmp_data(pin_monitor, - display_app.led_blink, display_app.loop_count, display_app.bmp_bus, display_app.bmp_address); + display_app.led_blink, display_app.loop_count, display_app.bmp_bus, display_app.bmp_address); // Thread.sleep(2000); // clear the matrix @@ -397,8 +391,8 @@ public static void main(String[] args) throws IOException, InterruptedException } // future //eChip = cfgU.enableChipPath(mainChip); display.show_time(pin_monitor, display_app.led_blink, - display_app.loop_count); - // clear the matrix + display_app.loop_count); + // clear the matrix for (c = 0; c < 8; c++) { matrix.fill(0, (byte) 0, 0); } @@ -408,11 +402,11 @@ public static void main(String[] args) throws IOException, InterruptedException for (c = 0; c < 8; c++) { matrix.fill(0, (byte) 0, 0); } - } else { // else leg continuously displays temperature/time + } else { // else leg continuously displays temperature/time while (true) { // future // eChip = cfgU.enableChipPath(mainChip); display.process_bmp_data(pin_monitor, - display_app.led_blink, display_app.loop_count, display_app.bmp_bus, display_app.bmp_address); + display_app.led_blink, display_app.loop_count, display_app.bmp_bus, display_app.bmp_address); Thread.sleep(2000); // clear the matrix for (c = 0; c < 8; c++) { @@ -420,7 +414,7 @@ public static void main(String[] args) throws IOException, InterruptedException } // future //eChip = cfgU.enableChipPath(mainChip); display.show_time(pin_monitor, display_app.led_blink, - display_app.loop_count); + display_app.loop_count); Thread.sleep(2000); // clear the matrix for (c = 0; c < 8; c++) { diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_test.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_test.java index 169c950..c8933ae 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_test.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/Is31Fl37_matrix_test.java @@ -50,344 +50,339 @@ public class Is31Fl37_matrix_test { + private DigitalOutput processGPIO; + private DigitalOutput warnGPIO; + private Context pi4j = null; + private int address; + private int bmp_address; + private int bus_num; + private int bmp_bus; + private final boolean verbose = false; + private int loop_count = 0; + private int repeat_count; + private int led_blink = 0; + private String traceLevel; + //mapUtils mapUtils; + private Logger logger = null; + private DigitalOutput resetPin = null; + private DigitalInput monitorPin = null; + private Console console; + + //GpioUtil gpioUtil; + + + public Is31Fl37_matrix_test() { + System.out.println(" default ctor"); + } - private DigitalOutput processGPIO; - private DigitalOutput warnGPIO; - private Context pi4j = null; - private int address; - private int bmp_address; - private int bus_num; - private int bmp_bus; - private boolean verbose = false; - private int loop_count = 0; - private int repeat_count; - private int led_blink = 0; - private String traceLevel; - //mapUtils mapUtils; - private Logger logger = null; - private DigitalOutput resetPin = null; - private DigitalInput monitorPin = null; - private Console console; - - //GpioUtil gpioUtil; - - - - public Is31Fl37_matrix_test() { - System.out.println(" default ctor"); - } - - public Is31Fl37_matrix_test(Context pi4j, Console console, int bus, int address, int bmpBus, int bmp_address, int loop_count, int repeat_count, int led_blink, - String traceLevel, DigitalOutput resetPin, DigitalInput monitorPin, DigitalOutput warnGpio, DigitalOutput processGpio) { - super(); - this.bus_num = bus; - this.address = address; - this.bmp_address = bmp_address; - this.loop_count = loop_count; - this.repeat_count = repeat_count; - this.led_blink = led_blink; - this.traceLevel = traceLevel; - this.resetPin = resetPin; - this.monitorPin = monitorPin; - this.pi4j = pi4j; - this.console = console; - this.bmp_bus = bmpBus; - this.warnGPIO = warnGpio; - this.processGPIO = processGpio; - - // "trace", "debug", "info", "warn", "error" or "off"). If not specified, defaults to "info" - // must fully qualify logger as others exist and the slf4 code will use the first it - // encounters if using the defaultLogLevel - System.setProperty("org.slf4j.simpleLogger.log." + com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test.class.getName(), this.traceLevel); - - this.logger = LoggerFactory.getLogger(com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test.class); - - // this.print_state(); - } + public Is31Fl37_matrix_test(Context pi4j, Console console, int bus, int address, int bmpBus, int bmp_address, int loop_count, int repeat_count, int led_blink, + String traceLevel, DigitalOutput resetPin, DigitalInput monitorPin, DigitalOutput warnGpio, DigitalOutput processGpio) { + super(); + this.bus_num = bus; + this.address = address; + this.bmp_address = bmp_address; + this.loop_count = loop_count; + this.repeat_count = repeat_count; + this.led_blink = led_blink; + this.traceLevel = traceLevel; + this.resetPin = resetPin; + this.monitorPin = monitorPin; + this.pi4j = pi4j; + this.console = console; + this.bmp_bus = bmpBus; + this.warnGPIO = warnGpio; + this.processGPIO = processGpio; + + // "trace", "debug", "info", "warn", "error" or "off"). If not specified, defaults to "info" + // must fully qualify logger as others exist and the slf4 code will use the first it + // encounters if using the defaultLogLevel + System.setProperty("org.slf4j.simpleLogger.log." + com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test.class.getName(), this.traceLevel); + + this.logger = LoggerFactory.getLogger(com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test.class); + + // this.print_state(); + } - public void print_state() { - /* - * System.out.println(" print_state() address: " + this.address + - * " bus_num: " + this.bus_num + " traceLevel: " + - * this.traceLevel + " loop_count: " + this.loop_count + - * " repeat_count: " + this.repeat_count + " led_blink: " + - * this.led_blink); - */ - this.logger.info(" print_state() Matrix address: " + String.format("0x%02X", this.address) + " Matrix bus_num: " - + this.bus_num + " BMP address: " + String.format("0x%02X", this.bmp_address) + " BMP bus_num: " - + this.bmp_bus +" traceLevel: " + this.traceLevel + " loop_count: " + this.loop_count - + " repeat_count: " + this.repeat_count + " led_blink: " + this.led_blink); + public void print_state() { + /* + * System.out.println(" print_state() address: " + this.address + + * " bus_num: " + this.bus_num + " traceLevel: " + + * this.traceLevel + " loop_count: " + this.loop_count + + * " repeat_count: " + this.repeat_count + " led_blink: " + + * this.led_blink); + */ + this.logger.info(" print_state() Matrix address: " + String.format("0x%02X", this.address) + " Matrix bus_num: " + + this.bus_num + " BMP address: " + String.format("0x%02X", this.bmp_address) + " BMP bus_num: " + + this.bmp_bus + " traceLevel: " + this.traceLevel + " loop_count: " + this.loop_count + + " repeat_count: " + this.repeat_count + " led_blink: " + this.led_blink); - } + } - public void clearGpioCfg() { - // final GpioController gpio = GpioFactory.getInstance(); - // gpio.shutdown(); - } + public void clearGpioCfg() { + // final GpioController gpio = GpioFactory.getInstance(); + // gpio.shutdown(); + } - public static void main(String[] args) throws IOException, InterruptedException { - // Logger logger = Logger.getLogger("ibm.simics.ProcessTable"); - /* - * Properties props = new java.util.Properties(); FileInputStream fis = - * new FileInputStream("table_wire.properties"); - * - * props.load(fis); - */ - int address = 0xff; - int bmp_address = 0xff; - int bus_num = 0xff; - int bmp_bus = 0xff; - int loop_count = 0; - int repeat_count = 0; - int led_blink = 0; - String traceLevel = "info"; - boolean tmpFileUse = false; - boolean parmsOk = true; - int resetPinNum = 0xff; - int monitorPinNum = 0xff; - int processGPIO = 0xff; - int warnGPIO = 0xff; - boolean createWarnPin = false; - boolean createProcessPin = false; - DigitalOutput processPin = null; - DigitalOutput warnPin = null; - DigitalOutput resetPin = null; - DigitalInput monitorPin = null; - boolean eChip = false; - String mainChip = null; - boolean doReset = false; - - - final Console console = new Console(); - Context pi4j = Pi4J.newAutoContext(); - - - - console.println("Is31Fl37_matrix_test entered : "); - String badParm = ""; - for (int i = 0; i < args.length; i++) { - String o = args[i]; - if (o.contentEquals("-t")) { - String a = args[i + 1]; - i++; - traceLevel = a; - if (a.contentEquals("trace") | a.contentEquals("debug") | a.contentEquals("info") | a.contentEquals("warn") | a.contentEquals("error") | a.contentEquals("off")) { - console.println("Changing trace level to : " + traceLevel); - } else { - console.println("Changing trace level invalid : " + traceLevel); - System.exit(40); - } - } else if (o.contentEquals("-h")) { - console.println( - " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31Fl37_matrix_test -b 0x1 -a 0x74 " + - " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + - "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + - "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\"" ); - System.exit(0); - } else if (o.contentEquals("-r")) { - String a = args[i + 1]; - resetPinNum = Integer.parseInt(a); - console.println("resetPin " + resetPinNum); - doReset = true; - i++; - } else if (o.contentEquals("-z")) { - String a = args[i + 1]; - monitorPinNum = Integer.parseInt(a); - console.println("monitorPin " + monitorPinNum); - i++; - } else if (o.contentEquals("-b")) { - String a = args[i + 1]; - bus_num = Integer.parseInt(a.substring(2), 16); - i++; - } else if (o.contentEquals("-bmpB")) { - String a = args[i + 1]; - bmp_bus = Integer.parseInt(a.substring(2), 16); - i++; - }else if (o.contentEquals("-l")) { - String a = args[i + 1]; - i++; - int num = Integer.parseInt(a); - if (num > 7) { - console.println("Too many loops, MAX of 7"); - badParm = "Too many loops, MAX of 7"; - parmsOk = false; - } else { - loop_count = Integer.parseInt(a); - } - } else if (o.contentEquals("-i")) { - String a = args[i + 1]; - i++; - int num = Integer.parseInt(a); - if (num > 810) { - console.println("Intensity too high, MAX of 810"); - badParm = "Intensity too high, MAX of 810"; - parmsOk = false; - } else { - led_blink = Integer.parseInt(a); - } - } else if (o.contentEquals("-a")) { - String a = args[i + 1]; - i++; - address = Integer.parseInt(a.substring(2), 16); - // display_app.address = Integer.parseInt(a, 16); - }else if (o.contentEquals("-bmpA")) { - String a = args[i + 1]; - i++; - traceLevel = a; - if (a.contentEquals("trace") | a.contentEquals("debug") | a.contentEquals("info") | a.contentEquals("warn") | a.contentEquals("error") | a.contentEquals("off")) { - console.println("Changing trace level to : " + traceLevel); - } else { - console.println("Changing trace level invalid : " + traceLevel); - System.exit(41); - } - } else if (o.contentEquals("-t")) { - String a = args[i + 1]; - i++; - bmp_address = Integer.parseInt(a.substring(2), 16); - // display_app.address = Integer.parseInt(a, 16); - } else if (o.contentEquals("-c")) { - String a = args[i + 1]; - i++; - repeat_count = Integer.parseInt(a.substring(0)); - } else if (o.contentEquals("-s")) { - tmpFileUse = true; - - } else if (o.contentEquals("-y")) { // mainChip - mainChip = args[i + 1]; - - // >>>tcaObj.bus_num = Integer.parseInt(a.substring(2), 16); - i++; - }else if (o.contentEquals("-g")) { - String a = args[i + 1]; - createProcessPin = true; - processGPIO = Integer.parseInt(a); - console.println("processGPIO Pin " + processGPIO); - i++; - } else if (o.contentEquals("-w")) { - String a = args[i + 1]; - createWarnPin = true; - warnGPIO = Integer.parseInt(a); - console.println("warnLED pin " + warnGPIO); - i++; - } else { - badParm = o; + public static void main(String[] args) throws IOException, InterruptedException { + // Logger logger = Logger.getLogger("ibm.simics.ProcessTable"); + /* + * Properties props = new java.util.Properties(); FileInputStream fis = + * new FileInputStream("table_wire.properties"); + * + * props.load(fis); + */ + int address = 0xff; + int bmp_address = 0xff; + int bus_num = 0xff; + int bmp_bus = 0xff; + int loop_count = 0; + int repeat_count = 0; + int led_blink = 0; + String traceLevel = "info"; + boolean tmpFileUse = false; + boolean parmsOk = true; + int resetPinNum = 0xff; + int monitorPinNum = 0xff; + int processGPIO = 0xff; + int warnGPIO = 0xff; + boolean createWarnPin = false; + boolean createProcessPin = false; + DigitalOutput processPin = null; + DigitalOutput warnPin = null; + DigitalOutput resetPin = null; + DigitalInput monitorPin = null; + boolean eChip = false; + String mainChip = null; + boolean doReset = false; + + + final Console console = new Console(); + Context pi4j = Pi4J.newAutoContext(); + + + console.println("Is31Fl37_matrix_test entered : "); + String badParm = ""; + for (int i = 0; i < args.length; i++) { + String o = args[i]; + if (o.contentEquals("-t")) { + String a = args[i + 1]; + i++; + traceLevel = a; + if (a.contentEquals("trace") | a.contentEquals("debug") | a.contentEquals("info") | a.contentEquals("warn") | a.contentEquals("error") | a.contentEquals("off")) { + console.println("Changing trace level to : " + traceLevel); + } else { + console.println("Changing trace level invalid : " + traceLevel); + System.exit(40); + } + } else if (o.contentEquals("-h")) { + console.println( + " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31Fl37_matrix_test -b 0x1 -a 0x74 " + + " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + + "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + + "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""); + System.exit(0); + } else if (o.contentEquals("-r")) { + String a = args[i + 1]; + resetPinNum = Integer.parseInt(a); + console.println("resetPin " + resetPinNum); + doReset = true; + i++; + } else if (o.contentEquals("-z")) { + String a = args[i + 1]; + monitorPinNum = Integer.parseInt(a); + console.println("monitorPin " + monitorPinNum); + i++; + } else if (o.contentEquals("-b")) { + String a = args[i + 1]; + bus_num = Integer.parseInt(a.substring(2), 16); + i++; + } else if (o.contentEquals("-bmpB")) { + String a = args[i + 1]; + bmp_bus = Integer.parseInt(a.substring(2), 16); + i++; + } else if (o.contentEquals("-l")) { + String a = args[i + 1]; + i++; + int num = Integer.parseInt(a); + if (num > 7) { + console.println("Too many loops, MAX of 7"); + badParm = "Too many loops, MAX of 7"; parmsOk = false; + } else { + loop_count = Integer.parseInt(a); } + } else if (o.contentEquals("-i")) { + String a = args[i + 1]; + i++; + int num = Integer.parseInt(a); + if (num > 810) { + console.println("Intensity too high, MAX of 810"); + badParm = "Intensity too high, MAX of 810"; + parmsOk = false; + } else { + led_blink = Integer.parseInt(a); + } + } else if (o.contentEquals("-a")) { + String a = args[i + 1]; + i++; + address = Integer.parseInt(a.substring(2), 16); + // display_app.address = Integer.parseInt(a, 16); + } else if (o.contentEquals("-bmpA")) { + String a = args[i + 1]; + i++; + traceLevel = a; + if (a.contentEquals("trace") | a.contentEquals("debug") | a.contentEquals("info") | a.contentEquals("warn") | a.contentEquals("error") | a.contentEquals("off")) { + console.println("Changing trace level to : " + traceLevel); + } else { + console.println("Changing trace level invalid : " + traceLevel); + System.exit(41); + } + } else if (o.contentEquals("-t")) { + String a = args[i + 1]; + i++; + bmp_address = Integer.parseInt(a.substring(2), 16); + // display_app.address = Integer.parseInt(a, 16); + } else if (o.contentEquals("-c")) { + String a = args[i + 1]; + i++; + repeat_count = Integer.parseInt(a); + } else if (o.contentEquals("-s")) { + tmpFileUse = true; + + } else if (o.contentEquals("-y")) { // mainChip + mainChip = args[i + 1]; + + // >>>tcaObj.bus_num = Integer.parseInt(a.substring(2), 16); + i++; + } else if (o.contentEquals("-g")) { + String a = args[i + 1]; + createProcessPin = true; + processGPIO = Integer.parseInt(a); + console.println("processGPIO Pin " + processGPIO); + i++; + } else if (o.contentEquals("-w")) { + String a = args[i + 1]; + createWarnPin = true; + warnGPIO = Integer.parseInt(a); + console.println("warnLED pin " + warnGPIO); + i++; + } else { + badParm = o; + parmsOk = false; } + } + // create the required GPIOs + var ledConfigIntr = DigitalInput.newConfigBuilder(pi4j) + .id("MatrixInterrupt") + .name("MatrixInterrupt") + .address(monitorPinNum) + .pull(PullResistance.PULL_UP) + .debounce(4000L) + .provider("gpiod-digital-input"); + try { + monitorPin = pi4j.create(ledConfigIntr); + } catch (Exception e) { + e.printStackTrace(); + console.println("create DigitalIn failed"); + System.exit(200); + } + var ledConfigReset = DigitalOutput.newConfigBuilder(pi4j) + .id("MatrixReset") + .name("MatrixReset") + .address(resetPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); + try { + resetPin = pi4j.create(ledConfigReset); + } catch (Exception e) { + e.printStackTrace(); + console.println("create DigOut reset failed"); + System.exit(201); + } - - // create the required GPIOs - var ledConfigIntr = DigitalInput.newConfigBuilder(pi4j) - .id("MatrixInterrupt") - .name("MatrixInterrupt") - .address(monitorPinNum) - .pull(PullResistance.PULL_UP) - .debounce(4000L) - .provider("gpiod-digital-input"); + if (createProcessPin) { + var ledConfigGreen = DigitalOutput.newConfigBuilder(pi4j) + .id("ProcessLED") + .name("ProcessLED") + .address(processGPIO) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { - monitorPin = pi4j.create(ledConfigIntr); + processPin = pi4j.create(ledConfigGreen); } catch (Exception e) { e.printStackTrace(); - console.println("create DigitalIn failed"); - System.exit(200); + console.println("create DigOut Process LED failed"); + System.exit(201); } - var ledConfigReset = DigitalOutput.newConfigBuilder(pi4j) - .id("MatrixReset") - .name("MatrixReset") - .address(resetPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + } + + if (createWarnPin) { + var ledConfigRed = DigitalOutput.newConfigBuilder(pi4j) + .id("WarnLED") + .name("WarnLED") + .address(warnGPIO) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { - resetPin = pi4j.create(ledConfigReset); + warnPin = pi4j.create(ledConfigRed); } catch (Exception e) { e.printStackTrace(); - console.println("create DigOut reset failed"); - System.exit(201); - } - - if(createProcessPin) { - var ledConfigGreen = DigitalOutput.newConfigBuilder(pi4j) - .id("ProcessLED") - .name("ProcessLED") - .address(processGPIO) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); - try { - processPin = pi4j.create(ledConfigGreen); - } catch (Exception e) { - e.printStackTrace(); - console.println("create DigOut Process LED failed"); - System.exit(201); - } - } - - if(createWarnPin) { - var ledConfigRed = DigitalOutput.newConfigBuilder(pi4j) - .id("WarnLED") - .name("WarnLED") - .address(warnGPIO) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); - try { - warnPin = pi4j.create(ledConfigRed); - } catch (Exception e) { - e.printStackTrace(); - console.println("create DigOut Warn LED failed"); - System.exit(202); - } + console.println("create DigOut Warn LED failed"); + System.exit(202); } + } - if(doReset){ - console.println("Do chip reset"); - resetPin.low(); - Thread.sleep(600); - resetPin.high(); - } + if (doReset) { + console.println("Do chip reset"); + resetPin.low(); + Thread.sleep(600); + resetPin.high(); + } - com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test display_app = new com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test(pi4j,console, bus_num, address, bmp_bus, bmp_address, loop_count, - repeat_count, led_blink, traceLevel, resetPin, monitorPin, warnPin, processPin); + com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test display_app = new com.pi4j.devices.is31Fl37Matrix.Is31Fl37_matrix_test(pi4j, console, bus_num, address, bmp_bus, bmp_address, loop_count, + repeat_count, led_blink, traceLevel, resetPin, monitorPin, warnPin, processPin); - if (parmsOk == false) { - console.println("Invalid parm : " + badParm); - console.println( - " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31Fl37_matrix_test -b 0x1 -a 0x74 " + - " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + - "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + - "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\"" ); - System.exit(0x42); - } + if (!parmsOk) { + console.println("Invalid parm : " + badParm); + console.println( + " java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31Fl37_matrix_test -b 0x1 -a 0x74 " + + " -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + + "-i intensity -c -l -s log -r resetGpio -z monitorGpio# " + + "-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""); + System.exit(0x42); + } - console.println(" Address : " + Integer.toHexString(address)); + console.println(" Address : " + Integer.toHexString(address)); - console.println("Arg processing completed..."); + console.println("Arg processing completed..."); + try { + Is31Fl37Matrix matrix = new Is31Fl37Matrix(display_app.bus_num, display_app.address, + display_app.bmp_address, display_app.logger, display_app.monitorPin, display_app.pi4j); + DisplayTemp display = new DisplayTemp(display_app.pi4j, display_app.console, matrix, display_app.logger); + ControlLeds pin_monitor = new ControlLeds(display_app.pi4j, display_app.console, display_app.warnGPIO, display_app.processGPIO, matrix, display_app.logger); try { - Is31Fl37Matrix matrix = new Is31Fl37Matrix(display_app.bus_num, display_app.address, - display_app.bmp_address, display_app.logger, display_app.monitorPin, display_app.pi4j); - DisplayTemp display = new DisplayTemp(display_app.pi4j, display_app.console, matrix, display_app.logger); - ControlLeds pin_monitor = new ControlLeds(display_app.pi4j, display_app.console,display_app.warnGPIO, display_app.processGPIO, matrix, display_app.logger); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + Thread.sleep(2000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - int c = 0; + int c = 0; - // if leg displays temperature/time count times then exists. - if (display_app.repeat_count > 0) { - for (int i = 0; i < display_app.repeat_count; i++) { - // future // eChip = cfgU.enableChipPath(mainChip); - // cfgU.displayEnableReg(bus_num, mainChip); - // cfgU.runCli(); + // if leg displays temperature/time count times then exists. + if (display_app.repeat_count > 0) { + for (int i = 0; i < display_app.repeat_count; i++) { + // future // eChip = cfgU.enableChipPath(mainChip); + // cfgU.displayEnableReg(bus_num, mainChip); + // cfgU.runCli(); /* display.process_bmp_data(pin_monitor, display_app.led_blink, display_app.loop_count, display_app.bmp_bus, display_app.bmp_address); @@ -399,22 +394,22 @@ public static void main(String[] args) throws IOException, InterruptedException } */ - // future //eChip = cfgU.enableChipPath(mainChip); - display.show_time(pin_monitor, display_app.led_blink, - display_app.loop_count); - // clear the matrix - for (c = 0; c < 8; c++) { - matrix.fill(0, (byte) 0, 0); - } - } - matrix.blink_write(0); + // future //eChip = cfgU.enableChipPath(mainChip); + display.show_time(pin_monitor, display_app.led_blink, + display_app.loop_count); // clear the matrix for (c = 0; c < 8; c++) { matrix.fill(0, (byte) 0, 0); } - } else { // else leg continuously displays temperature/time - while (true) { - // future // eChip = cfgU.enableChipPath(mainChip); + } + matrix.blink_write(0); + // clear the matrix + for (c = 0; c < 8; c++) { + matrix.fill(0, (byte) 0, 0); + } + } else { // else leg continuously displays temperature/time + while (true) { + // future // eChip = cfgU.enableChipPath(mainChip); /* display.process_bmp_data(pin_monitor, display_app.led_blink, display_app.loop_count, display_app.bmp_bus, display_app.bmp_address); Thread.sleep(2000); @@ -422,27 +417,27 @@ public static void main(String[] args) throws IOException, InterruptedException for (c = 0; c < 8; c++) { matrix.fill(0, (byte) 0, 0); }*/ - // future //eChip = cfgU.enableChipPath(mainChip); - display.show_time(pin_monitor, display_app.led_blink, - display_app.loop_count); - Thread.sleep(2000); - // clear the matrix - for (c = 0; c < 8; c++) { - matrix.fill(0, (byte) 0, 0); - } + // future //eChip = cfgU.enableChipPath(mainChip); + display.show_time(pin_monitor, display_app.led_blink, + display_app.loop_count); + Thread.sleep(2000); + // clear the matrix + for (c = 0; c < 8; c++) { + matrix.fill(0, (byte) 0, 0); } - /* - * display.blink(0); // THE FOLLOWING NEEDS A CTL-C HANDLER for - * (int i; i < 7; i++) { display.fill(1, false, 0); } - */ } - } catch (Exception e) { - e.printStackTrace(System.out); + /* + * display.blink(0); // THE FOLLOWING NEEDS A CTL-C HANDLER for + * (int i; i < 7; i++) { display.fill(1, false, 0); } + */ } - display_app.logger.info("program ending normal"); - display_app.clearGpioCfg(); - System.exit(0); - + } catch (Exception e) { + e.printStackTrace(System.out); } + display_app.logger.info("program ending normal"); + display_app.clearGpioCfg(); + System.exit(0); } + +} diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/MonitorInterrupt.java b/src/main/java/com/pi4j/devices/is31Fl37Matrix/MonitorInterrupt.java index 0e47b94..960780e 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/MonitorInterrupt.java +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/MonitorInterrupt.java @@ -1,7 +1,6 @@ package com.pi4j.devices.is31Fl37Matrix; - import com.pi4j.Pi4J; import com.pi4j.io.gpio.digital.*; import com.pi4j.util.Console; @@ -15,19 +14,18 @@ * This is coded specifically to the manner in which the IS31FL3731 chip * toggles the INTB pin. Used in debugging the Pi OS missing short * duration level changes on a GPIO - * It Is NOT a generic monitor program. - * + * It Is NOT a generic monitor program. + *

    * Sole purpose is unit testing. Pi4 with Pi OS 64bit * missing short duration interrupt. This program allows * measuring the interrupt duration. - * is31Fl37Matrix.MonitorInterrupt -p 25 -d DOWN + * is31Fl37Matrix.MonitorInterrupt -p 25 -d DOWN */ public class MonitorInterrupt { /** *

    Constructor for MonitorInterrupt.

    - * */ public MonitorInterrupt() { } @@ -78,13 +76,13 @@ public static void main(String[] args) throws Exception { if (pullDirection.contentEquals("UP")) { i++; pd = PullResistance.PULL_UP; - }else if (pullDirection.contentEquals("DOWN")) { + } else if (pullDirection.contentEquals("DOWN")) { i++; pd = PullResistance.PULL_UP; - }else if (pullDirection.contentEquals("OFF")) { + } else if (pullDirection.contentEquals("OFF")) { i++; pd = PullResistance.PULL_UP; - } else{ + } else { console.println("INVALID Parms -p pin to monitor interrupt, -d direction of pull "); } } @@ -100,15 +98,14 @@ public static void main(String[] args) throws Exception { // create a digital input instance using the default digital input provider // we will use the PULL_DOWN argument to set the pin pull-down resistance on this GPIO pin var config = DigitalInput.newConfigBuilder(pi4j) - .load(properties) - .provider("gpiod-digital-input") // linuxfs pigpio - .build(); + .load(properties) + .provider("gpiod-digital-input") // linuxfs pigpio + .build(); monitorPin = pi4j.create(config); monitorPin.addListener(new MatrixGpioListener()); - // lets read the digital output state console.print("DIGITAL INPUT ["); console.print(monitorPin); @@ -123,7 +120,7 @@ public static void main(String[] args) throws Exception { console.println(); console.println("CHANGE INPUT STATES VIA I/O HARDWARE AND CHANGE EVENTS WILL BE PRINTED BELOW:"); - for(int c = 0; c < countLoops; c++){ + for (int c = 0; c < countLoops; c++) { Thread.sleep(500); console.println(monitorPin.state() + "state"); } @@ -139,7 +136,8 @@ public static class MatrixGpioListener implements DigitalStateChangeListener { Instant startInstant; Instant endInstant; - public MatrixGpioListener() { + + public MatrixGpioListener() { /* Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("MatrixGpioListener: Performing ctl-C shutdown"); @@ -160,7 +158,7 @@ public void onDigitalStateChange(DigitalStateChangeEvent event) { start = System.currentTimeMillis(); startInstant = Instant.now(); System.out.println("onDigitalStateChange Pin went low"); - }else if (event.state() == DigitalState.HIGH) { + } else if (event.state() == DigitalState.HIGH) { end = System.currentTimeMillis(); Instant endInstant = Instant.now(); System.out.println("onDigitalStateChange Pin went high"); @@ -171,7 +169,7 @@ public void onDigitalStateChange(DigitalStateChangeEvent event) { } Duration timeElapsed = Duration.between(startInstant, endInstant); System.out.println("timeElapsed time MS " + timeElapsed.toMillis()); - }else{ + } else { System.out.println("Strange event state " + event.state()); } } diff --git a/src/main/java/com/pi4j/devices/is31Fl37Matrix/README.md b/src/main/java/com/pi4j/devices/is31Fl37Matrix/README.md index 0696ad5..d2f8039 100644 --- a/src/main/java/com/pi4j/devices/is31Fl37Matrix/README.md +++ b/src/main/java/com/pi4j/devices/is31Fl37Matrix/README.md @@ -1,60 +1,62 @@ - -Implementation of the Is31fl3731 matrix controller. +Implementation of the Is31fl3731 matrix controller. Uses a BMP280 and system time to alternately display the temperature and time. The program has the tables to translate numbers to matrix commands, it does not translate alphabetic characters. - - - 1. ./mvnw clean package - 2. cd target/distribution - 3. Execute command to perform desired Matrix operation - +1. ./mvnw clean package +2. cd target/distribution +3. Execute command to perform desired Matrix operation sudo ./runIs31fl37Matrix.sh -b 0x01 -a 0x74 -bmpB 0x01 -bmpA 0x76 -g 24 -w 20 -i 128 -c 1 -l 1 -r 16 -z 12 -t info - -sudo java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31fl37_matrix_app -b 0x1 -a 0x74 " + -" -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + -"-i intensity<128> -c -l -s log -r resetGpio -z monitorGpio# " + -"-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\" - +sudo java --module-path . --module com.pi4j.devices.multi/com.pi4j.devices.is31fl37Matrix.Is31fl37_matrix_app -b 0x1 -a +0x74 " + +" -bmpB 0x1 -bmpA 0x76 BMP280 address -g GPIO processing LED -w GPIO warning LED " + +"-i intensity<128> -c -l -s log -r resetGpio -z monitorGpio# " + +"-t values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\" GPIO pin -x -g -----------> processing indicator LED - -x -w ------------> warning indicator LED - - -x -r -------------------------------------------> Is31fl3731 SD - -- - -x -z <------------------------------------------- Is31fl3731 INTB +x -g -----------> processing indicator LED -x I2C -b bus -a address ----------------------- Is31fl3731 +x -w ------------> warning indicator LED +x -r -------------------------------------------> Is31fl3731 SD +-- -x I2C -bmpB bus -bmpA address ------------------ BMP280 +x -z <------------------------------------------- Is31fl3731 INTB +x I2C -b bus -a address ----------------------- Is31fl3731 +x I2C -bmpB bus -bmpA address ------------------ BMP280 Debug utilities -The following was used in debugging missed interrupts from the INTB line. Result +The following was used in debugging missed interrupts from the INTB line. Result was learning the V2 default debounce time is 10 ms, too great a value for this chips documented 7 ms interrupt duration. Java Monitor input GPIO pin 18 configured as an active low interrupt. com.pi4j.devices.multi/com.pi4j.devices.is31Fl37Matrix.MonitorInterrupt -p 18 -d DOWN -sudo /usr/lib/jvm/java-1.11.0-openjdk-arm64/bin/java -javaagent:/home/pi/Tools/Intellij/idea-IC-222.4167.29/lib/idea_rt.jar=43151:/home/pi/Tools/Intellij/idea-IC-222.4167.29/bin -Dfile.encoding=UTF-8 -classpath /home/pi/.m2/repository/org/jetbrains/annotations/23.0.0/annotations-23.0.0.jar -p /home/pi/.m2/repository/org/slf4j/slf4j-simple/2.0.3/slf4j-simple-2.0.3.jar:/home/pi/.m2/repository/com/jcraft/jsch/0.1.55/jsch-0.1.55.jar:/home/pi/Pi4J_V2/Pi4J_V2_Devices/target/classes:/home/pi/.m2/repository/com/pi4j/pi4j-library-linuxfs/2.2.1-SNAPSHOT/pi4j-library-linuxfs-2.2.1-SNAPSHOT.jar:/home/pi/.m2/repository/com/pi4j/pi4j-library-pigpio/2.2.1-SNAPSHOT/pi4j-library-pigpio-2.2.1-SNAPSHOT.jar:/home/pi/.m2/repository/com/pi4j/pi4j-core/2.2.1-SNAPSHOT/pi4j-core-2.2.1-SNAPSHOT.jar:/home/pi/.m2/repository/org/slf4j/slf4j-api/2.0.3/slf4j-api-2.0.3.jar:/home/pi/.m2/repository/com/pi4j/pi4j-plugin-pigpio/2.2.1-SNAPSHOT/pi4j-plugin-pigpio-2.2.1-SNAPSHOT.jar:/home/pi/.m2/repository/com/pi4j/pi4j-plugin-linuxfs/2.2.1-SNAPSHOT/pi4j-plugin-linuxfs-2.2.1-SNAPSHOT.jar:/home/pi/.m2/repository/com/pi4j/pi4j-plugin-raspberrypi/2.2.1-SNAPSHOT/pi4j-plugin-raspberrypi-2.2.1-SNAPSHOT.jar -m com.pi4j.devices/com.pi4j.devices.is31Fl37Matrix.MonitorInterrupt -p 25 -d DOWN - -sudo /usr/lib/jvm/java-1.11.0-openjdk-arm64/bin/java -cp .:/home/pi/Pi4J_V2/Pi4J_V2_Devices/target/distribution com.pi4j.devices.is31Fl37Matrix.MonitorInterrupt -p 25 -d DOWN - - - -Java Create output GPIO pin 18. Create interrupt by driving line low for 15 millisecond duration +sudo /usr/lib/jvm/java-1.11.0-openjdk-arm64/bin/java -javaagent: +/home/pi/Tools/Intellij/idea-IC-222.4167.29/lib/idea_rt.jar=43151:/home/pi/Tools/Intellij/idea-IC-222.4167.29/bin +-Dfile.encoding=UTF-8 -classpath /home/pi/.m2/repository/org/jetbrains/annotations/23.0.0/annotations-23.0.0.jar -p +/home/pi/.m2/repository/org/slf4j/slf4j-simple/2.0.3/slf4j-simple-2.0.3.jar: +/home/pi/.m2/repository/com/jcraft/jsch/0.1.55/jsch-0.1.55.jar:/home/pi/Pi4J_V2/Pi4J_V2_Devices/target/classes: +/home/pi/.m2/repository/com/pi4j/pi4j-library-linuxfs/2.2.1-SNAPSHOT/pi4j-library-linuxfs-2.2.1-SNAPSHOT.jar: +/home/pi/.m2/repository/com/pi4j/pi4j-library-pigpio/2.2.1-SNAPSHOT/pi4j-library-pigpio-2.2.1-SNAPSHOT.jar: +/home/pi/.m2/repository/com/pi4j/pi4j-core/2.2.1-SNAPSHOT/pi4j-core-2.2.1-SNAPSHOT.jar: +/home/pi/.m2/repository/org/slf4j/slf4j-api/2.0.3/slf4j-api-2.0.3.jar: +/home/pi/.m2/repository/com/pi4j/pi4j-plugin-pigpio/2.2.1-SNAPSHOT/pi4j-plugin-pigpio-2.2.1-SNAPSHOT.jar: +/home/pi/.m2/repository/com/pi4j/pi4j-plugin-linuxfs/2.2.1-SNAPSHOT/pi4j-plugin-linuxfs-2.2.1-SNAPSHOT.jar: +/home/pi/.m2/repository/com/pi4j/pi4j-plugin-raspberrypi/2.2.1-SNAPSHOT/pi4j-plugin-raspberrypi-2.2.1-SNAPSHOT.jar -m +com.pi4j.devices/com.pi4j.devices.is31Fl37Matrix.MonitorInterrupt -p 25 -d DOWN + +sudo /usr/lib/jvm/java-1.11.0-openjdk-arm64/bin/java -cp .:/home/pi/Pi4J_V2/Pi4J_V2_Devices/target/distribution +com.pi4j.devices.is31Fl37Matrix.MonitorInterrupt -p 25 -d DOWN + +Java Create output GPIO pin 18. Create interrupt by driving line low for 15 millisecond duration com.pi4j.devices.multi/com.pi4j.devices.is31Fl37Matrix.CreateInterrupt -p 18 -d LOW -m 15 Python3 to create interrupt of specific interval @@ -65,15 +67,9 @@ python3 ./monitorGpio.py -p 25 python3 monitorGpio2.py -p 25 +The python3 program monitorGpio2.py uses the GPIO.add_event_detect function callback to more closely +operate same as the java monitor program's event callback - -The python3 program monitorGpio2.py uses the GPIO.add_event_detect function callback to more closely -operate same as the java monitor program's event callback - - - - - -Special regression test. Only displaus time. Bogus but valid address passed on for -bmpA +Special regression test. Only displaus time. Bogus but valid address passed on for -bmpA sudo ./runIs31fl37MatrixTest.sh -b 0x01 -a 0x74 -bmpB 0x01 -bmpA 0x74 -g 24 -w 20 -i 128 -c 1 -l 1 -r 18 -z 25 -t info diff --git a/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A.java b/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A.java index 4501400..84a0bd7 100644 --- a/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A.java +++ b/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A.java @@ -38,7 +38,6 @@ import com.pi4j.context.Context; - import com.pi4j.util.Console; import org.slf4j.Logger; @@ -89,15 +88,14 @@ public void clearDisplay() { } /** - * - * @param str What to display - * @param line line of display, 1,2... - * @param offset offset within the line + * @param str What to display + * @param line line of display, 1,2... + * @param offset offset within the line */ - public void sendStringLineX(String str, int line,int offset) { + public void sendStringLineX(String str, int line, int offset) { this.logger.trace(">>> Enter: sendStringLineOne : " + str + " line : " + line + " Offset : " + offset); char[] chars = str.toCharArray(); - this.sendCommand(LCD1602A_Declares.setDDRAMCMD | ( 0x40 *(line-1)) | offset); + this.sendCommand(LCD1602A_Declares.setDDRAMCMD | (0x40 * (line - 1)) | offset); for (int i = 0; i < chars.length; i++) { this.sendChar(chars[i]); } @@ -105,13 +103,12 @@ public void sendStringLineX(String str, int line,int offset) { } - protected boolean lcdAvailable() { int c = 0; this.logger.trace(">>> Enter: lcdAvailable "); this.sleepTimeMilliS(10); boolean rval = this.isBfLow(); - while (rval == false) { + while (!rval) { this.logger.info("\n\n\n !!!!! BF was busy \n\n"); this.sleepTimeMilliS(400); c++; @@ -133,7 +130,7 @@ protected void sleepTimeNanoS(int nanoSec) { } catch (InterruptedException e) { throw new RuntimeException(e); } - + } @@ -167,6 +164,7 @@ protected void sendChar(byte c) { this.logger.trace(">>> Enter: sendChar : " + c); this.logger.trace("<<< Exit: sendChar "); } + // do required gpio->LCD_input dance before and after actual LCD pin update protected void sendCommand(int cmd) { this.logger.trace(">>> Enter: sendCommand "); @@ -183,10 +181,10 @@ protected void sendCommand(int cmd) { * * @return bit value of DB7 */ - protected boolean isBfLow(){ + protected boolean isBfLow() { this.logger.trace(">>> Enter: isBfLow "); this.logger.trace("<<< Exit: isBfLow "); - return(true); + return (true); } diff --git a/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A_Declares.java b/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A_Declares.java index bb2fb80..88225e1 100644 --- a/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A_Declares.java +++ b/src/main/java/com/pi4j/devices/lcd1602a/LCD1602A_Declares.java @@ -37,70 +37,70 @@ package com.pi4j.devices.lcd1602a; public class LCD1602A_Declares { - public static final int clearDispCMD = 0b0000000001; + public static final int clearDispCMD = 0b0000000001; - public static final int returnHomeCMD = 0b0000000010; + public static final int returnHomeCMD = 0b0000000010; - public static final int entryModeCMD = 0b0000000100; - public static final int entryModeIncCMD = 0b0000000010; - public static final int entryModeNoIncCMD = 0b0000000000; - public static final int entryModeShiftCMD = 0b0000000001; + public static final int entryModeCMD = 0b0000000100; + public static final int entryModeIncCMD = 0b0000000010; + public static final int entryModeNoIncCMD = 0b0000000000; + public static final int entryModeShiftCMD = 0b0000000001; - public static final int dispCMD = 0b0000001000; - public static final int dispOnBit = 0b0000000100; - public static final int dispOffBit = 0b0000000000; - public static final int dispOnCMD = 0b0000000000; - public static final int dispCrsOnBit = 0b0000000010; - public static final int dispCrsOffBit = 0b0000000000; - public static final int dispBlnkOnBit = 0b0000000001; - public static final int dispBlnkOffBit = 0b0000000000; + public static final int dispCMD = 0b0000001000; + public static final int dispOnBit = 0b0000000100; + public static final int dispOffBit = 0b0000000000; + public static final int dispOnCMD = 0b0000000000; + public static final int dispCrsOnBit = 0b0000000010; + public static final int dispCrsOffBit = 0b0000000000; + public static final int dispBlnkOnBit = 0b0000000001; + public static final int dispBlnkOffBit = 0b0000000000; // sr // cl - public static final int cursorCMD = 0b0000010000; - public static final int cusorLeftBit = 0b0000000000; - public static final int cusorRghtBit = 0b0000000100; - public static final int displayLeftBit = 0b0000001000; - public static final int displayRightBit = 0b0000001100; - - public static final int funcSetCMD = 0b0000100000; - public static final int func4BitsBit = 0b0000000000; - public static final int func8BitsBit = 0b0000010000; - public static final int func5x8OneBit = 0b0000000000; - public static final int func5x10OneBit = 0b0000000100; - public static final int func5x8TwoBit = 0b0000001000; + public static final int cursorCMD = 0b0000010000; + public static final int cusorLeftBit = 0b0000000000; + public static final int cusorRghtBit = 0b0000000100; + public static final int displayLeftBit = 0b0000001000; + public static final int displayRightBit = 0b0000001100; + + public static final int funcSetCMD = 0b0000100000; + public static final int func4BitsBit = 0b0000000000; + public static final int func8BitsBit = 0b0000010000; + public static final int func5x8OneBit = 0b0000000000; + public static final int func5x10OneBit = 0b0000000100; + public static final int func5x8TwoBit = 0b0000001000; // Not normally used aaaaaa - public static final int setCGRAMCMD = 0b0001000000; + public static final int setCGRAMCMD = 0b0001000000; // aaaaaaa - public static final int setDDRAMCMD = 0b0010000000; + public static final int setDDRAMCMD = 0b0010000000; - public static final int readBsfFlagCMD = 0b0100000000; + public static final int readBsfFlagCMD = 0b0100000000; // nano seconds // write operations - public static final int preWrtEnableCycleDelay = 500; // 400 - public static final int enableWrtCycleDuration = 200; // 150 - public static final int postWrtEnableCycleDelay = 500; // 400 + public static final int preWrtEnableCycleDelay = 500; // 400 + public static final int enableWrtCycleDuration = 200; // 150 + public static final int postWrtEnableCycleDelay = 500; // 400 - public static final int addressWrtSetupDuration = 50; // 30 - public static final int postAddressWrtSetupDelay = 90; // 60 + public static final int addressWrtSetupDuration = 50; // 30 + public static final int postAddressWrtSetupDelay = 90; // 60 - public static final int dataWrtSetupDuration = 90; // 60 - public static final int postDataWrtDelay = 60; // 10 + public static final int dataWrtSetupDuration = 90; // 60 + public static final int postDataWrtDelay = 60; // 10 // Read operations - public static final int preRdEnableCycleDelay = 500; // 400 - public static final int enableRdCycleDuration = 200; // 150 - public static final int postResetEnableCycleDelay = 100; - public static final int addressRdSetupDuration = 50; // 30 - public static final int preAddressWrtSetupDelay = 20; // 10 - - public static final int dataRdSetupDuration = 240; // 100 - public static final int postDataRdDelay = 10; // 5 + public static final int preRdEnableCycleDelay = 500; // 400 + public static final int enableRdCycleDuration = 200; // 150 + public static final int postResetEnableCycleDelay = 100; + public static final int addressRdSetupDuration = 50; // 30 + public static final int preAddressWrtSetupDelay = 20; // 10 + + public static final int dataRdSetupDuration = 240; // 100 + public static final int postDataRdDelay = 10; // 5 public static int enableWidthDuration = 450; } diff --git a/src/main/java/com/pi4j/devices/mcp23008/Mcp23008.java b/src/main/java/com/pi4j/devices/mcp23008/Mcp23008.java index 15d4ec3..99a3014 100644 --- a/src/main/java/com/pi4j/devices/mcp23008/Mcp23008.java +++ b/src/main/java/com/pi4j/devices/mcp23008/Mcp23008.java @@ -35,26 +35,14 @@ package com.pi4j.devices.mcp23008; import com.pi4j.context.Context; -import com.pi4j.devices.appConfig.AppConfigUtilities; import com.pi4j.devices.base_util.ffdc.FfdcUtil; -import com.pi4j.devices.base_util.gpio.BaseGpioInOut; -import com.pi4j.devices.base_util.mapUtil.MapUtil; +import com.pi4j.devices.base_util.gpio.GpioPinCfgData; import com.pi4j.devices.mcp23xxxApplication.Mcp23xxxParms; -import com.pi4j.devices.mcp23xxxCommon.Mcp23xxxUtil; import com.pi4j.devices.mcp23xxxCommon.McpBase; - -import com.pi4j.devices.base_util.gpio.GpioPinCfgData; -import com.pi4j.Pi4J; +import com.pi4j.util.Console; import java.util.HashMap; -import com.pi4j.devices.mcp23xxxCommon.McpConfigData; -import com.pi4j.exception.LifecycleException; -import com.pi4j.io.exception.IOException; -import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; - /** * Mcp23008 subclass of McpBase, used with chip MCP23008 */ @@ -63,31 +51,30 @@ public class Mcp23008 extends McpBase { /** * CTOR - * @param pi4j Context - * @param parms Contains all parms supplied by the program called - * @param ffdc logging - * @param dioPinData Pi Gpio config devices - * @param console Console + * + * @param pi4j Context + * @param parms Contains all parms supplied by the program called + * @param ffdc logging + * @param dioPinData Pi Gpio config devices + * @param console Console */ - public Mcp23008(Context pi4j,Mcp23xxxParms parms, FfdcUtil ffdc, HashMap dioPinData, Console console) { - super(parms,false, dioPinData, pi4j, ffdc, console); + public Mcp23008(Context pi4j, Mcp23xxxParms parms, FfdcUtil ffdc, HashMap dioPinData, Console console) { + super(parms, false, dioPinData, pi4j, ffdc, console); } /** - * - * @return Array of register addresses, offset defined by McpConfigData + * @return Array of register addresses, offset defined by McpConfigData *

    - * Overridden by each subclass to return the proper register offsets + * Overridden by each subclass to return the proper register offsets *

    */ public byte[] getAddrMapFirst8() { this.ffdc.ffdcMethodEntry("23008 getAddrMapFirst8"); - byte regAddr[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A }; + byte[] regAddr = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A}; this.ffdc.ffdcMethodExit("23008 getAddrMapFirst8"); return (regAddr); } - } diff --git a/src/main/java/com/pi4j/devices/mcp23008/Mcp23008App.java b/src/main/java/com/pi4j/devices/mcp23008/Mcp23008App.java index 63287e7..a1669c9 100644 --- a/src/main/java/com/pi4j/devices/mcp23008/Mcp23008App.java +++ b/src/main/java/com/pi4j/devices/mcp23008/Mcp23008App.java @@ -44,14 +44,11 @@ import com.pi4j.devices.mcp23xxxApplication.Mcp23xxxParms; import com.pi4j.devices.mcp23xxxCommon.Mcp23xxxUtil; import com.pi4j.devices.mcp23xxxCommon.McpConfigData; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; import java.util.HashMap; -public class Mcp23008App extends Mcp23008{ +public class Mcp23008App extends Mcp23008 { /** @@ -69,27 +66,28 @@ public Mcp23008App(Context pi4j, Mcp23xxxParms parms, FfdcUtil ffdc, HashMap - * Invoke various methods on MCP23008 instance + * Invoke various methods on MCP23008 instance *

    - * @param args user params + * + * @param args user params * @throws Exception */ public static void main(String[] args) throws Exception { var console = new Console(); - Context pi4j = Pi4J.newAutoContext(); + Context pi4j = Pi4J.newAutoContext(); console.title("<-- The Pi4J V2 Project Extension -->", "Mcp23008App"); HashMap dioPinData = new HashMap(); - Mcp23xxxParms parmsObj = Mcp23xxxUtil.processMain(pi4j,args,false, dioPinData, console); + Mcp23xxxParms parmsObj = Mcp23xxxUtil.processMain(pi4j, args, false, dioPinData, console); - FfdcUtil ffdc = new FfdcUtil(console, pi4j, parmsObj.ffdcControlLevel , Mcp23008.class); + FfdcUtil ffdc = new FfdcUtil(console, pi4j, parmsObj.ffdcControlLevel, Mcp23008.class); ffdc.ffdcDebugEntry("mcp23008App : Arg processing completed...\n"); - Mcp23008App mcpObj = new Mcp23008App(parmsObj.pi4j, parmsObj, ffdc, dioPinData, console); + Mcp23008App mcpObj = new Mcp23008App(parmsObj.pi4j, parmsObj, ffdc, dioPinData, console); BaseGpioInOut gpio = new BaseGpioInOut(parmsObj.pi4j, mcpObj.ffdc, mcpObj.dioPinData); mcpObj.gpio = gpio; @@ -100,25 +98,10 @@ public static void main(String[] args) throws Exception { mcpObj.mapUtils = new MapUtil(mcpObj.ffdc, mcpObj.gpio); - mcpObj.cfgData = new McpConfigData(ffdc); - Mcp23xxxUtil mcpUtil = new Mcp23xxxUtil(parmsObj.pi4j, ffdc, parmsObj.busNum, parmsObj.address, mcpObj.cfgData, mcpObj, console); - - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - ffdc.ffdcFlushShutdown(); // push all logs to the file - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); + Mcp23xxxUtil mcpUtil = new Mcp23xxxUtil(parmsObj.pi4j, ffdc, parmsObj.busNum, parmsObj.address, mcpObj.cfgData, mcpObj, console); + if (parmsObj.hasFullKeyedData) { // -g HashMap> outerMap = mcpObj.mapUtils.createFullMap(parmsObj.fullKeyedData); @@ -148,7 +131,7 @@ public void handle(Signal sig) { console.print("Chip register configurations completed"); - mcpObj.reinit("Mcp23008", "Mcp23008",parmsObj.busNum, parmsObj.address); + mcpObj.reinit("Mcp23008", "Mcp23008", parmsObj.busNum, parmsObj.address); if (parmsObj.dumpRegs) { mcpObj.dumpRegs(); @@ -161,13 +144,11 @@ public void handle(Signal sig) { } - if (parmsObj.readPin) { mcpObj.readInput(parmsObj.pin); } - mcpObj.ffdc.ffdcDebugEntry("program ending normal"); // ffdc.ffdcFlushShutdown(); // push all logs to the file diff --git a/src/main/java/com/pi4j/devices/mcp23008/README.md b/src/main/java/com/pi4j/devices/mcp23008/README.md index 598570e..d50032e 100644 --- a/src/main/java/com/pi4j/devices/mcp23008/README.md +++ b/src/main/java/com/pi4j/devices/mcp23008/README.md @@ -1,7 +1,7 @@ Pi4J :: Java I/O Library for Raspberry Pi :: Device :: Mcp23008 ========================================================================== -### This repository is a first device specific support project for the MCP23008 +### This repository is a first device specific support project for the MCP23008 ### This is an example implementation and will need to be adjusted to fit your needs. @@ -10,21 +10,20 @@ Project by Tom Aarts ========================================================================== https://ww1.microchip.com/downloads/en/DeviceDoc/21919e.pdf -MCP23008/MCP23S08 8-Bit I/O Expander with Serial Interface - - -Java classes to access the MCP23008 GPIO controller as an application. +MCP23008/MCP23S08 8-Bit I/O Expander with Serial Interface +Java classes to access the MCP23008 GPIO controller as an application. Supported functions. - 1. reset chip - 2. Configure any/all pins (all configurations options) - 3. Supports logging facilities implemented by log4_v2 - - Example does not use the MCp23008 interrupt capability. - To view/use code that confogures and uses the chip interrupt, - see-- com/pi4j/devices/mcp23xxxApplication/Mcp23008PinMonitor - + +1. reset chip +2. Configure any/all pins (all configurations options) +3. Supports logging facilities implemented by log4_v2 + + Example does not use the MCp23008 interrupt capability. + To view/use code that confogures and uses the chip interrupt, + see-- com/pi4j/devices/mcp23xxxApplication/Mcp23008PinMonitor + The classes are implemented using the Pi4j_V2 requirements of September 1 2020. The project uses one addition pom requirement of log4j version 2. The project @@ -37,102 +36,94 @@ listed in the parent pom file, therefore mvn (maven) commands in the parent path will not read this pom file. Program options - -q 9548#1 -r 3 -p pin0 -c 23008#1 -z 'pi GPIOs' -m 'MCP23xxx pin configuration' --q first chip in the i2c circuit. In the example this is a TCA9548 mux, If the 23008 chip was the +-q 9548#1 -r 3 -p pin0 -c 23008#1 -z 'pi GPIOs' -m 'MCP23xxx pin configuration' +-q first chip in the i2c circuit. In the example this is a TCA9548 mux, If the 23008 chip was the directly on the Pi bus, the the value would be -q 23008#1 -r read this MCP23xxx pin --d drive this MCP23xxx pin based on -o ON or OFF +-d drive this MCP23xxx pin based on -o ON or OFF -z Pi gpio configuration -m MCP23xxx pin configuration - 1. ./mvnw clean package 2. cd target/distribution 3. Execute command to set configuration data (will not be used by example) 4. Execute command to reset Mcp23008 5. Execute command to perform desired MCP23008 operation - - ependent upon the -f parameter value logging details will be stored in /tmp/logs/com.pi4j.devices.mcp23008.Mcp23008.log - - - - - - BCM gpio16 configured as output connected MCP23008 pin 4 pdip14 - - BCM gpio13 configured as output connected MCP23008 (bar) RESET pdip6 - - BCM gpio27 configured as input connected MCP23008 INT pdip8 - - BCM gpio22 configured as output connected to LED - - - Red LED (+) connected to pin0 pdip10 - Green LED (+) connected to pin1 pdip11 - Yellow LED (+) connected to pin2 pdip12 - - -MCP23008 on Pi BCM 1 address 0x20 +BCM gpio16 configured as output connected MCP23008 pin 4 pdip14 + +BCM gpio13 configured as output connected MCP23008 (bar) RESET pdip6 + +BCM gpio27 configured as input connected MCP23008 INT pdip8 + +BCM gpio22 configured as output connected to LED + +Red LED (+) connected to pin0 pdip10 +Green LED (+) connected to pin1 pdip11 +Yellow LED (+) connected to pin2 pdip12 + +MCP23008 on Pi BCM 1 address 0x20 All address pins (A0 A1 A2) are strapped to ground for the chips default address 0x20 _______________________ -- Pi BCM I2C bus 1 - ______________ -_______________________ | - | | | | - | | | | - | | | | - | | | | - | | | ____________________ - | | |__________> RESET > - MCP23008 0x20 - - | | ____________________ - | |________________ < INT < | | | | - | | LEDs - |_____________________> Drive GPIO >___| - +- Pi BCM I2C bus 1 - ______________ + _______________________ | + | | | | + | | | | + | | | | + | | | | + | | | ____________________ + | | |__________> RESET > - MCP23008 0x20 - + | | ____________________ + | |________________ < INT < | | | | + | | LEDs + |_____________________> Drive GPIO >___| NOTE !!!!! Using the $@ in the module call alows variable number of arguments. But, agruments wrapped by " " cannot contain spaces. So as you can see the -m and -z values wrapped by " " contain no spaces.. - - - - 1. Set pin and chip configuration -property files - sudo ./runAppPropertySet.sh - sudo ./runAppPropertyRead.sh + property files + sudo ./runAppPropertySet.sh + sudo ./runAppPropertyRead.sh + +2. Reset MCP23008 + sudo ./runMcp23008.sh -b 0x1 -a 0x20 -r 3 -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':'up'}},{' + gpio13':{'name':'ResetChip','dir':'out','int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out',' + int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in',' + pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':'out','int_ena':'no'}},{' + pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x + 13 -f 1 -2. Reset MCP23008 - sudo ./runMcp23008.sh -b 0x1 -a 0x20 -r 3 -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':'up'}},{'gpio13':{'name':'ResetChip','dir':'out','int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 13 -f 1 - - -3. Configure pins of MCP23008, do reset first - - All pins - sudo ./runMcp23008.sh -b 0x1 -a 0x20 -r 3 -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':'up'}},{'gpio13':{'name':'ResetChip','dir':'out','int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 13 -f 1 +3. Configure pins of MCP23008, do reset first +All pins +sudo ./runMcp23008.sh -b 0x1 -a 0x20 -r 3 -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':'up'}},{'gpio13': +{'name':'ResetChip','dir':'out','int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{' +pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in','pull':'up','default':' +1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out',' +int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 13 -f 1 4. Drive MCP23008 pin0 Red Led hi low - sudo ./runMcp23008.sh -b 0x1 -a 0x20 -d 0 -o ON -m "{{'pin0':{'dir':'out','int_ena':'no'}}}" -f 1 - sudo ./runMcp23008.sh -b 0x1 -a 0x20 -d 0 -o OFF -f 1 + sudo ./runMcp23008.sh -b 0x1 -a 0x20 -d 0 -o ON -m "{{'pin0':{'dir':'out','int_ena':'no'}}}" -f 1 + sudo ./runMcp23008.sh -b 0x1 -a 0x20 -d 0 -o OFF -f 1 5. Read MCP23008 pin4 - Read 4 - sudo ./runMcp23008.sh -b 0x1 -a 0x20 -r 4 -m "{{'pin4':{'dir':'in','pull':'down'}}}" -f 1 - This will set pin4 high or low -python3 -import RPi.GPIO as GPIO -GPIO.setmode(GPIO.BCM) -GPIO.setup(16, GPIO.OUT) -GPIO.output(16,GPIO.LOW) -GPIO.output( 16 , GPIO.HIGH) + Read 4 + sudo ./runMcp23008.sh -b 0x1 -a 0x20 -r 4 -m "{{'pin4':{'dir':'in','pull':'down'}}}" -f 1 + This will set pin4 high or low + python3 + import RPi.GPIO as GPIO + GPIO.setmode(GPIO.BCM) + GPIO.setup(16, GPIO.OUT) + GPIO.output(16,GPIO.LOW) + GPIO.output( 16 , GPIO.HIGH) diff --git a/src/main/java/com/pi4j/devices/mcp23017/Mcp23017.java b/src/main/java/com/pi4j/devices/mcp23017/Mcp23017.java index f452477..97fcdf3 100644 --- a/src/main/java/com/pi4j/devices/mcp23017/Mcp23017.java +++ b/src/main/java/com/pi4j/devices/mcp23017/Mcp23017.java @@ -34,22 +34,12 @@ package com.pi4j.devices.mcp23017; -import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.devices.appConfig.AppConfigUtilities; import com.pi4j.devices.base_util.ffdc.FfdcUtil; -import com.pi4j.devices.base_util.gpio.BaseGpioInOut; import com.pi4j.devices.base_util.gpio.GpioPinCfgData; -import com.pi4j.devices.base_util.mapUtil.MapUtil; import com.pi4j.devices.mcp23xxxApplication.Mcp23xxxParms; -import com.pi4j.devices.mcp23xxxCommon.Mcp23xxxUtil; import com.pi4j.devices.mcp23xxxCommon.McpBase; -import com.pi4j.devices.mcp23xxxCommon.McpConfigData; -import com.pi4j.exception.LifecycleException; -import com.pi4j.io.exception.IOException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; import java.util.HashMap; @@ -57,46 +47,45 @@ * Mcp23008 subclass of McpBase, used with chip MCP23017 */ -public class Mcp23017 extends McpBase { +public class Mcp23017 extends McpBase { /** * CTOR - * @param pi4j Context - * @param parmsObj Contains all parms supplied by the program called - * @param ffdc logging - * @param dioPinData Pi Gpio config devices - * @param console Console + * + * @param pi4j Context + * @param parmsObj Contains all parms supplied by the program called + * @param ffdc logging + * @param dioPinData Pi Gpio config devices + * @param console Console */ - public Mcp23017(Context pi4j, Mcp23xxxParms parmsObj, FfdcUtil ffdc, HashMap dioPinData, Console console) { - super(parmsObj,true, dioPinData, pi4j, ffdc, console); + public Mcp23017(Context pi4j, Mcp23xxxParms parmsObj, FfdcUtil ffdc, HashMap dioPinData, Console console) { + super(parmsObj, true, dioPinData, pi4j, ffdc, console); } /** - * - * @return Array of register addresses, offset defined by McpConfigData + * @return Array of register addresses, offset defined by McpConfigData *

    - * Overridden by each subclass to return the proper register offsets + * Overridden by each subclass to return the proper register offsets *

    */ public byte[] getAddrMapFirst8() { this.ffdc.ffdcMethodEntry("23017 getAddrMapFirst8"); - byte regAddr[] = { 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x10, 0x12, 0x14 }; + byte[] regAddr = {0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x10, 0x12, 0x14}; this.ffdc.ffdcMethodExit("23017 getAddrMapFirst8"); return (regAddr); } /** - * - * @return Array of register addresses, offset defined by McpConfigData + * @return Array of register addresses, offset defined by McpConfigData *

    - * Overridden by each subclass to return the proper register offsets + * Overridden by each subclass to return the proper register offsets *

    */ public byte[] getAddrMapSecond8() { this.ffdc.ffdcMethodEntry("23017 getAddrMapSecond8"); - byte regAddr[] = { 0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F, 0x11, 0x13, 0x15 }; + byte[] regAddr = {0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F, 0x11, 0x13, 0x15}; this.ffdc.ffdcMethodExit("23017 getAddrMapSecond8"); return (regAddr); } diff --git a/src/main/java/com/pi4j/devices/mcp23017/Mcp23017App.java b/src/main/java/com/pi4j/devices/mcp23017/Mcp23017App.java index 42ff6ea..d3d9233 100644 --- a/src/main/java/com/pi4j/devices/mcp23017/Mcp23017App.java +++ b/src/main/java/com/pi4j/devices/mcp23017/Mcp23017App.java @@ -44,10 +44,7 @@ import com.pi4j.devices.mcp23xxxApplication.Mcp23xxxParms; import com.pi4j.devices.mcp23xxxCommon.Mcp23xxxUtil; import com.pi4j.devices.mcp23xxxCommon.McpConfigData; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; import java.util.HashMap; @@ -74,7 +71,6 @@ public Mcp23017App(Context pi4j, Mcp23xxxParms parmsObj, FfdcUtil ffdc, HashMap< *

    * * @param args user params - * * @throws Exception */ public static void main(String[] args) throws Exception { @@ -107,20 +103,6 @@ public static void main(String[] args) throws Exception { Mcp23xxxUtil mcpUtil = new Mcp23xxxUtil(parmsObj.pi4j, ffdc, parmsObj.busNum, parmsObj.address, mcpObj.cfgData, mcpObj, console); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - ffdc.ffdcFlushShutdown(); // push all logs to the file - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); if (parmsObj.hasFullKeyedData) { // -g HashMap> outerMap = mcpObj.mapUtils.createFullMap(parmsObj.fullKeyedData); diff --git a/src/main/java/com/pi4j/devices/mcp23017/README.md b/src/main/java/com/pi4j/devices/mcp23017/README.md index fb0c6f1..ba55776 100644 --- a/src/main/java/com/pi4j/devices/mcp23017/README.md +++ b/src/main/java/com/pi4j/devices/mcp23017/README.md @@ -1,7 +1,7 @@ Pi4J :: Java I/O Library for Raspberry Pi :: Device :: Mcp23017 ========================================================================== -### This repository is a first device specific support project for the MCP23017 +### This repository is a first device specific support project for the MCP23017 ### This is an example implementation and will need to be adjusted to fit your needs. @@ -13,20 +13,18 @@ https://ww1.microchip.com/downloads/en/devicedoc/20001952c.pdf MCP23017/MCP23S17 16-Bit I/O Expander with Serial Interface +Java classes to access the MCP23017 GPIO controller as an application. - -Java classes to access the MCP23017 GPIO controller as an application. +Supported functions. +1. reset chip +2. Configure any/all pins (all configurations options) +3. Supports logging facilities implemented by log4_v2 + + Example does not use the MCp23017 interrupt capability. + To view/use code that confogures and uses the chip interrupt, + see-- com/pi4j/devices/mcp23xxxApplication/Mcp23017PinMonitor -Supported functions. - 1. reset chip - 2. Configure any/all pins (all configurations options) - 3. Supports logging facilities implemented by log4_v2 - - Example does not use the MCp23017 interrupt capability. - To view/use code that confogures and uses the chip interrupt, - see-- com/pi4j/devices/mcp23xxxApplication/Mcp23017PinMonitor - The classes are implemented using the Pi4j_V2 requirements of September 1 2020. The project uses one addition pom requirement of log4j version 2. The project @@ -38,13 +36,12 @@ In the projects base directory execute the following. Note: this project is not listed in the parent pom file, therefore mvn (maven) commands in the parent path will not read this pom file. - Program options - -q 9548#1 -r 3 -p pin0 -c 23008#1 -z 'pi GPIOs' -m 'MCP23xxx pin configuration' --q first chip in the i2c circuit. In the example this is a TCA9548 mux, If the 23008 chip was the +-q 9548#1 -r 3 -p pin0 -c 23008#1 -z 'pi GPIOs' -m 'MCP23xxx pin configuration' +-q first chip in the i2c circuit. In the example this is a TCA9548 mux, If the 23008 chip was the directly on the Pi bus, the the value would be -q 23008#1 -r read this MCP23xxx pin --d drive this MCP23xxx pin based on -o ON or OFF +-d drive this MCP23xxx pin based on -o ON or OFF -z Pi gpio configuration -m MCP23xxx pin configuration @@ -53,105 +50,107 @@ directly on the Pi bus, the the value would be -q 23008#1 3. Execute command to set configuration data (will not be used by example) 4. Execute command to reset Mcp23017 5. Execute command to perform desired MCP23017 operation - - - ependent upon the -f parameter value logging details will be stored in /tmp/logs/com.pi4j.devices.mcp23017.Mcp23017.log - +BCM gpio12 configured as output connected MCP23017 pin 4 spdip25 + +BCM gpio18 configured as output connected MCP23017 pin 15 spdip8 + +BCM gpio5 configured as output connected MCP23017 (bar) RESET spdip18 - - BCM gpio12 configured as output connected MCP23017 pin 4 spdip25 - - BCM gpio18 configured as output connected MCP23017 pin 15 spdip8 +BCM gpio23 configured as input connected MCP23017 INTA spdip20 - BCM gpio5 configured as output connected MCP23017 (bar) RESET spdip18 - - BCM gpio23 configured as input connected MCP23017 INTA spdip20 - - BCM gpio21 configured as input connected MCP23017 INTB spdip19 +BCM gpio21 configured as input connected MCP23017 INTB spdip19 - BCM gpio22 configured as output connected to LED - - - Red LED (+) connected to pin0 spdip21 - Green LED (+) connected to pin9 spdip2 - Yellow LED (+) connected to pin14 spdip7 - - +BCM gpio22 configured as output connected to LED -MCP23008 on TCA9548 switch bus 1 address 0x22 +Red LED (+) connected to pin0 spdip21 +Green LED (+) connected to pin9 spdip2 +Yellow LED (+) connected to pin14 spdip7 -All address pins (A0 A2) are strapped to ground, (A1) strapped to 3.3 V for the chip address 0x22 +MCP23008 on TCA9548 switch bus 1 address 0x22 + +All address pins (A0 A2) are strapped to ground, (A1) strapped to 3.3 V for the chip address 0x22 _______________________ -- Pi BCM I2C bus 1 - _______________ -_______________________ | - | | || | | - | | || | | - | | || | | - | | || | | - | | || | ____|________________ - | | || |__________> RESET > - MCP23017 0x22 - - | | ||_______________< INTA < _____________________ - | | |________________ < INTB < | | | | | - | |___________________> Drive GPIO > | | LEDs - |_____________________> Drive GPIO >___| - - - NOTE !!!!! - Using the $@ in the module call alows variable number of arguments. But, agruments wrapped by " " cannot - contain spaces. So as you can see the -m and -z values wrapped by " " contain no spaces.. +- Pi BCM I2C bus 1 - _______________ + _______________________ | + | | || | | + | | || | | + | | || | | + | | || | | + | | || | ____|________________ + | | || |__________> RESET > - MCP23017 0x22 - + | | ||_______________< INTA < _____________________ + | | |________________ < INTB < | | | | | + | |___________________> Drive GPIO > | | LEDs + |_____________________> Drive GPIO >___| +NOTE !!!!! +Using the $@ in the module call alows variable number of arguments. But, agruments wrapped by " " cannot +contain spaces. So as you can see the -m and -z values wrapped by " " contain no spaces.. 1. Set pin and chip configuration -property files - sudo ./runAppPropertySet.sh - sudo ./runAppPropertyRead.sh + property files + sudo ./runAppPropertySet.sh + sudo ./runAppPropertyRead.sh + +2. Reset MCP23017 + sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 4 -z "{{'gpio23':{'name':'InterruptADetect','dir':'in','pull':'up'}},{' + gpio21':{'name':'InterruptBDdetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no',' + initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4': + {'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':' + up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6': + {'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 1 -2. Reset MCP23017 - sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 4 -z "{{'gpio23':{'name':'InterruptADetect','dir':'in','pull':'up'}},{'gpio21':{'name':'InterruptBDdetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 1 - - -3. Drive pin0 hi low. Drives Red LED. +3. Drive pin0 hi low. Drives Red LED. - sudo ./runMcp23017.sh -b 0x01 -a 0x20 -d 0 -o ON -m "{{'pin0':{'dir':'out','int_ena':'no'}}}" -f 1 - sudo ./runMcp23017.sh -b 0x01 -a 0x20 -d 0 -o OFF -f 1 +sudo ./runMcp23017.sh -b 0x01 -a 0x20 -d 0 -o ON -m "{{'pin0':{'dir':'out','int_ena':'no'}}}" -f 1 +sudo ./runMcp23017.sh -b 0x01 -a 0x20 -d 0 -o OFF -f 1 -4. Drive pin14 hi low. Drives Yellow LED. +4. Drive pin14 hi low. Drives Yellow LED. - sudo ./runMcp23017.sh -b 0x01 -a 0x22 -d 14 -o ON -m "{{'pin14':{'dir':'out','int_ena':'no'}}}" -f 1 - sudo ./runMcp23017.sh -b 0x01 -a 0x22 -d 14 -o OFF -f 1 +sudo ./runMcp23017.sh -b 0x01 -a 0x22 -d 14 -o ON -m "{{'pin14':{'dir':'out','int_ena':'no'}}}" -f 1 +sudo ./runMcp23017.sh -b 0x01 -a 0x22 -d 14 -o OFF -f 1 5. Read pin4 -sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 4 -z "{{'gpio23':{'name':'InterruptADdetect','dir':'in','pull':'up'}},{'gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 1 -sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 4 -f 1 + sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 4 -z "{{'gpio23':{'name':'InterruptADdetect','dir':'in','pull':'up'}},{' + gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no',' + initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4': + {'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':' + up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin5': + {'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f + 1 + sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 4 -f 1 In separate terminal, alter pin4 python3 import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) -GPIO.setup(12, GPIO.OUT) +GPIO.setup(12, GPIO.OUT) GPIO.output(12,GPIO.LOW) GPIO.output( 12 , GPIO.HIGH) - - 6. Read pin 15 - sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 15 -z "{{'gpio23':{'name':'InterruptADetect','dir':'in','pull':'up'}},{'gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 1 - sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 15 -f 1 - + sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 15 -z "{{'gpio23':{'name':'InterruptADetect','dir':'in','pull':'up'}},{' + gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no',' + initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4': + {'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':' + up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin5': + {'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f + 1 + sudo ./runMcp23017.sh -b 0x01 -a 0x22 -r 15 -f 1 In separate terminal, alter pin15 python3 import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) -GPIO.setup(18, GPIO.OUT) +GPIO.setup(18, GPIO.OUT) GPIO.output(18,GPIO.LOW) GPIO.output( 18 , GPIO.HIGH) diff --git a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A.java b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A.java index 900a7c1..436f3e2 100644 --- a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A.java @@ -49,24 +49,23 @@ public class MCP23017_LCD1602A extends LCD1602A { private I2C mcpDev = null; - private int busNum; - private int address; + private final int busNum; + private final int address; private DigitalOutput ResetPin = null; // private int resetPinNum = 0x42; /** - * * @param pi4j * @param console - * @param resetPin GPIO connected to MCP23017 RESET line + * @param resetPin GPIO connected to MCP23017 RESET line * @param bus * @param address * @param traceLevel */ - public MCP23017_LCD1602A(Context pi4j, Console console ,int resetPin, int bus, int address , String traceLevel) { - super(pi4j, console, false, traceLevel); + public MCP23017_LCD1602A(Context pi4j, Console console, int resetPin, int bus, int address, String traceLevel) { + super(pi4j, console, false, traceLevel); this.resetPinNum = resetPin; this.traceLevel = traceLevel; this.busNum = bus; @@ -89,12 +88,12 @@ public void init() { var outputConfig1 = DigitalOutput.newConfigBuilder(pi4j) - .id("RESET_pin") - .name("Reset") - .address(this.resetPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("RESET_pin") + .name("Reset") + .address(this.resetPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { this.ResetPin = pi4j.create(outputConfig1); } catch (Exception e) { @@ -104,11 +103,9 @@ public void init() { } - - // POR and reset configures all pins as input. // Set IODIR A&B to zeros so pins 0-11 are output. - for(int pin = 0; pin < 11; pin++){ + for (int pin = 0; pin < 11; pin++) { this.configPinOutput(pin); } @@ -117,13 +114,13 @@ public void init() { //this.setEnLow(0x00); this.sleepTimeNanoS(LCD1602A_Declares.postWrtEnableCycleDelay); // enable LCD with blink - this.sendCommand(LCD1602A_Declares.dispCMD | LCD1602A_Declares.dispOnBit| LCD1602A_Declares.dispBlnkOnBit | LCD1602A_Declares.dispCrsOnBit ); + this.sendCommand(LCD1602A_Declares.dispCMD | LCD1602A_Declares.dispOnBit | LCD1602A_Declares.dispBlnkOnBit | LCD1602A_Declares.dispCrsOnBit); // entry mode, cursor moves right each character this.sendCommand(LCD1602A_Declares.entryModeCMD | LCD1602A_Declares.entryModeIncCMD); - this.sendCommand(LCD1602A_Declares.funcSetCMD | LCD1602A_Declares.func8BitsBit | LCD1602A_Declares.func5x8TwoBit); - if(this.clearDisplay){ + this.sendCommand(LCD1602A_Declares.funcSetCMD | LCD1602A_Declares.func8BitsBit | LCD1602A_Declares.func5x8TwoBit); + if (this.clearDisplay) { this.logger.trace("Clear Display"); this.clearDisplay(); } @@ -134,8 +131,7 @@ public void init() { } /** - * - * @param pin MCP23017 pin to configure as output + * @param pin MCP23017 pin to configure as output */ private void configPinOutput(int pin) { this.logger.trace(">>> Enter: configPinOutput Pin: " + pin); @@ -153,7 +149,7 @@ private void configPinOutput(int pin) { // # read return a list, get the single entry [0] logger.trace(" I2cDevice on bus " + this.busNum + " Chip address : " - + String.format("0x%02X", this.address) + " offset " + thisOffset); + + String.format("0x%02X", this.address) + " offset " + thisOffset); reg = (byte) this.mcpDev.readRegister(thisOffset); logger.trace(" Read returned : " + String.format("0x%02X", reg)); /* ("in")) @@ -171,41 +167,43 @@ private void configPinOutput(int pin) { /** * Write byte to actual device I2C interface + * * @param data */ - private void writeToDev(int data){ + private void writeToDev(int data) { // TODO data |= MCP23017_LCD1602A_Declares.backlight_on; - this.logger.trace(">>> Enter: writeToDev data: "+ String.format("%02x ", data) ); + this.logger.trace(">>> Enter: writeToDev data: " + String.format("%02x ", data)); String logData = ""; - logData += " \n P7-DB7: "+ ((data >> 7) & 0x1) + " P6-DB6: "+ ((data >> 6) & 0x1) + " P5-DB5: "+ ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + - "\n BackLight: " + ((data >> 3) & 0x1) + " EN: " + ((data >> 2) & 0x1) + " RW: " + ((data>>1) & 0x1) + " RS: " + ((data) & 0x1) + "\n Data : " + String.format("0X%02x: ",((data >> 4 ) &0xff)); + logData += " \n P7-DB7: " + ((data >> 7) & 0x1) + " P6-DB6: " + ((data >> 6) & 0x1) + " P5-DB5: " + ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + + "\n BackLight: " + ((data >> 3) & 0x1) + " EN: " + ((data >> 2) & 0x1) + " RW: " + ((data >> 1) & 0x1) + " RS: " + ((data) & 0x1) + "\n Data : " + String.format("0X%02x: ", ((data >> 4) & 0xff)); this.logger.trace(logData); // TODO drive each pin, start from pin0 through pin10 int rc = this.mcpDev.write(data); - this.sleepTimeMicroS(LCD1602A_Declares.preAddressWrtSetupDelay*2); + this.sleepTimeMicroS(LCD1602A_Declares.preAddressWrtSetupDelay * 2); - this.logger.trace("Exit: writeToDev RC : " + rc); + this.logger.trace("Exit: writeToDev RC : " + rc); } /** * Write byte to device P0-P7, RS RW and EN pins, then pulse EN * pin so all pins are read into LCD + * * @param data */ protected void writeElevenBits(int data) { - this.logger.trace(">>> Enter: writeElevenBits : " + data + String.format(" 0X%02x: ", data)); + this.logger.trace(">>> Enter: writeElevenBits : " + data + String.format(" 0X%02x: ", data)); String logData = ""; - logData += " \n P7-DB7: "+ ((data >> 7) & 0x1) + " P6-DB6: "+ ((data >> 6) & 0x1) + " P5-DB5: "+ ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + - " \n P3-DB3: "+ ((data >> 3) & 0x1) + " P2-DB2: "+ ((data >> 2) & 0x1) + " P1-DB1: "+ ((data >> 1) & 0x1) + " P0-DB0: " + ((data >> 0) & 0x1) + - "\n EN: " + ((data >> 10) & 0x1) + " RW: " + ((data>>9) & 0x1) + " RS: " + ((data>>8) & 0x1) + "\n Data : " + String.format("0X%02x: ",((data ) & 0xff)); + logData += " \n P7-DB7: " + ((data >> 7) & 0x1) + " P6-DB6: " + ((data >> 6) & 0x1) + " P5-DB5: " + ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + + " \n P3-DB3: " + ((data >> 3) & 0x1) + " P2-DB2: " + ((data >> 2) & 0x1) + " P1-DB1: " + ((data >> 1) & 0x1) + " P0-DB0: " + ((data >> 0) & 0x1) + + "\n EN: " + ((data >> 10) & 0x1) + " RW: " + ((data >> 9) & 0x1) + " RS: " + ((data >> 8) & 0x1) + "\n Data : " + String.format("0X%02x: ", ((data) & 0xff)); this.logger.trace(logData); - for(int i = 0; i < 11; i++){ + for (int i = 0; i < 11; i++) { int pin = i; - boolean level = (((data>>i)&0x01) == 1); + boolean level = (((data >> i) & 0x01) == 1); this.drivePin(pin, level); } this.pulseEnable(data); @@ -215,19 +213,20 @@ protected void writeElevenBits(int data) { /** * Write byte to device P0-P7, then pulse EN pin so all pins are read into LCD + * * @param data */ protected void writeEightBits(int data) { - this.logger.trace(">>> Enter: writeEightBits : " + data + String.format(" 0X%02x: ", data)); + this.logger.trace(">>> Enter: writeEightBits : " + data + String.format(" 0X%02x: ", data)); String logData = ""; - logData += " \n P7-DB7: "+ ((data >> 7) & 0x1) + " P6-DB6: "+ ((data >> 6) & 0x1) + " P5-DB5: "+ ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + - " \n P3-DB3: "+ ((data >> 3) & 0x1) + " P2-DB2: "+ ((data >> 2) & 0x1) + " P1-DB1: "+ ((data >> 1) & 0x1) + " P0-DB0: " + ((data >> 0) & 0x1) + - "\n EN: " + ((data >> 10) & 0x1) + " RW: " + ((data>>9) & 0x1) + " RS: " + ((data>>8) & 0x1) + "\n Data : " + String.format("0X%02x: ",((data ) & 0xff)); + logData += " \n P7-DB7: " + ((data >> 7) & 0x1) + " P6-DB6: " + ((data >> 6) & 0x1) + " P5-DB5: " + ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + + " \n P3-DB3: " + ((data >> 3) & 0x1) + " P2-DB2: " + ((data >> 2) & 0x1) + " P1-DB1: " + ((data >> 1) & 0x1) + " P0-DB0: " + ((data >> 0) & 0x1) + + "\n EN: " + ((data >> 10) & 0x1) + " RW: " + ((data >> 9) & 0x1) + " RS: " + ((data >> 8) & 0x1) + "\n Data : " + String.format("0X%02x: ", ((data) & 0xff)); this.logger.trace(logData); - for(int i = 0; i < 8; i++){ + for (int i = 0; i < 8; i++) { int pin = i; - boolean level = (((data>>i)&0x01) == 1); + boolean level = (((data >> i) & 0x01) == 1); this.drivePin(pin, level); } this.pulseEnable(data); @@ -240,10 +239,10 @@ protected void writeEightBits(int data) { * * @param data */ protected void sendChar(char data) { - this.logger.trace(">>> Enter: sendChar : " + data + String.format(" 0X%02x: ", (int)data)); + this.logger.trace(">>> Enter: sendChar : " + data + String.format(" 0X%02x: ", (int) data)); if (this.lcdAvailable()) { - int c= this.setRSHigh((byte) (data & 0xfff)); + int c = this.setRSHigh((byte) (data & 0xfff)); this.writeElevenBits(c); } else { this.logger.trace("LCD in busy state, request not possible"); @@ -255,6 +254,7 @@ protected void sendChar(char data) { /** * Set RS bit low and the 11 bits to LCD via MCP23017 + * * @param data */ protected void sendCommand(int data) { @@ -262,7 +262,7 @@ protected void sendCommand(int data) { if (this.lcdAvailable()) { int cmd = this.setRSLow(data & 0xfff); this.writeElevenBits(cmd); - } else { + } else { this.logger.trace("LCD in busy state, request not possible"); } this.logger.trace("<<< Exit: sendCommand "); @@ -270,27 +270,26 @@ protected void sendCommand(int data) { /** * Modify data byte to set EN bit, write to device. - * Wait + * Wait * Clear EN bit and write to device * * @param b - * */ - protected int pulseEnable(int b){ + protected int pulseEnable(int b) { this.logger.trace(">>> Enter: pulseEnable "); b = this.setEnHigh(b); b = this.setEnLow(b); this.logger.trace("<<< Exit: pulseEnable : " + b); - return(b); + return (b); } - /** - * Set EN bit low. Drive MCP23017 pin 10 low, wait, return + * Set EN bit low. Drive MCP23017 pin 10 low, wait, return + * * @param b byte - * @return modified byte + * @return modified byte */ private int setEnLow(int b) { this.logger.trace(">>> Enter: setEnLow"); @@ -304,74 +303,80 @@ private int setEnLow(int b) { /** - * Set EN bit high. Drive MCP23017 pin 10 high, wait, return + * Set EN bit high. Drive MCP23017 pin 10 high, wait, return + * * @param b int - * @return modified int + * @return modified int */ private int setEnHigh(int b) { this.logger.trace(">>> Enter: setEnHigh"); - b &= MCP23017_LCD1602A_Declares.E_bit_mask_off; + b &= MCP23017_LCD1602A_Declares.E_bit_mask_off; b |= MCP23017_LCD1602A_Declares.E_high; this.drivePin(MCP23017_LCD1602A_Declares.EN_MCP_PinNum, true); this.sleepTimeMicroS(LCD1602A_Declares.postWrtEnableCycleDelay); this.logger.trace("<<< Exit: setEnHigh"); - return(b); + return (b); } /** - * Set RS bit low + * Set RS bit low + * * @param b int - * @return modified int + * @return modified int */ private int setRSLow(int b) { this.logger.trace(">>> Enter: setRSLow"); - b &= MCP23017_LCD1602A_Declares.RS_bit_mask_off; + b &= MCP23017_LCD1602A_Declares.RS_bit_mask_off; b |= MCP23017_LCD1602A_Declares.RS_low; this.logger.trace("<<< Exit: setRSLow"); - return(b); + return (b); } /** - * Set RS bit high + * Set RS bit high + * * @param b int - * @return modified int + * @return modified int */ - private int setRSHigh(int b) { + private int setRSHigh(int b) { this.logger.trace(">>> Enter: setRSHigh"); - b &= MCP23017_LCD1602A_Declares.RS_bit_mask_off; - b |= MCP23017_LCD1602A_Declares.RS_high; + b &= MCP23017_LCD1602A_Declares.RS_bit_mask_off; + b |= MCP23017_LCD1602A_Declares.RS_high; this.logger.trace("<<< Exit: setRSHigh"); - return(b); + return (b); } /** - * Set RW bit low + * Set RW bit low + * * @param b int - * @return modified int + * @return modified int */ private int setRWLow(int b) { this.logger.trace(">>> Enter: setRWLow"); - b &= MCP23017_LCD1602A_Declares.RW_bit_mask_off; - b |= MCP23017_LCD1602A_Declares.RW_low; + b &= MCP23017_LCD1602A_Declares.RW_bit_mask_off; + b |= MCP23017_LCD1602A_Declares.RW_low; this.logger.trace("<<< Exit: setRWLow"); - return(b); + return (b); } /** - * Set RW bit high + * Set RW bit high + * * @param b int - * @return modified int + * @return modified int */ private int setRWHigh(int b) { this.logger.trace(">>> Enter: setRWHigh"); - b &= MCP23017_LCD1602A_Declares.RW_bit_mask_off; - b |= MCP23017_LCD1602A_Declares.RW_high; + b &= MCP23017_LCD1602A_Declares.RW_bit_mask_off; + b |= MCP23017_LCD1602A_Declares.RW_high; this.logger.trace("<<< Exit: setRWHigh"); - return(b); + return (b); } + private void createI2cDevice() { this.logger.trace(">>> Enter:createI2cDevice bus " + this.busNum + " address " + this.address); @@ -381,12 +386,12 @@ private void createI2cDevice() { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id(id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id(id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); this.mcpDev = this.pi4j.create(i2cDeviceConfig); this.logger.trace("<<< Exit:createI2cDevice "); } @@ -394,112 +399,111 @@ private void createI2cDevice() { ///////////////////////////////////////////////////////////////////////////////// // PIN behaviour + /** - * - * @return Array of register addresses, offset defined by McpConfigData + * @return Array of register addresses, offset defined by McpConfigData *

    - * Overridden by each subclass to return the proper register offsets + * Overridden by each subclass to return the proper register offsets *

    */ public byte[] getAddrMapFirst8() { this.logger.trace(">>> Enter 23017 getAddrMapFirst8"); - byte regAddr[] = { 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x10, 0x12, 0x14 }; + byte[] regAddr = {0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x10, 0x12, 0x14}; this.logger.trace("<<< Exit 23017 getAddrMapFirst8"); return (regAddr); } /** - * - * @return Array of register addresses, offset defined by McpConfigData + * @return Array of register addresses, offset defined by McpConfigData *

    - * Overridden by each subclass to return the proper register offsets + * Overridden by each subclass to return the proper register offsets *

    */ public byte[] getAddrMapSecond8() { this.logger.trace(">>> Enter 23017 getAddrMapSecond8"); - byte regAddr[] = { 0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F, 0x11, 0x13, 0x15 }; + byte[] regAddr = {0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F, 0x11, 0x13, 0x15}; this.logger.trace("<<< Exit 23017 getAddrMapSecond8"); return (regAddr); } /** * - * @return Array of register addresses, offset defined by McpConfigData + * @return Array of register addresses, offset defined by McpConfigData *

    * Overridden by each subclass to return the proper register offsets *

    */ - + /** * PrettyPrint register values */ public void dumpRegs() { this.logger.info(">>> Enter dump_regs "); - String regName[] = { "_IODIR ", "_IPOL ", "_GPINTE ", "_DEFVAL ", "_INTCON ", "_IOCON ", "_GPPU ", - "_INTF ", "_INTCAP ", "_GPIO ", "_OLAT " }; - byte regAddr[] = this.getAddrMapFirst8(); + String[] regName = {"_IODIR ", "_IPOL ", "_GPINTE ", "_DEFVAL ", "_INTCON ", "_IOCON ", "_GPPU ", + "_INTF ", "_INTCAP ", "_GPIO ", "_OLAT "}; + byte[] regAddr = this.getAddrMapFirst8(); this.logger.info("this.getAddrMapFirst8() function returned " + this.getAddrMapFirst8()); - String regNameB[] = { "_IODIRB ", "_IPOLB ", "_GPINTEB", "_DEFVALB", "_INTCONB", "_IOCON ", "_GPPUB ", - "_INTFB ", "_INTCAPB", "_GPIOB ", "_OLATB " }; - String[][] pinName = { { "IO7 IO6 IO5 IO4 IO3 IO2 IO1 IO0" }, - { "IP7 IP6 IP5 IP4 IP3 IP2 IP1 IP0 " }, - { "GPINT7 GPINT6 GPINT5 GPINT4 GPINT3 GPINT2 GPINT1 GPINT0 " }, - { "DEF7 DEF6 DEF5 DEF4 DEF3 DEF2 DEF1 DEF0 " }, - { "IOC7 IOC6 IOC5 IOC4 IOC3 IOC2 IOC1 IOC0 " }, - { "BANK MIRROR SEQOP DISSLW HAEN ODR INTPOL " }, - { "PU7 PU6 PU5 PU4 PU3 PU2 PU1 PU0 " }, - { "INT7 INT6 INT5 INT4 INT3 INT2 INT1 INT0 " }, - { "ICP7 ICP6 ICP5 ICP4 ICP3 ICP2 ICP1 ICP0 " }, - { "GP7 GP6 GP5 GP4 GP3 GP2 GP1 GP0 " }, - { "OL7 OL6 OL5 OL4 OL3 OL2 OL1 OL0 " }, }; - byte regAddrB[] = this.getAddrMapSecond8(); + String[] regNameB = {"_IODIRB ", "_IPOLB ", "_GPINTEB", "_DEFVALB", "_INTCONB", "_IOCON ", "_GPPUB ", + "_INTFB ", "_INTCAPB", "_GPIOB ", "_OLATB "}; + String[][] pinName = {{"IO7 IO6 IO5 IO4 IO3 IO2 IO1 IO0"}, + {"IP7 IP6 IP5 IP4 IP3 IP2 IP1 IP0 "}, + {"GPINT7 GPINT6 GPINT5 GPINT4 GPINT3 GPINT2 GPINT1 GPINT0 "}, + {"DEF7 DEF6 DEF5 DEF4 DEF3 DEF2 DEF1 DEF0 "}, + {"IOC7 IOC6 IOC5 IOC4 IOC3 IOC2 IOC1 IOC0 "}, + {"BANK MIRROR SEQOP DISSLW HAEN ODR INTPOL "}, + {"PU7 PU6 PU5 PU4 PU3 PU2 PU1 PU0 "}, + {"INT7 INT6 INT5 INT4 INT3 INT2 INT1 INT0 "}, + {"ICP7 ICP6 ICP5 ICP4 ICP3 ICP2 ICP1 ICP0 "}, + {"GP7 GP6 GP5 GP4 GP3 GP2 GP1 GP0 "}, + {"OL7 OL6 OL5 OL4 OL3 OL2 OL1 OL0 "},}; + byte[] regAddrB = this.getAddrMapSecond8(); this.logger.info("this.getAddrMapSecond8() function returned " + this.getAddrMapSecond8()); String regAstr = ""; - int reg ; + int reg; for (int i = 0; i < regName.length; i++) { // this.logger.trace(" regAddr " + regAddr[i]); // System.out.println(" regAddr " + regAddr[i]); reg = this.mcpDev.readRegister(regAddr[i]); - regAstr = regAstr.concat("\n Reg " + regName[i] + " offset ("+ i + ") data: " + String.format("0x%02X", reg) + "\n"); - int val = reg; + regAstr = regAstr.concat("\n Reg " + regName[i] + " offset (" + i + ") data: " + String.format("0x%02X", reg) + "\n"); + int val = reg; // System.out.println("pin7 pin6 pin5 pin4 pin3 pin2 pin1 pin0"); regAstr = regAstr.concat(pinName[i][0] + "\n"); regAstr = regAstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " - + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " + + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); } this.logger.info(regAstr); //System.out.println(regAstr); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String regBstr = ""; - int regB; - - for (int i = 0; i < regNameB.length; i++) { - // this.logger.trace(" regAddrB " + regAddrB[i]); - // System.out.println(" regAddrB " + regAddrB[i]); - - regB = this.mcpDev.readRegister(regAddrB[i]); - regBstr = regBstr.concat("\n RegB " + regNameB[i] + " offset ("+ i + ") data: " + String.format("0x%02X", regB) + "\n"); - int val = regB; - // System.out.println("pin7 pin6 pin5 pin4 pin3 pin2 pin1 - // pin0"); - regBstr = regBstr.concat(pinName[i][0] + "\n"); - regBstr = regBstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) - + " " + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) - + "\n"); - } - this.logger.info(regBstr); - //System.out.println(regBstr); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String regBstr = ""; + int regB; + + for (int i = 0; i < regNameB.length; i++) { + // this.logger.trace(" regAddrB " + regAddrB[i]); + // System.out.println(" regAddrB " + regAddrB[i]); + + regB = this.mcpDev.readRegister(regAddrB[i]); + regBstr = regBstr.concat("\n RegB " + regNameB[i] + " offset (" + i + ") data: " + String.format("0x%02X", regB) + "\n"); + int val = regB; + // System.out.println("pin7 pin6 pin5 pin4 pin3 pin2 pin1 + // pin0"); + regBstr = regBstr.concat(pinName[i][0] + "\n"); + regBstr = regBstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + + " " + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + + "\n"); + } + this.logger.info(regBstr); + //System.out.println(regBstr); this.logger.info("<<< Exit dumpRegs"); } @@ -512,16 +516,16 @@ public void resetChip() { this.logger.trace(">>> Enter resetChip "); // POR/Reset set output values to zero try { - this.ResetPin.low(); - this.sleepTimeMilliS(5000); - this.ResetPin.high(); + this.ResetPin.low(); + this.sleepTimeMilliS(5000); + this.ResetPin.high(); } catch (IOException e) { e.printStackTrace(); } // POR/Reset set output values to zero - for(int pin = 0; pin < 11; pin++){ + for (int pin = 0; pin < 11; pin++) { this.configPinOutput(pin); } @@ -533,11 +537,10 @@ public void resetChip() { } /** - * - * @param pin MCP pin to drive - * @param pinOn If true drive HIGH, else drive LOW + * @param pin MCP pin to drive + * @param pinOn If true drive HIGH, else drive LOW */ - public void drivePin(int pin, boolean pinOn){ + public void drivePin(int pin, boolean pinOn) { this.logger.trace(">>> Enter drivePin"); // get the regs and make sure the desired pin is configed as output. Log // error if not @@ -545,7 +548,7 @@ public void drivePin(int pin, boolean pinOn){ int b; int reg; int absPin = pin; // if in second bank must subtract 8 - byte first8[] = this.getAddrMapFirst8(); + byte[] first8 = this.getAddrMapFirst8(); byte thisOffsetIOD = first8[MCP23017_LCD1602A_Declares._IODIR]; @@ -553,7 +556,7 @@ public void drivePin(int pin, boolean pinOn){ byte thisOffsetOLA = first8[MCP23017_LCD1602A_Declares._OLAT]; if (pin > 7) { absPin = absPin - 8; - byte second8[] = this.getAddrMapSecond8(); + byte[] second8 = this.getAddrMapSecond8(); thisOffsetIOD = second8[MCP23017_LCD1602A_Declares._IODIRB]; thisOffsetGPI = second8[MCP23017_LCD1602A_Declares._GPIOB]; @@ -568,16 +571,16 @@ public void drivePin(int pin, boolean pinOn){ System.out.println("Pin" + pin + " not configured for output"); System.exit(500); } - reg = this.mcpDev.readRegister( thisOffsetGPI); + reg = this.mcpDev.readRegister(thisOffsetGPI); // System.out.println("read GPI " + String.format("0x%02X", reg[0])); if (pinOn) { Integer integerObject = ((1 << absPin)); b = integerObject.byteValue(); - reg = (byte)(reg | b); + reg = (byte) (reg | b); } else { Integer integerObject = (~(1 << absPin)); b = integerObject.byteValue(); - reg = (byte)(reg & b); + reg = (byte) (reg & b); } // System.out.println("write GPI " + String.format("0x%02X", reg[0])); @@ -586,11 +589,11 @@ public void drivePin(int pin, boolean pinOn){ this.mcpDev.writeRegister(thisOffsetGPI, (byte) reg); // OLAT - reg = this.mcpDev.readRegister( thisOffsetOLA); + reg = this.mcpDev.readRegister(thisOffsetOLA); if (pinOn) { Integer integerObject = ((1 << absPin)); b = integerObject.byteValue(); - reg = (reg | b); + reg = (reg | b); } else { Integer integerObject = (~(1 << absPin)); b = integerObject.byteValue(); @@ -604,13 +607,12 @@ public void drivePin(int pin, boolean pinOn){ } /** - * - * @param pin MCP pin to read - *

    - * Pin read and detail logged. - *

    + * @param pin MCP pin to read + *

    + * Pin read and detail logged. + *

    */ - public void readInput(int pin){ + public void readInput(int pin) { this.logger.trace(">>> Enter readPin"); // # get the regs and make sure the desired pin is configed as input. @@ -618,13 +620,13 @@ public void readInput(int pin){ int configed; int reg; int absPin = pin; // if in second bank must subtract 8 - byte first8[] = this.getAddrMapFirst8(); + byte[] first8 = this.getAddrMapFirst8(); byte thisOffsetIOD = first8[MCP23017_LCD1602A_Declares._IODIR]; byte thisOffsetGPI = first8[MCP23017_LCD1602A_Declares._GPIO]; if (pin > 7) { absPin = absPin - 8; - byte second8[] = this.getAddrMapSecond8(); + byte[] second8 = this.getAddrMapSecond8(); thisOffsetIOD = second8[MCP23017_LCD1602A_Declares._IODIRB]; thisOffsetGPI = second8[MCP23017_LCD1602A_Declares._GPIOB]; } @@ -641,10 +643,10 @@ public void readInput(int pin){ if ((configed & (1 << absPin)) == 0) { this.logger.trace("Pin" + String.format("0x%02X", pin) + " not configured for input"); - this.logger.trace("Incorrect Pin direction", 510); + this.logger.trace("Incorrect Pin direction", 510); } - reg = this.mcpDev.readRegister( thisOffsetGPI); + reg = this.mcpDev.readRegister(thisOffsetGPI); if ((reg & (1 << absPin)) == 0) { //System.out.println("Pin" + pin + " Low"); this.logger.trace("Pin" + pin + " Low"); diff --git a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_App.java b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_App.java index da763c5..5940dfe 100644 --- a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_App.java +++ b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_App.java @@ -39,7 +39,6 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; import com.pi4j.devices.bmp280.BMP280Declares; -import com.pi4j.devices.pcf8574a_lcd1602a.PCF8574A_LCD1602A; import com.pi4j.io.exception.IOException; import com.pi4j.util.Console; @@ -75,10 +74,10 @@ public static void main(String[] args) throws InterruptedException, IOException console.title("<-- The Pi4J V2 Project Extension -->", "HD44780U_App"); String helpString = " parms: HD44780U -b hex value bus -a hex value address -t trace \n " + - " -x resetPin -r doReset -line1 LcdString,-line1Offset offset ," + - " -line2 LcdString, -line2Offset offset, -shiftL left shift -clearLCD \n" + - "-t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\" \n" ; + " -x resetPin -r doReset -line1 LcdString,-line1Offset offset ," + + " -line2 LcdString, -line2Offset offset, -shiftL left shift -clearLCD \n" + + "-t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\" \n"; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { @@ -91,7 +90,7 @@ public static void main(String[] args) throws InterruptedException, IOException String a = args[i + 1]; i++; address = Integer.parseInt(a.substring(2), 16); - } else if(o.contentEquals("-line1")) { + } else if (o.contentEquals("-line1")) { String a = args[i + 1]; lineOne = a; i++; @@ -107,11 +106,11 @@ public static void main(String[] args) throws InterruptedException, IOException String a = args[i + 1]; lineTwoOffset = Integer.parseInt(a); i++; - }else if (o.contentEquals("-x")) { + } else if (o.contentEquals("-x")) { String a = args[i + 1]; resetPin = Integer.parseInt(a); i++; - }else if (o.contentEquals("-r")) { + } else if (o.contentEquals("-r")) { doReset = true; } else if (o.contentEquals("-shiftL")) { String a = args[i + 1]; @@ -147,15 +146,15 @@ public static void main(String[] args) throws InterruptedException, IOException pi4j.providers().describe().print(System.out); System.out.println("----------------------------------------------------------"); - MCP23017_LCD1602A dispObj = new MCP23017_LCD1602A(pi4j, console, resetPin, busNum, address, traceLevel); + MCP23017_LCD1602A dispObj = new MCP23017_LCD1602A(pi4j, console, resetPin, busNum, address, traceLevel); - if(doReset){ + if (doReset) { dispObj.resetChip(); } if (lineOne.length() > 0) { - dispObj.sendStringLineX(lineOne,1, lineOneOffset); + dispObj.sendStringLineX(lineOne, 1, lineOneOffset); } @@ -168,7 +167,7 @@ public static void main(String[] args) throws InterruptedException, IOException dispObj.shiftLeft(shiftLeftCount); Thread.sleep(5000); - if(clearLCD) { + if (clearLCD) { dispObj.clearDisplay(); } Thread.sleep(5000); diff --git a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_Declares.java b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_Declares.java index 58993ba..07b5f1b 100644 --- a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_Declares.java +++ b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/MCP23017_LCD1602A_Declares.java @@ -38,28 +38,26 @@ public class MCP23017_LCD1602A_Declares { - protected static final int E_bit_mask = 0b10000000000; // E P2 - protected static final int E_bit_mask_off = 0b01111111111; + protected static final int E_bit_mask = 0b10000000000; // E P2 + protected static final int E_bit_mask_off = 0b01111111111; - protected static final int EN_MCP_PinNum = 10; - protected static final int E_low = 0b00000000000; // P2 off - protected static final int E_high = 0b10000000000; // P2 on + protected static final int EN_MCP_PinNum = 10; + protected static final int E_low = 0b00000000000; // P2 off + protected static final int E_high = 0b10000000000; // P2 on + protected static final int RS_MCP_PinNum = 8; - protected static final int RS_MCP_PinNum = 8; + protected static final int RS_bit_mask_off = 0b11011111111; // RS P0 + protected static final int RS_low = 0b00000000000; // P0 off + protected static final int RS_high = 0b00100000000; // P0 on - protected static final int RS_bit_mask_off = 0b11011111111; // RS P0 - protected static final int RS_low = 0b00000000000; // P0 off - protected static final int RS_high = 0b00100000000; // P0 on + protected static final int RW_MCP_PinNum = 9; - - protected static final int RW_MCP_PinNum = 9; - - protected static final int RW_bit_mask_off = 0b10111111111; // RW P1 - protected static final int RW_low = 0b00000000000; // P1 off - protected static final int RW_high = 0b01000000000; // P1 on + protected static final int RW_bit_mask_off = 0b10111111111; // RW P1 + protected static final int RW_low = 0b00000000000; // P1 off + protected static final int RW_high = 0b01000000000; // P1 on protected static final int _IODIR = 0x00; protected static final int _IPOL = 0x01; diff --git a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/README.md b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/README.md index c1f3fcd..eeefa28 100644 --- a/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/README.md +++ b/src/main/java/com/pi4j/devices/mcp23017_lcd1602a/README.md @@ -1,80 +1,104 @@ # + # -# * -# * - -# * #%L -# * ********************************************************************** -# * ORGANIZATION : Pi4J -# * PROJECT : Pi4J :: EXTENSION -# * FILENAME : README.md -# * -# * This file is part of the Pi4J project. More information about -# * this project can be found here: https://pi4j.com/ -# * ********************************************************************** -# * %% -# * * Copyright (C) 2012 - 2022 Pi4J -# * %% -# * -# * Licensed under the Apache License, Version 2.0 (the "License"); -# * you may not use this file except in compliance with the License. -# * You may obtain a copy of the License at -# * -# * http://www.apache.org/licenses/LICENSE-2.0 -# * -# * Unless required by applicable law or agreed to in writing, software -# * distributed under the License is distributed on an "AS IS" BASIS, -# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# * See the License for the specific language governing permissions and -# * limitations under the License. -# * #L% -# * -# -# +# * + +# * - + +# * #%L + +# * ********************************************************************** + +# * ORGANIZATION : Pi4J + +# * PROJECT : Pi4J :: EXTENSION + +# * FILENAME : README.md + +# * + +# * This file is part of the Pi4J project. More information about + +# * this project can be found here: https://pi4j.com/ + +# * ********************************************************************** + +# * %% + +# * * Copyright (C) 2012 - 2022 Pi4J + +# * %% + +# * -MCP23017 1602A -GPB0 RS -GPB1 RW -GPB2 EN -GPA0 D0 -GPA1 D1 -GPA2 D2 -GPA3 D3 -GPA4 D4 -GPA5 D5 -GPA6 D6 -GPA7 D7 - VSS grnd - VDD +5 - V0 grnd - A +5 - K grnd - A2 grnd - A1 +5 - A0 grnd +# * Licensed under the Apache License, Version 2.0 (the "License"); +# * you may not use this file except in compliance with the License. +# * You may obtain a copy of the License at +# * +# * http://www.apache.org/licenses/LICENSE-2.0 -Simple implementation of MCP23017, specific to controlling a 1602A LCD. If you are interested +# * + +# * Unless required by applicable law or agreed to in writing, software + +# * distributed under the License is distributed on an "AS IS" BASIS, + +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +# * See the License for the specific language governing permissions and + +# * limitations under the License. + +# * #L% + +# * + +# + +# + +MCP23017 1602A +GPB0 RS +GPB1 RW +GPB2 EN +GPA0 D0 +GPA1 D1 +GPA2 D2 +GPA3 D3 +GPA4 D4 +GPA5 D5 +GPA6 D6 +GPA7 D7 +VSS grnd +VDD +5 +V0 grnd +A +5 +K grnd +A2 grnd +A1 +5 +A0 grnd + +Simple implementation of MCP23017, specific to controlling a 1602A LCD. If you are interested in a full utilization of all MCP23017 functionality, see : src/main/java/com/pi4j/devices/mcp23017/README.md and -src/main/java/com/pi4j/devices/mcp23xxxApplication/README.md - - +src/main/java/com/pi4j/devices/mcp23xxxApplication/README.md 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runMCP23017_LCD.sh.sh parms........ - -sudo ./runMCP23017_LCD.sh -b 0x01 -a 0x21 -x 4 -t trace -line1 aBc -line2 XyZ -Bus 1, address 0x21, reset pin GPIO4, detailed logging , line one text, line two text +sudo ./runMCP23017_LCD.sh -b 0x01 -a 0x21 -x 4 -t trace -line1 aBc -line2 XyZ +Bus 1, address 0x21, reset pin GPIO4, detailed logging , line one text, line two text Clears display, Line1 begins in fourth position, line2 begins in second position -sudo ./runMCP23017_LCD.sh -b 0x01 -a 0x21 -x 4 -r -clearLCD -t trace -line1 aaaaaa -line1Offset 4 -line2 zzzzzz -line2Offset 2 +sudo ./runMCP23017_LCD.sh -b 0x01 -a 0x21 -x 4 -r -clearLCD -t trace -line1 aaaaaa -line1Offset 4 -line2 zzzzzz +-line2Offset 2 line one starts at offset 4, line two offset 2 -Param -shiftL 2 shift both lines 2 positions to left +Param -shiftL 2 shift both lines 2 positions to left diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23008PinMonitor.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23008PinMonitor.java index ef9b265..db6990d 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23008PinMonitor.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23008PinMonitor.java @@ -40,26 +40,20 @@ import com.pi4j.Pi4J; +import com.pi4j.context.Context; import com.pi4j.devices.appConfig.AppConfigUtilities; +import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.devices.base_util.gpio.BaseGpioInOut; +import com.pi4j.devices.base_util.gpio.GpioPinCfgData; import com.pi4j.devices.base_util.mapUtil.MapUtil; import com.pi4j.devices.mcp23008.Mcp23008; - -import com.pi4j.context.Context; -import com.pi4j.devices.base_util.ffdc.FfdcUtil; -import com.pi4j.devices.base_util.gpio.GpioPinCfgData; import com.pi4j.devices.mcp23xxxCommon.Mcp23xxxUtil; import com.pi4j.devices.mcp23xxxCommon.McpConfigData; -import com.pi4j.exception.LifecycleException; import com.pi4j.io.gpio.digital.DigitalState; import com.pi4j.util.Console; import java.util.HashMap; - -import sun.misc.Signal; -import sun.misc.SignalHandler; - /** * Mcp23008PinMonitor * @@ -101,9 +95,9 @@ public void installInterruptHandler() { this.ffdc.ffdcMethodEntry("installInterruptHandler"); for (int i = 0; i < 7; i++) { - System.out.println(""); + System.out.println(); PinInterruptDefault dummy = new PinInterruptDefault(this.pi4j, this.pin, this.ffdc, this, - this.dioPinData, this.cfgU, this.priChipName); + this.dioPinData, this.cfgU, this.priChipName); this.jumpTable[i] = new PinInterruptActionIntf() { public void interruptAction(int pinNumber, DigitalState pinState) { dummy.dummyAct(pinNumber, pinState); @@ -112,7 +106,7 @@ public void interruptAction(int pinNumber, DigitalState pinState) { } PinInterruptLED action = new PinInterruptLED(this.pi4j, this.pin, this.ffdc, this, this.dioPinData, cfgU, - this.priChipName); + this.priChipName); this.jumpTable[3] = new PinInterruptActionIntf() { public void interruptAction(int pinNumber, DigitalState pinState) { action.changeLed(pinNumber, pinState); @@ -236,20 +230,6 @@ public static void main(String[] args) throws Exception { // cfgU.enableGpioPath Mcp23xxxUtil mcpUtil = new Mcp23xxxUtil(parmsObj.pi4j, ffdc, parmsObj.busNum, parmsObj.priChipAddress, mcpObj.cfgData, mcpObj, console); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - ffdc.ffdcFlushShutdown(); // push all logs to the file - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); if (parmsObj.hasFullKeyedData) { // -g HashMap> outerMap = mcpObj.mapUtils.createFullMap(parmsObj.fullKeyedData); diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23017PinMonitor.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23017PinMonitor.java index df08b32..224f5de 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23017PinMonitor.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23017PinMonitor.java @@ -35,21 +35,17 @@ package com.pi4j.devices.mcp23xxxApplication; import com.pi4j.Pi4J; +import com.pi4j.context.Context; import com.pi4j.devices.appConfig.AppConfigUtilities; +import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.devices.base_util.gpio.BaseGpioInOut; +import com.pi4j.devices.base_util.gpio.GpioPinCfgData; import com.pi4j.devices.base_util.mapUtil.MapUtil; import com.pi4j.devices.mcp23017.Mcp23017; - -import com.pi4j.context.Context; -import com.pi4j.devices.base_util.ffdc.FfdcUtil; -import com.pi4j.devices.base_util.gpio.GpioPinCfgData; import com.pi4j.devices.mcp23xxxCommon.Mcp23xxxUtil; import com.pi4j.devices.mcp23xxxCommon.McpConfigData; -import com.pi4j.exception.LifecycleException; import com.pi4j.io.gpio.digital.DigitalState; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; import java.util.HashMap; @@ -95,7 +91,7 @@ public void installInterruptHandler() { for (int i = 0; i < 7; i++) { System.out.println(); PinInterruptDefault dummy = new PinInterruptDefault(this.pi4j, this.pin, this.ffdc, this, - this.dioPinData, this.cfgU, this.priChipName); + this.dioPinData, this.cfgU, this.priChipName); this.jumpTable[i] = new PinInterruptActionIntf() { public void interruptAction(int pinNumber, DigitalState pinState) { dummy.dummyAct(pinNumber, pinState); @@ -104,7 +100,7 @@ public void interruptAction(int pinNumber, DigitalState pinState) { } PinInterruptLED action = new PinInterruptLED(this.pi4j, this.pin, this.ffdc, this, this.dioPinData, cfgU, - this.priChipName); + this.priChipName); this.jumpTable[3] = new PinInterruptActionIntf() { public void interruptAction(int pinNumber, DigitalState pinState) { action.changeLed(pinNumber, pinState); @@ -120,7 +116,7 @@ public void interruptAction(int pinNumber, DigitalState pinState) { for (int i = 8; i < 16; i++) { System.out.println(); PinInterruptDefault dummy = new PinInterruptDefault(this.pi4j, this.pin, this.ffdc, this, - this.dioPinData, cfgU, this.priChipName); + this.dioPinData, cfgU, this.priChipName); this.jumpTable[i] = new PinInterruptActionIntf() { public void interruptAction(int pinNumber, DigitalState pinState) { dummy.dummyAct(pinNumber, pinState); @@ -128,7 +124,7 @@ public void interruptAction(int pinNumber, DigitalState pinState) { }; } PinInterruptLED ledAction = new PinInterruptLED(this.pi4j, this.pin, this.ffdc, this, this.dioPinData, - cfgU, this.priChipName); + cfgU, this.priChipName); this.jumpTable[15] = new PinInterruptActionIntf() { public void interruptAction(int pinNumber, DigitalState pinState) { ledAction.changeLed(pinNumber, pinState); @@ -193,8 +189,7 @@ public static void main(String[] args) throws Exception { FfdcUtil ffdc = new FfdcUtil(console, pi4j, parmsObj.ffdcControlLevel, Mcp23017PinMonitor.class); - ffdc.ffdcDebugEntry("mcp23017PinMonitor : Arg processing completed...\n" + - ""); + ffdc.ffdcDebugEntry("mcp23017PinMonitor : Arg processing completed...\n"); Mcp23017PinMonitor mcpObj = new Mcp23017PinMonitor(parmsObj.pi4j, parmsObj, ffdc, dioPinData, console); @@ -250,21 +245,6 @@ public static void main(String[] args) throws Exception { // cfgU.enableGpioPath Mcp23xxxUtil mcpUtil = new Mcp23xxxUtil(parmsObj.pi4j, ffdc, parmsObj.busNum, parmsObj.priChipAddress, mcpObj.cfgData, mcpObj, console); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - ffdc.ffdcFlushShutdown(); // push all logs to the file - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); - if (parmsObj.hasFullKeyedData) { // -z HashMap> outerMap = mcpObj.mapUtils.createFullMap(parmsObj.fullKeyedData); diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxAppProcessParms.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxAppProcessParms.java index 155457d..824a70e 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxAppProcessParms.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxAppProcessParms.java @@ -34,26 +34,28 @@ package com.pi4j.devices.mcp23xxxApplication; +import com.pi4j.context.Context; import com.pi4j.devices.base_util.gpio.GpioPinCfgData; import com.pi4j.util.Console; -import com.pi4j.context.Context; + import java.util.HashMap; /** * Mcp23xxxAppProcessParms *

    - * Common code the process the many arguments passed into the - * MCP23008 and MCP23017 application + * Common code the process the many arguments passed into the + * MCP23008 and MCP23017 application *

    */ public class Mcp23xxxAppProcessParms { private final Console console; /** - * Class CTOR + * Class CTOR + * * @param console Console */ - public Mcp23xxxAppProcessParms(Console console){ + public Mcp23xxxAppProcessParms(Console console) { super(); this.console = console; @@ -61,17 +63,18 @@ public Mcp23xxxAppProcessParms(Console console){ /** - * processMain - * @param pi4j Context - * @param args Arguments passed in by application caller. - * @param bankCapable Whether this chip CAN be banked. MCP23008 can't, the - * MCP23017 can. This determines the chip register mapping - * @param dioPinData Chip Pin data + * processMain + * + * @param pi4j Context + * @param args Arguments passed in by application caller. + * @param bankCapable Whether this chip CAN be banked. MCP23008 can't, the + * MCP23017 can. This determines the chip register mapping + * @param dioPinData Chip Pin data * @param generalConsole Console - * @return Mcp23xxx Parms instance whose state contains the details pass + * @return Mcp23xxx Parms instance whose state contains the details pass * in by application caller. */ - public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankCapable, HashMap dioPinData , Console generalConsole) { + public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean bankCapable, HashMap dioPinData, Console generalConsole) { var console = generalConsole; Mcp23xxxParms parmsObj = new Mcp23xxxParms(console); parmsObj.pi4j = pi4j; @@ -92,11 +95,11 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC parmsObj.ffdcControlLevel = Integer.parseInt(a); } else if (o.contentEquals("-y")) { parmsObj.dumpRegs = true; - } else if (o.contentEquals("-b")) { // bus + } else if (o.contentEquals("-b")) { // bus String a = args[i + 1]; parmsObj.busNum = Integer.parseInt(a.substring(2), 16); i++; - } else if (o.contentEquals("-a")) { // device address + } else if (o.contentEquals("-a")) { // device address String a = args[i + 1]; i++; parmsObj.address = Integer.parseInt(a.substring(2), 16); @@ -107,7 +110,7 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC parmsObj.monitorIntrp = true; parmsObj.offOn = args[i + 1]; i++; - } else if (o.contentEquals("-g")) { + } else if (o.contentEquals("-g")) { String a = args[i + 1]; parmsObj.gpioNum = Integer.parseInt(a); i++; @@ -124,7 +127,7 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC if ((parmsObj.bankCapable) && (parmsObj.pin > 15)) { badParmDetail = ("Pin too large, MAX of 15"); badParm = true; - } else if ((parmsObj.bankCapable == false) && (parmsObj.pin > 7)) { + } else if ((!parmsObj.bankCapable) && (parmsObj.pin > 7)) { badParmDetail = ("Pin too large, MAX of 7 "); badParm = true; } else { @@ -138,7 +141,7 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC * i++; parmsObj.address = Integer.parseInt(a.substring(2), 16); * haveAddress = true; // displayMain.address = * Integer.parseInt(a, 16); } - */else if (o.contentEquals("-z")) { + */ else if (o.contentEquals("-z")) { parmsObj.hasFullKeyedData = true; parmsObj.fullKeyedData = args[i + 1]; i++; @@ -150,7 +153,7 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC parmsObj.hasIOCONKeyedData = true; parmsObj.IOCONKeyedData = args[i + 1]; i++; - } else if (o.contentEquals("-r")) { + } else if (o.contentEquals("-r")) { String a = args[i + 1]; i++; // needs work @@ -158,7 +161,7 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC if ((parmsObj.bankCapable) && (parmsObj.pin > 15)) { badParmDetail = ("Pin too large, MAX of 15"); badParm = true; - } else if ((parmsObj.bankCapable == false) && (parmsObj.pin > 7)) { + } else if ((!parmsObj.bankCapable) && (parmsObj.pin > 7)) { badParmDetail = ("Pin too large, MAX of 7"); badParm = true; } else { @@ -189,7 +192,7 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC parmsObj.mainChip = args[i + 1]; i++; } else { - console.print("Invalid parm : " + o + " "); + console.print("Invalid parm : " + o + " "); parmsObj.usage(); System.exit(2); } @@ -199,7 +202,7 @@ public static Mcp23xxxParms processMain(Context pi4j,String[] args,boolean bankC System.exit(701); } } - return(parmsObj); + return (parmsObj); } } diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxParms.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxParms.java index f75727f..d7a6650 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxParms.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxParms.java @@ -40,7 +40,7 @@ /** * Mcp23xxxParms - * + *

    * State only class, used to pass may variable to the various methods. */ @@ -48,9 +48,10 @@ public class Mcp23xxxParms { /** * CTOR + * * @param console Console object */ - public Mcp23xxxParms(Console console){ + public Mcp23xxxParms(Console console) { super(); this.console = console; @@ -100,12 +101,12 @@ public Mcp23xxxParms(Console console){ // , -b bus, -a address public void usage() { System.out.println("options -h 'help', -d drive-pin with -o ON/OFF, \n" - + "-r read-pin , -k \"{'dir':'out','int_ena':'no'}\" (using -d or -r) \n" - + "-m \"{'pin1':{'dir':'in','pull':'down','default':'0','do_compare':'yes','int_ena':'yes','act':'high'}}\"\n" - + "-c primary chip -p primary pin \n" - + "-z gpios config dict -i interript monitor on/off -q mainChip \n" - + "-g gpio, -x reset-chip GPIO# -n resetPin -f ffdc_lvl -y dumpRegs \n" - + " ffdc_lvl 0 < TRACE 1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF \n"); + + "-r read-pin , -k \"{'dir':'out','int_ena':'no'}\" (using -d or -r) \n" + + "-m \"{'pin1':{'dir':'in','pull':'down','default':'0','do_compare':'yes','int_ena':'yes','act':'high'}}\"\n" + + "-c primary chip -p primary pin \n" + + "-z gpios config dict -i interript monitor on/off -q mainChip \n" + + "-g gpio, -x reset-chip GPIO# -n resetPin -f ffdc_lvl -y dumpRegs \n" + + " ffdc_lvl 0 < TRACE 1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF \n"); } } diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxPinMonitorIntf.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxPinMonitorIntf.java index 298cdae..6e516be 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxPinMonitorIntf.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/Mcp23xxxPinMonitorIntf.java @@ -41,34 +41,38 @@ */ public interface Mcp23xxxPinMonitorIntf { - /** - * drivePin - * @param pin pin number, its data and device object contained - * in the pinDict - * @param pinOn Whether to drive pin high (true) or low (false), - * @throws InterruptedException - * @throws IOException - */ - default void drivePin(int pin, boolean pinOn) - throws InterruptedException, IOException{} ; + /** + * drivePin + * + * @param pin pin number, its data and device object contained + * in the pinDict + * @param pinOn Whether to drive pin high (true) or low (false), + * @throws InterruptedException + * @throws IOException + */ + default void drivePin(int pin, boolean pinOn) + throws InterruptedException, IOException { + } - /** - * readInput - *

    - * Used to log the pin state and print the state to the screen. - *

    - * @param pin pin number, its data and device object contained - * in the pinDict - *

    - * PreCond: pin pin number, its data and device object contained - * in the pinDict - *

    - * @throws InterruptedException - * @throws IOException - */ - default void readInput(int pin) - throws InterruptedException, IOException{} ; + /** + * readInput + *

    + * Used to log the pin state and print the state to the screen. + *

    + * + * @param pin pin number, its data and device object contained + * in the pinDict + *

    + * PreCond: pin pin number, its data and device object contained + * in the pinDict + *

    + * @throws InterruptedException + * @throws IOException + */ + default void readInput(int pin) + throws InterruptedException, IOException { + } } diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptActionIntf.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptActionIntf.java index e1004e2..f83f904 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptActionIntf.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptActionIntf.java @@ -38,17 +38,17 @@ /** * PinInterruptActionIntf - * + *

    * Implementing class can take whatever action/steps they want - + *

    * Class implementing this interface are each specific to the device that * created the interrupt */ public interface PinInterruptActionIntf { /** - * interruptAction + * interruptAction * - * @param pinNumber MCP23008 or MCP23017 pin that caused the chip interrupt + * @param pinNumber MCP23008 or MCP23017 pin that caused the chip interrupt * @param pinState DigitalState */ void interruptAction(int pinNumber, DigitalState pinState); diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptBase.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptBase.java index 770cf28..ab7243e 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptBase.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptBase.java @@ -34,23 +34,24 @@ package com.pi4j.devices.mcp23xxxApplication; +import com.pi4j.context.Context; import com.pi4j.devices.appConfig.AppConfigUtilities; import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.devices.base_util.gpio.GpioPinCfgData; -import com.pi4j.context.Context; + import java.util.HashMap; /** * PinInterruptBase - * + *

    * Instances of this class are associated with an PinInterruptActionIntf as * the instance to call for effecting some action. - * + *

    * Subclasses can take unique and specific steps when the interrupt occurs. */ public class PinInterruptBase { - public PinInterruptBase(Context pi4j,int pin, FfdcUtil ffdc, Mcp23xxxPinMonitorIntf mcpObj, + public PinInterruptBase(Context pi4j, int pin, FfdcUtil ffdc, Mcp23xxxPinMonitorIntf mcpObj, HashMap pinDict, AppConfigUtilities cfgU, String priChipName) { @@ -72,6 +73,4 @@ public PinInterruptBase(Context pi4j,int pin, FfdcUtil ffdc, Mcp23xxxPinMonitorI Context pi4j; - - } diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptDefault.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptDefault.java index cb909c8..f1a2b85 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptDefault.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptDefault.java @@ -34,42 +34,44 @@ package com.pi4j.devices.mcp23xxxApplication; +import com.pi4j.context.Context; import com.pi4j.devices.appConfig.AppConfigUtilities; import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.devices.base_util.gpio.GpioPinCfgData; -import com.pi4j.context.Context; -import java.util.HashMap; import com.pi4j.io.gpio.digital.DigitalState; +import java.util.HashMap; + /** * PinInterruptDefault - * + *

    * Instances of this class are associated with an PinInterruptActionIntf as * the instance to call for effecting some action. - * - */ + */ -public class PinInterruptDefault extends PinInterruptBase { +public class PinInterruptDefault extends PinInterruptBase { - /**CTOR + /** + * CTOR * - * @param pi4j Context - * @param pin Pin on the MCP23008 or MCP23017 - * @param ffdc logging - * @param mcpObj MCP23008 or MCP23017 instance - * @param pinDict pin configuration disctionary - * @param cfgU utilities - * @param priChipName Name of the MCP23008 or MCP23017 chip owning the 'pin' + * @param pi4j Context + * @param pin Pin on the MCP23008 or MCP23017 + * @param ffdc logging + * @param mcpObj MCP23008 or MCP23017 instance + * @param pinDict pin configuration disctionary + * @param cfgU utilities + * @param priChipName Name of the MCP23008 or MCP23017 chip owning the 'pin' */ public PinInterruptDefault(Context pi4j, int pin, FfdcUtil ffdc, Mcp23xxxPinMonitorIntf mcpObj, HashMap pinDict, AppConfigUtilities cfgU, String priChipName) { - super(pi4j, pin, ffdc, mcpObj, pinDict, cfgU, priChipName); + super(pi4j, pin, ffdc, mcpObj, pinDict, cfgU, priChipName); } /** - * dummyAct - * @param pinNumber effect pin - * @param pinState DigitalState + * dummyAct + * + * @param pinNumber effect pin + * @param pinState DigitalState */ public void dummyAct(int pinNumber, DigitalState pinState) { System.out.println("Dummy action for pin: " + pinNumber + " pin state: " + pinState); diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptLED.java b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptLED.java index b6eb301..5ea3fdc 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptLED.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/PinInterruptLED.java @@ -35,55 +35,54 @@ package com.pi4j.devices.mcp23xxxApplication; +import com.pi4j.context.Context; import com.pi4j.devices.appConfig.AppConfigUtilities; import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.devices.base_util.gpio.BaseGpioInOut; import com.pi4j.devices.base_util.gpio.GpioPinCfgData; - -import java.util.HashMap; import com.pi4j.io.exception.IOException; import com.pi4j.io.gpio.digital.DigitalState; -import com.pi4j.context.Context; + +import java.util.HashMap; /** * PinInterruptLED - * + *

    * Instances of this class are associated with an PinInterruptActionIntf as * the instance to call for effecting some action. - * */ -public class PinInterruptLED extends PinInterruptBase implements Mcp23xxxPinMonitorIntf{ +public class PinInterruptLED extends PinInterruptBase implements Mcp23xxxPinMonitorIntf { - /**CTOR + /** + * CTOR * - * @param pi4j Context - * @param pin Pin on the MCP23008 or MCP23017 - * @param ffdc logging - * @param mcpObj MCP23008 or MCP23017 instance - * @param pinDict pin configuration disctionary - * @param cfgU utilities - * @param priChipName Name of the MCP23008 or MCP23017 chip owning the 'pin' + * @param pi4j Context + * @param pin Pin on the MCP23008 or MCP23017 + * @param ffdc logging + * @param mcpObj MCP23008 or MCP23017 instance + * @param pinDict pin configuration disctionary + * @param cfgU utilities + * @param priChipName Name of the MCP23008 or MCP23017 chip owning the 'pin' */ - public PinInterruptLED(Context pi4j,int pin, FfdcUtil ffdc, Mcp23xxxPinMonitorIntf mcpObj, + public PinInterruptLED(Context pi4j, int pin, FfdcUtil ffdc, Mcp23xxxPinMonitorIntf mcpObj, HashMap pinDict, AppConfigUtilities cfgU, String priChipName) { super(pi4j, pin, ffdc, mcpObj, pinDict, cfgU, priChipName); } /** - * changeLed + * changeLed * - *

    - * Use the AppConfigUtilities to determine what action to - * take when a specific pin causes an interrupt. - * The actions may in fact effect others pins, depended upon the - * details in the GpioToApp class. + *

    + * Use the AppConfigUtilities to determine what action to + * take when a specific pin causes an interrupt. + * The actions may in fact effect others pins, depended upon the + * details in the GpioToApp class. * - * - * @param pinNumber effect pin - * @param pinState DigitalState + * @param pinNumber effect pin + * @param pinState DigitalState */ public void changeLed(int pinNumber, DigitalState pinState) { ffdc.ffdcMethodEntry("changeLed pin : " + pinNumber + " pin state :" + pinState + " this instance for pin " + this.pin); @@ -107,7 +106,7 @@ public void changeLed(int pinNumber, DigitalState pinState) { // path String ledGpio = pinDetails.get("gpioNumLED"); int pinNum = Character.getNumericValue(ledGpio.charAt(3)); // dionx - if(ledGpio.length() == 5) { // dioxx + if (ledGpio.length() == 5) { // dioxx pinNum = pinNum * 10; pinNum += Character.getNumericValue(ledGpio.charAt(4)); } @@ -125,12 +124,12 @@ public void changeLed(int pinNumber, DigitalState pinState) { ffdc.ffdcDebugEntry("PinMap details contains pin " + pinDetails.get("pin")); String ledGpio = pinDetails.get("pin"); int pinNum = Character.getNumericValue(ledGpio.charAt(3)); // pinx - if(ledGpio.length() == 5) { // pinxx + if (ledGpio.length() == 5) { // pinxx pinNum = pinNum * 10; pinNum += Character.getNumericValue(ledGpio.charAt(4)); } HashMap target = this.cfgU.getPinMapDetails(this.priChipName, - pinDetails.get("pin")); + pinDetails.get("pin")); this.cfgU.enableGpioPath(pinDetails.get("pin"), this.priChipName); // enable // any // mux @@ -151,7 +150,7 @@ public void changeLed(int pinNumber, DigitalState pinState) { String ledGpio = pinDetails.get("gpioNumLED"); BaseGpioInOut gpio = new BaseGpioInOut(this.pi4j, this.ffdc, this.pinDict); int pinNum = Character.getNumericValue(ledGpio.charAt(3)); // diox - if(ledGpio.length() == 5) { // dioxx + if (ledGpio.length() == 5) { // dioxx pinNum = pinNum * 10; pinNum += Character.getNumericValue(ledGpio.charAt(4)); } @@ -166,12 +165,12 @@ public void changeLed(int pinNumber, DigitalState pinState) { } else if (pinDetails.containsKey("pin")) { String ledGpio = pinDetails.get("pin"); int pinNum = Character.getNumericValue(ledGpio.charAt(3)); // pinx - if(ledGpio.length() == 5) { // pinxx + if (ledGpio.length() == 5) { // pinxx pinNum = pinNum * 10; // mov first digit to tens column pinNum += Character.getNumericValue(ledGpio.charAt(4)); // last digit is ones column } HashMap target = this.cfgU.getPinMapDetails(this.priChipName, - pinDetails.get("pin")); + pinDetails.get("pin")); this.cfgU.enableGpioPath(pinDetails.get("pin"), this.priChipName); // enable // any // mux @@ -198,7 +197,7 @@ public void changeLed(int pinNumber, DigitalState pinState) { private void controlChip(HashMap chipDetail, int pinNum, String action, DigitalState pinState) { // TODO Auto-generated method stub String chipPCA = chipDetail.get("pca"); - if ((chipPCA.equals("23017")) || (chipPCA.equals("23008")) ) { + if ((chipPCA.equals("23017")) || (chipPCA.equals("23008"))) { int busNumber = Integer.parseInt(chipDetail.get("busNum").substring(2), 16); int chipAddress = Integer.parseInt(chipDetail.get("address").substring(2), 16); if (action.equals("hilow")) { @@ -212,11 +211,7 @@ private void controlChip(HashMap chipDetail, int pinNum, String } } else if (action.equals("reflect")) { try { - if (pinState == DigitalState.HIGH) { - this.mcpObj.drivePin(pinNum, true); - } else { - this.mcpObj.drivePin(pinNum, false); - } + this.mcpObj.drivePin(pinNum, pinState == DigitalState.HIGH); } catch (InterruptedException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/src/main/java/com/pi4j/devices/mcp23xxxApplication/README.md b/src/main/java/com/pi4j/devices/mcp23xxxApplication/README.md index 948cfb3..7171c24 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxApplication/README.md +++ b/src/main/java/com/pi4j/devices/mcp23xxxApplication/README.md @@ -5,34 +5,34 @@ Pi4J :: Java I/O Library for Raspberry Pi :: Device :: Mcp23xxPinMonitor ### This is an example implementation and will need to be adjusted to fit your needs. -Project by Tom Aarts +Project by Tom Aarts ========================================================================== https://ww1.microchip.com/downloads/en/DeviceDoc/21919e.pdf -MCP23008/MCP23S08 8-Bit I/O Expander with Serial Interface +MCP23008/MCP23S08 8-Bit I/O Expander with Serial Interface See com.pi4j.devices.tca9548.Tca9548 for details on the connected I2C switch. - Java classes to access the MCP23008 GPIO controller as an application. The MCP23008 -is located downstrean of a TCA9548 I2C switch. The Tca9548 I2C switch is automatically +is located downstrean of a TCA9548 I2C switch. The Tca9548 I2C switch is automatically configured allowing access to the MCP23008. The sample application configures MCP23008 pin to drive LEDs, and one pin as an input -with interrupts enabled. A Pi BCM GPIO is used to drive this input pin. The application -monitors the Pi BCM GPIO connected to the MCP23008 INY pin. When the MCP23008 interrupts, +with interrupts enabled. A Pi BCM GPIO is used to drive this input pin. The application +monitors the Pi BCM GPIO connected to the MCP23008 INY pin. When the MCP23008 interrupts, the apllication determines if the pin causing the interrupt is the one monitored, and if so -performs the intended action. The example interrupt event handler drives LEDs also +performs the intended action. The example interrupt event handler drives LEDs also connected to the same MCP23008. Supported functions. - 1. reset chip - 2. Configure any/all pins (all configurations options) - 3. Monitor any specific pin for input interrupts. These interrupts - will call the event handler on the event class associated with the pin - 4. Supports logging facilities implemented by log4_v2 - + +1. reset chip +2. Configure any/all pins (all configurations options) +3. Monitor any specific pin for input interrupts. These interrupts + will call the event handler on the event class associated with the pin +4. Supports logging facilities implemented by log4_v2 + The classes are implemented using the Pi4j_V2 requirements of September 1 2020. The project uses one addition pom requirement of log4j version 2. The project @@ -45,20 +45,16 @@ listed in the parent pom file, therefore mvn (maven) commands in the parent path will not read this pom file. Program options - -q 9548#1 -r 3 -p pin0 -c 23008#1 -g 27 -i on -z 'pi GPIOs' -m 'MCP23xxx pin configuration' --q first chip in the i2c circuit. In the example this is a TCA9548 mux, If the 23008 chip was the +-q 9548#1 -r 3 -p pin0 -c 23008#1 -g 27 -i on -z 'pi GPIOs' -m 'MCP23xxx pin configuration' +-q first chip in the i2c circuit. In the example this is a TCA9548 mux, If the 23008 chip was the directly on the Pi bus, the the value would be -q 23008#1 -r read this MCP23xxx pin --d drive this MCP23xxx pin based on -o ON or OFF +-d drive this MCP23xxx pin based on -o ON or OFF -g Pi gpio connected to MCP23xxx interrupt line --i interrupts monitor is ON or OFF +-i interrupts monitor is ON or OFF -z Pi gpio configuration -m MCP23xxx pin configuration - - - - 1. ./mvnw clean package 2. cd target/distribution 3. Execute command to set configuration data @@ -66,262 +62,266 @@ directly on the Pi bus, the the value would be -q 23008#1 5. Execute command to perform desired MCP23008 operation 6. Use the following python code to drive signals to the MCP23008 pin confirgured as input with interrups enabled. - - Note: If you prefer less or more logging detail, edit run23008App.sh changing the -f parameter VALUE See com.pi4j.devices.base_util.ffdc.FfdcUtil.java - + Dependent upon the -f parameter value logging details will be stored in /tmp/logs/com.pi4j.devices.mcp23xxxApplication.Mcp23008PinMonitor.log - java program to ensure the application configuration was completed. Second, the java MCP23008 application is invoked, this will remain active monitoring -interrupts from the MCP23008. - The application configures a DigitalStateChangeListener for -each MCP23008 pin. - The listener for pin4 will control LEDs also connected to the same -MCP23008 and LEDs connected to the BCM gpio. See com.pi4j.devices.appConfig.AppConfigUtilities.java and +interrupts from the MCP23008. +The application configures a DigitalStateChangeListener for +each MCP23008 pin. +The listener for pin4 will control LEDs also connected to the same +MCP23008 and LEDs connected to the BCM gpio. See com.pi4j.devices.appConfig.AppConfigUtilities.java and com.pi4j.devices.mcp23xxxApplication.PinInterruptLED.java TCA9548 I2C switch, on PI bus 1, address 0x70 -MCP23008 on TCA9548 switch bus 0 address 0x20 +MCP23008 on TCA9548 switch bus 0 address 0x20 _______________________ _______________________ -- Pi BCM I2C bus 1 - -------> - TCA9548 - -_______________________ - 0x70 - - | | | - Bus0 ..... Bus7 - - | | | _______________________ - | | | | - | | | | - | | | ____________________ - | | |__________> RESET > - MCP23008 0x20 - - | | ____________________ - | |________________ < INT < | | | | - | | LEDs - |_____________________> Drive GPIO >___| - +- Pi BCM I2C bus 1 - -------> - TCA9548 - + _______________________ - 0x70 - + | | | - Bus0 ..... Bus7 - + | | | _______________________ + | | | | + | | | | + | | | ____________________ + | | |__________> RESET > - MCP23008 0x20 - + | | ____________________ + | |________________ < INT < | | | | + | | LEDs + |_____________________> Drive GPIO >___| +BCM gpio16 configured as output connected MCP23008 pin 4 pdip14 - BCM gpio16 configured as output connected MCP23008 pin 4 pdip14 - - BCM gpio13 configured as output connected MCP23008 (bar) RESET pdip6 - - BCM gpio27 configured as input connected MCP23008 INT pdip8 - - BCM gpio22 configured as output connected to LED - - - Red LED (+) connected to pin0 pdip10 - Green LED (+) connected to pin1 pdip11 - Yellow LED (+) connected to pin2 pdip12 - - - +BCM gpio13 configured as output connected MCP23008 (bar) RESET pdip6 +BCM gpio27 configured as input connected MCP23008 INT pdip8 +BCM gpio22 configured as output connected to LED +Red LED (+) connected to pin0 pdip10 +Green LED (+) connected to pin1 pdip11 +Yellow LED (+) connected to pin2 pdip12 NOTE !!!!! Using the $@ in the module call alows variable number of arguments. But, agruments wrapped by " " cannot contain spaces. So as you can see the -m and -z values wrapped by " " contain no spaces.. -sudo ./runAppPropertySet.sh +sudo ./runAppPropertySet.sh 1. Set pin and chip configuration -property files - sudo ./runAppPropertySet.sh - sudo ./runAppPropertyRead.sh + property files + sudo ./runAppPropertySet.sh + sudo ./runAppPropertyRead.sh 2. Reset TCA9548 mux - sudo ./runTca9548.sh -b 0x01 -a 0x70 -f 1 -l -r 0x6 - -3. Reset MCP23008 - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 3 -p pin0 -c 23008#1 -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':up'}},{'gpio13':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 13 -f 0 - + sudo ./runTca9548.sh -b 0x01 -a 0x70 -f 1 -l -r 0x6 + +3. Reset MCP23008 + sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 3 -p pin0 -c 23008#1 -z "{{'gpio27':{'name':'InterruptDetect','dir':' + in','pull':up'}},{'gpio13':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':high'}}}" -m "{{'pin0': + {'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3': + {'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':'out',' + int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out',' + int_ena':'no'}}}" -x 13 -f 0 - -4. Configure pins of MCP23008 - - All pins - sudo ./runMcp23008PinMonitor.sh -x 13 -q 9548#1 -g 27 -r 3 -p pin0 -c 23008#1 -f 1 -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':up'}},{'gpio13':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" +4. Configure pins of MCP23008 -5. Drive MCP23008 pin0 hi low Red LED on/off - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 0 -o ON -p pin0 -c 23008#1 -m "{{'pin0':{'dir':'out','int_ena':'no'}}}" -f 1 - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 0 -o OFF -p pin0 -c 23008#1 -f 1 +All pins +sudo ./runMcp23008PinMonitor.sh -x 13 -q 9548#1 -g 27 -r 3 -p pin0 -c 23008#1 -f 1 -z "{{'gpio27':{'name':' +InterruptDetect','dir':'in','pull':up'}},{'gpio13':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':high'}}}" +-m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':' +no'}},{'pin3':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin4':{'dir':' +out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out',' +int_ena':'no'}}}" +5. Drive MCP23008 pin0 hi low Red LED on/off + sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 0 -o ON -p pin0 -c 23008#1 -m "{{'pin0':{'dir':'out','int_ena':' + no'}}}" -f 1 + sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 0 -o OFF -p pin0 -c 23008#1 -f 1 6. Read MCP23008 pin4 - Read 4 - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 4 -p pin0 -c 23008#1 -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'down','default':'0','do_compare':'no','int_ena':'yes','act':'low'}}}" -x 13 -f 2 - This will set pin4 high or low -python3 -import RPi.GPIO as GPIO -GPIO.setmode(GPIO.BCM) -GPIO.setup(16, GPIO.OUT) -GPIO.output(16,GPIO.LOW) -GPIO.output( 16 , GPIO.HIGH) - - -7. Monitor pin 4 (does chip reset) - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 4 -p pin0 -c 23008#1 -g 27 -i on -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':up'}},{'gpio22':{'name':'LED-gpio','dir':'out,'int_ena':'no','initial':low'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'down','default':'0','do_compare':'no','int_ena':'yes','act':'low'}}}" -x 13 -f 2 - - In another terminal - i2cdump -y 1 0x20 This will clear existing interrupts in the chip - -8. Trip interrupt GPIO16->p4 (in separate terminal console) -pin0 Red LED will reflect state of pin4 when it interrupts -sudo python3 -import RPi.GPIO as GPIO -GPIO.setmode(GPIO.BCM) -GPIO.setup(16, GPIO.OUT) -GPIO.output(16,GPIO.LOW) -GPIO.output( 16 , GPIO.HIGH) -GPIO.output(16,GPIO.LOW) + Read 4 + sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 4 -p pin0 -c 23008#1 -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1': + {'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'down','default':'0',' + do_compare':'no','int_ena':'yes','act':'low'}}}" -x 13 -f 2 + This will set pin4 high or low + python3 + import RPi.GPIO as GPIO + GPIO.setmode(GPIO.BCM) + GPIO.setup(16, GPIO.OUT) + GPIO.output(16,GPIO.LOW) + GPIO.output( 16 , GPIO.HIGH) + + +7. Monitor pin 4 (does chip reset) + sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 4 -p pin0 -c 23008#1 -g 27 -i on -z "{{'gpio27':{'name':' + InterruptDetect','dir':'in','pull':up'}},{'gpio22':{'name':'LED-gpio','dir':'out,'int_ena':'no','initial':low'}}}" + -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':' + no'}},{'pin4':{'dir':'in','pull':'down','default':'0','do_compare':'no','int_ena':'yes','act':'low'}}}" -x 13 -f 2 + + In another terminal + i2cdump -y 1 0x20 This will clear existing interrupts in the chip + +8. Trip interrupt GPIO16->p4 (in separate terminal console) + pin0 Red LED will reflect state of pin4 when it interrupts + sudo python3 + import RPi.GPIO as GPIO + GPIO.setmode(GPIO.BCM) + GPIO.setup(16, GPIO.OUT) + GPIO.output(16,GPIO.LOW) + GPIO.output( 16 , GPIO.HIGH) + GPIO.output(16,GPIO.LOW) // pin0 Red LED will reflect state of pin4 when it interrupts - + "{'pin4':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}} } }," - - // pin0 drivenHi then drivenLow when pin4 interrupts - + "{'pin4':{'appName':'input','action':'hilow','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}} } }," - //////////////////////////////////////////////////////////// - // gpio22 drivenHi then drivenLow when pin4 interrupts - + "{'pin4':{'appName':'input','action':'hilow','chipName':'23008#1','gpioNumLED':'dio22'}} } }," - - // gpio22 reflects pin4 when it interrupts - + "{'pin4':{'appName':'input','action':'reflect','chipName':'23008#1','gpioNumLED':'dio22'}} } }," ++ "{'pin4':{'appName':'input','action':'reflect','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}} } }," + +// pin0 drivenHi then drivenLow when pin4 interrupts + ++ "{'pin4':{'appName':'input','action':'hilow','chipName':'23008#1','pin':'pin0','pinChip':'23008#1'}} } }," + //////////////////////////////////////////////////////////// + // gpio22 drivenHi then drivenLow when pin4 interrupts ++ "{'pin4':{'appName':'input','action':'hilow','chipName':'23008#1','gpioNumLED':'dio22'}} } }," + +// gpio22 reflects pin4 when it interrupts ++ "{'pin4':{'appName':'input','action':'reflect','chipName':'23008#1','gpioNumLED':'dio22'}} } }," !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -The current usage of PIGPIO prevents the following test. A single application can access the pigpio libraries at one time +The current usage of PIGPIO prevents the following test. A single application can access the pigpio libraries at one +time Monitor pin 3 - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 3 -p pin0 -c 23008#1 -g 27 -i on -z "{{'gpio27':{'name':'InterruptDetect','dir':'in','pull':up'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2':{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}}}" - - Trip interrupt p7->p3 - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 7 -o ON -p pin0 -c 23008#1 -m "{{'pin7':{'dir':'out','int_ena':'no'}}}" - sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 7 -o OFF -p pin0 -c 23008#1 - - +sudo ./runMcp23008PinMonitor.sh -q 9548#1 -r 3 -p pin0 -c 23008#1 -g 27 -i on -z "{{'gpio27':{'name':'InterruptDetect',' +dir':'in','pull':up'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin1':{'dir':'out','int_ena':'no'}},{'pin2': +{'dir':'out','int_ena':'no'}},{'pin3':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':' +low'}}}" +Trip interrupt p7->p3 +sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 7 -o ON -p pin0 -c 23008#1 -m "{{'pin7':{'dir':'out','int_ena':'no'}}}" +sudo ./runMcp23008PinMonitor.sh -q 9548#1 -d 7 -o OFF -p pin0 -c 23008#1 //////////// MCP23017 +BCM gpio12 configured as output connected MCP23017 pin 4 spdip25 + +BCM gpio18 configured as output connected MCP23017 pin 15 spdip8 + +BCM gpio5 configured as output connected MCP23017 (bar) RESET spdip18 + +BCM gpio23 configured as input connected MCP23017 INTA spdip20 + +BCM gpio21 configured as input connected MCP23017 INTB spdip19 + +BCM gpio22 configured as output connected to LED + +Red LED (+) connected to pin0 spdip21 +Green LED (+) connected to pin9 spdip2 +Yellow LED (+) connected to pin14 spdip7 - BCM gpio12 configured as output connected MCP23017 pin 4 spdip25 - - BCM gpio18 configured as output connected MCP23017 pin 15 spdip8 - - BCM gpio5 configured as output connected MCP23017 (bar) RESET spdip18 - - BCM gpio23 configured as input connected MCP23017 INTA spdip20 - - BCM gpio21 configured as input connected MCP23017 INTB spdip19 - - BCM gpio22 configured as output connected to LED - - - Red LED (+) connected to pin0 spdip21 - Green LED (+) connected to pin9 spdip2 - Yellow LED (+) connected to pin14 spdip7 - - TCA9548 I2C switch, on PI bus 1, address 0x70 -MCP23008 on TCA9548 switch bus 1 address 0x22 +MCP23008 on TCA9548 switch bus 1 address 0x22 _______________________ _______________________ -- Pi BCM I2C bus 1 - -------> - TCA9548 - -_______________________ - 0x70 - - | | || | - . Bus1 ..... Bus7 - - | | || | _______________________ - | | || | | - | | || | | - | | || | ____________________ - | | || |__________> RESET > - MCP23017 0x22 - - | | ||_______________< INTA < ____________________ - | | |________________ < INTB < | | | | | - | |___________________> Drive GPIO > | | LEDs + +- Pi BCM I2C bus 1 - -------> - TCA9548 - + _______________________ - 0x70 - + | | || | - . Bus1 ..... Bus7 - + | | || | _______________________ + | | || | | + | | || | | + | | || | ____________________ + | | || |__________> RESET > - MCP23017 0x22 - + | | ||_______________< INTA < ____________________ + | | |________________ < INTB < | | | | | + | |___________________> Drive GPIO > | | LEDs |_____________________> Drive GPIO >___| - + NOTE !!!!! Using the $@ in the module call alows variable number of arguments. But, agruments wrapped by " " cannot contain spaces. So as you can see the -m and -z values wrapped by " " contain no spaces.. - 1. Set pin and chip configuration property files - sudo ./runAppPropertySet.sh - sudo ./runAppPropertyRead.sh - - + sudo ./runAppPropertySet.sh + sudo ./runAppPropertyRead.sh + + 2. Reset TCA9548 mux - sudo ./runTca9548.sh -b 0x01 -a 0x70 -f 1 -l -r 0x6 - -3. Reset MCP23017 - sudo ./runMcp23017PinMonitor.sh -q 9548#1 -r 4 -p pin0 -c 23017#1 -z "{{'gpio23':{'name':'InterruptADetect','dir':'in','pull':'up'}},{'gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 0 - - - Configure pins of MCP23017 - - - Listen A side - sudo ./runMcp23017PinMonitor.sh -q 9548#1 -g 23 -i on -r 4 -p pin0 -c 23017#1 -z "{{'gpio23':{'name':'InterruptADetect','dir':'in','pull':'up'}},{'gpio27':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin15':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14':{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 13 -f 0 - In another terminal - i2cdump -y 1 0x22 This will clear existing interrupts in the chip - - Yellow LED will flash on/off once each interrupt -Trip interrupt GPIO12->p4 + sudo ./runTca9548.sh -b 0x01 -a 0x70 -f 1 -l -r 0x6 + +3. Reset MCP23017 + sudo ./runMcp23017PinMonitor.sh -q 9548#1 -r 4 -p pin0 -c 23017#1 -z "{{'gpio23':{'name':'InterruptADetect','dir':' + in','pull':'up'}},{'gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':' + out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin14':{'dir':'out',' + int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{' + pin15':{'dir':'in','pull':'up','default':'1','do_compare':'yes','int_ena':'yes','act':'low'}},{'pin5':{'dir':'out',' + int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 0 + +Configure pins of MCP23017 + +Listen A side +sudo ./runMcp23017PinMonitor.sh -q 9548#1 -g 23 -i on -r 4 -p pin0 -c 23017#1 -z "{{'gpio23':{'name':' +InterruptADetect','dir':'in','pull':'up'}},{'gpio27':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5': +{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{' +pin14':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes',' +act':'low'}},{'pin15':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14': +{'dir':'out','int_ena':'no'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7': +{'dir':'out','int_ena':'no'}}}" -x 13 -f 0 +In another terminal +i2cdump -y 1 0x22 This will clear existing interrupts in the chip + +Yellow LED will flash on/off once each interrupt +Trip interrupt GPIO12->p4 python3 import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) -GPIO.setup(6, GPIO.OUT) +GPIO.setup(6, GPIO.OUT) GPIO.output(6,GPIO.LOW) GPIO.output( 6 , GPIO.HIGH) -GPIO.output(6,GPIO.LOW) - - - Listen B side - sudo ./runMcp23017PinMonitor.sh -q 9548#1 -g 21 -i on -r 14 -p pin0 -c 23017#1 -z "{{'gpio21':{'name':'InterruptADetect','dir':'in','pull':'up'}},{'gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5':{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{'pin4':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6':{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 0 - In another terminal - i2cdump -y 1 0x22 This will clear existing interruupts in the chip - - Trip interrupt GPIO18->p15 Red LED reflects level of pin 15 +GPIO.output(6,GPIO.LOW) + +Listen B side +sudo ./runMcp23017PinMonitor.sh -q 9548#1 -g 21 -i on -r 14 -p pin0 -c 23017#1 -z "{{'gpio21':{'name':' +InterruptADetect','dir':'in','pull':'up'}},{'gpio21':{'name':'InterruptBDetect','dir':'in','pull':'up'}},{'gpio5': +{'name':'ResetChip','dir':'out,'int_ena':'no','initial':'high'}}}" -m "{{'pin0':{'dir':'out','int_ena':'no'}},{' +pin4':{'dir':'in','pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin14':{'dir':'in',' +pull':'up','default':'0','do_compare':'no','int_ena':'yes','act':'low'}},{'pin5':{'dir':'out','int_ena':'no'}},{'pin6': +{'dir':'out','int_ena':'no'}},{'pin7':{'dir':'out','int_ena':'no'}}}" -x 5 -f 0 +In another terminal +i2cdump -y 1 0x22 This will clear existing interruupts in the chip + +Trip interrupt GPIO18->p15 Red LED reflects level of pin 15 python3 import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) -GPIO.setup(12, GPIO.OUT) +GPIO.setup(12, GPIO.OUT) GPIO.output(12,GPIO.LOW) GPIO.output( 12 , GPIO.HIGH) GPIO.output(12,GPIO.LOW) - -Drive pin0 hi low Red LED - - sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 0 -o ON -p pin0 -c 23017#1 -m "{{'pin0':{'dir':'out','int_ena':'no'}}}" - sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 0 -o OFF -p pin0 -c 23017#1 - -Drive pin14 hi low Yellow LED - - sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 14 -o ON -p pin0 -c 23017#1 -m "{{'pin14':{'dir':'out','int_ena':'no'}}}" - sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 14 -o OFF -p pin0 -c 23017#1 - - - - - +Drive pin0 hi low Red LED +sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 0 -o ON -p pin0 -c 23017#1 -m "{{'pin0':{'dir':'out','int_ena':'no'}}}" +sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 0 -o OFF -p pin0 -c 23017#1 +Drive pin14 hi low Yellow LED +sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 14 -o ON -p pin0 -c 23017#1 -m "{{'pin14':{'dir':'out','int_ena':'no'}}}" +sudo ./runMcp23017PinMonitor.sh -q 9548#1 -d 14 -o OFF -p pin0 -c 23017#1 - NOTES +NOTES ~/Pi4j_v2/Pi4J_V2_devices/src/main/python/monitor_py sudo pigpiod sudo killall pigpiod diff --git a/src/main/java/com/pi4j/devices/mcp23xxxCommon/Mcp23xxxUtil.java b/src/main/java/com/pi4j/devices/mcp23xxxCommon/Mcp23xxxUtil.java index 4ee6679..de0fd06 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxCommon/Mcp23xxxUtil.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxCommon/Mcp23xxxUtil.java @@ -51,23 +51,23 @@ * Mcp23xxxUtil * *

    - * Utilities common to the MCP23008 and MCP23017 + * Utilities common to the MCP23008 and MCP23017 *

    */ -public class Mcp23xxxUtil extends BasicI2cDevice{ +public class Mcp23xxxUtil extends BasicI2cDevice { /** - * CTOR + * CTOR * - * @param pi4j Context - * @param ffdc logging - * @param busNum Pi bus number - * @param address Chip device address - * @param cfgData Chip defines/constants - * @param mcpObj MCP23008 and MCP23017 instance - * @param console Context + * @param pi4j Context + * @param ffdc logging + * @param busNum Pi bus number + * @param address Chip device address + * @param cfgData Chip defines/constants + * @param mcpObj MCP23008 and MCP23017 instance + * @param console Context */ - public Mcp23xxxUtil(Context pi4j, FfdcUtil ffdc, int busNum, int address, McpConfigData cfgData, McpBase mcpObj, Console console) { + public Mcp23xxxUtil(Context pi4j, FfdcUtil ffdc, int busNum, int address, McpConfigData cfgData, McpBase mcpObj, Console console) { super(pi4j, ffdc, busNum, address, console); this.ffdc = ffdc; this.cfgData = cfgData; @@ -75,13 +75,12 @@ public Mcp23xxxUtil(Context pi4j, FfdcUtil ffdc, int busNum, int address, McpCo } /** - * - * @param pin number of pin on MCPxxxxx chip - * @param pinOn drive pin high if true, else low - *

    - * Use overloaded getAddrMapFirst8 - * and getAddrMapSecond8 to obtain correct register address - *

    + * @param pin number of pin on MCPxxxxx chip + * @param pinOn drive pin high if true, else low + *

    + * Use overloaded getAddrMapFirst8 + * and getAddrMapSecond8 to obtain correct register address + *

    */ public void drivePin(int pin, boolean pinOn) { // get the regs and make sure the desired pin is configed as output. Log @@ -105,12 +104,12 @@ public void drivePin(int pin, boolean pinOn) { this.ffdc.ffdcMethodEntry("drivePin pin" + String.format("0x%02X", pin) + " pinOn : " + pinOn); this.ffdc.ffdcMethodEntry( - "drivePin banked capable " + this.mcpB.bankCapable + " banked : " + this.mcpB.banked); + "drivePin banked capable " + this.mcpB.bankCapable + " banked : " + this.mcpB.banked); configed = (byte) this.readRegister(thisOffsetIOD); if ((configed & (1 << absPin)) > 0) { - this.ffdc.ffdcErrorExit("Pin" + pin + " not configured for output",500); + this.ffdc.ffdcErrorExit("Pin" + pin + " not configured for output", 500); } reg = (byte) this.readRegister(thisOffsetGPI); if (pinOn) { @@ -124,9 +123,9 @@ public void drivePin(int pin, boolean pinOn) { reg = (byte) (reg & b); } - this.writeByte( thisOffsetGPI, reg); + this.writeByte(thisOffsetGPI, reg); - if (pinOn) { + if (pinOn) { Integer integerObject; integerObject = (1 << absPin); b = integerObject.byteValue(); @@ -137,19 +136,18 @@ public void drivePin(int pin, boolean pinOn) { b = integerObject.byteValue(); reg = (byte) (reg & b); } - this.ffdc.ffdcMethodExit("drivePin"); + this.ffdc.ffdcMethodExit("drivePin"); } /** - * - * @param pin number of pin on MCPxxxxx chip - *

    - * Use overloaded getAddrMapFirst8 - * and getAddrMapSecond8 to obtain correct register address - *

    - * Read and display pin state high/low - *

    - *

    + * @param pin number of pin on MCPxxxxx chip + *

    + * Use overloaded getAddrMapFirst8 + * and getAddrMapSecond8 to obtain correct register address + *

    + * Read and display pin state high/low + *

    + *

    */ public void readInput(int pin) { // # get the regs and make sure the desired pin is configed as input. @@ -170,13 +168,13 @@ public void readInput(int pin) { this.ffdc.ffdcMethodEntry(" readInput pin " + String.format("0x%02X", pin)); this.ffdc.ffdcMethodEntry( - "drivePin banked capable " + this.mcpB.bankCapable + " banked : " + this.mcpB.banked); + "drivePin banked capable " + this.mcpB.bankCapable + " banked : " + this.mcpB.banked); configed = this.readRegister(thisOffsetIOD); this.examineReturnRead(reg); if ((configed & (1 << absPin)) == 0) { - this.ffdc.ffdcErrorExit("Pin" + String.format("0x%02X", pin) + " not configured for input",510); + this.ffdc.ffdcErrorExit("Pin" + String.format("0x%02X", pin) + " not configured for input", 510); } reg = this.readRegister(thisOffsetGPI); @@ -190,7 +188,7 @@ public void readInput(int pin) { } - public void processKeyedData() { + public void processKeyedData() { // this.cfgData; // this.keyedData; this.ffdc.ffdcMethodEntry("processKeyedData "); @@ -200,19 +198,19 @@ public void processKeyedData() { Set outerSet = outerMap.entrySet(); Iterator>> outerIterator = outerSet.iterator(); while (outerIterator.hasNext()) { - Map.Entry> mentry = (Map.Entry) outerIterator.next(); + Map.Entry> mentry = outerIterator.next(); // iterate inner map HashMap innerMap = new HashMap(); Iterator> child = (mentry.getValue()).entrySet().iterator(); while (child.hasNext()) { Entry childPair = child.next(); - String key = childPair.getKey(); + String key = childPair.getKey(); byte[] first8 = this.mcpB.getAddrMapFirst8(); byte regValOffset = first8[this.cfgData._IOCON]; if (key.equals("act")) { byte ioconReg; ioconReg = (byte) this.readRegister(regValOffset); - String level = childPair.getValue(); + String level = childPair.getValue(); if (level.contains("low")) { ioconReg = (byte) (ioconReg & (~2)); } else if (level.contains("high")) { @@ -221,8 +219,8 @@ public void processKeyedData() { this.writeByte(regValOffset, ioconReg); } } - String[] pinList = { "pin0", "pin1", "pin2", "pin3", "pin4", "pin5", "pin6", "pin7", "pin8", "pin9", - "pin10", "pin11", "pin12", "pin13", "pin14", "pin15" }; + String[] pinList = {"pin0", "pin1", "pin2", "pin3", "pin4", "pin5", "pin6", "pin7", "pin8", "pin9", + "pin10", "pin11", "pin12", "pin13", "pin14", "pin15"}; for (int i = 0; i < pinList.length; i++) { if (outerMap.containsKey(pinList[i])) { this.processPinData(i, pinList[i], outerMap.get(pinList[i])); @@ -237,9 +235,9 @@ public void processKeyedData() { public void processPinData(int pin_num, String pin, HashMap innerData) { // this.cfgData; this.ffdc.ffdcMethodEntry("processPinData pinNum : " + String.format("0x%02X", pin_num) + " " + pin - + " innerData : " + innerData); + + " innerData : " + innerData); String value; - String[] opt_list = { "dir", "pull", "default", "do_compare", "int_ena" }; + String[] opt_list = {"dir", "pull", "default", "do_compare", "int_ena"}; for (int c = 0; c < opt_list.length; c++) { // System.out.println("pin_list[i] " + pin_list[i] + " \n outerMap " // + outerMap); @@ -251,7 +249,7 @@ public void processPinData(int pin_num, String pin, HashMap inne this.ffdc.ffdcMethodExit("processPinData"); } - public void processOptData(int pin, String key, String value){ + public void processOptData(int pin, String key, String value) { this.ffdc.ffdcMethodEntry(" processOptData pin " + pin + " key " + key + " value " + value); byte reg; byte b; @@ -267,8 +265,8 @@ public void processOptData(int pin, String key, String value){ // # read return a list, get the single entry [0] this.ffdc.ffdcDebugEntry(" I2cDevice on bus " + this.busNum + " Chip address : " - + String.format("0x%02X", this.address) + " offset " + thisOffset); - // TODO Must we ever remap the bus/address ??? + + String.format("0x%02X", this.address) + " offset " + thisOffset); + // TODO Must we ever remap the bus/address ??? reg = (byte) this.readRegister(thisOffset); this.ffdc.ffdcDebugEntry(" Read returned : " + String.format("0x%02X", reg)); if (value.contains("in")) { @@ -280,7 +278,7 @@ public void processOptData(int pin, String key, String value){ b = integerObject.byteValue(); reg = (byte) (reg & b); } - this.writeByte( thisOffset, reg); + this.writeByte(thisOffset, reg); } else if (key.contains("pull")) { byte[] first8 = this.mcpB.getAddrMapFirst8(); byte thisOffset = first8[this.cfgData._GPPU]; @@ -290,7 +288,7 @@ public void processOptData(int pin, String key, String value){ thisOffset = second8[this.cfgData._GPPUB]; } // # read return a list, get the single entry [0] - reg = (byte) this.readRegister( thisOffset); + reg = (byte) this.readRegister(thisOffset); this.ffdc.ffdcDebugEntry(" Read returned : " + String.format("0x%02X", reg)); if (value.contains("up")) { Integer integerObject = (1 << absPin); @@ -301,7 +299,7 @@ public void processOptData(int pin, String key, String value){ b = integerObject.byteValue(); reg = (byte) (reg & b); } - this.writeByte( thisOffset, reg); + this.writeByte(thisOffset, reg); } else if (key.contains("default")) { byte[] first8 = this.mcpB.getAddrMapFirst8(); byte thisOffset = first8[this.cfgData._DEFVAL]; @@ -325,15 +323,15 @@ public void processOptData(int pin, String key, String value){ } this.writeByte(thisOffset, reg); } else if (key.contains("do_compare")) { - byte first8[] = this.mcpB.getAddrMapFirst8(); + byte[] first8 = this.mcpB.getAddrMapFirst8(); byte thisOffset = first8[this.cfgData._INTCON]; if (pin > 7) { absPin = absPin - 8; - byte second8[] = this.mcpB.getAddrMapSecond8(); + byte[] second8 = this.mcpB.getAddrMapSecond8(); thisOffset = second8[this.cfgData._INTCON]; } // # read return a list, get the single entry [0] - reg = (byte) this.readRegister(thisOffset ); + reg = (byte) this.readRegister(thisOffset); this.ffdc.ffdcDebugEntry(" Read returned : " + String.format("0x%02X", reg)); if (value.contains("yes")) { Integer integerObject = (1 << absPin); @@ -345,17 +343,17 @@ public void processOptData(int pin, String key, String value){ b = integerObject.byteValue(); reg = (byte) (reg & b); } - this.writeByte( thisOffset, reg); + this.writeByte(thisOffset, reg); } else if (key.contains("invert")) { - byte first8[] = this.mcpB.getAddrMapFirst8(); + byte[] first8 = this.mcpB.getAddrMapFirst8(); byte thisOffset = first8[this.cfgData._IPOL]; if (pin > 7) { absPin = absPin - 8; - byte second8[] = this.mcpB.getAddrMapSecond8(); + byte[] second8 = this.mcpB.getAddrMapSecond8(); thisOffset = second8[this.cfgData._IPOLB]; } // # read return a list, get the single entry [0] - reg = (byte)this.readRegister( thisOffset); + reg = (byte) this.readRegister(thisOffset); this.ffdc.ffdcDebugEntry(" Read returned : " + String.format("0x%02X", reg)); if (value.contains("yes")) { Integer integerObject; @@ -367,17 +365,17 @@ public void processOptData(int pin, String key, String value){ b = integerObject.byteValue(); reg = (byte) (reg & b); } - this.writeByte( thisOffset, reg); + this.writeByte(thisOffset, reg); } else if (key.contains("int_ena")) { - byte first8[] = this.mcpB.getAddrMapFirst8(); + byte[] first8 = this.mcpB.getAddrMapFirst8(); byte thisOffset = first8[this.cfgData._GPINTEN]; if (pin > 7) { absPin = absPin - 8; - byte second8[] = this.mcpB.getAddrMapSecond8(); + byte[] second8 = this.mcpB.getAddrMapSecond8(); thisOffset = second8[this.cfgData._GPINTENB]; } // # read return a list, get the single entry [0] - reg = (byte) this.readRegister( thisOffset); + reg = (byte) this.readRegister(thisOffset); this.ffdc.ffdcDebugEntry(" Read returned : " + String.format("0x%02X", reg)); if (value.contains("yes")) { Integer integerObject = (1 << absPin); @@ -399,8 +397,6 @@ public void processOptData(int pin, String key, String value){ McpBase mcpB; /** - * - * * @param pi4j * @param args * @param bankCapable @@ -409,7 +405,7 @@ public void processOptData(int pin, String key, String value){ * @return */ - public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean bankCapable, HashMap dioPinData , Console generalConsole) { + public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean bankCapable, HashMap dioPinData, Console generalConsole) { // TODO Auto-generated method stub var console = generalConsole; @@ -438,11 +434,11 @@ public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean ban parmsObj.ffdcControlLevel = Integer.parseInt(a); } else if (o.contentEquals("-y")) { parmsObj.dumpRegs = true; - } else if (o.contentEquals("-b")) { // bus + } else if (o.contentEquals("-b")) { // bus String a = args[i + 1]; parmsObj.busNum = Integer.parseInt(a.substring(2), 16); i++; - } else if (o.contentEquals("-a")) { // device address + } else if (o.contentEquals("-a")) { // device address String a = args[i + 1]; i++; parmsObj.address = Integer.parseInt(a.substring(2), 16); @@ -450,7 +446,7 @@ public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean ban } else if (o.contentEquals("-h")) { parmsObj.usage(); System.exit(0); - } else if (o.contentEquals("-x")) { + } else if (o.contentEquals("-x")) { String a = args[i + 1]; parmsObj.doReset = true; parmsObj.gpioReset = Integer.parseInt(a); @@ -463,13 +459,13 @@ public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean ban if ((parmsObj.bankCapable) && (parmsObj.pin > 15)) { badParmDetail = ("Pin too large, MAX of 15"); badParm = true; - } else if ((parmsObj.bankCapable == false) && (parmsObj.pin > 7)) { + } else if ((!parmsObj.bankCapable) && (parmsObj.pin > 7)) { badParmDetail = ("Pin too large, MAX of 7 "); badParm = true; } else { parmsObj.setPin = true; } - } else if (o.contentEquals("-z")) { + } else if (o.contentEquals("-z")) { parmsObj.hasFullKeyedData = true; parmsObj.fullKeyedData = args[i + 1]; i++; @@ -481,7 +477,7 @@ public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean ban parmsObj.hasIOCONKeyedData = true; parmsObj.IOCONKeyedData = args[i + 1]; i++; - } else if (o.contentEquals("-r")) { + } else if (o.contentEquals("-r")) { String a = args[i + 1]; i++; // needs work @@ -489,7 +485,7 @@ public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean ban if ((parmsObj.bankCapable) && (parmsObj.pin > 15)) { badParmDetail = ("Pin too large, MAX of 15"); badParm = true; - } else if ((parmsObj.bankCapable == false) && (parmsObj.pin > 7)) { + } else if ((!parmsObj.bankCapable) && (parmsObj.pin > 7)) { badParmDetail = ("Pin too large, MAX of 7"); badParm = true; } else { @@ -507,7 +503,7 @@ public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean ban badParm = true; } } else { - console.print("Invalid parm : " + o + " "); + console.print("Invalid parm : " + o + " "); parmsObj.usage(); System.exit(2); } @@ -517,18 +513,18 @@ public static Mcp23xxxParms processMain(Context pi4j, String[] args, boolean ban System.exit(701); } } - return(parmsObj); + return (parmsObj); } public static void usage() { System.out.println("options -h 'help', -d drive-pin with -o ON/OFF, \n" - + "-r read-pin , -k \"{'dir':'out','int_ena':'no'}\" (using -d or -r) \n" - + " -b bus -a address \n" - + "-m \"{'pin1':{'dir':'in','pull':'down','default':'0','do_compare':'yes','int_ena':'yes','act':'high'}}\" \n" - + "-c primary chip -p primary pin \n" - + "-z gpios config dict -q mainChip \n" - + "-x reset-chip GPIO# -n resetPin -f ffdc_lvl -y dumpRegs \n" - + "ffdc_lvl 0 < TRACE 1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF "); + + "-r read-pin , -k \"{'dir':'out','int_ena':'no'}\" (using -d or -r) \n" + + " -b bus -a address \n" + + "-m \"{'pin1':{'dir':'in','pull':'down','default':'0','do_compare':'yes','int_ena':'yes','act':'high'}}\" \n" + + "-c primary chip -p primary pin \n" + + "-z gpios config dict -q mainChip \n" + + "-x reset-chip GPIO# -n resetPin -f ffdc_lvl -y dumpRegs \n" + + "ffdc_lvl 0 < TRACE 1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF "); } } diff --git a/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpBase.java b/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpBase.java index ebb4e2d..f4cab99 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpBase.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpBase.java @@ -34,6 +34,7 @@ package com.pi4j.devices.mcp23xxxCommon; +import com.pi4j.context.Context; import com.pi4j.devices.appConfig.AppConfigUtilities; import com.pi4j.devices.base_i2c.MutableI2cDevice; import com.pi4j.devices.base_util.ffdc.FfdcUtil; @@ -41,37 +42,35 @@ import com.pi4j.devices.base_util.gpio.GpioPinCfgData; import com.pi4j.devices.base_util.mapUtil.MapUtil; import com.pi4j.devices.mcp23xxxApplication.Mcp23xxxParms; -import com.pi4j.io.gpio.digital.*; -import com.pi4j.context.Context; -import com.pi4j.util.Console; -import java.util.HashMap; - import com.pi4j.devices.mcp23xxxApplication.PinInterruptActionIntf; - - - import com.pi4j.io.gpio.digital.DigitalState; +import com.pi4j.io.gpio.digital.DigitalStateChangeEvent; +import com.pi4j.io.gpio.digital.DigitalStateChangeListener; +import com.pi4j.util.Console; + +import java.util.HashMap; /** * McpBase *

    - * Base class for simple MCP23008 and MCP23017 implementations and the more complex - * Application for these two classes + * Base class for simple MCP23008 and MCP23017 implementations and the more complex + * Application for these two classes *

    */ -public class McpBase extends MutableI2cDevice { +public class McpBase extends MutableI2cDevice { /** - * CTOR - * @param parmsObj Contains the many options supplied to the main functions - * @param bankCapable If true a MCP23017 chip, else a MCP23008 chip - * @param dioPinData MCP chip pin configuration objects - * @param pi4j Context - * @param ffdc Logging - * @param console Console + * CTOR + * + * @param parmsObj Contains the many options supplied to the main functions + * @param bankCapable If true a MCP23017 chip, else a MCP23008 chip + * @param dioPinData MCP chip pin configuration objects + * @param pi4j Context + * @param ffdc Logging + * @param console Console */ public McpBase(Mcp23xxxParms parmsObj, boolean bankCapable, HashMap dioPinData, Context pi4j, FfdcUtil ffdc, Console console) { - super(pi4j, ffdc, console); + super(pi4j, ffdc, console); this.parmsObj = parmsObj; // copy all parmsObj attributes into the MCPxxxx Base class. this.priChipName = parmsObj.priChipName; @@ -107,10 +106,9 @@ public McpBase(Mcp23xxxParms parmsObj, boolean bankCapable, HashMap - * Overridden by each subclass to return the proper register offsets + * Overridden by each subclass to return the proper register offsets *

    */ public byte[] getAddrMapFirst8() { @@ -119,10 +117,9 @@ public byte[] getAddrMapFirst8() { } /** - * - * @return Array of register addresses, offset defined by McpConfigData + * @return Array of register addresses, offset defined by McpConfigData *

    - * Overridden by each subclass to return the proper register offsets + * Overridden by each subclass to return the proper register offsets *

    */ public byte[] getAddrMapSecond8() { @@ -136,42 +133,42 @@ public byte[] getAddrMapSecond8() { public void dumpRegs() { this.ffdc.ffdcMethodEntry("dump_regs "); - String regName[] = { "_IODIR ", "_IPOL ", "_GPINTE ", "_DEFVAL ", "_INTCON ", "_IOCON ", "_GPPU ", - "_INTF ", "_INTCAP ", "_GPIO ", "_OLAT " }; - byte regAddr[] = this.getAddrMapFirst8(); + String[] regName = {"_IODIR ", "_IPOL ", "_GPINTE ", "_DEFVAL ", "_INTCON ", "_IOCON ", "_GPPU ", + "_INTF ", "_INTCAP ", "_GPIO ", "_OLAT "}; + byte[] regAddr = this.getAddrMapFirst8(); this.ffdc.ffdcDebugEntry("this.getAddrMapFirst8() function returned " + this.getAddrMapFirst8()); - String regNameB[] = { "_IODIRB ", "_IPOLB ", "_GPINTEB", "_DEFVALB", "_INTCONB", "_IOCON ", "_GPPUB ", - "_INTFB ", "_INTCAPB", "_GPIOB ", "_OLATB " }; - String[][] pinName = { { "IO7 IO6 IO5 IO4 IO3 IO2 IO1 IO0" }, - { "IP7 IP6 IP5 IP4 IP3 IP2 IP1 IP0 " }, - { "GPINT7 GPINT6 GPINT5 GPINT4 GPINT3 GPINT2 GPINT1 GPINT0 " }, - { "DEF7 DEF6 DEF5 DEF4 DEF3 DEF2 DEF1 DEF0 " }, - { "IOC7 IOC6 IOC5 IOC4 IOC3 IOC2 IOC1 IOC0 " }, - { "BANK MIRROR SEQOP DISSLW HAEN ODR INTPOL " }, - { "PU7 PU6 PU5 PU4 PU3 PU2 PU1 PU0 " }, - { "INT7 INT6 INT5 INT4 INT3 INT2 INT1 INT0 " }, - { "ICP7 ICP6 ICP5 ICP4 ICP3 ICP2 ICP1 ICP0 " }, - { "GP7 GP6 GP5 GP4 GP3 GP2 GP1 GP0 " }, - { "OL7 OL6 OL5 OL4 OL3 OL2 OL1 OL0 " }, }; - byte regAddrB[] = this.getAddrMapSecond8(); + String[] regNameB = {"_IODIRB ", "_IPOLB ", "_GPINTEB", "_DEFVALB", "_INTCONB", "_IOCON ", "_GPPUB ", + "_INTFB ", "_INTCAPB", "_GPIOB ", "_OLATB "}; + String[][] pinName = {{"IO7 IO6 IO5 IO4 IO3 IO2 IO1 IO0"}, + {"IP7 IP6 IP5 IP4 IP3 IP2 IP1 IP0 "}, + {"GPINT7 GPINT6 GPINT5 GPINT4 GPINT3 GPINT2 GPINT1 GPINT0 "}, + {"DEF7 DEF6 DEF5 DEF4 DEF3 DEF2 DEF1 DEF0 "}, + {"IOC7 IOC6 IOC5 IOC4 IOC3 IOC2 IOC1 IOC0 "}, + {"BANK MIRROR SEQOP DISSLW HAEN ODR INTPOL "}, + {"PU7 PU6 PU5 PU4 PU3 PU2 PU1 PU0 "}, + {"INT7 INT6 INT5 INT4 INT3 INT2 INT1 INT0 "}, + {"ICP7 ICP6 ICP5 ICP4 ICP3 ICP2 ICP1 ICP0 "}, + {"GP7 GP6 GP5 GP4 GP3 GP2 GP1 GP0 "}, + {"OL7 OL6 OL5 OL4 OL3 OL2 OL1 OL0 "},}; + byte[] regAddrB = this.getAddrMapSecond8(); this.ffdc.ffdcDebugEntry("this.getAddrMapSecond8() function returned " + this.getAddrMapSecond8()); String regAstr = ""; - int reg ; + int reg; for (int i = 0; i < regName.length; i++) { // this.ffdc.ffdcDebugEntry(" regAddr " + regAddr[i]); // System.out.println(" regAddr " + regAddr[i]); reg = this.readRegister(regAddr[i]); - regAstr = regAstr.concat("\n Reg " + regName[i] + " offset ("+ i + ") data: " + String.format("0x%02X", reg) + "\n"); - int val = reg; + regAstr = regAstr.concat("\n Reg " + regName[i] + " offset (" + i + ") data: " + String.format("0x%02X", reg) + "\n"); + int val = reg; // System.out.println("pin7 pin6 pin5 pin4 pin3 pin2 pin1 pin0"); regAstr = regAstr.concat(pinName[i][0] + "\n"); regAstr = regAstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " - + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " + + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); } this.ffdc.ffdcDebugEntry(regAstr); //System.out.println(regAstr); @@ -179,7 +176,7 @@ public void dumpRegs() { try { Thread.sleep(1000); } catch (InterruptedException e) { - e.printStackTrace(); + e.printStackTrace(); } String regBstr = ""; int regB; @@ -189,15 +186,15 @@ public void dumpRegs() { // System.out.println(" regAddrB " + regAddrB[i]); regB = this.readRegister(regAddrB[i]); - regBstr = regBstr.concat("\n RegB " + regNameB[i] + " offset ("+ i + ") data: " + String.format("0x%02X", regB) + "\n"); - int val = regB; + regBstr = regBstr.concat("\n RegB " + regNameB[i] + " offset (" + i + ") data: " + String.format("0x%02X", regB) + "\n"); + int val = regB; // System.out.println("pin7 pin6 pin5 pin4 pin3 pin2 pin1 // pin0"); regBstr = regBstr.concat(pinName[i][0] + "\n"); regBstr = regBstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) - + " " + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) - + "\n"); + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + + " " + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + + "\n"); } this.ffdc.ffdcDebugEntry(regBstr); //System.out.println(regBstr); @@ -214,23 +211,22 @@ public void pgmSleep(int mills) { public void resetChip() { this.ffdc.ffdcMethodEntry("resetChip "); - this.gpio.resetChip(this.gpioReset,this.pi4j,5000,true, this.ffdc); + this.gpio.resetChip(this.gpioReset, this.pi4j, 5000, true, this.ffdc); this.ffdc.ffdcMethodExit("resetChip"); } /** - * - * @param pin MCP pin to drive - * @param pinOn If true drive HIGH, else drive LOW + * @param pin MCP pin to drive + * @param pinOn If true drive HIGH, else drive LOW */ - public void drivePin(int pin, boolean pinOn){ + public void drivePin(int pin, boolean pinOn) { // get the regs and make sure the desired pin is configed as output. Log // error if not int configed; int b; int reg; int absPin = pin; // if in second bank must subtract 8 - byte first8[] = this.getAddrMapFirst8(); + byte[] first8 = this.getAddrMapFirst8(); byte thisOffsetIOD = first8[this.cfgData._IODIR]; @@ -238,7 +234,7 @@ public void drivePin(int pin, boolean pinOn){ byte thisOffsetOLA = first8[this.cfgData._OLAT]; if (pin > 7) { absPin = absPin - 8; - byte second8[] = this.getAddrMapSecond8(); + byte[] second8 = this.getAddrMapSecond8(); thisOffsetIOD = second8[this.cfgData._IODIRB]; thisOffsetGPI = second8[this.cfgData._GPIOB]; @@ -253,16 +249,16 @@ public void drivePin(int pin, boolean pinOn){ System.out.println("Pin" + pin + " not configured for output"); System.exit(500); } - reg = this.readRegister( thisOffsetGPI); + reg = this.readRegister(thisOffsetGPI); // System.out.println("read GPI " + String.format("0x%02X", reg[0])); if (pinOn) { Integer integerObject = ((1 << absPin)); b = integerObject.byteValue(); - reg = (byte)(reg | b); + reg = (byte) (reg | b); } else { Integer integerObject = (~(1 << absPin)); b = integerObject.byteValue(); - reg = (byte)(reg & b); + reg = (byte) (reg & b); } // System.out.println("write GPI " + String.format("0x%02X", reg[0])); @@ -271,11 +267,11 @@ public void drivePin(int pin, boolean pinOn){ this.writeByte(thisOffsetGPI, (byte) reg); // OLAT - reg = this.readRegister( thisOffsetOLA); + reg = this.readRegister(thisOffsetOLA); if (pinOn) { Integer integerObject = ((1 << absPin)); b = integerObject.byteValue(); - reg = (reg | b); + reg = (reg | b); } else { Integer integerObject = (~(1 << absPin)); b = integerObject.byteValue(); @@ -289,25 +285,24 @@ public void drivePin(int pin, boolean pinOn){ } /** - * - * @param pin MCP pin to read - *

    - * Pin read and detail logged. - *

    - */ - public void readInput(int pin){ + * @param pin MCP pin to read + *

    + * Pin read and detail logged. + *

    + */ + public void readInput(int pin) { // # get the regs and make sure the desired pin is configed as input. // Log error if not int configed; int reg; int absPin = pin; // if in second bank must subtract 8 - byte first8[] = this.getAddrMapFirst8(); + byte[] first8 = this.getAddrMapFirst8(); byte thisOffsetIOD = first8[this.cfgData._IODIR]; byte thisOffsetGPI = first8[this.cfgData._GPIO]; if (pin > 7) { absPin = absPin - 8; - byte second8[] = this.getAddrMapSecond8(); + byte[] second8 = this.getAddrMapSecond8(); thisOffsetIOD = second8[this.cfgData._IODIRB]; thisOffsetGPI = second8[this.cfgData._GPIOB]; } @@ -324,10 +319,10 @@ public void readInput(int pin){ if ((configed & (1 << absPin)) == 0) { this.ffdc.ffdcConfigWarningEntry("Pin" + String.format("0x%02X", pin) + " not configured for input"); - this.ffdc.ffdcErrorExit("Incorrect Pin direction", 510); + this.ffdc.ffdcErrorExit("Incorrect Pin direction", 510); } - reg = this.readRegister( thisOffsetGPI); + reg = this.readRegister(thisOffsetGPI); if ((reg & (1 << absPin)) == 0) { System.out.println("Pin" + pin + " Low"); this.ffdc.ffdcDebugEntry("Pin" + pin + " Low"); @@ -340,27 +335,26 @@ public void readInput(int pin){ /** - * * @param onOff Enable listener if true, else (at present disable not possible) - * @param gpioPin Pi GPIO to apply the listener - * These listen to pi DIO interrupts. If on occurs this pgm handler is - * called. The handler then - * interrogates the 23xxx chip to see which of its pins created the - * interrupt. - *

    - * PreCond: BaseGpioInOut contains a relevant GpioPinCfgData. - * This data supplied by the program user must include gpioPin - * as Input and the needed pullDown value - *

    + * @param gpioPin Pi GPIO to apply the listener + * These listen to pi DIO interrupts. If on occurs this pgm handler is + * called. The handler then + * interrogates the 23xxx chip to see which of its pins created the + * interrupt. + *

    + * PreCond: BaseGpioInOut contains a relevant GpioPinCfgData. + * This data supplied by the program user must include gpioPin + * as Input and the needed pullDown value + *

    */ - public void addListener(String onOff,int gpioPin) { + public void addListener(String onOff, int gpioPin) { // find BCM number for this pin this.ffdc.ffdcMethodEntry(" addListener onOff : " + onOff + " pin" + gpioPin); int intPin = gpioPin; if (onOff.equals("on")) { - this.gpio.getCfgData(intPin).input.addListener((DigitalStateChangeListener) new McpBaseIntrpListener(this)); + this.gpio.getCfgData(intPin).input.addListener(new McpBaseIntrpListener(this)); } else if (onOff.equals("off")) { - ; // cannot remove handler (yet) + // cannot remove handler (yet) } else { this.ffdc.ffdcErrorExit("addListener: invalid onOff", 521); } @@ -368,24 +362,23 @@ public void addListener(String onOff,int gpioPin) { } /** - *

    - * - *

    When a Pi gpio detects a level change, if a Listener is attached, this - * method is called. - *

    - *

    - * The method will examine registers in the MCP chip to determine which - * pin changed and caused the interrupt. When the interrupting pin is - * determined, the processPinInterrupt method in a subclasss is called. - *

    + *

    * + *

    When a Pi gpio detects a level change, if a Listener is attached, this + * method is called. + *

    + *

    + * The method will examine registers in the MCP chip to determine which + * pin changed and caused the interrupt. When the interrupting pin is + * determined, the processPinInterrupt method in a subclasss is called. + *

    * - * @param event DigitalStateChangeEvent + * @param event DigitalStateChangeEvent */ public void intrpHappened(DigitalStateChangeEvent event) { // System.out.println("intrpHappened"); this.ffdc.ffdcMethodEntry( - " intrpHappened : GPIO PIN STATE CHANGE: " + event.state());// figure + " intrpHappened : GPIO PIN STATE CHANGE: " + event.state());// figure // out, which, pins // interrupted int reg; boolean foundIntrBit = false; @@ -393,9 +386,9 @@ public void intrpHappened(DigitalStateChangeEvent event) { int testVal = 0; DigitalState effectedPinState = DigitalState.HIGH; if (this.pin < 8) { - byte first8[] = this.getAddrMapFirst8(); + byte[] first8 = this.getAddrMapFirst8(); - reg = this.readRegister(first8[this.cfgData._INTF]); + reg = this.readRegister(first8[this.cfgData._INTF]); // find the bit (pin) that interrupted this time. testVal = reg; testVal = testVal & 0xff; @@ -408,7 +401,7 @@ public void intrpHappened(DigitalStateChangeEvent event) { pinNum = c; foundIntrBit = true; // get pin state for c + *. Set effectedPinState - reg = this.readRegister( first8[this.cfgData._INTCAP]); + reg = this.readRegister(first8[this.cfgData._INTCAP]); testVal = reg; testVal = testVal & 0xff; if ((testVal >> c) == 1) { @@ -423,9 +416,9 @@ public void intrpHappened(DigitalStateChangeEvent event) { } else { if (this.pin > 7) { // search B bank this.ffdc.ffdcDebugEntry("Pin 8 - 15, inspect _INTCAPB "); - byte second8[] = this.getAddrMapSecond8(); + byte[] second8 = this.getAddrMapSecond8(); - reg = this.readRegister( second8[this.cfgData._INTFB]); + reg = this.readRegister(second8[this.cfgData._INTFB]); // find the bit (pin) that interrupted this time. testVal = reg; testVal = testVal & 0xff; @@ -452,40 +445,41 @@ public void intrpHappened(DigitalStateChangeEvent event) { } } // pin 8-15 - if (foundIntrBit == false) { + if (!foundIntrBit) { this.ffdc.ffdcDebugEntry("Bit not found in _INTF(B) "); } else { - String[] pinList = { "pin0", "pin1", "pin2", "pin3", "pin4", "pin5", "pin6", "pin7", "pin8", "pin9", - "pin10", "pin11", "pin12", "pin13", "pin14", "pin15" }; + String[] pinList = {"pin0", "pin1", "pin2", "pin3", "pin4", "pin5", "pin6", "pin7", "pin8", "pin9", + "pin10", "pin11", "pin12", "pin13", "pin14", "pin15"}; if (event.state() == DigitalState.LOW) { this.ffdc.ffdcDebugEntry(" McpBase GPIO " + pinNum + " LOW, chip pin: " + pinList[pinNum] - + " State: " + effectedPinState); + + " State: " + effectedPinState); } else { this.ffdc.ffdcDebugEntry(" McpBase GPIO " + pinNum + " HIGH, chip pin: " + pinList[pinNum] - + " State: " + effectedPinState); + + " State: " + effectedPinState); } if (this.pin == pinNum) { this.processPinInterrupt(pinNum, effectedPinState, this.ffdc); } else { this.ffdc.ffdcDebugEntry( - " McpBase effected pin: " + pinNum + " is not our monitored pin: " + this.pin); + " McpBase effected pin: " + pinNum + " is not our monitored pin: " + this.pin); } this.intrptCount++; this.ffdc.ffdcDebugEntry( - "Interrupt occured " + " interrupt count : " + String.format("0x%02X", this.intrptCount)); + "Interrupt occured " + " interrupt count : " + String.format("0x%02X", this.intrptCount)); } this.ffdc.ffdcMethodExit(" intrpHappened"); } /** *

    - * The McpBase subclass installed event handler will have control. + * The McpBase subclass installed event handler will have control. *

    - * @param pinNum MVP pin causing the interrupt - * @param pinState Pi Gpio pin state detected - * @param ffdc logging - * @return true if interrupt processed, false if failed + * + * @param pinNum MVP pin causing the interrupt + * @param pinState Pi Gpio pin state detected + * @param ffdc logging + * @return true if interrupt processed, false if failed */ public boolean processPinInterrupt(int pinNum, DigitalState pinState, FfdcUtil ffdc) { boolean rval = false; @@ -499,12 +493,12 @@ public boolean processPinInterrupt(int pinNum, DigitalState pinState, FfdcUtil f // , -b bus, -a address public void usage() { System.out.println("options -h 'help', -d drive-pin with -o ON/OFF, " - + "-r read-pin , -k \"{'dir':'out','int_ena':'no'}\" (using -d or -r)" - + "-m \"{'pin1':{'dir':'in','pull':'down','default':'0','do_compare':'yes','int_ena':'yes','act':'high'}}\"" - + "-p (uses compiled in pin data) " + "-c primary chip -p primary pin" - + "-z gpios config dict -q mainChip" - + "Interrupt detect via gpio -p, monitoring pin -p -g gpio, -i on./off " + - " -x reset-chip -n resetPin -f ffdc_lvl -y dumpRegs "); + + "-r read-pin , -k \"{'dir':'out','int_ena':'no'}\" (using -d or -r)" + + "-m \"{'pin1':{'dir':'in','pull':'down','default':'0','do_compare':'yes','int_ena':'yes','act':'high'}}\"" + + "-p (uses compiled in pin data) " + "-c primary chip -p primary pin" + + "-z gpios config dict -q mainChip" + + "Interrupt detect via gpio -p, monitoring pin -p -g gpio, -i on./off " + + " -x reset-chip -n resetPin -f ffdc_lvl -y dumpRegs "); } /** @@ -518,9 +512,9 @@ public ShutDownTask(McpBase mcp) { public void run() { System.out.println("Performing ctl-C shutdown"); // TODO - // this.ffdc.ffdcFlushShutdown(); // push all logs to the file + // this.ffdc.ffdcFlushShutdown(); // push all logs to the file // Shutdown Pi4J - // pi4j.shutdown(); + // pi4j.shutdown(); } @@ -570,9 +564,8 @@ public void run() { public Mcp23xxxParms parmsObj; - public class McpBaseIntrpListener implements DigitalStateChangeListener { - ; + public McpBaseIntrpListener(McpBase chip) { this.chip = chip; Runtime.getRuntime().addShutdownHook(new Thread() { @@ -595,9 +588,9 @@ public void onDigitalStateChange(DigitalStateChangeEvent event) { this.chip.intrpHappened(event); } } - McpBase chip; - } + McpBase chip; + } } diff --git a/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpConfigData.java b/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpConfigData.java index 8459a3c..07e2038 100644 --- a/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpConfigData.java +++ b/src/main/java/com/pi4j/devices/mcp23xxxCommon/McpConfigData.java @@ -51,7 +51,8 @@ public class McpConfigData { /** * CTOR - * @param ffdc logginf + * + * @param ffdc logginf */ public McpConfigData(FfdcUtil ffdc) { @@ -70,7 +71,6 @@ public void init() { } - // # Offset into data from getAddrMapFirst8(); and getAddrMapSecond8() . // This is the register address based on // PCA and whether banked-23017 @@ -102,7 +102,8 @@ public void init() { /** * Unit testing - * @return HashMap + * + * @return HashMap */ public HashMap> getFullMap() { this.ffdc.ffdcMethodEntry("getFullMap"); @@ -113,6 +114,7 @@ public HashMap> getFullMap() { /** * Unit testing + * * @param newMap */ public void replaceMap(HashMap> newMap) { @@ -124,22 +126,22 @@ public void replaceMap(HashMap> newMap) { /** * Unit testing. Dump and pretty print HashMap - */ + */ public void DumpGpiosConfig() { this.ffdc.ffdcMethodEntry("mcpConfigure::DumpGpiosConfig (program details)"); HashMap> outerMap = this.getFullMap(); Set outerSet = outerMap.entrySet(); Iterator>> outerIterator = outerSet.iterator(); while (outerIterator.hasNext()) { - Map.Entry> mentry = (Map.Entry) outerIterator.next(); - this.ffdc.ffdcDebugEntry("key is: " + mentry.getKey() ); + Map.Entry> mentry = outerIterator.next(); + this.ffdc.ffdcDebugEntry("key is: " + mentry.getKey()); // System.out.println(mentry.getValue()); // iterate inner map HashMap innerMap = new HashMap(); Iterator> child = (mentry.getValue()).entrySet().iterator(); while (child.hasNext()) { Map.Entry childPair = child.next(); - this.ffdc.ffdcDebugEntry("childPair: " + childPair.getKey() + " -> " + childPair.getValue()); + this.ffdc.ffdcDebugEntry("childPair: " + childPair.getKey() + " -> " + childPair.getValue()); } } this.ffdc.ffdcMethodExit("DumpGpiosConfig"); @@ -149,5 +151,4 @@ public void DumpGpiosConfig() { FfdcUtil ffdc; - } diff --git a/src/main/java/com/pi4j/devices/mcp3008/MCP3008.java b/src/main/java/com/pi4j/devices/mcp3008/MCP3008.java index 201d487..be45603 100644 --- a/src/main/java/com/pi4j/devices/mcp3008/MCP3008.java +++ b/src/main/java/com/pi4j/devices/mcp3008/MCP3008.java @@ -31,20 +31,21 @@ public MCP3008(Context pi4j, SpiBus spiBus, SpiChipSelect chipSelect, short pinC } - private void init(){ + private void init() { var spiConfig = Spi.newConfigBuilder(pi4j) - .id("SPI" + spiBus + " " + chipSelect) - .name("A/D converter") - .bus(spiBus) - .chipSelect(chipSelect) - .flags(0b0000000000000000000000L) - .baud(Spi.DEFAULT_BAUD) - .mode(SpiMode.MODE_0) - .provider("pigpio-spi") - .build(); + .id("SPI" + spiBus + " " + chipSelect) + .name("A/D converter") + .bus(spiBus) + .chipSelect(chipSelect) + .flags(0b0000000000000000000000L) + .baud(Spi.DEFAULT_BAUD) + .mode(SpiMode.MODE_0) + .provider("pigpio-spi") + .build(); this.spi = this.pi4j.create(spiConfig); } + public void displayProgramID() { // print program title/header this.logger.trace(">>> Enter displayProgramID"); @@ -127,18 +128,18 @@ public int getConversionValue(short channel) throws IOException { this.logger.trace(">>> Enter getConversionValue channel : " + channel); // create a data buffer and initialize a conversion request payload - byte data[] = new byte[]{(byte) 0b00000001, // first byte, start bit - (byte) (0b10000000 | (((channel & 7) << 4))), // second byte - // transmitted - // -> (SGL/DIF = - // 1, - // D2=D1=D0=0) - (byte) 0b00000000 // third byte transmitted....don't care + byte[] data = new byte[]{(byte) 0b00000001, // first byte, start bit + (byte) (0b10000000 | (((channel & 7) << 4))), // second byte + // transmitted + // -> (SGL/DIF = + // 1, + // D2=D1=D0=0) + (byte) 0b00000000 // third byte transmitted....don't care }; // send conversion request to ADC chip via SPI channel //int bytesWritten = this.spi.write(data); - byte value[] = new byte[3]; + byte[] value = new byte[3]; int bytesRead = this.spi.transfer(data, 0, value, 0, 3); @@ -147,7 +148,8 @@ public int getConversionValue(short channel) throws IOException { // to get 10-bit result result |= (value[2] & 0xff); this.logger.info("Channel : " + channel + " Bytes read : " + bytesRead + " Value : " + result); - if(this.vref > 0){this.logger.info("A/D read input voltage : "+ ((result * this.vref )/1024 + " \n")); + if (this.vref > 0) { + this.logger.info("A/D read input voltage : " + ((result * this.vref) / 1024 + " \n")); } this.logger.trace("<<< Exit getConversionValue "); @@ -163,7 +165,7 @@ public int getConversionValue(short channel) throws IOException { private boolean doallChannels = false; private short channel; private Spi spi; - private Console console; + private final Console console; private final String traceLevel; private final Logger logger; @@ -171,7 +173,7 @@ public int getConversionValue(short channel) throws IOException { private final SpiChipSelect chipSelect; private final SpiBus spiBus; - private Context pi4j; + private final Context pi4j; } diff --git a/src/main/java/com/pi4j/devices/mcp3008/MCP3008App.java b/src/main/java/com/pi4j/devices/mcp3008/MCP3008App.java index 376eadf..bad49b3 100644 --- a/src/main/java/com/pi4j/devices/mcp3008/MCP3008App.java +++ b/src/main/java/com/pi4j/devices/mcp3008/MCP3008App.java @@ -3,10 +3,8 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; import com.pi4j.io.exception.IOException; -import com.pi4j.io.spi.Spi; import com.pi4j.io.spi.SpiBus; import com.pi4j.io.spi.SpiChipSelect; -import com.pi4j.io.spi.SpiMode; import com.pi4j.util.Console; public class MCP3008App { @@ -21,15 +19,15 @@ public static void main(String[] args) throws InterruptedException, IOException short pinNumber = 0; double vref = 0; - + SpiChipSelect chipSelect = SpiChipSelect.CS_0; SpiBus spiBus = SpiBus.BUS_0; console.title("<-- The Pi4J V2 Project Extension -->", "MCP3008App"); String helpString = " parms: -p HEX value pinToRead 0, the will display calculated Channel input voltage. +3. sudo ./runMcp3008.sh +-vref option: if > 0, the will display calculated Channel input voltage. -To monitor all pins 0 Vref of 5.0 volts -sudo ./runMcp3008.sh -vref 5.0 - +To monitor all pins 0 Vref of 5.0 volts +sudo ./runMcp3008.sh -vref 5.0 To monitor only pin 0 -sudo ./runMcp3008.sh -p 0x0 - -Change the logging detail to 'trace' vref voltage of 3.3 -sudo ./runMcp3008.sh -p 0x0 -t trace -vref 3.3 +sudo ./runMcp3008.sh -p 0x0 +Change the logging detail to 'trace' vref voltage of 3.3 +sudo ./runMcp3008.sh -p 0x0 -t trace -vref 3.3 Use SPI 1 sudo ./runMcp3008.sh -p 0x0 -s 0x01 - Use ChipSelect 1 sudo ./runMcp3008.sh -p 0x0 -c 0x01 - - sudo ./runMcp3008.sh -p 0x0 -c 0x00 -INFO com.pi4j.devices.mcp3008.MCP3008 - Channel : 0 Bytes read : 3 Value : 1023 - - +INFO com.pi4j.devices.mcp3008.MCP3008 - Channel : 0 Bytes read : 3 Value : 1023 sudo ./runMcp3008.sh -p 0x01 -INFO com.pi4j.devices.mcp3008.MCP3008 - Channel : 1 Bytes read : 3 Value : 647 +INFO com.pi4j.devices.mcp3008.MCP3008 - Channel : 1 Bytes read : 3 Value : 647 diff --git a/src/main/java/com/pi4j/devices/mcp4725/MCP4725.java b/src/main/java/com/pi4j/devices/mcp4725/MCP4725.java index c20b65b..89c0c52 100644 --- a/src/main/java/com/pi4j/devices/mcp4725/MCP4725.java +++ b/src/main/java/com/pi4j/devices/mcp4725/MCP4725.java @@ -38,7 +38,6 @@ import com.pi4j.context.Context; import com.pi4j.io.i2c.I2C; -import com.pi4j.io.i2c.I2CRegister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -81,17 +80,17 @@ public MCP4725(Context pi4j, int bus, int address, int registerData, String trac I2C createI2cDevice(int bus, int address) { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); - this.logger.trace("Enter: createI2cDevice MCP4725 DAC " + id + "" + name); + this.logger.trace("Enter: createI2cDevice MCP4725 DAC " + id + name); I2C rval = null; var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id("MCP4725_DAC " + id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id("MCP4725_DAC " + id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); rval = this.pi4j.create(i2cDeviceConfig); - this.logger.trace("Exit: createI2cDevice MCP4725 DAC " + id + "" + name); + this.logger.trace("Exit: createI2cDevice MCP4725 DAC " + id + name); return (rval); } @@ -124,20 +123,20 @@ void resetChip() { boolean setOutputVoltEEPROM(float twelveBitData) { this.logger.trace(">>> Enter: setOutputVoltEEPROM data : " + twelveBitData); boolean rval = false; - int twelveBit = (int) Math.round((twelveBitData *4096)/ this.vref) - 1; + int twelveBit = (int) Math.round((twelveBitData * 4096) / this.vref) - 1; rval = this.setOutputEEPROM(twelveBit); this.logger.trace("<<< Exit: setOutputVoltEEPROM : " + rval); return (rval); } - boolean setOutputEEPROM(int twelveBitData) { + boolean setOutputEEPROM(int twelveBitData) { boolean rval = false; this.registerData = twelveBitData; String binaryString = Integer.toBinaryString(this.registerData & 0xff); String withLeadingZeros = String.format("0b%12s", binaryString).replace(' ', '0'); this.logger.trace(">>> Enter: setOutputEEPROM data : " + withLeadingZeros + " " + this.registerData); if (this.chipIdle()) { - byte data[] = new byte[MCP4725_Declares._MCP4725_SET_EEPROM_SIZE]; + byte[] data = new byte[MCP4725_Declares._MCP4725_SET_EEPROM_SIZE]; data[0] = (byte) (data[0] | MCP4725_Declares._MCP4725_WRITE_CMD_DAC_EEPROM | MCP4725_Declares._MCP4725_PD_MODE_NORMAL); data[1] = (byte) ((this.registerData & 0x0ff0) >> 4); data[2] = (byte) ((this.registerData & 0x000f) << 4); @@ -149,14 +148,14 @@ boolean setOutputEEPROM(int twelveBitData) { } else { this.logger.info("setOutputEEPROM not possible, chip BSY "); } - this.logger.trace("<<< Exit: setOutputEEPROM :" + rval); + this.logger.trace("<<< Exit: setOutputEEPROM :" + rval); return (rval); } boolean setOutputVoltFast(float twelveBitData) { this.logger.trace(">>> Enter: setOutputVoltFast data : " + twelveBitData); boolean rval = false; - int twelveBit = (int) Math.round((twelveBitData *4096)/ this.vref) - 1; + int twelveBit = (int) Math.round((twelveBitData * 4096) / this.vref) - 1; rval = this.setOutputFast(twelveBit); this.logger.trace("<<< Exit: setOutputVoltFast : " + rval); return (rval); @@ -169,7 +168,7 @@ boolean setOutputFast(int twelveBitData) { String withLeadingZeros = String.format("0b%12s", binaryString).replace(' ', '0'); this.logger.trace(">>> Enter: setOutputFast data : " + withLeadingZeros + " " + this.registerData); if (this.chipIdle()) { - byte data[] = new byte[MCP4725_Declares._MCP4725_SET_FAST_SIZE]; + byte[] data = new byte[MCP4725_Declares._MCP4725_SET_FAST_SIZE]; data[0] = (byte) (data[0] | MCP4725_Declares._MCP4725_WRITE_CMD_FAST | MCP4725_Declares._MCP4725_PD_MODE_NORMAL); data[0] = (byte) (data[0] | (byte) ((this.registerData & 0x0f00) >> 8)); data[1] = (byte) (this.registerData & 0x00ff); @@ -203,9 +202,9 @@ boolean chipIdle() { void dumpChip() { this.logger.trace(">>> Enter: dumpChip "); - int data[]; + int[] data; // allow time for a possible EEPROM update to complete - if (this.chipIdle() == false) { + if (!this.chipIdle()) { this.logger.trace("Wait for EEPROM to complete and test COMPLETED one more time "); this.sleepMS(55); } @@ -213,14 +212,14 @@ void dumpChip() { if (this.chipIdle()) { data = this.readBuffer(MCP4725_Declares._MCP4725_CHIP_READ_SIZE); String info = " RAW chip data \n"; - for (int i = 0; i < data.length; i++){ - info = info + String.format("0x%08x ", data[i]) +" "; + for (int i = 0; i < data.length; i++) { + info = info + String.format("0x%08x ", data[i]) + " "; } // possibly class was instantiated with registerData of 0. If so, we need to // prime this state for possible dump procedure - if(this.registerData == 0 ){ + if (this.registerData == 0) { this.logger.trace("Prime registerData state"); - this.registerData = ((data[1] & 0xff)<<4) + ((data[2]&0xf0) >> 4); + this.registerData = ((data[1] & 0xff) << 4) + ((data[2] & 0xf0) >> 4); } info = info + "\n"; this.logger.info(info); @@ -242,27 +241,27 @@ void prettyPrint(int[] data, int bytesData) { outP = outP + " chip Incomplete state \n"; } outP = outP + " PD1: " + (data[0] & MCP4725_Declares._MCP4725_DAC_PD1_MODE_MASK) - + " PD0: " + (data[0] & MCP4725_Declares._MCP4725_DAC_PD0_MODE_MASK) + " \n"; + + " PD0: " + (data[0] & MCP4725_Declares._MCP4725_DAC_PD0_MODE_MASK) + " \n"; String binaryString = Integer.toBinaryString(data[1] & 0xff); String withLeadingZeros = String.format("%8s", binaryString).replace(' ', '0'); - outP = outP + " Second byte DAC D11...D4 : "+ withLeadingZeros + " \n"; + outP = outP + " Second byte DAC D11...D4 : " + withLeadingZeros + " \n"; String binaryString2 = Integer.toBinaryString((data[2] & 0xf0) >> 4); String withLeadingZeros2 = String.format("%4s", binaryString2).replace(' ', '0'); outP = outP + " Third byte DAC D3...D0 : " + withLeadingZeros2 + " \n"; int a1 = ((data[2] & 0xf0) >> 4); - int b1 = ((data[1] & 0xff) << 4); + int b1 = ((data[1] & 0xff) << 4); int c1 = a1 + b1; - outP = outP + " 12bit DAC :" + String.format("%04x ", c1) + " \n"; - if(this.vref > 0){ - outP = outP + " Calculated DAC output voltage : "+ ((this.vref*this.registerData)/4096 + " \n"); + outP = outP + " 12bit DAC :" + String.format("%04x ", c1) + " \n"; + if (this.vref > 0) { + outP = outP + " Calculated DAC output voltage : " + ((this.vref * this.registerData) / 4096 + " \n"); } outP = outP + " First byte EEPROM \n"; outP = outP + " PD1: " + (data[3] & MCP4725_Declares._MCP4725_EEPROM_PD1_MODE_MASK) - + " PD0: " + (data[3] & MCP4725_Declares._MCP4725_EEPROM_PD0_MODE_MASK) + " \n"; + + " PD0: " + (data[3] & MCP4725_Declares._MCP4725_EEPROM_PD0_MODE_MASK) + " \n"; String binaryString3 = Integer.toBinaryString(data[3] & 0x0f); @@ -272,11 +271,11 @@ void prettyPrint(int[] data, int bytesData) { String withLeadingZeros4 = String.format("%8s", binaryString4).replace(' ', '0'); outP = outP + " Third byte EEPROM D7...D0 : " + withLeadingZeros4 + " \n"; int a = (data[4] & 0xff); - int b = ((data[3] & 0x0f)<<8); + int b = ((data[3] & 0x0f) << 8); int c = a + b; - outP = outP + " 12bit EEPROM : " + String.format("%04x ", c) + "\n" ; - if(this.vref > 0){ - outP = outP + " Calculated EEPROM output voltage : "+ ((this.vref * c)/4096 + " \n"); + outP = outP + " 12bit EEPROM : " + String.format("%04x ", c) + "\n"; + if (this.vref > 0) { + outP = outP + " Calculated EEPROM output voltage : " + ((this.vref * c) / 4096 + " \n"); } this.logger.info(outP); @@ -285,8 +284,6 @@ void prettyPrint(int[] data, int bytesData) { } - - /** * @param mSecs Time to sleep this thread */ @@ -317,14 +314,10 @@ int[] readBuffer(int readLen) { } - - - - private final Context pi4j; private final int bus; private final int address; - private I2C device; + private final I2C device; private final Logger logger; private final String traceLevel; diff --git a/src/main/java/com/pi4j/devices/mcp4725/MCP4725_App.java b/src/main/java/com/pi4j/devices/mcp4725/MCP4725_App.java index cd1c076..28d9c76 100644 --- a/src/main/java/com/pi4j/devices/mcp4725/MCP4725_App.java +++ b/src/main/java/com/pi4j/devices/mcp4725/MCP4725_App.java @@ -38,12 +38,8 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.devices.mcp4725.MCP4725; -import com.pi4j.devices.mcp4725.MCP4725_Declares; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; + public class MCP4725_App { @@ -55,19 +51,6 @@ public static void main(String[] args) { /* var pi4j = Pi4J.newContextBuilder().add( linuxfs-i2cProvider.newInstance()).build(); */ - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); final Console console = new Console(); @@ -89,11 +72,11 @@ public void handle(Signal sig) { float fastVolt = 0; String helpString = " parms: -b 0x? hex value bus -a 0x?? hex value address -t trace \n " + - " -r reset chip -d dumpChipData -rde 0x???? update DAC and EEPROM \n" + - " -ev eeprom voltage -fv fast voltage \n" + - " -rdf 0x????update DAC fast -vref decimal reference voltage\n " + - " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; + " -r reset chip -d dumpChipData -rde 0x???? update DAC and EEPROM \n" + + " -ev eeprom voltage -fv fast voltage \n" + + " -rdf 0x????update DAC fast -vref decimal reference voltage\n " + + " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { @@ -120,39 +103,39 @@ public void handle(Signal sig) { console.println("Changing trace level invalid : " + traceLevel); System.exit(40); } - } else if (o.contentEquals("-r")) { + } else if (o.contentEquals("-r")) { doReset = true; - } else if (o.contentEquals("-d")) { + } else if (o.contentEquals("-d")) { dumpChip = true; - } else if (o.contentEquals("-rde")) { + } else if (o.contentEquals("-rde")) { String a = args[i + 1]; i++; - registerData = (Integer.parseInt(a.substring(2), 16) ); + registerData = (Integer.parseInt(a.substring(2), 16)); setOutputEEPROM = true; - if(registerData > 0x0fff){ + if (registerData > 0x0fff) { console.println("-rde cannot exceed 0x0fff"); System.exit(36); } - } else if (o.contentEquals("-rdf")) { + } else if (o.contentEquals("-rdf")) { String a = args[i + 1]; i++; setOutputFast = true; - registerData = (Integer.parseInt(a.substring(2), 16) ); - if(registerData > 0x0fff){ + registerData = (Integer.parseInt(a.substring(2), 16)); + if (registerData > 0x0fff) { console.println("-rdf cannot exceed 0x0fff"); System.exit(37); } - }else if (o.contentEquals("-h")) { + } else if (o.contentEquals("-h")) { console.println(helpString); System.exit(39); } else if (o.contentEquals("-fv")) { // eeprom volts String a = args[i + 1]; i++; - eepromVolt = Float.parseFloat(a); - } else if (o.contentEquals("-ev")) { // fast volts + eepromVolt = Float.parseFloat(a); + } else if (o.contentEquals("-ev")) { // fast volts String a = args[i + 1]; i++; - fastVolt = Float.parseFloat(a); + fastVolt = Float.parseFloat(a); } else { console.println(" !!! Invalid Parm " + args); console.println(helpString); @@ -161,19 +144,18 @@ public void handle(Signal sig) { } - - if(vref == 0){ + if (vref == 0) { console.println("-vref is zero"); System.exit(50); } - if(eepromVolt > vref){ + if (eepromVolt > vref) { console.println("-ev greater than -vref"); System.exit(51); } - if(fastVolt > vref){ + if (fastVolt > vref) { console.println("-ef greater than -vref"); System.exit(51); @@ -185,36 +167,36 @@ public void handle(Signal sig) { dacChip.resetChip(); } - if(setOutputEEPROM){ + if (setOutputEEPROM) { boolean worked = dacChip.setOutputEEPROM(registerData); - if(worked == false){ + if (!worked) { console.println("setOutputEEPROM failed"); } } - if(setOutputFast){ + if (setOutputFast) { boolean worked = dacChip.setOutputFast(registerData); - if(worked == false){ + if (!worked) { console.println("setOutputFast failed"); } } - if(eepromVolt > 0){ + if (eepromVolt > 0) { boolean worked = dacChip.setOutputVoltEEPROM(eepromVolt); - if(worked == false){ + if (!worked) { console.println("setOutputVoltEEPROM failed"); } } - if(fastVolt > 0){ + if (fastVolt > 0) { boolean worked = dacChip.setOutputVoltFast(fastVolt); - if(worked == false){ + if (!worked) { console.println("setOutputVoltFast failed"); } } - if(dumpChip){ + if (dumpChip) { dacChip.dumpChip(); } } diff --git a/src/main/java/com/pi4j/devices/mcp4725/MCP4725_Declares.java b/src/main/java/com/pi4j/devices/mcp4725/MCP4725_Declares.java index def4957..f931fa9 100644 --- a/src/main/java/com/pi4j/devices/mcp4725/MCP4725_Declares.java +++ b/src/main/java/com/pi4j/devices/mcp4725/MCP4725_Declares.java @@ -37,35 +37,35 @@ package com.pi4j.devices.mcp4725; public class MCP4725_Declares { - public static final int _MCP4725_DEFAULT_ADDRESS = 0x62; + public static final int _MCP4725_DEFAULT_ADDRESS = 0x62; - public static final int _MCP4725_SET_EEPROM_SIZE = 0x06; - public static final int _MCP4725_SET_FAST_SIZE = 0x04; - public static final int _MCP4725_CHIP_READ_SIZE = 0x05; + public static final int _MCP4725_SET_EEPROM_SIZE = 0x06; + public static final int _MCP4725_SET_FAST_SIZE = 0x04; + public static final int _MCP4725_CHIP_READ_SIZE = 0x05; - public static final byte _MCP4725_WRITE_CMD_FAST = 0b00000000; - public static final byte _MCP4725_WRITE_CMD_DAC = 0b01000000; - public static final byte _MCP4725_WRITE_CMD_DAC_EEPROM = 0b01100000; + public static final byte _MCP4725_WRITE_CMD_FAST = 0b00000000; + public static final byte _MCP4725_WRITE_CMD_DAC = 0b01000000; + public static final byte _MCP4725_WRITE_CMD_DAC_EEPROM = 0b01100000; - public static final byte _MCP4725_PD_MODE_NORMAL = 0b00000000; - public static final byte _MCP4725_PD_MODE_INOPT = 0b00000110; + public static final byte _MCP4725_PD_MODE_NORMAL = 0b00000000; + public static final byte _MCP4725_PD_MODE_INOPT = 0b00000110; - public static final byte _MCP4725_DAC_PD0_MODE_MASK = 0b00000010; - public static final byte _MCP4725_DAC_PD1_MODE_MASK = 0b00000100; + public static final byte _MCP4725_DAC_PD0_MODE_MASK = 0b00000010; + public static final byte _MCP4725_DAC_PD1_MODE_MASK = 0b00000100; - public static final int _MCP4725_EEPROM_PD1_MODE_MASK = 0b10000000; - public static final byte _MCP4725_EEPROM_PD0_MODE_MASK = 0b01000000; + public static final int _MCP4725_EEPROM_PD1_MODE_MASK = 0b10000000; + public static final byte _MCP4725_EEPROM_PD0_MODE_MASK = 0b01000000; // Indicate EEPROM write/update status - public static final byte _MCP4725_READ_CMD_RDY_BSY_MSK = (byte) 0b10000000; - public static final byte _MCP4725_READ_CMD_IS_COMPLT = (byte) 0b10000000; - public static final byte _MCP4725_READ_CMD_IS_NOT_COMPLT = (byte) 0b00000000; + public static final byte _MCP4725_READ_CMD_RDY_BSY_MSK = (byte) 0b10000000; + public static final byte _MCP4725_READ_CMD_IS_COMPLT = (byte) 0b10000000; + public static final byte _MCP4725_READ_CMD_IS_NOT_COMPLT = (byte) 0b00000000; // POR device load EEPROM - public static final byte _MCP4725_GEN_CALL_RESET_CMD = (byte) 0b00000110; + public static final byte _MCP4725_GEN_CALL_RESET_CMD = (byte) 0b00000110; // POR device PD1 and PD0 set to 0 for normal operation - public static final byte _MCP4725_GEN_CALL_WAKEUP_CMD = (byte) 0b00001001; + public static final byte _MCP4725_GEN_CALL_WAKEUP_CMD = (byte) 0b00001001; // Write diff --git a/src/main/java/com/pi4j/devices/mcp4725/README.md b/src/main/java/com/pi4j/devices/mcp4725/README.md index 05cd622..5f68bd9 100644 --- a/src/main/java/com/pi4j/devices/mcp4725/README.md +++ b/src/main/java/com/pi4j/devices/mcp4725/README.md @@ -7,20 +7,17 @@ Project by Tom Aarts Adafruit MCP4725 - Pi 5V Vin - Pi Grnd GND - Pi Pin5 SCL - Pi Pin3 SDA - Pi Grnd A0 - MCP3008 ch7 Vout - - +Pi 5V Vin +Pi Grnd GND +Pi Pin5 SCL +Pi Pin3 SDA +Pi Grnd A0 +MCP3008 ch7 Vout 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runMCP4725.sh parms........ - https://datasheetspdf.com/pdf-file/634126/MicrochipTechnology/MCP4725/1 -rde anf -rdf both have max input value 0x0FFF @@ -29,38 +26,34 @@ https://datasheetspdf.com/pdf-file/634126/MicrochipTechnology/MCP4725/1 -vref option: the -d feature will display calculated output voltage. -Updates using raw binary value -To Update DAC and EEPROM, set to 50 % of reference voltage Vin of 5 volts - -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rde 0x7ff -vref 5.0 +Updates using raw binary value +To Update DAC and EEPROM, set to 50 % of reference voltage Vin of 5 volts +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rde 0x7ff -vref 5.0 -To Update DAC Fast, set to 50 % of reference voltage -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rdf 0x7ff -vref 5.0 - -To Update DAC Fast, set to 50 % of reference voltage Set trace level 'off' -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rdf 0x07ff -t off -vref 5.0 - -To Update DAC Fast, set to 50 % of reference voltage, reset chip, dump DAC and EEPROM -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rdf 0x07ff -r -d -vref 5.0 +To Update DAC Fast, set to 50 % of reference voltage +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rdf 0x7ff -vref 5.0 +To Update DAC Fast, set to 50 % of reference voltage Set trace level 'off' +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rdf 0x07ff -t off -vref 5.0 +To Update DAC Fast, set to 50 % of reference voltage, reset chip, dump DAC and EEPROM +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -rdf 0x07ff -r -d -vref 5.0 Updates using voltage value -To Update DAC and EEPROM, set to 50 % of reference voltage Vin of 5 volts - -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -fv 2 -vref 5.0 +To Update DAC and EEPROM, set to 50 % of reference voltage Vin of 5 volts +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -fv 2 -vref 5.0 -To Update DAC Fast, set to 50 % of reference voltage -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -fv 1.8 -vref 5.0 +To Update DAC Fast, set to 50 % of reference voltage +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -fv 1.8 -vref 5.0 -To Update DAC Fast, set to 50 % of reference voltage Set trace level 'off' -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -ev 5.0 -t off -vref 5.0 +To Update DAC Fast, set to 50 % of reference voltage Set trace level 'off' +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -ev 5.0 -t off -vref 5.0 -To Update DAC Fast, set to 50 % of reference voltage, reset chip, dump DAC and EEPROM -sudo ./runMCP4725.sh -b 0x01 -a 0x62 -ev 3.1 -r -d -vref 5.0 +To Update DAC Fast, set to 50 % of reference voltage, reset chip, dump DAC and EEPROM +sudo ./runMCP4725.sh -b 0x01 -a 0x62 -ev 3.1 -r -d -vref 5.0 diff --git a/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2.java b/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2.java index f5cbfd5..b480df5 100644 --- a/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2.java +++ b/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2.java @@ -37,7 +37,6 @@ package com.pi4j.devices.mpl3115a2; import com.pi4j.context.Context; - import com.pi4j.io.gpio.digital.*; import com.pi4j.io.i2c.I2C; import com.pi4j.io.i2c.I2CConfig; @@ -47,18 +46,16 @@ /** - * Implementation for the MPL3115A2 sensor. Chip is altitude, pressure and - * temperature capable. - * - * Code uses the basic sampling procedures using GPIO to indicate drdy, data ready. - * The code does not support setting limits that signal interrupts when surpassed. - * - * Java docs are sparse as the method names describe the intended - * function to be performed. - * - * https://www.nxp.com/docs/en/data-sheet/MPL3115A2.pdf - * - * + * Implementation for the MPL3115A2 sensor. Chip is altitude, pressure and + * temperature capable. + *

    + * Code uses the basic sampling procedures using GPIO to indicate drdy, data ready. + * The code does not support setting limits that signal interrupts when surpassed. + *

    + * Java docs are sparse as the method names describe the intended + * function to be performed. + *

    + * https://www.nxp.com/docs/en/data-sheet/MPL3115A2.pdf */ public class MPL3115A2 { @@ -80,9 +77,8 @@ public class MPL3115A2 { public static final String I2C_PROVIDER_ID = ID + "-i2c"; - - private Logger logger = null; - private String traceLevel = null; + private Logger logger = null; + private String traceLevel = null; // local/internal I2C reference for communication with hardware chip @@ -104,7 +100,7 @@ public class MPL3115A2 { /** - * @param pi4j Context instance used acccross application + * @param pi4j Context instance used acccross application * @param console * @param bus * @param address @@ -112,7 +108,7 @@ public class MPL3115A2 { * @param int2_gpio * @param traceLevel */ - public MPL3115A2(Context pi4j, Console console, int bus, int address,int int1_gpio, int int2_gpio, String traceLevel) { + public MPL3115A2(Context pi4j, Console console, int bus, int address, int int1_gpio, int int2_gpio, String traceLevel) { super(); this.pi4j = pi4j; this.address = address; @@ -125,7 +121,7 @@ public MPL3115A2(Context pi4j, Console console, int bus, int address,int int1_gp // must fully qualify logger as others exist and the slf4 code will use the first it // encounters if using the defaultLogLevel System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "TRACE"); - + System.setProperty("org.slf4j.simpleLogger.log." + MPL3115A2.class.getName(), this.traceLevel); this.logger = LoggerFactory.getLogger(MPL3115A2.class); @@ -135,7 +131,6 @@ public MPL3115A2(Context pi4j, Console console, int bus, int address,int int1_gp } - /** * @return i2c state */ @@ -159,53 +154,53 @@ private void createI2cDevice() { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id(id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id(id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); this.config = i2cDeviceConfig; this.i2c = this.pi4j.create(i2cDeviceConfig); this.logger.trace("<<< Exit:createI2cDevice "); } -private void init(){ - this.logger.trace(">>> Enter: init"); - - var ledConfigIntr = DigitalInput.newConfigBuilder(pi4j) - .id("Interrupt_1") - .name("Interrupt_1_TW_PW") - .address(this.int1_gpio) - .pull(PullResistance.OFF) - .debounce(4000L) - .provider("gpiod-digital-input"); - try { - this.int1 = pi4j.create(ledConfigIntr); - this.int1.addListener(new MonitorInterrupt1(this)); - } catch (Exception e) { - e.printStackTrace(); - console.println("create Digital 1 failed"); - System.exit(200); - } + private void init() { + this.logger.trace(">>> Enter: init"); + + var ledConfigIntr = DigitalInput.newConfigBuilder(pi4j) + .id("Interrupt_1") + .name("Interrupt_1_TW_PW") + .address(this.int1_gpio) + .pull(PullResistance.OFF) + .debounce(4000L) + .provider("gpiod-digital-input"); + try { + this.int1 = pi4j.create(ledConfigIntr); + this.int1.addListener(new MonitorInterrupt1(this)); + } catch (Exception e) { + e.printStackTrace(); + console.println("create Digital 1 failed"); + System.exit(200); + } - var ledConfigIntr2 = DigitalInput.newConfigBuilder(pi4j) + var ledConfigIntr2 = DigitalInput.newConfigBuilder(pi4j) .id("Interrupt_2") .name("Interrupt_2_DRDY") .address(this.int2_gpio) .pull(PullResistance.OFF) .debounce(4000L) .provider("gpiod-digital-input"); - try { - this.int2 = pi4j.create(ledConfigIntr2); - } catch (Exception e) { - e.printStackTrace(); - console.println("create Digital 2 failed"); - System.exit(201); + try { + this.int2 = pi4j.create(ledConfigIntr2); + } catch (Exception e) { + e.printStackTrace(); + console.println("create Digital 2 failed"); + System.exit(201); + } + this.validateWhoAmI(); + this.logger.trace("<<< Exit: init"); } - this.validateWhoAmI(); - this.logger.trace("<<< Exit: init"); -} /** * @return string containing a description of the attached I2C path @@ -217,22 +212,21 @@ public String i2cDetail() { } - - private boolean validateWhoAmI(){ + private boolean validateWhoAmI() { this.logger.trace(">>> Enter: validateWhoAmI"); boolean rval = false; - // this.i2c.read(); - int who = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_WHO_AM_I) & 0xff; - if(who == MPL3115A2_Declares.WHO_AM_I){ + // this.i2c.read(); + int who = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_WHO_AM_I) & 0xff; + if (who == MPL3115A2_Declares.WHO_AM_I) { rval = true; - }else{ + } else { this.logger.error("validateWhoAmI failure"); System.exit(300); } int config = 0xff; - - this.logger.trace("<<< Exit: validateWhoAmI : "+ rval); - return(rval); + + this.logger.trace("<<< Exit: validateWhoAmI : " + rval); + return (rval); } @@ -241,25 +235,23 @@ private boolean validateWhoAmI(){ * Note: The reset operation disables the I2C interface so the associated I2C write * give the appearance of failing. */ - public void reset(){ + public void reset() { this.logger.trace(">>> Enter: reset"); byte reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL1); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL1, reg & MPL3115A2_Declares.CTL1_SBYB_STBY_MASK); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL1, reg & MPL3115A2_Declares.CTL1_SBYB_STBY_MASK); this.busyWaitMS(10); // ensure chip quiet - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL1, reg | MPL3115A2_Declares.CTL1_SBYB_SFT_RESET); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL1, reg | MPL3115A2_Declares.CTL1_SBYB_SFT_RESET); this.busyWaitMS(10000); // allow time fir the reboot/POR this.logger.trace("<<< Exit : reset"); } - - /** - * Configure chip to calculate Altimeter - * Configure interrupt pins to match the Pi GPIO pin configurations - * Enter standby and then active to initiate calculation + * Configure chip to calculate Altimeter + * Configure interrupt pins to match the Pi GPIO pin configurations + * Enter standby and then active to initiate calculation */ - private boolean forceAltCalc(){ + private boolean forceAltCalc() { this.logger.trace(">>> Enter: forceAltCalc : "); boolean rval = false; this.busyWaitMS(1000); // ensure chip quiet @@ -278,20 +270,20 @@ private boolean forceAltCalc(){ // wait INT2 int i = 0; - for(i=0;i<400;i++){ - if(this.int2.state() == DigitalState.LOW) { + for (i = 0; i < 400; i++) { + if (this.int2.state() == DigitalState.LOW) { break; - }else{ - this.logger.trace("Not desired State counter " + i); + } else { + this.logger.trace("Not desired State counter " + i); this.busyWaitMS(40); // depending upon 'sample rate' possible delay 512MS } } - if(i >= 400){ + if (i >= 400) { this.logger.trace("int2 Time Out ...\r\n"); } byte source = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_INT_SOURCE); - if((source & MPL3115A2_Declares.REG_INT_SOURCE_DRDY) > 0){ + if ((source & MPL3115A2_Declares.REG_INT_SOURCE_DRDY) > 0) { rval = true; } this.busyWaitMS(500); // ensure chip quiet @@ -301,11 +293,11 @@ private boolean forceAltCalc(){ /** - * Configure chip to calculate Pressure - * Configure interrupt pins to match the Pi GPIO pin configurations - * Enter standby and then active to initiate calculation + * Configure chip to calculate Pressure + * Configure interrupt pins to match the Pi GPIO pin configurations + * Enter standby and then active to initiate calculation */ - private boolean forcePressCalc(){ + private boolean forcePressCalc() { this.logger.trace(">>> Enter: forcePressCalc : "); boolean rval = false; this.busyWaitMS(1000); // ensure chip quiet @@ -328,20 +320,20 @@ private boolean forcePressCalc(){ // wait INT2 int i = 0; - for(i=0;i<400;i++){ - if(this.int2.state() == DigitalState.LOW) { + for (i = 0; i < 400; i++) { + if (this.int2.state() == DigitalState.LOW) { break; - }else{ - this.logger.trace("Not desired State counter " + i); + } else { + this.logger.trace("Not desired State counter " + i); this.busyWaitMS(40); // depending upon 'sample rate' possible delay 512MS } } - if(i >= 400){ + if (i >= 400) { this.logger.trace("int2 Time Out ...\r\n"); } byte source = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_INT_SOURCE); - if((source & MPL3115A2_Declares.REG_INT_SOURCE_DRDY) > 0){ + if ((source & MPL3115A2_Declares.REG_INT_SOURCE_DRDY) > 0) { rval = true; } this.busyWaitMS(500); // ensure chip quiet @@ -351,12 +343,13 @@ private boolean forcePressCalc(){ // + /** - * Configure chip to calculate temperature - * Configure interrupt pins to match the Pi GPIO pin configurations - * Enter standby and then active to initiate calculation + * Configure chip to calculate temperature + * Configure interrupt pins to match the Pi GPIO pin configurations + * Enter standby and then active to initiate calculation */ - private boolean forceTempCalc(){ + private boolean forceTempCalc() { this.logger.trace(">>> Enter: forceTempCalc : "); boolean rval = false; this.busyWaitMS(1000); // ensure chip quiet @@ -367,7 +360,7 @@ private boolean forceTempCalc(){ reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_PT_DATA_CFG); this.i2c.writeRegister(MPL3115A2_Declares.REG_PT_DATA_CFG, reg | MPL3115A2_Declares.PT_DATA_CFG_EVNT_ENBL | MPL3115A2_Declares.PT_DATA_CFG_EVNT_T); - reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL4); + reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL4); this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_DRDY); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL1); @@ -375,20 +368,20 @@ private boolean forceTempCalc(){ // wait INT2 int i = 0; - for(i=0;i<400;i++){ - if(this.int2.state() == DigitalState.LOW) { + for (i = 0; i < 400; i++) { + if (this.int2.state() == DigitalState.LOW) { break; - }else{ - this.logger.trace("Not desired State counter " + i); + } else { + this.logger.trace("Not desired State counter " + i); this.busyWaitMS(20); // depending upon 'sample rate' possible delay 512MS } } - if(i >= 400){ + if (i >= 400) { this.logger.trace("int2 Time Out ...\r\n"); } byte source = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_INT_SOURCE); - if((source & MPL3115A2_Declares.REG_INT_SOURCE_DRDY) > 0){ + if ((source & MPL3115A2_Declares.REG_INT_SOURCE_DRDY) > 0) { rval = true; } this.busyWaitMS(500); // ensure chip quiet @@ -397,13 +390,10 @@ private boolean forceTempCalc(){ } - - - - private double readAltimeter(){ + private double readAltimeter() { this.logger.trace(">>> Enter: readAltimeter"); double rval = 0; - if(this.forceAltCalc()) { + if (this.forceAltCalc()) { byte[] compVal = new byte[2]; @@ -415,27 +405,27 @@ private double readAltimeter(){ // fill in rval double // 16 bits are integer value 4 bits frac - Double alt = Double.valueOf((dig_a1 << 8) | (dig_a2 & 0xff) ); - // mask the bits, shift right for proper LSB as first bit. + Double alt = Double.valueOf((dig_a1 << 8) | (dig_a2 & 0xff)); + // mask the bits, shift right for proper LSB as first bit. // The shift right 4 to make the fraction // see // https://indepth.dev/posts/1019/the-simple-math-behind-decimal-binary-conversion-algorithms - Double lsbFrac = ((dig_a3 >> 4) & 0xF)/16.0; + Double lsbFrac = ((dig_a3 >> 4) & 0xF) / 16.0; rval = alt + lsbFrac; - }else{ + } else { this.logger.error("forceAltCalc failure"); } this.logger.trace("<<< Exit : readAltimeter :" + rval); - return(rval); + return (rval); } - private double readPressure(){ + private double readPressure() { this.logger.trace(">>> Enter: readPressure"); double rval = 0; - if(this.forcePressCalc()) { + if (this.forcePressCalc()) { byte[] compVal = new byte[2]; @@ -450,27 +440,27 @@ private double readPressure(){ // 18 bits are integer value 2 bits frac // see // https://indepth.dev/posts/1019/the-simple-math-behind-decimal-binary-conversion-algorithms - Double lsbFrac = ((dig_p3 >> 4) & 0x3)/4.0; - Double prs = Double.valueOf(((dig_p1 & 0xff) << 10) | ((dig_p2 & 0xff)<<2) | ((dig_p3 &0xC0) >>6) ); + Double lsbFrac = ((dig_p3 >> 4) & 0x3) / 4.0; + Double prs = Double.valueOf(((dig_p1 & 0xff) << 10) | ((dig_p2 & 0xff) << 2) | ((dig_p3 & 0xC0) >> 6)); - rval = prs + lsbFrac; + rval = prs + lsbFrac; - }else{ + } else { this.logger.error("forcePressCalc failure"); } this.logger.trace("<<< Exit : readPressure :" + rval); - return(rval); + return (rval); } - private double readTemperature(){ + private double readTemperature() { this.logger.trace(">>> Enter: readTemperature"); double rval = 0; - if(this.forceTempCalc()) { + if (this.forceTempCalc()) { byte[] compVal = new byte[2]; - int dig_t1 = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_T_MSB); + int dig_t1 = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_T_MSB); int dig_t2 = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_T_LSB); @@ -480,40 +470,40 @@ private double readTemperature(){ // https://indepth.dev/posts/1019/the-simple-math-behind-decimal-binary-conversion-algorithms Double temp = Double.valueOf(dig_t1); // sign bit still attached - Double tempFrac = (((dig_t2 & 0xF0) >> 4)/16.0); + Double tempFrac = (((dig_t2 & 0xF0) >> 4) / 16.0); rval = temp + tempFrac; - }else{ + } else { this.logger.error("forceTempCalc failure"); } this.logger.trace("<<< Exit : readTemperature :" + rval); - return(rval); + return (rval); } - public double readAltimeterM(){ + public double readAltimeterM() { this.logger.trace(">>> Enter: readAltimeterM"); - double rval = this.readAltimeter(); + double rval = this.readAltimeter(); this.logger.trace("<<< Exit : readAltimeterM :" + rval); - return(rval); + return (rval); } - public double readAltimeterF(){ + public double readAltimeterF() { this.logger.trace(">>> Enter: readAltimeterF"); double meter = this.readAltimeterM(); - double rval = (meter*39.37)/12; + double rval = (meter * 39.37) / 12; this.logger.trace("<<< Exit : readAltimeterF :" + rval); - return(rval); + return (rval); } - public double readTemperatureC(){ + public double readTemperatureC() { this.logger.trace(">>> Enter: readTemperatureC"); double rval = 0.0; rval = this.readTemperature(); this.logger.trace("<<< Exit : readTemperatureC :" + rval); - return(rval); + return (rval); } - public double readTemperatureF() { + public double readTemperatureF() { this.logger.trace("enter: temperatureF"); double fTemp = this.readTemperatureC() * 1.8 + 32; this.logger.trace("exit: temperatureF " + fTemp); @@ -521,39 +511,38 @@ public double readTemperatureF() { } - public double readPresurePa(){ + public double readPresurePa() { this.logger.trace(">>> Enter: readPresurePa"); double rval = this.readPressure(); this.logger.trace("<<< Exit : readPresurePa :" + rval); - return(rval); + return (rval); } - public double readPresureMb(){ + public double readPresureMb() { this.logger.trace(">>> Enter: readPresureMb"); - double rval = this.readPresurePa() /100; + double rval = this.readPresurePa() / 100; this.logger.trace("<<< Exit : readPresureMb :" + rval); - return(rval); + return (rval); } private void busyWaitMS(long ms) { long waitUntil = System.nanoTime() + (ms * 1000000); while (waitUntil > System.nanoTime()) { - ; } } // SRC_PTH alt/press limit. When exceeded // interrupt thru int2 - public void set_P_PGT(long target){ + public void set_P_PGT(long target) { this.logger.trace(">>> Enter: set_P_TGT : " + target); - this.i2c.writeRegister(MPL3115A2_Declares.REG_P_TGT_MSB, (byte) ((target ) >> 8)); - this.i2c.writeRegister(MPL3115A2_Declares.REG_P_TGT_LSB, (byte) (target )); + this.i2c.writeRegister(MPL3115A2_Declares.REG_P_TGT_MSB, (byte) ((target) >> 8)); + this.i2c.writeRegister(MPL3115A2_Declares.REG_P_TGT_LSB, (byte) (target)); byte reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_PT_DATA_CFG); this.i2c.writeRegister(MPL3115A2_Declares.REG_PT_DATA_CFG, reg | MPL3115A2_Declares.PT_DATA_CFG_EVNT_ENBL | MPL3115A2_Declares.PT_DATA_CFG_EVNT_PA | MPL3115A2_Declares.PT_DATA_CFG_EVNT_T); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL4); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_PTH | MPL3115A2_Declares.CTL4_INT_EN_PW); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_PTH | MPL3115A2_Declares.CTL4_INT_EN_PW); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL5); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_PW | MPL3115A2_Declares.CTL5_INT_CFG_PTH); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_PW | MPL3115A2_Declares.CTL5_INT_CFG_PTH); this.logger.trace("<<< Exit: set_P_TGT "); } @@ -561,16 +550,16 @@ public void set_P_PGT(long target){ // SRC_PW alt/press window limit. When exceeded // interrupt thru int2 - public void set_P_WND(long window){ + public void set_P_WND(long window) { this.logger.trace(">>> Enter: set_P_WND : " + window); this.i2c.writeRegister(MPL3115A2_Declares.REG_P_WND_MSB, (byte) ((window & 0xff00) >> 8)); this.i2c.writeRegister(MPL3115A2_Declares.REG_P_WND_LSB, (byte) (window & 0xff)); byte reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_PT_DATA_CFG); this.i2c.writeRegister(MPL3115A2_Declares.REG_PT_DATA_CFG, reg | MPL3115A2_Declares.PT_DATA_CFG_EVNT_ENBL | MPL3115A2_Declares.PT_DATA_CFG_EVNT_PA | MPL3115A2_Declares.PT_DATA_CFG_EVNT_T); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL4); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_PW | MPL3115A2_Declares.CTL4_INT_EN_PTH); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_PW | MPL3115A2_Declares.CTL4_INT_EN_PTH); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL5); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_PW | MPL3115A2_Declares.CTL5_INT_CFG_PTH); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_PW | MPL3115A2_Declares.CTL5_INT_CFG_PTH); this.logger.trace("<<< Exit: set_P_WND "); } @@ -578,15 +567,15 @@ public void set_P_WND(long window){ // SRC_TTH temp limit. When exceeded // interrupt thru int1 - public void set_T_TGT(long target){ + public void set_T_TGT(long target) { this.logger.trace(">>> Enter: set_T_TGT : " + target); this.i2c.writeRegister(MPL3115A2_Declares.REG_T_TGT, (byte) (target & 0x00ff)); byte reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_PT_DATA_CFG); this.i2c.writeRegister(MPL3115A2_Declares.REG_PT_DATA_CFG, reg | MPL3115A2_Declares.PT_DATA_CFG_EVNT_ENBL | MPL3115A2_Declares.PT_DATA_CFG_EVNT_PA | MPL3115A2_Declares.PT_DATA_CFG_EVNT_T); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL4); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_TTH | MPL3115A2_Declares.CTL4_INT_EN_PW); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_TTH | MPL3115A2_Declares.CTL4_INT_EN_PW); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL5); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_TW | MPL3115A2_Declares.CTL5_INT_CFG_TTH); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_TW | MPL3115A2_Declares.CTL5_INT_CFG_TTH); this.logger.trace("<<< Exit: set_T_TGT "); } @@ -594,26 +583,25 @@ public void set_T_TGT(long target){ // SRC_TW temp window limit. When exceeded // interrupt thru int1 - public void set_T_WND(long window){ + public void set_T_WND(long window) { this.logger.trace(">>> Enter: set_T_WND : " + window); boolean rval = false; this.i2c.writeRegister(MPL3115A2_Declares.REG_T_WND, (byte) (window & 0xff)); byte reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_PT_DATA_CFG); this.i2c.writeRegister(MPL3115A2_Declares.REG_PT_DATA_CFG, reg | MPL3115A2_Declares.PT_DATA_CFG_EVNT_ENBL | MPL3115A2_Declares.PT_DATA_CFG_EVNT_PA | MPL3115A2_Declares.PT_DATA_CFG_EVNT_T); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL4); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_TW | MPL3115A2_Declares.CTL4_INT_EN_TTH); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL4, reg | MPL3115A2_Declares.CTL4_INT_EN_TW | MPL3115A2_Declares.CTL4_INT_EN_TTH); reg = this.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL5); - this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_TW | MPL3115A2_Declares.CTL5_INT_CFG_TTH); + this.i2c.writeRegister(MPL3115A2_Declares.REG_CTRL5, reg | MPL3115A2_Declares.CTL5_INT_CFG_TW | MPL3115A2_Declares.CTL5_INT_CFG_TTH); - this.logger.trace("<<< Exit: set_T_WND " ); + this.logger.trace("<<< Exit: set_T_WND "); } - // Chip perform altitude calc using 101,326 Pa. If local Pa is different // the Altitude calculation will be incorrect. - public void set_local_Pa_correction(long pa){ + public void set_local_Pa_correction(long pa) { this.logger.trace(">>> Enter: set_local_Pa_correction : " + pa); pa = pa >> 1; this.i2c.writeRegister(MPL3115A2_Declares.REG_BAR_IN_MSB, (byte) ((pa & 0xff00) >> 8)); @@ -623,9 +611,6 @@ public void set_local_Pa_correction(long pa){ } - - - // Interrupt handler @@ -633,11 +618,12 @@ public void set_local_Pa_correction(long pa){ * The code at present just prints the present value for what * caused the interrupt. You could change the code to take some action * based on what occurred. - */ + */ public static class MonitorInterrupt1 implements DigitalStateChangeListener { MPL3115A2 mplObj; - public MonitorInterrupt1( MPL3115A2 mplObj) { - this.mplObj = mplObj; + + public MonitorInterrupt1(MPL3115A2 mplObj) { + this.mplObj = mplObj; } @@ -648,15 +634,15 @@ public void onDigitalStateChange(DigitalStateChangeEvent event) { // + event.getPin() + " = " + event.getState()); if (event.state() == DigitalState.LOW) { // determine which condition occured - this.mplObj.logger.trace("onDigitalStateChange Pin " + event.toString() + " went low, see who caused it" + "\n"); + this.mplObj.logger.trace("onDigitalStateChange Pin " + event + " went low, see who caused it" + "\n"); byte source = this.mplObj.i2c.readRegisterByte(MPL3115A2_Declares.REG_INT_SOURCE); if ((source & MPL3115A2_Declares.REG_INT_SOURCE_PW) > 0) { byte reg = this.mplObj.i2c.readRegisterByte(MPL3115A2_Declares.REG_CTRL1); - if((reg & MPL3115A2_Declares.CTL1_ALT_PRESS_MASK ) > 0){ + if ((reg & MPL3115A2_Declares.CTL1_ALT_PRESS_MASK) > 0) { double rval = this.mplObj.readPresureMb(); // User add meaningful code here System.out.println("Pressure limit exceeded " + rval + "\n"); - }else{ + } else { double rval = this.mplObj.readAltimeterM(); // User add meaningful code here System.out.println("Altitude limit exceeded " + rval + "\n"); @@ -664,14 +650,14 @@ public void onDigitalStateChange(DigitalStateChangeEvent event) { } else if ((source & MPL3115A2_Declares.REG_INT_SOURCE_TW) > 0) { double rval = this.mplObj.readTemperatureF(); // User add meaningful code here - System.out.println("Temperature limit exceeded " + rval + "\n"); + System.out.println("Temperature limit exceeded " + rval + "\n"); } else { - this.mplObj.logger.trace("onDigitalStateChange " + event.toString() + " unexpected source" + "\n"); + this.mplObj.logger.trace("onDigitalStateChange " + event + " unexpected source" + "\n"); } } else if (event.state() == DigitalState.HIGH) { - this.mplObj.logger.trace("onDigitalStateChange " + event.toString() + " Pin went high NOP" + "\n"); + this.mplObj.logger.trace("onDigitalStateChange " + event + " Pin went high NOP" + "\n"); } else { - this.mplObj.logger.trace("Pin " + event.toString() + " Strange event state " + event.state() + "\n"); + this.mplObj.logger.trace("Pin " + event + " Strange event state " + event.state() + "\n"); } } } diff --git a/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_App.java b/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_App.java index 5b3c948..cbc7957 100644 --- a/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_App.java +++ b/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_App.java @@ -38,10 +38,8 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; + public class MPL3115A2_App { @@ -52,14 +50,14 @@ public class MPL3115A2_App { /** * See -h help text for usage - * + *

    * Also, the -x reset chip. Initial chip access may fail to retrieve data * and log an error message. When the chip has completed reset normal data * retrieval will resume. - * - * - * At present supports retrieval Temperature Pressure and Altitude. - * A future commit will incorporate 'target' interrupt support. + *

    + *

    + * At present supports retrieval Temperature Pressure and Altitude. + * A future commit will incorporate 'target' interrupt support. */ public static void main(String[] args) throws Exception { @@ -68,13 +66,13 @@ public static void main(String[] args) throws Exception { int address = MPL3115A2_Declares.DEFAULT_ADDRESS; boolean doReset = false; - int gpio_int_1_num = 0x42 ; - int gpio_int_2_num = 0x42 ; + int gpio_int_1_num = 0x42; + int gpio_int_2_num = 0x42; float pw = 0; float tw = 0; float tg = 0; float pg = 0; - float pa = 0 ; + float pa = 0; // ------------------------------------------------------------ // Initialize the Pi4J Runtime Context @@ -99,20 +97,6 @@ public static void main(String[] args) throws Exception { System.out.println("----------------------------------------------------------"); pi4j.providers().describe().print(System.out); System.out.println("----------------------------------------------------------"); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); - final Console console = new Console(); console.print("=============================================================="); @@ -121,9 +105,9 @@ public void handle(Signal sig) { String helpString = " parms: -b hex value bus -a hex value address -int1 interrupt1 gpio," + - " -int2 interrrupt2 gpio, -x do reset, -t trace -Pa local_Pa\n" + - " -PW pressure/alt window -PG pressure/alt limit -TW temp window -TG temp limit \n" + - " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; + " -int2 interrrupt2 gpio, -x do reset, -t trace -Pa local_Pa\n" + + " -PW pressure/alt window -PG pressure/alt limit -TW temp window -TG temp limit \n" + + " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { String o = args[i]; @@ -131,39 +115,39 @@ public void handle(Signal sig) { String a = args[i + 1]; busNum = Integer.parseInt(a.substring(2), 16); i++; - }else if (o.contentEquals("-TG")) { // temp limit + } else if (o.contentEquals("-TG")) { // temp limit String a = args[i + 1]; i++; - tg = Float.parseFloat(a); - }else if (o.contentEquals("-TW")) { // temp window + tg = Float.parseFloat(a); + } else if (o.contentEquals("-TW")) { // temp window String a = args[i + 1]; i++; - tw = Float.parseFloat(a); - }else if (o.contentEquals("-PG")) { // pressure limit + tw = Float.parseFloat(a); + } else if (o.contentEquals("-PG")) { // pressure limit String a = args[i + 1]; i++; - pg = Float.parseFloat(a); - }else if (o.contentEquals("-PW")) { // pressure window + pg = Float.parseFloat(a); + } else if (o.contentEquals("-PW")) { // pressure window String a = args[i + 1]; i++; - pw = Float.parseFloat(a); + pw = Float.parseFloat(a); } else if (o.contentEquals("-Pa")) { // local Pa String a = args[i + 1]; i++; - pa = Float.parseFloat(a); - }else if (o.contentEquals("-int1")) { + pa = Float.parseFloat(a); + } else if (o.contentEquals("-int1")) { String a = args[i + 1]; i++; gpio_int_1_num = Integer.parseInt(a); - }else if (o.contentEquals("-int2")) { + } else if (o.contentEquals("-int2")) { String a = args[i + 1]; i++; gpio_int_2_num = Integer.parseInt(a); - }else if (o.contentEquals("-a")) { // device address + } else if (o.contentEquals("-a")) { // device address String a = args[i + 1]; i++; address = Integer.parseInt(a.substring(2), 16); - }else if (o.contentEquals("-x")) { + } else if (o.contentEquals("-x")) { doReset = true; } else if (o.contentEquals("-t")) { String a = args[i + 1]; @@ -186,12 +170,12 @@ public void handle(Signal sig) { } - var mplDev = new MPL3115A2(pi4j, console, busNum, address,gpio_int_1_num,gpio_int_2_num, traceLevel); + var mplDev = new MPL3115A2(pi4j, console, busNum, address, gpio_int_1_num, gpio_int_2_num, traceLevel); console.println(" Dev I2C detail " + mplDev.i2cDetail()); console.println(" Setup ----------------------------------------------------------"); - if(doReset){ + if (doReset) { mplDev.reset(); } @@ -215,7 +199,7 @@ public void handle(Signal sig) { console.println("Adjust the Pa used in altitude calculation "); - if(pa > 0){ + if (pa > 0) { mplDev.set_local_Pa_correction((long) (pa)); } console.println("Again obtain the altitude in meters using new Pa "); @@ -224,16 +208,16 @@ public void handle(Signal sig) { console.println(" Altitude Meters = " + altitudePa); - if(pg > 0){ + if (pg > 0) { mplDev.set_P_PGT((long) pg); } - if(pw > 0){ + if (pw > 0) { mplDev.set_P_WND((long) pw); } - if(tg > 0){ + if (tg > 0) { mplDev.set_T_TGT((long) tg); } - if(tw > 0){ + if (tw > 0) { mplDev.set_T_WND((long) tw); } diff --git a/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_Declares.java b/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_Declares.java index d1b5acb..a476184 100644 --- a/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_Declares.java +++ b/src/main/java/com/pi4j/devices/mpl3115a2/MPL3115A2_Declares.java @@ -36,104 +36,99 @@ package com.pi4j.devices.mpl3115a2; -import com.pi4j.devices.bmp280.BMP280Declares; - public class MPL3115A2_Declares { - - protected final static int DEFAULT_ADDRESS = 0x60; - protected final static int DEFAULT_BUS = 0x01; - - - protected final static int GPIO_3_IS_IN = 0b10000000; // - - - protected final static int GPIO_0_MASK = 0b00000001; // - - protected final static int CTL1_ALT_ALTIM = 0b10000000; // OR set to altimeter - protected final static int CTL1_ALT_PRESS_MASK = 0b01111111; // & clear, set to Press - protected final static int CTL1_SBYB_ACT = 0b00000001; // OR set to active - protected final static int CTL1_SBYB_STBY_MASK = 0b11111110; // & Clear, set to standby - protected final static int CTL1_SBYB_SFT_RESET = 0b00000100; // Sofware reset - protected final static int CTL1_OVR_SAMPL_MAX = 0b00111000; // ration 128 - - protected final static int CTL3_PP_OD1_DRAIN = 0b00010000; // open drain - protected final static int CTL3_PP_OD2_DRAIN = 0b00000001; // open drain - - - protected final static int CTL4_INT_EN_DRDY = 0b10000000; // interrupt enabled - protected final static int CTL4_INT_EN_PW = 0b00100000; // interrupt enabled pressure win - protected final static int CTL4_INT_EN_TW = 0b00010000; // interrupt enabled temp win - protected final static int CTL4_INT_EN_PTH = 0b00001000; // interrupt enabled press limit - protected final static int CTL4_INT_EN_TTH = 0b00000100; // interrupt enabled temp limit - - protected final static int CTL5_INT_CFG_PW = 0b00100000; // interrupt PW thru int1 - protected final static int CTL5_INT_CFG_TW = 0b00010000; // interrupt TW thru int1 - protected final static int CTL5_INT_CFG_PTH = 0b00001000; // interrupt PTH thru int1 - protected final static int CTL5_INT_CFG_TTH = 0b00000100; // interrupt TTH thru int1 - - protected final static int PT_DATA_CFG_EVNT_ENBL = 0b00000100; // enable events - protected final static int PT_DATA_CFG_EVNT_PA = 0b00000010; // for Alt and Press - protected final static int PT_DATA_CFG_EVNT_T = 0b00000001; // for Temp - - - protected final static int REG_INT_SOURCE_DRDY = 0b10000000; // Data ready to read - protected final static int REG_INT_SOURCE_PW = 0b00100000; // pressure/alti limit-window - protected final static int REG_INT_SOURCE_TW = 0b00010000; // temp limit-window - - - protected final static int WHO_AM_I = 0xC4; // expected chip ID - - - - - protected final static int REG_STATUS = 0x00; - protected final static int REG_P_MSB = 0x01; // b12-19 - protected final static int REG_P_CSB = 0x02; // b4-11 - protected final static int REG_P_LSB = 0x03; // b0-3 - protected final static int REG_T_MSB = 0x04; // b4-11 - protected final static int REG_T_LSB = 0x05; // b0-3 - protected final static int REG_DR_STATUS = 0x06; - protected final static int REG_P_DELTA_MSB = 0x07; //b12-19 - protected final static int REG_P_DELTA_CSB = 0x08; // b4-11 - protected final static int REG_P_DELTA_LSB = 0x09; // b0-3; - protected final static int REG_T_DELTA_MSB = 0x0A; //b4-11 - protected final static int REG_T_DELTA_LSB = 0x0B; // b0-3; - protected final static int REG_WHO_AM_I = 0x0C; // ID - protected final static int REG_F_STATUS = 0x0D; // fifo status - protected final static int REG_F_DATA = 0x0E; // fifo 8 bit access - protected final static int REG_F_SETUP = 0x0F; // fifo setup - protected final static int REG_TIME_DLY = 0x10; // since fifo overflow - protected final static int REG_SYSMOD = 0x11; // current system mode - protected final static int REG_INT_SOURCE = 0x12; // interrupt status - protected final static int REG_PT_DATA_CFG = 0x13; // dta event flag - protected final static int REG_BAR_IN_MSB = 0x14; // b8-15 input for ALT calc - protected final static int REG_BAR_IN_LSB = 0x15; // b0-7nput for ALT calc - protected final static int REG_P_TGT_MSB = 0x16; // b8-15 input for ALT calc - protected final static int REG_P_TGT_LSB = 0x17; // b0-7nput for ALT calc - protected final static int REG_T_TGT = 0x18; // temp tgt - protected final static int REG_P_WND_MSB = 0x19; // b8-15 - protected final static int REG_P_WND_LSB = 0x1A; // b0-7 - protected final static int REG_T_WND = 0x1B; // temp window value - protected final static int REG_P_MIN_MSB = 0x1C; // b12-19 - protected final static int REG_P_MIN_CSB = 0x1D; // b4-11 - protected final static int REG_P_MIN_LSB = 0x1E; // b0-3 - protected final static int REG_T_MIN_MSB = 0x1F; // b8-15 - protected final static int REG_T_MIN_LSB = 0x20; // b0-7 - protected final static int REG_P_MAX_MSB = 0x21; // b12-19 - protected final static int REG_P_MAX_CSB = 0x22; // b4-11 - protected final static int REG_P_MAX_LSB = 0x23; // b0-3 - protected final static int REG_T_MAX_MSB = 0x24; // b8-15 - protected final static int REG_T_MAX_LSB = 0x25; // b0-7 - protected final static int REG_CTRL1 = 0x26; - protected final static int REG_CTRL2 = 0x27; - protected final static int REG_CTRL3 = 0x28; - protected final static int REG_CTRL4 = 0x29; - protected final static int REG_CTRL5 = 0x2A; - protected final static int REG_OFF_P = 0x2B; - protected final static int REG_OFF_T = 0x2C; - protected final static int REG_OFF_H = 0x2D; + protected final static int DEFAULT_ADDRESS = 0x60; + protected final static int DEFAULT_BUS = 0x01; + + + protected final static int GPIO_3_IS_IN = 0b10000000; // + + + protected final static int GPIO_0_MASK = 0b00000001; // + + protected final static int CTL1_ALT_ALTIM = 0b10000000; // OR set to altimeter + protected final static int CTL1_ALT_PRESS_MASK = 0b01111111; // & clear, set to Press + protected final static int CTL1_SBYB_ACT = 0b00000001; // OR set to active + protected final static int CTL1_SBYB_STBY_MASK = 0b11111110; // & Clear, set to standby + protected final static int CTL1_SBYB_SFT_RESET = 0b00000100; // Sofware reset + protected final static int CTL1_OVR_SAMPL_MAX = 0b00111000; // ration 128 + + protected final static int CTL3_PP_OD1_DRAIN = 0b00010000; // open drain + protected final static int CTL3_PP_OD2_DRAIN = 0b00000001; // open drain + + + protected final static int CTL4_INT_EN_DRDY = 0b10000000; // interrupt enabled + protected final static int CTL4_INT_EN_PW = 0b00100000; // interrupt enabled pressure win + protected final static int CTL4_INT_EN_TW = 0b00010000; // interrupt enabled temp win + protected final static int CTL4_INT_EN_PTH = 0b00001000; // interrupt enabled press limit + protected final static int CTL4_INT_EN_TTH = 0b00000100; // interrupt enabled temp limit + + protected final static int CTL5_INT_CFG_PW = 0b00100000; // interrupt PW thru int1 + protected final static int CTL5_INT_CFG_TW = 0b00010000; // interrupt TW thru int1 + protected final static int CTL5_INT_CFG_PTH = 0b00001000; // interrupt PTH thru int1 + protected final static int CTL5_INT_CFG_TTH = 0b00000100; // interrupt TTH thru int1 + + protected final static int PT_DATA_CFG_EVNT_ENBL = 0b00000100; // enable events + protected final static int PT_DATA_CFG_EVNT_PA = 0b00000010; // for Alt and Press + protected final static int PT_DATA_CFG_EVNT_T = 0b00000001; // for Temp + + + protected final static int REG_INT_SOURCE_DRDY = 0b10000000; // Data ready to read + protected final static int REG_INT_SOURCE_PW = 0b00100000; // pressure/alti limit-window + protected final static int REG_INT_SOURCE_TW = 0b00010000; // temp limit-window + + + protected final static int WHO_AM_I = 0xC4; // expected chip ID + + + protected final static int REG_STATUS = 0x00; + protected final static int REG_P_MSB = 0x01; // b12-19 + protected final static int REG_P_CSB = 0x02; // b4-11 + protected final static int REG_P_LSB = 0x03; // b0-3 + protected final static int REG_T_MSB = 0x04; // b4-11 + protected final static int REG_T_LSB = 0x05; // b0-3 + protected final static int REG_DR_STATUS = 0x06; + protected final static int REG_P_DELTA_MSB = 0x07; //b12-19 + protected final static int REG_P_DELTA_CSB = 0x08; // b4-11 + protected final static int REG_P_DELTA_LSB = 0x09; // b0-3; + protected final static int REG_T_DELTA_MSB = 0x0A; //b4-11 + protected final static int REG_T_DELTA_LSB = 0x0B; // b0-3; + protected final static int REG_WHO_AM_I = 0x0C; // ID + protected final static int REG_F_STATUS = 0x0D; // fifo status + protected final static int REG_F_DATA = 0x0E; // fifo 8 bit access + protected final static int REG_F_SETUP = 0x0F; // fifo setup + protected final static int REG_TIME_DLY = 0x10; // since fifo overflow + protected final static int REG_SYSMOD = 0x11; // current system mode + protected final static int REG_INT_SOURCE = 0x12; // interrupt status + protected final static int REG_PT_DATA_CFG = 0x13; // dta event flag + protected final static int REG_BAR_IN_MSB = 0x14; // b8-15 input for ALT calc + protected final static int REG_BAR_IN_LSB = 0x15; // b0-7nput for ALT calc + protected final static int REG_P_TGT_MSB = 0x16; // b8-15 input for ALT calc + protected final static int REG_P_TGT_LSB = 0x17; // b0-7nput for ALT calc + protected final static int REG_T_TGT = 0x18; // temp tgt + protected final static int REG_P_WND_MSB = 0x19; // b8-15 + protected final static int REG_P_WND_LSB = 0x1A; // b0-7 + protected final static int REG_T_WND = 0x1B; // temp window value + protected final static int REG_P_MIN_MSB = 0x1C; // b12-19 + protected final static int REG_P_MIN_CSB = 0x1D; // b4-11 + protected final static int REG_P_MIN_LSB = 0x1E; // b0-3 + protected final static int REG_T_MIN_MSB = 0x1F; // b8-15 + protected final static int REG_T_MIN_LSB = 0x20; // b0-7 + protected final static int REG_P_MAX_MSB = 0x21; // b12-19 + protected final static int REG_P_MAX_CSB = 0x22; // b4-11 + protected final static int REG_P_MAX_LSB = 0x23; // b0-3 + protected final static int REG_T_MAX_MSB = 0x24; // b8-15 + protected final static int REG_T_MAX_LSB = 0x25; // b0-7 + protected final static int REG_CTRL1 = 0x26; + protected final static int REG_CTRL2 = 0x27; + protected final static int REG_CTRL3 = 0x28; + protected final static int REG_CTRL4 = 0x29; + protected final static int REG_CTRL5 = 0x2A; + protected final static int REG_OFF_P = 0x2B; + protected final static int REG_OFF_T = 0x2C; + protected final static int REG_OFF_H = 0x2D; // twenty bit data // 7 6 5 4 3 2 1 0 @@ -147,13 +142,10 @@ public class MPL3115A2_Declares { // b7-0 x x x x x x x x - // twelve bit data // 7 6 5 4 3 2 1 0 // b11-4 x x x x x x x x // b3-0 x x x x - - - - - - } diff --git a/src/main/java/com/pi4j/devices/mpl3115a2/README.md b/src/main/java/com/pi4j/devices/mpl3115a2/README.md index 72595e5..e872b35 100644 --- a/src/main/java/com/pi4j/devices/mpl3115a2/README.md +++ b/src/main/java/com/pi4j/devices/mpl3115a2/README.md @@ -1,105 +1,122 @@ # + # -# * -# * - -# * #%L -# * ********************************************************************** -# * ORGANIZATION : Pi4J -# * PROJECT : Pi4J :: EXTENSION -# * FILENAME : README.md -# * -# * This file is part of the Pi4J project. More information about -# * this project can be found here: https://pi4j.com/ -# * ********************************************************************** -# * %% -# * * Copyright (C) 2012 - 2022 Pi4J -# * %% -# * -# * Licensed under the Apache License, Version 2.0 (the "License"); -# * you may not use this file except in compliance with the License. -# * You may obtain a copy of the License at -# * -# * http://www.apache.org/licenses/LICENSE-2.0 -# * -# * Unless required by applicable law or agreed to in writing, software -# * distributed under the License is distributed on an "AS IS" BASIS, -# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# * See the License for the specific language governing permissions and -# * limitations under the License. -# * #L% -# * -# -# +# * + +# * - + +# * #%L + +# * ********************************************************************** + +# * ORGANIZATION : Pi4J + +# * PROJECT : Pi4J :: EXTENSION + +# * FILENAME : README.md + +# * + +# * This file is part of the Pi4J project. More information about + +# * this project can be found here: https://pi4j.com/ + +# * ********************************************************************** + +# * %% + +# * * Copyright (C) 2012 - 2022 Pi4J + +# * %% + +# * + +# * Licensed under the Apache License, Version 2.0 (the "License"); + +# * you may not use this file except in compliance with the License. + +# * You may obtain a copy of the License at + +# * + +# * http://www.apache.org/licenses/LICENSE-2.0 -https://www.nxp.com/docs/en/data-sheet/MPL3115A2.pdf +# * +# * Unless required by applicable law or agreed to in writing, software +# * distributed under the License is distributed on an "AS IS" BASIS, + +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +# * See the License for the specific language governing permissions and + +# * limitations under the License. + +# * #L% + +# * + +# + +# + +https://www.nxp.com/docs/en/data-sheet/MPL3115A2.pdf ----Pi------------------MPL3115A2 ------- 3.3v--------------------P1---Vdd Grnd--------------------P2---Gnd 3.3v--------------------P3---3v -GPIO26------------------P4---INT2 USE: for DRDY -GPIO15------------------P5---INT1 USE: for P/A & T interrupt +GPIO26------------------P4---INT2 USE: for DRDY +GPIO15------------------P5---INT1 USE: for P/A & T interrupt SCL---------------------P6---SCL -SDA---------------------P7---SDA - +SDA---------------------P7---SDA At present supports retrieval Temperature Pressure and Altitude. -A future commit will incorporate 'target' interrupt support. +A future commit will incorporate 'target' interrupt support. - - - -1. ./mvnw clean package -2. cd target/distribution -3. sudo ./runMPL3115A2.sh +1. ./mvnw clean package +2. cd target/distribution +3. sudo ./runMPL3115A2.sh The application demonstrates usage of public interfaces to the chip. The app obtains pressure, altitide and temperature in the commons formats. -It then adjusts the altitude calculation to use the local pressure Pa value. - - - +It then adjusts the altitude calculation to use the local pressure Pa value. Use of different bus or device address or GPIO, use the applicable values in the following command. -sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t trace - -Bus and address, GPIOs connected to int1 and int2 Trace level - +sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t trace -sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t trace -x -Bus and address, GPIOs connected to int1 and int2 Trace level --x reset chip. Initial chip access may fail to retrieve data and log an error -message. When the chip has completed reset normal data retrieval will resume. +Bus and address, GPIOs connected to int1 and int2 Trace level +sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t trace -x +Bus and address, GPIOs connected to int1 and int2 Trace level +-x reset chip. Initial chip access may fail to retrieve data and log an error +message. When the chip has completed reset normal data retrieval will resume. // using limits and window -sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t trace +sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t trace -Read the temperature 'C' value. Set -TW and -TG a few degrees above this +Read the temperature 'C' value. Set -TW and -TG a few degrees above this value. --PW pressure/alt window -PG pressure/alt limit -TW temp window -TG temp limit +-PW pressure/alt window -PG pressure/alt limit -TW temp window -TG temp limit -sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t info -PW 3 -PG 314 -TW 1 -TG 35 +sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -t info -PW 3 -PG 314 -TW 1 -TG 35 -Use heat gun on circuit board and temp interrupt1 will fire. +Use heat gun on circuit board and temp interrupt1 will fire. The altimeter and pressure share the same registers for limit and window. Whether your application last called getting the altimeter or pressure will -effect the chips comparisons and interrupt handler. +effect the chips comparisons and interrupt handler. Example: If you set the altitude to 300 meters limit, but the previous operation was getting the pressure, the chip will compare the pressure which is a large value to that 300 limit and fire the interrupt. So in this case, get the altitude value from the chip before setting the -altitude limit. - - +altitude limit. -sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -Pa 97720 +sudo ./runMPL3115A2.sh -b 0x01 -a 0x60 -int1 15 -int2 26 -Pa 97720 To restore the chip using its default pressure, set -Pa 101326 or reset the chip. diff --git a/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V.java b/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V.java index 4ea04ac..87d775d 100644 --- a/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V.java +++ b/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V.java @@ -59,7 +59,7 @@ public class NeoPixel94V extends Component { PixelColor pixel; - private String traceLevel; + private final String traceLevel; /** * Default Channel of the SPI Pins */ @@ -113,7 +113,7 @@ public class NeoPixel94V extends Component { */ private final byte Bit_0 = (byte) 0b11000000; // 192 in Decimal private final byte Bit_1 = (byte) 0b11111000;// 248 in Decimal - /** + /** * Brightness value between 0 and 1 */ private double brightness; @@ -189,14 +189,14 @@ void init() { */ private SpiConfig buildSpiConfig(Context pi4j, int channel, int frequency) { return Spi.newConfigBuilder(pi4j) - .id("SPI" + 1) - .name("LED Matrix") - .bus(SpiBus.BUS_1) - .address(channel) - .mode(SpiMode.MODE_0) - .baud(8 * DEFAULT_FREQUENCY_PI4) // bit-banging from Bit to SPI-Byte - .provider("pigpio-spi") - .build(); + .id("SPI" + 1) + .name("LED Matrix") + .bus(SpiBus.BUS_1) + .address(channel) + .mode(SpiMode.MODE_0) + .baud(8 * DEFAULT_FREQUENCY_PI4) // bit-banging from Bit to SPI-Byte + .provider("pigpio-spi") + .build(); } @@ -432,7 +432,7 @@ public int wheel(int wheelPos) { */ public int createColorRGB(float red, float green, float blue) { return createColorRGB(round(Color_COMPONENT_MAX * red), - round(Color_COMPONENT_MAX * green), round(Color_COMPONENT_MAX * blue)); + round(Color_COMPONENT_MAX * green), round(Color_COMPONENT_MAX * blue)); } /** @@ -537,7 +537,7 @@ private float HueToRGB(float p, float q, float h) { public void validateColorComponent(String color, int value) { if (value < 0 || value >= 256) { throw new IllegalArgumentException("Illegal Color value (" + value + - ") for '" + color + "' - must be 0.." + Color_COMPONENT_MAX); + ") for '" + color + "' - must be 0.." + Color_COMPONENT_MAX); } } diff --git a/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V_App.java b/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V_App.java index 30971a7..2e3a75b 100644 --- a/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V_App.java +++ b/src/main/java/com/pi4j/devices/neopixel94v/NeoPixel94V_App.java @@ -38,10 +38,8 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; + public class NeoPixel94V_App { @@ -57,18 +55,6 @@ public static void main(String[] args) throws Exception { String traceLevel = "info"; boolean doTest = false; - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - // Thread.dumpStack(); - System.exit(2); - } - }); for (int i = 0; i < args.length; i++) { String o = args[i]; @@ -82,10 +68,10 @@ public void handle(Signal sig) { console.println("Changing trace level invalid : " + traceLevel); System.exit(40); } - }else { + } else { console.println(" !!! Invalid Parm " + o); console.println(" -trace " + - " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""); + " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""); System.exit(42); } } @@ -94,7 +80,6 @@ public void handle(Signal sig) { final NeoPixel94V ledStrip = new NeoPixel94V(pi4j, console, pixels, 0.5, traceLevel); - // System.out.println("Blink as configured"); //ledStrip.blinkViaPwm(); //ledStrip.waitForInput(); @@ -108,14 +93,14 @@ public void handle(Signal sig) { System.out.println("setting the LEDs to RED"); - ledStrip.setStripColor(ledStrip.pixel.RED); + ledStrip.setStripColor(NeoPixel94V.PixelColor.RED); ledStrip.render(); ledStrip.sleep(3000, 0); ledStrip.waitForInput(); System.out.println("setting the first led to green"); - ledStrip.setPixelColor(0, ledStrip.pixel.GREEN); + ledStrip.setPixelColor(0, NeoPixel94V.PixelColor.GREEN); ledStrip.render(); ledStrip.sleep(3000, 0); @@ -123,7 +108,7 @@ public void handle(Signal sig) { System.out.println("setting the LEDs to Blue"); - ledStrip.setStripColor(ledStrip.pixel.BLUE); + ledStrip.setStripColor(NeoPixel94V.PixelColor.BLUE); ledStrip.render(); ledStrip.sleep(3000, 0); @@ -131,7 +116,7 @@ public void handle(Signal sig) { System.out.println("setting the first led to Purple"); - ledStrip.setPixelColor(0, ledStrip.pixel.PURPLE); + ledStrip.setPixelColor(0, NeoPixel94V.PixelColor.PURPLE); ledStrip.render(); ledStrip.sleep(3000, 0); @@ -145,7 +130,7 @@ public void handle(Signal sig) { System.out.println("setting the brightness to full and just show the first led as White"); ledStrip.setBrightness(1); - ledStrip.setPixelColor(0, ledStrip.pixel.WHITE); + ledStrip.setPixelColor(0, NeoPixel94V.PixelColor.WHITE); ledStrip.render(); ledStrip.sleep(3000, 0); @@ -162,7 +147,7 @@ public void handle(Signal sig) { // !!!!!!!! System.out.println("setting the brightness to full and just show the fourth led as Red"); ledStrip.setBrightness(1); - ledStrip.setPixelColor(3, ledStrip.pixel.RED); //3 + ledStrip.setPixelColor(3, NeoPixel94V.PixelColor.RED); //3 ledStrip.render(); ledStrip.sleep(3000, 0); @@ -177,7 +162,7 @@ public void handle(Signal sig) { System.out.println("setting the LEDs to Orange"); - ledStrip.setStripColor(ledStrip.pixel.ORANGE); + ledStrip.setStripColor(NeoPixel94V.PixelColor.ORANGE); ledStrip.render(); ledStrip.sleep(3000, 0); @@ -189,10 +174,9 @@ public void handle(Signal sig) { ledStrip.waitForInput(); - System.out.println("setting the brightness to 50% and just show the sixth led as orange"); ledStrip.setBrightness(0.5); - ledStrip.setPixelColor(5, ledStrip.pixel.ORANGE); // 5 + ledStrip.setPixelColor(5, NeoPixel94V.PixelColor.ORANGE); // 5 ledStrip.render(); ledStrip.sleep(3000, 0); @@ -206,7 +190,7 @@ public void handle(Signal sig) { ledStrip.waitForInput(); System.out.println("setting the brightness to 50% and just show the seventh led as yellow"); - ledStrip.setPixelColor(6, ledStrip.pixel.YELLOW); // 6 + ledStrip.setPixelColor(6, NeoPixel94V.PixelColor.YELLOW); // 6 ledStrip.render(); ledStrip.sleep(3000, 0); @@ -221,7 +205,7 @@ public void handle(Signal sig) { System.out.println("setting the brightness to full and just show the fifth led as Green"); ledStrip.setBrightness(1); - ledStrip.setPixelColor(4, ledStrip.pixel.GREEN); //4 + ledStrip.setPixelColor(4, NeoPixel94V.PixelColor.GREEN); //4 ledStrip.render(); ledStrip.sleep(3000, 0); diff --git a/src/main/java/com/pi4j/devices/neopixel94v/README.md b/src/main/java/com/pi4j/devices/neopixel94v/README.md index da68809..4a34759 100644 --- a/src/main/java/com/pi4j/devices/neopixel94v/README.md +++ b/src/main/java/com/pi4j/devices/neopixel94v/README.md @@ -1,36 +1,66 @@ # + # -# * -# * - -# * #%L -# * ********************************************************************** -# * ORGANIZATION : Pi4J -# * PROJECT : Pi4J :: EXTENSION -# * FILENAME : README.md -# * -# * This file is part of the Pi4J project. More information about -# * this project can be found here: https://pi4j.com/ -# * ********************************************************************** -# * %% -# * * Copyright (C) 2012 - 2023 Pi4J -# * %% -# * -# * Licensed under the Apache License, Version 2.0 (the "License"); -# * you may not use this file except in compliance with the License. -# * You may obtain a copy of the License at -# * -# * http://www.apache.org/licenses/LICENSE-2.0 -# * -# * Unless required by applicable law or agreed to in writing, software -# * distributed under the License is distributed on an "AS IS" BASIS, -# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# * See the License for the specific language governing permissions and -# * limitations under the License. -# * #L% -# * + +# * + +# * - + +# * #%L + +# * ********************************************************************** + +# * ORGANIZATION : Pi4J + +# * PROJECT : Pi4J :: EXTENSION + +# * FILENAME : README.md + +# * + +# * This file is part of the Pi4J project. More information about + +# * this project can be found here: https://pi4j.com/ + +# * ********************************************************************** + +# * %% + +# * * Copyright (C) 2012 - 2023 Pi4J + +# * %% + +# * + +# * Licensed under the Apache License, Version 2.0 (the "License"); + +# * you may not use this file except in compliance with the License. + +# * You may obtain a copy of the License at + +# * + +# * http://www.apache.org/licenses/LICENSE-2.0 + +# * + +# * Unless required by applicable law or agreed to in writing, software + +# * distributed under the License is distributed on an "AS IS" BASIS, + +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +# * See the License for the specific language governing permissions and + +# * limitations under the License. + +# * #L% + +# * + # + # - # NeoPixel94V GRB Stick @@ -39,52 +69,47 @@ 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runNeopixel.sh OPT parms........ -Parm -t traceLevel + Parm -t traceLevel + +# NOTE: -# NOTE: At present this code uses the SPI. The timing is calculated for the Pi4 hardware. NEOPIXEL WS2812B uses the following timing to represent a '1' or a '0' bit. To accomplish in SPI, a '1' sends a byte0b11111000 and a '0' sends a byte 0b11000000. -When the array of bytes are sent via SPI at a specific frequency the WS2812B +When the array of bytes are sent via SPI at a specific frequency the WS2812B interprets the bytes as correctly timed 0's and 1's. To accomplish the SPI frequency is set to 8*500_000. - Pulse duration to represent a one or a zero. -int32_t highTime0NanoSeconds, 400 ns -int32_t lowTime0NanoSeconds, 850 ns -int32_t highTime1NanoSeconds, 800 ns -int32_t lowTime1NanoSeconds, 450 ns - +int32_t highTime0NanoSeconds, 400 ns +int32_t lowTime0NanoSeconds, 850 ns +int32_t highTime1NanoSeconds, 800 ns +int32_t lowTime1NanoSeconds, 450 ns -RED LEDSTRIP 0x00FF00; -Transmits 8 short, 8 long, 8 short +RED LEDSTRIP 0x00FF00; +Transmits 8 short, 8 long, 8 short -GREEN LEDSTRIP 0xFF0000 -Transmits 8 long, 8 short, 8 short +GREEN LEDSTRIP 0xFF0000 +Transmits 8 long, 8 short, 8 short BLUE LEDSTRIP 0x0000FF -Transmits 8 short, 8 short, 8 long - +Transmits 8 short, 8 short, 8 long 800/400 300/900 - - - Composition of 24bit data: G7 G6 G5 G4 G3 G2 G1 G0 R7 R6 R5 R4 R3 R2 R1 R0 B7 B6 B5 B4 B3 B2 B1 B0 Note: Follow the order of GRB to sent data and the high bit sent at first. -The NeoPixel94V class assumes the above order Green Red Blue. The code -method Render() uses this assumption when inflating the LEDs integer bits +The NeoPixel94V class assumes the above order Green Red Blue. The code +method Render() uses this assumption when inflating the LEDs integer bits to individual bytes. -If your LED strip uses a different order within the 24 bits the render function +If your LED strip uses a different order within the 24 bits the render function must be modified. diff --git a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_App_LCD1602A.java b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_App_LCD1602A.java index 8acd2b7..b31ec28 100644 --- a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_App_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_App_LCD1602A.java @@ -39,7 +39,6 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; import com.pi4j.devices.bmp280.BMP280Declares; - import com.pi4j.io.exception.IOException; import com.pi4j.util.Console; @@ -72,10 +71,10 @@ public static void main(String[] args) throws InterruptedException, IOException console.title("<-- The Pi4J V2 Project Extension -->", "HD44780U_App"); String helpString = " parms: HD44780U -b hex value bus -a hex value address -t trace \n " + - " -line1 LcdString,-line1Offset offset ," + - " -line2 LcdString, -line2Offset offset, -shiftL left shift -clearLCD \n" + - "-t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; + " -line1 LcdString,-line1Offset offset ," + + " -line2 LcdString, -line2Offset offset, -shiftL left shift -clearLCD \n" + + "-t trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { @@ -88,7 +87,7 @@ public static void main(String[] args) throws InterruptedException, IOException String a = args[i + 1]; i++; address = Integer.parseInt(a.substring(2), 16); - } else if(o.contentEquals("-line1")) { + } else if (o.contentEquals("-line1")) { String a = args[i + 1]; lineOne = a; i++; @@ -142,7 +141,7 @@ public static void main(String[] args) throws InterruptedException, IOException if (lineOne.length() > 0) { - dispObj.sendStringLineX(lineOne,1, lineOneOffset); + dispObj.sendStringLineX(lineOne, 1, lineOneOffset); } @@ -155,14 +154,13 @@ public static void main(String[] args) throws InterruptedException, IOException dispObj.shiftLeft(shiftLeftCount); Thread.sleep(5000); - if(clearLCD) { + if (clearLCD) { dispObj.clearDisplay(); } Thread.sleep(5000); - // dispObj.sendStringLineX("HelloWorld" , 1, 5); + // dispObj.sendStringLineX("HelloWorld" , 1, 5); } - } diff --git a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_Declares_LCD1602A.java b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_Declares_LCD1602A.java index f0c4f37..7bea7ff 100644 --- a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_Declares_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_Declares_LCD1602A.java @@ -38,33 +38,32 @@ public class PCF8574A_Declares_LCD1602A { - protected static final int pcf8574A_OutputValid = 4; - protected static final int pcf8574A_InputHold = 4; + protected static final int pcf8574A_OutputValid = 4; + protected static final int pcf8574A_InputHold = 4; - protected static final int data_bits_mask = 0b11110000; - protected static final int RS_bit_mask = 0b00000001; + protected static final int data_bits_mask = 0b11110000; + protected static final int RS_bit_mask = 0b00000001; - protected static final int E_bit_mask = 0b00000100; // E P2 - protected static final int E_bit_mask_off = 0b11111011; + protected static final int E_bit_mask = 0b00000100; // E P2 + protected static final int E_bit_mask_off = 0b11111011; - protected static final int E_low = 0b00000000; // P2 off - protected static final int E_high = 0b00000100; // P2 on + protected static final int E_low = 0b00000000; // P2 off + protected static final int E_high = 0b00000100; // P2 on - protected static final int backlight_on = 0b00001000; // P2 on - protected static final int backlight_off = 0b00000000; // P2 on + protected static final int backlight_on = 0b00001000; // P2 on + protected static final int backlight_off = 0b00000000; // P2 on - - protected static final int RS_bit_mask_off = 0b11111110; // RS P0 - protected static final int RS_low = 0b00000000; // P0 off + protected static final int RS_bit_mask_off = 0b11111110; // RS P0 + protected static final int RS_low = 0b00000000; // P0 off protected static final int RS_high = 0b00000001; // P0 on - protected static final int RW_bit_mask_off = 0b11111101; // RW P1 - protected static final int RW_low = 0b00000000; // P1 off - protected static final int RW_high = 0b00000010; // P1 on + protected static final int RW_bit_mask_off = 0b11111101; // RW P1 + protected static final int RW_low = 0b00000000; // P1 off + protected static final int RW_high = 0b00000010; // P1 on } diff --git a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_LCD1602A.java b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_LCD1602A.java index e35f188..b586b53 100644 --- a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_LCD1602A.java +++ b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/PCF8574A_LCD1602A.java @@ -47,12 +47,11 @@ public class PCF8574A_LCD1602A extends LCD1602A { private I2C pcfDev = null; - private int busNum; - private int address; + private final int busNum; + private final int address; - - public PCF8574A_LCD1602A(Context pi4j, Console console, String traceLevel, int bus, int address) { + public PCF8574A_LCD1602A(Context pi4j, Console console, String traceLevel, int bus, int address) { super(pi4j, console, false, traceLevel); this.busNum = bus; this.address = address; @@ -78,11 +77,11 @@ public void init() { this.sendCommand((byte) 0x3); this.sendCommand((byte) 0x2); - this.sendCommand(LCD1602A_Declares.funcSetCMD | LCD1602A_Declares.func4BitsBit | LCD1602A_Declares.func5x8TwoBit ); + this.sendCommand(LCD1602A_Declares.funcSetCMD | LCD1602A_Declares.func4BitsBit | LCD1602A_Declares.func5x8TwoBit); // enable LCD with blink - this.sendCommand(LCD1602A_Declares.dispCMD | LCD1602A_Declares.dispOnBit ); //| LCD1602A_Declares.dispCrsOnBit - this.sendCommand( LCD1602A_Declares.clearDispCMD); - // entry mode, cursor moves right each character + this.sendCommand(LCD1602A_Declares.dispCMD | LCD1602A_Declares.dispOnBit); //| LCD1602A_Declares.dispCrsOnBit + this.sendCommand(LCD1602A_Declares.clearDispCMD); + // entry mode, cursor moves right each character this.sendCommand(LCD1602A_Declares.entryModeCMD | LCD1602A_Declares.entryModeIncCMD); this.writeToDev((byte) LCD1602A_Declares.dispCMD); @@ -95,26 +94,28 @@ public void init() { /** * Write byte to actual device I2C interface - * @param data + * + * @param data */ - private void writeToDev(byte data){ - data |= PCF8574A_Declares_LCD1602A.backlight_on; - this.logger.trace(">>> Enter: writeToDev data: "+ String.format("%02x ", data) ); + private void writeToDev(byte data) { + data |= PCF8574A_Declares_LCD1602A.backlight_on; + this.logger.trace(">>> Enter: writeToDev data: " + String.format("%02x ", data)); String logData = ""; - logData += " \n P7-DB7: "+ ((data >> 7) & 0x1) + " P6-DB6: "+ ((data >> 6) & 0x1) + " P5-DB5: "+ ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + - "\n BackLight: " + ((data >> 3) & 0x1) + " EN: " + ((data >> 2) & 0x1) + " RW: " + ((data>>1) & 0x1) + " RS: " + ((data) & 0x1) + "\n Data : " + String.format("0X%02x: ",((data >> 4 ) &0xf)); + logData += " \n P7-DB7: " + ((data >> 7) & 0x1) + " P6-DB6: " + ((data >> 6) & 0x1) + " P5-DB5: " + ((data >> 5) & 0x1) + " P4-DB4: " + ((data >> 4) & 0x1) + + "\n BackLight: " + ((data >> 3) & 0x1) + " EN: " + ((data >> 2) & 0x1) + " RW: " + ((data >> 1) & 0x1) + " RS: " + ((data) & 0x1) + "\n Data : " + String.format("0X%02x: ", ((data >> 4) & 0xf)); this.logger.trace(logData); int rc = this.pcfDev.write(data); - this.sleepTimeMicroS(LCD1602A_Declares.preAddressWrtSetupDelay*2); + this.sleepTimeMicroS(LCD1602A_Declares.preAddressWrtSetupDelay * 2); - this.logger.trace("Exit: writeToDev RC : " + rc); + this.logger.trace("Exit: writeToDev RC : " + rc); } /** - * Set EN bit low + * Set EN bit low + * * @param b byte - * @return modified byte + * @return modified byte */ private byte setEnLow(byte b) { this.logger.trace(">>> Enter: setEnLow"); @@ -126,72 +127,78 @@ private byte setEnLow(byte b) { /** - * Set EN bit high + * Set EN bit high + * * @param b byte - * @return modified byte + * @return modified byte */ private byte setEnHigh(byte b) { this.logger.trace(">>> Enter: setEnHigh"); - b &= PCF8574A_Declares_LCD1602A.E_bit_mask_off; + b &= PCF8574A_Declares_LCD1602A.E_bit_mask_off; b |= PCF8574A_Declares_LCD1602A.E_high; this.logger.trace("<<< Exit: setEnHigh"); - return(b); + return (b); } /** - * Set RS bit low + * Set RS bit low + * * @param b byte - * @return modified byte + * @return modified byte */ private byte setRSLow(byte b) { this.logger.trace(">>> Enter: setRSLow"); - b &= PCF8574A_Declares_LCD1602A.RS_bit_mask_off; + b &= PCF8574A_Declares_LCD1602A.RS_bit_mask_off; b |= PCF8574A_Declares_LCD1602A.RS_low; this.logger.trace("<<< Exit: setRSLow"); - return(b); + return (b); } /** - * Set RS bit high + * Set RS bit high + * * @param b byte - * @return modified byte + * @return modified byte */ - private byte setRSHigh(byte b) { + private byte setRSHigh(byte b) { this.logger.trace(">>> Enter: setRSHigh"); - b &= PCF8574A_Declares_LCD1602A.RS_bit_mask_off; - b |= PCF8574A_Declares_LCD1602A.RS_high; + b &= PCF8574A_Declares_LCD1602A.RS_bit_mask_off; + b |= PCF8574A_Declares_LCD1602A.RS_high; this.logger.trace("<<< Exit: setRSHigh"); - return(b); + return (b); } /** - * Set RW bit low + * Set RW bit low + * * @param b byte - * @return modified byte + * @return modified byte */ private byte setRWLow(byte b) { this.logger.trace(">>> Enter: setRWLow"); - b &= PCF8574A_Declares_LCD1602A.RW_bit_mask_off; - b |= PCF8574A_Declares_LCD1602A.RW_low; + b &= PCF8574A_Declares_LCD1602A.RW_bit_mask_off; + b |= PCF8574A_Declares_LCD1602A.RW_low; this.logger.trace("<<< Exit: setRWLow"); - return(b); + return (b); } /** - * Set RW bit high + * Set RW bit high + * * @param b byte - * @return modified byte + * @return modified byte */ private byte setRWHigh(byte b) { this.logger.trace(">>> Enter: setRWHigh"); - b &= PCF8574A_Declares_LCD1602A.RW_bit_mask_off; - b |= PCF8574A_Declares_LCD1602A.RW_high; + b &= PCF8574A_Declares_LCD1602A.RW_bit_mask_off; + b |= PCF8574A_Declares_LCD1602A.RW_high; this.logger.trace("<<< Exit: setRWHigh"); - return(b); + return (b); } + private void createI2cDevice() { this.logger.trace(">>> Enter:createI2cDevice bus " + this.busNum + " address " + this.address); @@ -201,41 +208,41 @@ private void createI2cDevice() { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id(id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id(id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); this.pcfDev = this.pi4j.create(i2cDeviceConfig); this.logger.trace("<<< Exit:createI2cDevice "); } /** * Write byte to device P4-P7, then pulse EN pin so P4-P7 are read into LCD + * * @param b */ protected void writeFourBits(byte b) { - this.logger.trace(">>> Enter: writeFourBits : " + b + String.format(" 0X%02x: ", (int)b)); - this.writeToDev((byte) (b)); + this.logger.trace(">>> Enter: writeFourBits : " + b + String.format(" 0X%02x: ", (int) b)); + this.writeToDev(b); this.pulseEnable(b); this.logger.trace("<<< Exit: writeFourBits "); } - - /** * Set RS bit high and write high then low nibble to device + * * @param data */ protected void sendChar(char data) { - this.logger.trace(">>> Enter: sendChar : " + data + String.format(" 0X%02x: ", (int)data)); + this.logger.trace(">>> Enter: sendChar : " + data + String.format(" 0X%02x: ", (int) data)); if (this.lcdAvailable()) { - byte c= this.setRSHigh((byte) (data & 0xf0)); + byte c = this.setRSHigh((byte) (data & 0xf0)); this.writeFourBits(c); - c = this.setRSHigh((byte)((data << 4) & 0xF0)); + c = this.setRSHigh((byte) ((data << 4) & 0xF0)); this.writeFourBits(c); } else { this.logger.trace("LCD in busy state, request not possible"); @@ -247,6 +254,7 @@ protected void sendChar(char data) { /** * Set RS bit low and write high then low nibble to device + * * @param data */ protected void sendCommand(int data) { @@ -265,14 +273,13 @@ protected void sendCommand(int data) { /** * Modify data byte to set EN bit, write to device. - * Wait + * Wait * Clear bit and write to device * * @param b - * */ - protected void pulseEnable(byte b){ + protected void pulseEnable(byte b) { this.logger.trace(">>> Enter: pulseEnable "); b = this.setEnHigh(b); this.writeToDev(b); diff --git a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/README.md b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/README.md index 6d07a81..2cd6114 100644 --- a/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/README.md +++ b/src/main/java/com/pi4j/devices/pcf8574a_lcd1602a/README.md @@ -14,35 +14,29 @@ https://www.sparkfun.com/datasheets/LCD/ADM1602K-NSR-FBS-3.3v.pdf PCF8574A I2C controlling a 1602A LCD -D7-D4 High bit nibble sent first, then lower nibble - +D7-D4 High bit nibble sent first, then lower nibble i2c https://www.robotshop.com/community/forum/t/drive-a-standard-hd44780-lcd-using-a-pcf8574-and-i2c/12876 - - -PCF LCD -P0 RS -P1 RW -P2 E -P3 backlight -P4 D4 -P5 D5 -P6 D6 -P7 D7 - - +PCF LCD +P0 RS +P1 RW +P2 E +P3 backlight +P4 D4 +P5 D5 +P6 D6 +P7 D7 1. ./mvnw clean package 2. cd target/distribution 3. sudo ./runPCF8574A_LCD1602A.sh parms........ - -sudo ./runPCF8574A_LCD1602A.sh -b 0x01 -a 0x27 -t trace -line1 aBc -line2 XyZ +sudo ./runPCF8574A_LCD1602A.sh -b 0x01 -a 0x27 -t trace -line1 aBc -line2 XyZ Clears display, Line1 begins in fourth position, line2 begins in second position -sudo ./runPCF8574A_LCD1602A.sh -b 0x01 -a 0x27 -clearLCD -t trace -line1 aaaaaa -line1Offset 4 -line2 zzzzzz -line2Offset 2 - +sudo ./runPCF8574A_LCD1602A.sh -b 0x01 -a 0x27 -clearLCD -t trace -line1 aaaaaa -line1Offset 4 -line2 zzzzzz +-line2Offset 2 -Param -shiftL 2 shift both lines 2 positions to left +Param -shiftL 2 shift both lines 2 positions to left diff --git a/src/main/java/com/pi4j/devices/rotary_encoder/README.md b/src/main/java/com/pi4j/devices/rotary_encoder/README.md index bc9da64..c1f596e 100644 --- a/src/main/java/com/pi4j/devices/rotary_encoder/README.md +++ b/src/main/java/com/pi4j/devices/rotary_encoder/README.md @@ -1,59 +1,89 @@ #!/usr/bin/env bash + # + # -# -# * -# * - -# * #%L -# * ********************************************************************** -# * ORGANIZATION : Pi4J -# * PROJECT : Pi4J :: EXTENSION -# * FILENAME : runRotaryEncoder.sh -# * -# * This file is part of the Pi4J project. More information about -# * this project can be found here: https://pi4j.com/ -# * ********************************************************************** -# * %% -# * * Copyright (C) 2012 - 2022 Pi4J -# * %% -# * -# * Licensed under the Apache License, Version 2.0 (the "License"); -# * you may not use this file except in compliance with the License. -# * You may obtain a copy of the License at -# * -# * http://www.apache.org/licenses/LICENSE-2.0 -# * -# * Unless required by applicable law or agreed to in writing, software -# * distributed under the License is distributed on an "AS IS" BASIS, -# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# * See the License for the specific language governing permissions and -# * limitations under the License. -# * #L% -# * -# -# + # +# * +# * - -https://github.com/adafruit/Adafruit_CircuitPython_seesaw +# * #%L +# * ********************************************************************** +# * ORGANIZATION : Pi4J -Interrupt pin GPIO 21, Hex 15 +# * PROJECT : Pi4J :: EXTENSION + +# * FILENAME : runRotaryEncoder.sh + +# * + +# * This file is part of the Pi4J project. More information about + +# * this project can be found here: https://pi4j.com/ + +# * ********************************************************************** + +# * %% + +# * * Copyright (C) 2012 - 2022 Pi4J + +# * %% + +# * + +# * Licensed under the Apache License, Version 2.0 (the "License"); + +# * you may not use this file except in compliance with the License. + +# * You may obtain a copy of the License at + +# * +# * http://www.apache.org/licenses/LICENSE-2.0 + +# * + +# * Unless required by applicable law or agreed to in writing, software + +# * distributed under the License is distributed on an "AS IS" BASIS, + +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +# * See the License for the specific language governing permissions and + +# * limitations under the License. + +# * #L% + +# * + +# + +# + +# + +https://github.com/adafruit/Adafruit_CircuitPython_seesaw + +Interrupt pin GPIO 21, Hex 15 I2C connection path. + 1. mvn clean install 2. cd target/distribution 3. sudo ./runRotaryEncoder.sh Args Interrupt pin or address must be set, optionally -p - -sudo ./runRotaryEncoder.sh -i 0x15 -a 0x36 -p 0x0 -parms: -a hex address -i hex interrupt GPIO number, -p hex position, -h help +sudo ./runRotaryEncoder.sh -i 0x15 -a 0x36 -p 0x0 + +parms: -a hex address -i hex interrupt GPIO number, -p hex position, -h help -As the knob is twisted, each indent should change the returned +As the knob is twisted, each indent should change the returned encoder position by a value of 1. sudo is included in the command, depending on the I2C provider being used this may diff --git a/src/main/java/com/pi4j/devices/rotary_encoder/RotaryEncoderId5880I2C.java b/src/main/java/com/pi4j/devices/rotary_encoder/RotaryEncoderId5880I2C.java index 0f662db..9819000 100644 --- a/src/main/java/com/pi4j/devices/rotary_encoder/RotaryEncoderId5880I2C.java +++ b/src/main/java/com/pi4j/devices/rotary_encoder/RotaryEncoderId5880I2C.java @@ -36,14 +36,11 @@ package com.pi4j.devices.rotary_encoder; import com.pi4j.Pi4J; -import com.pi4j.exception.LifecycleException; import com.pi4j.io.gpio.digital.*; import com.pi4j.io.i2c.I2C; import com.pi4j.io.i2c.I2CConfig; import com.pi4j.io.i2c.I2CProvider; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; import static java.util.Arrays.fill; @@ -62,18 +59,6 @@ public static void main(String[] args) throws Exception { int address = 0x77; int pin = 42; int position = 0; - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - // Thread.dumpStack(); - System.exit(2); - } - }); String helpString = " parms: -a hex address -i hex interrupt GPIO number, -p hex position, -h help \n "; for (int i = 0; i < args.length; i++) { @@ -215,7 +200,6 @@ private static boolean set_encoder_position(I2C rotary, int pos) { } - private static boolean enable_encoder_interrupt(I2C rotary) { byte[] data = new byte[3]; data[0] = (byte) EncoderDeclares.base_addr; diff --git a/src/main/java/com/pi4j/devices/sn74hc595/README.md b/src/main/java/com/pi4j/devices/sn74hc595/README.md index d3658b4..cb43cfa 100644 --- a/src/main/java/com/pi4j/devices/sn74hc595/README.md +++ b/src/main/java/com/pi4j/devices/sn74hc595/README.md @@ -17,13 +17,13 @@ Specific usage of sn74hc595 to control 1602A LCD 9 8 gnd -gpio13 10 7 QH Red LED -gpio6 11 6 QG -gpio5 12 5 QF -gpio20 13 4 QE -gpio23 14 3 QD -QA 15 2 QC Green LED -Vdd 5v 16 1 QB +gpio13 10 7 QH Red LED +gpio6 11 6 QG +gpio5 12 5 QF +gpio20 13 4 QE +gpio23 14 3 QD +QA 15 2 QC Green LED +Vdd 5v 16 1 QB 1. ./mvnw clean package 2. cd target/distribution diff --git a/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595.java b/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595.java index f7ae551..cfba415 100644 --- a/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595.java +++ b/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595.java @@ -46,7 +46,6 @@ /** * SN74HC595 8 Bit shift register. Serial device. Uses GPIOs line manipulation to clock data into the device - * */ public class SN74HC595 implements HD44780U_Interface_LCD1602A { private final Console console; @@ -66,22 +65,18 @@ public class SN74HC595 implements HD44780U_Interface_LCD1602A { int DSPinNum = 0xff; - /** - * * @param pi4j - * @param console - * GPIO output lines from Pi, all are input signals to the chip - * The param name matches the spec. Three of the params document the - * state name used with in the source code. This rename makes their usage more obvious - * @param dsGpio DataPin sending from Pi to the chip + * @param console GPIO output lines from Pi, all are input signals to the chip + * The param name matches the spec. Three of the params document the + * state name used with in the source code. This rename makes their usage more obvious + * @param dsGpio DataPin sending from Pi to the chip * @param oeGpio - * @param stcpGpio Latch control - * @param shcpGpio Clock signal + * @param stcpGpio Latch control + * @param shcpGpio Clock signal * @param mrGpio - * - * @param registerData 8 bita, each representing the intended state of the output lines. QH------Qa - * @param traceLevel slf4j log level + * @param registerData 8 bita, each representing the intended state of the output lines. QH------Qa + * @param traceLevel slf4j log level */ public SN74HC595(Context pi4j, Console console, int dsGpio, int oeGpio, int stcpGpio, int shcpGpio, int mrGpio, byte registerData, String traceLevel) { super(); @@ -98,8 +93,8 @@ public SN74HC595(Context pi4j, Console console, int dsGpio, int oeGpio, int stcp } /** - * Create the five output pins - * Reset the chip, output enable the pins QH------Qa + * Create the five output pins + * Reset the chip, output enable the pins QH------Qa */ void init() { @@ -114,12 +109,12 @@ void init() { this.logger.trace("SHCP Pin " + this.SHCPPinNum); var outputConfig1 = DigitalOutput.newConfigBuilder(pi4j) - .id("OE_pin") - .name("Enable") - .address(this.OEPinNum) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); + .id("OE_pin") + .name("Enable") + .address(this.OEPinNum) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { this.oeGpio = pi4j.create(outputConfig1); } catch (Exception e) { @@ -128,12 +123,12 @@ void init() { System.exit(201); } var outputConfig2 = DigitalOutput.newConfigBuilder(pi4j) - .id("STCP_pin") - .name("STCP") - .address(this.STCPPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("STCP_pin") + .name("STCP") + .address(this.STCPPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { this.latchPin = pi4j.create(outputConfig2); } catch (Exception e) { @@ -142,12 +137,12 @@ void init() { System.exit(201); } var outputConfig3 = DigitalOutput.newConfigBuilder(pi4j) - .id("SHCP_pin") - .name("SHCP") - .address(this.SHCPPinNum) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); + .id("SHCP_pin") + .name("SHCP") + .address(this.SHCPPinNum) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { this.clockPin = pi4j.create(outputConfig3); } catch (Exception e) { @@ -156,12 +151,12 @@ void init() { System.exit(201); } var outputConfig4 = DigitalOutput.newConfigBuilder(pi4j) - .id("MR_pin") - .name("MR") - .address(this.MRPinNum) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("MR_pin") + .name("MR") + .address(this.MRPinNum) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); try { this.mrGpio = pi4j.create(outputConfig4); } catch (Exception e) { @@ -170,12 +165,12 @@ void init() { System.exit(201); } var outputConfig5 = DigitalOutput.newConfigBuilder(pi4j) - .id("DS_pin") - .name("DS") - .address(this.DSPinNum) - .shutdown(DigitalState.LOW) - .initial(DigitalState.LOW) - .provider("gpiod-digital-output"); + .id("DS_pin") + .name("DS") + .address(this.DSPinNum) + .shutdown(DigitalState.LOW) + .initial(DigitalState.LOW) + .provider("gpiod-digital-output"); try { this.dataPin = pi4j.create(outputConfig5); } catch (Exception e) { @@ -222,34 +217,32 @@ private void sleepTime(int ms) { @Override public void sendCommand(int cmd) { - String binaryString = Integer.toBinaryString(cmd & 0xff); - String withLeadingZeros = String.format("%8s", binaryString).replace(' ', '0'); - this.logger.trace(">>> Enter: sendCommand shift data " + withLeadingZeros); - - // walk through the byte of shift data, LSB to MSB - // Set the dataPin same as the shift bit. For each bit toggle the clockPin. - // After all bits processed, Toggle latchPin - this.latchPin.low(); // make certain chip is quiet + String binaryString = Integer.toBinaryString(cmd & 0xff); + String withLeadingZeros = String.format("%8s", binaryString).replace(' ', '0'); + this.logger.trace(">>> Enter: sendCommand shift data " + withLeadingZeros); + + // walk through the byte of shift data, LSB to MSB + // Set the dataPin same as the shift bit. For each bit toggle the clockPin. + // After all bits processed, Toggle latchPin + this.latchPin.low(); // make certain chip is quiet + this.clockPin.low(); + this.dataPin.low(); + for (int i = 7; i >= 0; i--) { this.clockPin.low(); - this.dataPin.low(); - for (int i = 7; i >= 0; i--) { - this.clockPin.low(); - int compareBit = 1; - compareBit = compareBit << i; - boolean bitSet = ((cmd & compareBit) > 0); - if (bitSet) { - this.dataPin.high(); - } else { - this.dataPin.low(); - } - this.clockPin.high(); + int compareBit = 1; + compareBit = compareBit << i; + boolean bitSet = ((cmd & compareBit) > 0); + if (bitSet) { + this.dataPin.high(); + } else { this.dataPin.low(); - ; - } - this.clockPin.low(); - this.latchPin.high(); + this.clockPin.high(); + this.dataPin.low(); + } + this.clockPin.low(); + this.latchPin.high(); this.logger.trace("<<< Exit: sendCommand"); diff --git a/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595App.java b/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595App.java index f027187..c0cc81a 100644 --- a/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595App.java +++ b/src/main/java/com/pi4j/devices/sn74hc595/SN74HC595App.java @@ -38,10 +38,7 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; /** @@ -69,21 +66,6 @@ public static void main(String[] args) { Context pi4j = Pi4J.newAutoContext(); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); - - final Console console = new Console(); console.print("=============================================================="); console.print("startup SN74HC595App "); @@ -91,9 +73,9 @@ public void handle(Signal sig) { String helpString = " parms: -t trace -ds HEX DS gpio\n" + - " -oe OE gpio, -st STCP gpio, -sh SHCP gpio, -mr MR gpio -rd HEX registerData \n" + - " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; + " -oe OE gpio, -st STCP gpio, -sh SHCP gpio, -mr MR gpio -rd HEX registerData \n" + + " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { @@ -118,7 +100,7 @@ public void handle(Signal sig) { String a = args[i + 1]; MRPinNum = Integer.parseInt(a); i++; - } else if (o.contentEquals("-rd")) { + } else if (o.contentEquals("-rd")) { String a = args[i + 1]; i++; registerData = (byte) (Integer.parseInt(a.substring(2), 16) & 0xff); diff --git a/src/main/java/com/pi4j/devices/ssd1306/SSD1306.java b/src/main/java/com/pi4j/devices/ssd1306/SSD1306.java index 73bdbc5..3d580c0 100644 --- a/src/main/java/com/pi4j/devices/ssd1306/SSD1306.java +++ b/src/main/java/com/pi4j/devices/ssd1306/SSD1306.java @@ -203,12 +203,12 @@ private void createI2cDevice() { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id(id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id(id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); this.config = i2cDeviceConfig; this.i2c = this.pi4j.create(i2cDeviceConfig); this.logger.info("Exit:createI2cDevice "); diff --git a/src/main/java/com/pi4j/devices/ssd1306/SSD1306Sample128X64IMAGE.java b/src/main/java/com/pi4j/devices/ssd1306/SSD1306Sample128X64IMAGE.java index 63dd638..87bc1f5 100644 --- a/src/main/java/com/pi4j/devices/ssd1306/SSD1306Sample128X64IMAGE.java +++ b/src/main/java/com/pi4j/devices/ssd1306/SSD1306Sample128X64IMAGE.java @@ -66,68 +66,68 @@ public class SSD1306Sample128X64IMAGE { static public byte[] ImageOne = - {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xf7, (byte) 0x98, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xdf, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x3f, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0f, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0xa0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xf6, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xdf, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x3f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xec, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x23, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x23, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x3f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xec, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xdf, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x5f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xf6, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1b, (byte) 0xff, (byte) 0xff, (byte) 0xa0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0f, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x3f, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xdf, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xf7, (byte) 0x98, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}; + {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xf7, (byte) 0x98, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xdf, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x3f, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0f, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0xa0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xf6, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xdf, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x3f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xec, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x23, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x23, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x3f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xec, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xdf, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xe0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x5f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xfe, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xf6, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1b, (byte) 0xff, (byte) 0xff, (byte) 0xa0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0xff, (byte) 0xff, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0f, (byte) 0xff, (byte) 0xff, (byte) 0xc0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x3f, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xdf, (byte) 0xfc, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xf7, (byte) 0x98, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}; } diff --git a/src/main/java/com/pi4j/devices/ssd1306/SSD1306_Example.java b/src/main/java/com/pi4j/devices/ssd1306/SSD1306_Example.java index 5226b11..1ee9764 100644 --- a/src/main/java/com/pi4j/devices/ssd1306/SSD1306_Example.java +++ b/src/main/java/com/pi4j/devices/ssd1306/SSD1306_Example.java @@ -38,11 +38,7 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; -import com.pi4j.plugin.linuxfs.provider.i2c.LinuxFsI2CProvider; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; import java.util.Arrays; @@ -80,8 +76,7 @@ public static void main(String[] args) throws Exception { // may include 'Platforms' and 'I/O Providers' - - Context pi4j = Pi4J.newAutoContext(); + Context pi4j = Pi4J.newAutoContext(); // print installed providers System.out.println("----------------------------------------------------------"); @@ -89,19 +84,6 @@ public static void main(String[] args) throws Exception { System.out.println("----------------------------------------------------------"); pi4j.providers().describe().print(System.out); System.out.println("----------------------------------------------------------"); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); final Console console = new Console(); @@ -111,7 +93,7 @@ public void handle(Signal sig) { String helpString = " parms: -b hex value bus -a hex value address -t trace \n " + - " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; + " \n trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { String o = args[i]; diff --git a/src/main/java/com/pi4j/devices/tca9548/README.md b/src/main/java/com/pi4j/devices/tca9548/README.md index aa11bec..bfaeb6e 100644 --- a/src/main/java/com/pi4j/devices/tca9548/README.md +++ b/src/main/java/com/pi4j/devices/tca9548/README.md @@ -8,17 +8,18 @@ Pi4J :: Java I/O Library for Raspberry Pi :: Device :: TCA9548 Project by Tom Aarts ========================================================================== - -Java classes to access the TCA9548 Low-Voltage 8-Channel I2C Switch. Includes + +Java classes to access the TCA9548 Low-Voltage 8-Channel I2C Switch. Includes a Sample application class SampleTca9548App. This sample demonstrates using the Tca9548 class to effect chip register modifications and show recovery concerns if an incorrect request fails. Supported functions. - 1. reset chip - 2. enable a particular bus - 3. disable a particular bus - 4. Pretty-Print bus enablement status + +1. reset chip +2. enable a particular bus +3. disable a particular bus +4. Pretty-Print bus enablement status The classes are implemented using the Pi4j_V2 requirements of September 1 2020. @@ -35,44 +36,43 @@ path will not read this pom file. 2. cd target/distribution 3. sudo ./runTca9548.sh -b 0x01 -a 0x70 -f 1 -l -e 0x2 -r 0x6 - Dependent upon the -f parameter value logging details will be stored in /tmp/logs/com.pi4j.devices.tca9548.Tca9548.log The run command will cd into the base classes directory and invoke the application with parameters that reset the chip and then enables bus 2. - You can review the SampleTca9548App usage() method for parameter values. - The command assumes GPIO6 is wired to the TCA9548 reset pin, modify the - parameter "-r 0x06" value to align with your environment. In addition - parameter -b 0x01 value assumes the chip is connected to raspberry I2C bus 1, - and the chip is operating at default address -a 0x70. +You can review the SampleTca9548App usage() method for parameter values. +The command assumes GPIO6 is wired to the TCA9548 reset pin, modify the +parameter "-r 0x06" value to align with your environment. In addition +parameter -b 0x01 value assumes the chip is connected to raspberry I2C bus 1, +and the chip is operating at default address -a 0x70. If you are debugging a problem: Execute your code with the -f parm 0. After your execution the log file /tmp/logs/com.pi4j.devices.tca9548.Tca9548.log will contain its maximum detail, this can be used to debug your error. Classes: -com.pi4j.devices.base_i2c.BasicI2cDevice Simple layer between TCA9548 and the - pi4j_v2 infratructure to add logging details to assist in debug. -com.pi4j.devices.base_i2c.I2cSimpleRead Utility to read bytes one at a time. +com.pi4j.devices.base_i2c.BasicI2cDevice Simple layer between TCA9548 and the +pi4j_v2 infratructure to add logging details to assist in debug. +com.pi4j.devices.base_i2c.I2cSimpleRead Utility to read bytes one at a time. Used to debug. com.pi4j.devices.base_util.ffdc.FfdcLoggingSystem Interface to print system details. com.pi4j.devices.base_util.ffdc.FfdcLoggingModule Interface to perform logging. Allows implementing class to add details to any message. -com.pi4j.devices.base_util.ffdc.FfdcUtil Implements the FfdcLoggingSystem and +com.pi4j.devices.base_util.ffdc.FfdcUtil Implements the FfdcLoggingSystem and FfdcLoggingModule interface -com.pi4j.devices.base_util.gpio.GpioBasics Gpio utilties +com.pi4j.devices.base_util.gpio.GpioBasics Gpio utilties -com.pi4j.devices.base_util.PrintInfo Static methods used by FfdcLoggingSystem +com.pi4j.devices.base_util.PrintInfo Static methods used by FfdcLoggingSystem implemtentor. com.pi4j.devices.tca9548.Tca9548ConfigData Maps bus number mask value. Although - a simple 1 shifted left busNumberTimes could accomplish the same, this was - implemented as a method to support any future chip datasheet. +a simple 1 shifted left busNumberTimes could accomplish the same, this was +implemented as a method to support any future chip datasheet. com.pi4j.devices.tca9548.Tca9548 TCA9548 implementation -com.pi4j.devices.tca9548.SampleTca9548App Demonstrate application use of the +com.pi4j.devices.tca9548.SampleTca9548App Demonstrate application use of the Tca9548 class. diff --git a/src/main/java/com/pi4j/devices/tca9548/SampleTca9548App.java b/src/main/java/com/pi4j/devices/tca9548/SampleTca9548App.java index c541642..b55edf2 100644 --- a/src/main/java/com/pi4j/devices/tca9548/SampleTca9548App.java +++ b/src/main/java/com/pi4j/devices/tca9548/SampleTca9548App.java @@ -34,16 +34,11 @@ package com.pi4j.devices.tca9548; -import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; +import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.util.Console; -import com.pi4j.devices.tca9548.Tca9548; -import sun.misc.Signal; -import sun.misc.SignalHandler; - /** * SampleTca9548App *

    @@ -64,9 +59,9 @@ public class SampleTca9548App { */ static private void usage() { System.out.println( - "options -h 'help', -b bus, -a address," + "-n number of bytes -s sysCfg " + - " -f ffdc_lvl :1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF " + - " -e busToEnabled -d busToDisabled -l displayEnableReg -r resetChip GPIO# \n "); + "options -h 'help', -b bus, -a address," + "-n number of bytes -s sysCfg " + + " -f ffdc_lvl :1 DEBUG < 2 INFO < 3 WARN < 4 ERROR < 5 FATAL < 6 OFF " + + " -e busToEnabled -d busToDisabled -l displayEnableReg -r resetChip GPIO# \n "); } /** @@ -167,20 +162,6 @@ public static void main(String[] args) throws Exception { FfdcUtil ffdc = new FfdcUtil(console, pi4j, ffdcControlLevel, Tca9548.class); var tcaMux = new Tca9548(pi4j, ffdc, busNum, address, console); - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - ffdc.ffdcFlushShutdown(); // push all logs to the file - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); // Based upon parms the user supplied, call Tca9548 methods if (showUsage) { @@ -197,7 +178,7 @@ public void handle(Signal sig) { // Set controls for the log4j logging if (setFfdcLvl) { - if (ffdc.setLevel(ffdcControlLevel) == false) { + if (!ffdc.setLevel(ffdcControlLevel)) { console.println("FFDC level invalid :" + ffdcControlLevel); // recovery code needed } @@ -208,14 +189,14 @@ public void handle(Signal sig) { } // enable a bus if (enableBus) { - if (tcaMux.enableBus(muxBusNumber) == false) { + if (!tcaMux.enableBus(muxBusNumber)) { console.println("enable bus failed. -e was :" + muxBusNumber); // Recovery code to use correct bus number ? Maybe error exit } } // disable a bus if (disableBus) { - if (tcaMux.disableBus(muxBusNumber) == false) { + if (!tcaMux.disableBus(muxBusNumber)) { console.println("enable bus failed. -e was :" + muxBusNumber); // Recovery code to use correct bus number ? Maybe error exit } diff --git a/src/main/java/com/pi4j/devices/tca9548/Tca9548.java b/src/main/java/com/pi4j/devices/tca9548/Tca9548.java index e9840b9..30755a9 100644 --- a/src/main/java/com/pi4j/devices/tca9548/Tca9548.java +++ b/src/main/java/com/pi4j/devices/tca9548/Tca9548.java @@ -35,14 +35,14 @@ package com.pi4j.devices.tca9548; -import com.pi4j.devices.base_util.ffdc.FfdcUtil; import com.pi4j.context.Context; +import com.pi4j.devices.base_i2c.BasicI2cDevice; +import com.pi4j.devices.base_util.ffdc.FfdcUtil; +import com.pi4j.devices.base_util.gpio.GpioBasics; import com.pi4j.io.exception.IOException; import com.pi4j.io.gpio.digital.DigitalOutput; import com.pi4j.io.gpio.digital.DigitalState; import com.pi4j.util.Console; -import com.pi4j.devices.base_i2c.BasicI2cDevice; -import com.pi4j.devices.base_util.gpio.GpioBasics; /** @@ -99,13 +99,13 @@ private void init() { * PreCond: Tca9548 instance initialized. See CTOR * * @param disableBusNum Bus to disable - *

    - * PostCond: If successful return true, else false. - *

    - *

    - * Note: register contents for disableBusNumber are effected, all other register - * contents are NOT modified. - *

    + *

    + * PostCond: If successful return true, else false. + *

    + *

    + * Note: register contents for disableBusNumber are effected, all other register + * contents are NOT modified. + *

    */ public boolean disableBus(int disableBusNum) { // TODO Auto-generated method stub @@ -115,7 +115,7 @@ public boolean disableBus(int disableBusNum) { this.ffdc.ffdcMethodEntry(this.getMethodName() + " bus number: " + disableBusNum); try { - reg = this.readByte(); + reg = this.readByte(); } catch (java.io.IOException e) { this.ffdc.ffdcErrorEntry("disableBus readByte failed"); rval = false; @@ -128,19 +128,19 @@ public boolean disableBus(int disableBusNum) { } if (rval) { - String regAstr = ""; + String regAstr = ""; int val = busBits; regAstr = regAstr.concat("busBits \n"); regAstr = regAstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " - + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " + + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); this.ffdc.ffdcDebugEntry(regAstr); val = ~busBits; regAstr = regAstr.concat("busBits \n"); regAstr = regAstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " - + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " + + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); this.ffdc.ffdcDebugEntry(regAstr); reg = (byte) (reg & (~busBits)); reg = (byte) this.write(reg); @@ -157,13 +157,13 @@ public boolean disableBus(int disableBusNum) { * * @param enableBusNum Bus to enable * - *

    - * PostCond: If successful return true, else false. - *

    - *

    - * Note: register contents for enableBusNumber are effected, all other register - * contents are NOT modified. - *

    + *

    + * PostCond: If successful return true, else false. + *

    + *

    + * Note: register contents for enableBusNumber are effected, all other register + * contents are NOT modified. + *

    */ public boolean enableBus(int enableBusNum) { byte reg = 0; @@ -183,11 +183,11 @@ public boolean enableBus(int enableBusNum) { rval = false; } - if(rval){ + if (rval) { reg = (byte) (reg | busBits); rcode = this.write(reg); rval = this.examineReturnWrite(rcode); - } + } this.ffdc.ffdcMethodExit((this.getMethodName() + " rval :" + rval)); return (rval); } @@ -222,8 +222,8 @@ public void displayBusEnable() { regAstr = regAstr.concat("tca9548 bus enable register \n"); regAstr = regAstr.concat(pinName + "\n"); regAstr = regAstr.concat(" " + ((val & 0x80) >> 7) + " " + ((val & 0x40) >> 6) + " " - + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " - + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); + + ((val & 0x20) >> 5) + " " + ((val & 0x10) >> 4) + " " + ((val & 0x08) >> 3) + " " + + ((val & 0x04) >> 2) + " " + ((val & 0x02) >> 1) + " " + ((val & 0x01)) + "\n"); this.ffdc.ffdcDebugEntry(regAstr); System.out.println(regAstr); } @@ -242,16 +242,16 @@ public void displayBusEnable() { * *

    * PostCond: Chip reset. - */ + */ public void resetChip(int resetGpio) { this.ffdc.ffdcMethodEntry(this.getMethodName() + " GPIO" + resetGpio); var ledConfig = DigitalOutput.newConfigBuilder(pi4j) - .id("restPin") - .name("tca95448 reset") - .address(resetGpio) - .shutdown(DigitalState.HIGH) - .initial(DigitalState.HIGH) - .provider("gpiod-digital-output"); + .id("restPin") + .name("tca95448 reset") + .address(resetGpio) + .shutdown(DigitalState.HIGH) + .initial(DigitalState.HIGH) + .provider("gpiod-digital-output"); DigitalOutput resetPin = null; try { resetPin = pi4j.create(ledConfig); @@ -273,5 +273,4 @@ public void resetChip(int resetGpio) { } - } diff --git a/src/main/java/com/pi4j/devices/tca9548/Tca9548ConfigData.java b/src/main/java/com/pi4j/devices/tca9548/Tca9548ConfigData.java index 1d50d5f..c5464e6 100644 --- a/src/main/java/com/pi4j/devices/tca9548/Tca9548ConfigData.java +++ b/src/main/java/com/pi4j/devices/tca9548/Tca9548ConfigData.java @@ -34,7 +34,7 @@ package com.pi4j.devices.tca9548; -import com.pi4j.devices.base_util.ffdc.*; +import com.pi4j.devices.base_util.ffdc.FfdcUtil; /** * Class contains chip specific values.Details found in the chip Data Sheet. diff --git a/src/main/java/com/pi4j/devices/vl53L0X/README.md b/src/main/java/com/pi4j/devices/vl53L0X/README.md index 39d6d76..4a0628f 100644 --- a/src/main/java/com/pi4j/devices/vl53L0X/README.md +++ b/src/main/java/com/pi4j/devices/vl53L0X/README.md @@ -42,14 +42,13 @@ At power on the chip is configured to 0x29 device address, default parm values w Config the i2c mux -sudo ./runTca9548.sh -b 0x01 -a 0x70 -f 1 -l -e 0x2 -r 0x13 - +sudo ./runTca9548.sh -b 0x01 -a 0x70 -f 1 -l -e 0x2 -r 0x13 sudo ./runVL53L0X.sh The user can reconfigure the chips device (ACK) address -sudo ./runVL53L0X.sh -b 0x1 -a 0x2D -r 21 -x 0x29 -t info - -a 0x2D desired future address -r 21 Pi gpio connected to the chips XSHUT pin -x existing address +sudo ./runVL53L0X.sh -b 0x1 -a 0x2D -r 21 -x 0x29 -t info +-a 0x2D desired future address -r 21 Pi gpio connected to the chips XSHUT pin -x existing address sudo ./runVL53L0X.sh -b 0x1 -a 0x2D Must supply the newly configured device address \ No newline at end of file diff --git a/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_App.java b/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_App.java index ca5b720..fd15991 100644 --- a/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_App.java +++ b/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_App.java @@ -36,10 +36,7 @@ import com.pi4j.Pi4J; import com.pi4j.context.Context; -import com.pi4j.exception.LifecycleException; import com.pi4j.util.Console; -import sun.misc.Signal; -import sun.misc.SignalHandler; /** @@ -55,19 +52,6 @@ public static void main(String[] args) { /* var pi4j = Pi4J.newContextBuilder().add( linuxfs-i2cProvider.newInstance()).build(); */ - // Prior to running methods, set up control-c handler - Signal.handle(new Signal("INT"), new SignalHandler() { - public void handle(Signal sig) { - System.out.println("Performing ctl-C shutdown"); - try { - pi4j.shutdown(); - } catch (LifecycleException e) { - e.printStackTrace(); - } - Thread.dumpStack(); - System.exit(2); - } - }); final Console console = new Console(); @@ -85,9 +69,9 @@ public void handle(Signal sig) { int gpioReset = 0; String helpString = " parms: -b hex value bus -a hex value address -t trace \n " + - " -r reset integer value GPIO -x hex value address prior to reset \n " + - " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + - " or \"off\" Default \"info\""; + " -r reset integer value GPIO -x hex value address prior to reset \n " + + " trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + + " or \"off\" Default \"info\""; String traceLevel = "info"; for (int i = 0; i < args.length; i++) { @@ -129,7 +113,7 @@ public void handle(Signal sig) { System.exit(42); } } - if ((doReset && (existingSet == false)) || ((doReset == false) && (existingSet))) { + if ((doReset && (!existingSet)) || ((!doReset) && (existingSet))) { console.println(" !!! Invalid Parm combination, if either -r or -x is used, requires both"); console.println(" parms: -b hex value bus -a hex value address -r reset integer value GPIO -x hex value existing address prior to reset "); System.exit(43); diff --git a/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_Device.java b/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_Device.java index 59df48d..84a0ca9 100644 --- a/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_Device.java +++ b/src/main/java/com/pi4j/devices/vl53L0X/VL53L0X_Device.java @@ -89,17 +89,17 @@ public VL53L0X_Device(Context pi4j, int bus, int address, String traceLevel) { I2C createI2cDevice(int bus, int address) { String id = String.format("0X%02x: ", bus); String name = String.format("0X%02x: ", address); - this.logger.info("Enter: createI2cDevice VL53L0X_TOF" + id + "" + name); + this.logger.info("Enter: createI2cDevice VL53L0X_TOF" + id + name); I2C rval = null; var i2cDeviceConfig = I2C.newConfigBuilder(this.pi4j) - .bus(bus) - .device(address) - .id("VL53L0X_TOF " + id + " " + name) - .name(name) - .provider("linuxfs-i2c") - .build(); + .bus(bus) + .device(address) + .id("VL53L0X_TOF " + id + " " + name) + .name(name) + .provider("linuxfs-i2c") + .build(); rval = this.pi4j.create(i2cDeviceConfig); - this.logger.info("Exit: createI2cDevice VL53L0X_TOF" + id + "" + name); + this.logger.info("Exit: createI2cDevice VL53L0X_TOF" + id + name); return (rval); } @@ -155,8 +155,8 @@ void init(int bus, int address) { } int[][] pair3 = {{0xFF, 0x01}, {Vl53L0X_Declares._DYNAMIC_SPAD_REF_EN_START_OFFSET, 0x00}, - {Vl53L0X_Declares._DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C}, {0xFF, 0x00}, - {Vl53L0X_Declares._GLOBAL_CONFIG_REF_EN_START_SELECT, 0xB4}}; + {Vl53L0X_Declares._DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C}, {0xFF, 0x00}, + {Vl53L0X_Declares._GLOBAL_CONFIG_REF_EN_START_SELECT, 0xB4}}; for (int i = 0; i < pair3.length; i++) { this.writeDevice8(pair3[i][0], (byte) pair3[i][1]); } @@ -185,19 +185,19 @@ void init(int bus, int address) { } int[][] pair4 = {{0xFF, 0x01}, {0x00, 0x00}, {0xFF, 0x00}, {0x09, 0x00}, {0x10, 0x00}, - {0x11, 0x00}, {0x24, 0x01}, {0x25, 0xFF}, {0x75, 0x00}, {0xFF, 0x01}, {0x4E, 0x2C}, - {0x48, 0x00}, {0x30, 0x20}, {0xFF, 0x00}, {0x30, 0x09}, {0x54, 0x00}, {0x31, 0x04}, - {0x32, 0x03}, {0x40, 0x83}, {0x46, 0x25}, {0x60, 0x00}, {0x27, 0x00}, {0x50, 0x06}, - {0x51, 0x00}, {0x52, 0x96}, {0x56, 0x08}, {0x57, 0x30}, {0x61, 0x00}, {0x62, 0x00}, - {0x64, 0x00}, {0x65, 0x00}, {0x66, 0xA0}, {0xFF, 0x01}, {0x22, 0x32}, {0x47, 0x14}, - {0x49, 0xFF}, {0x4A, 0x00}, {0xFF, 0x00}, {0x7A, 0x0A}, {0x7B, 0x00}, {0x78, 0x21}, - {0xFF, 0x01}, {0x23, 0x34}, {0x42, 0x00}, {0x44, 0xFF}, {0x45, 0x26}, {0x46, 0x05}, - {0x40, 0x40}, {0x0E, 0x06}, {0x20, 0x1A}, {0x43, 0x40}, {0xFF, 0x00}, {0x34, 0x03}, - {0x35, 0x44}, {0xFF, 0x01}, {0x31, 0x04}, {0x4B, 0x09}, {0x4C, 0x05}, {0x4D, 0x04}, - {0xFF, 0x00}, {0x44, 0x00}, {0x45, 0x20}, {0x47, 0x08}, {0x48, 0x28}, {0x67, 0x00}, - {0x70, 0x04}, {0x71, 0x01}, {0x72, 0xFE}, {0x76, 0x00}, {0x77, 0x00}, {0xFF, 0x01}, - {0x0D, 0x01}, {0xFF, 0x00}, {0x80, 0x01}, {0x01, 0xF8}, {0xFF, 0x01}, {0x8E, 0x01}, - {0x00, 0x01}, {0xFF, 0x00}, {0x80, 0x00}}; + {0x11, 0x00}, {0x24, 0x01}, {0x25, 0xFF}, {0x75, 0x00}, {0xFF, 0x01}, {0x4E, 0x2C}, + {0x48, 0x00}, {0x30, 0x20}, {0xFF, 0x00}, {0x30, 0x09}, {0x54, 0x00}, {0x31, 0x04}, + {0x32, 0x03}, {0x40, 0x83}, {0x46, 0x25}, {0x60, 0x00}, {0x27, 0x00}, {0x50, 0x06}, + {0x51, 0x00}, {0x52, 0x96}, {0x56, 0x08}, {0x57, 0x30}, {0x61, 0x00}, {0x62, 0x00}, + {0x64, 0x00}, {0x65, 0x00}, {0x66, 0xA0}, {0xFF, 0x01}, {0x22, 0x32}, {0x47, 0x14}, + {0x49, 0xFF}, {0x4A, 0x00}, {0xFF, 0x00}, {0x7A, 0x0A}, {0x7B, 0x00}, {0x78, 0x21}, + {0xFF, 0x01}, {0x23, 0x34}, {0x42, 0x00}, {0x44, 0xFF}, {0x45, 0x26}, {0x46, 0x05}, + {0x40, 0x40}, {0x0E, 0x06}, {0x20, 0x1A}, {0x43, 0x40}, {0xFF, 0x00}, {0x34, 0x03}, + {0x35, 0x44}, {0xFF, 0x01}, {0x31, 0x04}, {0x4B, 0x09}, {0x4C, 0x05}, {0x4D, 0x04}, + {0xFF, 0x00}, {0x44, 0x00}, {0x45, 0x20}, {0x47, 0x08}, {0x48, 0x28}, {0x67, 0x00}, + {0x70, 0x04}, {0x71, 0x01}, {0x72, 0xFE}, {0x76, 0x00}, {0x77, 0x00}, {0xFF, 0x01}, + {0x0D, 0x01}, {0xFF, 0x00}, {0x80, 0x01}, {0x01, 0xF8}, {0xFF, 0x01}, {0x8E, 0x01}, + {0x00, 0x01}, {0xFF, 0x00}, {0x80, 0x00}}; for (int i = 0; i < pair4.length; i++) { this.writeDevice8(pair4[i][0], (byte) pair4[i][1]); @@ -286,18 +286,18 @@ public void setNewAddress(int gpioReset, int newAddress, Console console, int ex void resetChip(int resetGpio, Context pi4j, int delay, boolean bar, DigitalState initial, Console console) { this.logger.trace("Enter: resetChip gpio " + resetGpio + " delay " + delay + " UnderBar " + bar + " initial state " + initial); var resetConfig = DigitalOutput.newConfigBuilder(pi4j) - .id("resetPin") - .name("Chip reset") - .address(resetGpio) - .shutdown(initial) - .initial(initial) - .provider("gpiod-digital-output"); + .id("resetPin") + .name("Chip reset") + .address(resetGpio) + .shutdown(initial) + .initial(initial) + .provider("gpiod-digital-output"); DigitalOutput resetPin = null; try { resetPin = pi4j.create(resetConfig); } catch (Exception e) { e.printStackTrace(); - console.println(String.format("reset_chip %s", e.toString()), 600); + console.println(String.format("reset_chip %s", e), 600); } try { if (bar) { // active low @@ -436,12 +436,12 @@ private void set_measurement_timing_budget(int budget_us) { } int final_range_timeout_us = budget_us - used_budget_us; int final_range_timeout_mclks = this.get_timeout_microseconds_to_mclks(final_range_timeout_us, - final_range_vcsel_period_pclks); + final_range_vcsel_period_pclks); if (pre_range) { final_range_timeout_mclks += pre_range_mclks; } this.writeDevice16(Vl53L0X_Declares._FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, - this.encode_timeout(final_range_timeout_mclks)); + this.encode_timeout(final_range_timeout_mclks)); this.measurement_timing_budget_us = budget_us; this.logger.trace("Exit: set_measurement_timing_budget "); @@ -458,18 +458,18 @@ private StepTimeouts get_sequence_step_timeouts(boolean pre_range) { int msrc_dss_tcc_mclks = (this.readDevice8(Vl53L0X_Declares._MSRC_CONFIG_TIMEOUT_MACROP) + 1) & 0xFF; int msrc_dss_tcc_us = this.timeout_mclks_to_microseconds(msrc_dss_tcc_mclks, pre_range_vcsel_period_pclks); int pre_range_mclks = this - .decode_timeout(this.readDevice16(Vl53L0X_Declares._PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI)); + .decode_timeout(this.readDevice16(Vl53L0X_Declares._PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI)); int pre_range_us = this.timeout_mclks_to_microseconds(pre_range_mclks, pre_range_vcsel_period_pclks); int final_range_vcsel_period_pclks = this.get_vcsel_pulse_period(Vl53L0X_Declares._VCSEL_PERIOD_FINAL_RANGE); int final_range_mclks = this - .decode_timeout(this.readDevice16(Vl53L0X_Declares._FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI)); + .decode_timeout(this.readDevice16(Vl53L0X_Declares._FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI)); if (pre_range) { final_range_mclks -= pre_range_mclks; } int final_range_us = this.timeout_mclks_to_microseconds(final_range_mclks, final_range_vcsel_period_pclks); StepTimeouts rval = new StepTimeouts(msrc_dss_tcc_us, pre_range_us, final_range_us, - final_range_vcsel_period_pclks, pre_range_mclks); - this.logger.trace("Exit: get_sequence_step_timeouts StepTimeouts " + rval.toString()); + final_range_vcsel_period_pclks, pre_range_mclks); + this.logger.trace("Exit: get_sequence_step_timeouts StepTimeouts " + rval); return (rval); } @@ -512,7 +512,7 @@ private StepEnable get_sequence_step_enables() { boolean pre_range = ((sequence_config >> 6) & 0x1) > 0; boolean final_range = ((sequence_config >> 7) & 0x1) > 0; StepEnable rval = new StepEnable(tcc, dss, msrc, pre_range, final_range); - this.logger.trace("Exit: get_sequence_step_enables " + rval.toString()); + this.logger.trace("Exit: get_sequence_step_enables " + rval); return (rval); } @@ -731,7 +731,7 @@ int range() { this.logger.trace("Entered range()"); int[][] pair = {{0x80, 0x01}, {0xFF, 0x01}, {0x00, 0x00}, {0x91, this._stop_variable}, {0x00, 0x01}, - {0xFF, 0x00}, {0x80, 0x00}, {Vl53L0X_Declares._SYSRANGE_START, 0x01}}; + {0xFF, 0x00}, {0x80, 0x00}, {Vl53L0X_Declares._SYSRANGE_START, 0x01}}; for (int i = 0; i < pair.length; i++) { this.writeDevice8(pair[i][0], (byte) pair[i][1]); } @@ -739,7 +739,7 @@ int range() { float start = System.nanoTime() / (float) 1000000; while ((this.readDevice8(Vl53L0X_Declares._SYSRANGE_START) & 0x01) > 0) { if (((System.nanoTime() / (float) 1000000) > 0) - && (((System.nanoTime() / (float) 1000000) - start) >= this.io_timeout_s)) { + && (((System.nanoTime() / (float) 1000000) - start) >= this.io_timeout_s)) { this.logger.error("Timeout waiting for VL53L0X!"); System.exit(60); }