0
\$\begingroup\$

I have a Python program for reading both TDS and pH sensors on a Raspberry Pi 4 and sending the data to the Blynk app.

I have a question about the code:

import RPi.GPIO as GPIO
import board
import busio
import time
import sys
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
import requests

GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)
GPIO.output(20, GPIO.HIGH)
GPIO.output(21, GPIO.HIGH)
token="##"

# Setup
i2c = busio.I2C(board.SCL, board.SDA)
ads = ADS.ADS1115(i2c)

def ph_sensor():
    pH = 20
    GPIO.setup(pH, GPIO.OUT)
    GPIO.output(pH, GPIO.LOW)
    channel = AnalogIn(ads, ADS.P0)
    buf = list()
    for i in range(20): # Take 10 samples
        buf.append(channel.voltage)
    buf.sort() # Sort samples and discard highest and lowest
    buf = buf[4:-4]
    avg = (sum(map(float,buf))/12) # Get average value from remaining 6
    ph = round(avg/0.34286,2)
    time.sleep(10)
    GPIO.output(pH, GPIO.HIGH)
    return ph

def ppm():
    TDS = 21
    GPIO.setup(TDS, GPIO.OUT)
    GPIO.output(TDS, GPIO.LOW)
    channel = AnalogIn(ads, ADS.P1)
    buf = list()
    for i in range(20): # Take 10 samples
        buf.append(channel.voltage)#-0.373212)
    buf.sort() # Sort samples and discard highest and lowest
    buf = buf[4:-4]
    avg = (sum(map(float,buf))/6) # Get average value from remaining 6
    ppm = abs(round(((avg*1000)/2.3),2))
    time.sleep(10)
    GPIO.output(TDS, GPIO.HIGH)
    return ppm

def write(token,pin,value):
    api_url = "https://blynk.cloud/external/api/update?token="+token+"&"+pin+"="+value
    response = requests.get(api_url)
    write(token,"v2",str(ppm()))
    time.sleep(5)
    write(token,"v3",str(ph_sensor()))
  • In this line of code ph = round(avg/0.34286,2), why do we divide by 0.34286? What does this number even mean?
  • In this line of code ppm = abs(round(((avg*1000)/2.3),2)) why do we multiply by 1000 and then divide by 2.3? Can anyone explain?
\$\endgroup\$
1
  • \$\begingroup\$ Is this really a valid EE topic? It's solely about code understanding... \$\endgroup\$
    – datenheim
    Feb 14 at 7:16

1 Answer 1

3
\$\begingroup\$

You have to look at the scaling between the particular sensor that this software was written for and the engineering units that are produced.

For example, I might imagine that the pH sensor produces +2.4V for pH of +7 so by dividing by 0.34286 you get 7.00. Invoking this kind of 'magic number' without comments is a nasty coding style.

The comments are misleading, by the way (eg. 20 samples are taken not 10). And the Python indent formatting (which is part of the syntax) has been destroyed.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.