javaraspberry-pisensorsgrovepi+

how to get pH in Java using Grove - PH Sensor Kit (E-201C-Blue) Raspberry pi Zero and GrovePi Zero Board


I have GrovePi Zero(GrovePi0) from GrovePi Zero Base Kit and Grove - PH Sensor Kit (E-201C-Blue) I am using Java (I can use any version of JDK 8...17) on a Raspberry Pi Zerro 2. with GrovePi-pi4j with Pi4j version 1.4 (can use any version)

my class GrovePHSensor below represents the PH Sensor.

@GroveAnalogPin
public class GrovePHSensor extends GroveAnalogInputDevice<Double> {
   
public GrovePHSensor(GrovePi grovePi, int pin) throws IOException {
    super(grovePi.getAnalogIn(pin, 4));
}

@Override
public Double get(byte[] data) {
 /// WHAT TO DO HERE?
}
}

the problem is that there are tons of strange code out there that give different result and even if I think that I understand what it does I am not sure if it the right thing to do.

for example the this thread is very confusing https://forum.dexterindustries.com/t/grove-ph-sensor-kit-e-201c-blue-raspberry-pi-zero/7961/13

at the same time wiki page at Seeed https://wiki.seeedstudio.com/Grove-PH-Sensor-kit/ gives a sample code for Arduino with different formula

when I read the 4 byte[] i get something like [Pi4J IO read][0, 1, -106, -1] if i read more than 4 bytes than all the bytes at the end are -1

would be nice to have a clear implementation of the public Double get(byte[] data) {} function ...


Solution

  • @GroveAnalogPin
    public class GrovePHSensor extends GroveAnalogInputDevice<Double> {
         private static final Logger l = 
         LogManager.getLogger(GrovePHSensor.class.getName());
         /*** pH values range */
         public static final double PH_RANGE = 14.0;
        /*** 
          number of possible samples with 10 bit analog to digital converter 
         */
        public static final int A2D_RANGE = 1023;
    
    public GrovePHSensor(GrovePi grovePi, int pin) throws IOException {
        super(grovePi.getAnalogIn(pin, 4));
    }
    
    @Override
    public Double get(byte[] data) {
        // the extraction of the value is taken from the sample of the 
        // RotarySensor3Led 
        // https://github.com/DexterInd/GrovePi/blob/master/Software/Java8/GrovePi-spec/src/main/java/org/iot/raspberry/grovepi/devices/GroveRotarySensor.java
        // this is how its is done there
    
        int[] v = GroveUtil.unsign(data);
        double sensorValue = (v[1] * 256) + v[2];
    
        // the Analog to Digital is 10 bit -> 1023 intervals that cover the range of pH of 0 to 14
        // hence the pH value is the sensor value that is 0 to 1024
        // times the pH per interval of the A2D 14/1023
        double ph = sensorValue * (PH_RANGE / (double) A2D_RANGE);
        l.trace("sensorValue = {}  ph={}", sensorValue, ph);
        return ph;
        }
    }