Skip to content

Instantly share code, notes, and snippets.

@mmoollllee
Last active March 10, 2024 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmoollllee/46aa20417576cd3eebb4d3fba16bc4e0 to your computer and use it in GitHub Desktop.
Save mmoollllee/46aa20417576cd3eebb4d3fba16bc4e0 to your computer and use it in GitHub Desktop.
Read Input Voltage from UUGears Witty Pi 4 on RaspberryPi
#!/bin/bash
# Read voltage from i2c if Wittypi is mounted
# run with `bash witty_voltage.sh`
readonly I2C_MC_ADDRESS=0x08
readonly I2C_VOLTAGE_IN_I=1
readonly I2C_VOLTAGE_IN_D=2
i2c_read()
{
local retry=0
if [ $# -gt 3 ]; then
retry=$4
fi
local result=$(/usr/sbin/i2cget -y $1 $2 $3)
if [[ "$result" =~ ^0x[0-9a-fA-F]{2}$ ]]; then
echo $result;
else
retry=$(( $retry + 1 ))
if [ $retry -ne 4 ]; then
sleep 1
i2c_read $1 $2 $3 $retry
else
echo "Error reading I2C value" >&2
return 1
fi
fi
}
calc()
{
awk "BEGIN { print $*}";
}
i=$(i2c_read 0x01 $I2C_MC_ADDRESS $I2C_VOLTAGE_IN_I)
d=$(i2c_read 0x01 $I2C_MC_ADDRESS $I2C_VOLTAGE_IN_D)
if [[ -z $i ]] || [[ -z $d ]]; then
echo "Failed to read voltage values."
exit 1
fi
calc $(($i))+$(($d))/100
exit 0
@mmoollllee
Copy link
Author

Calling it like this in python:

def read_voltage(config):
    voltage = "unknown"
    if config.witty:
        log.debug("helpers.read_voltage(): start")
        try:
            v = subprocess.run(["/usr/bin/bash", abs_path("witty_voltage.sh")], capture_output=True, text=True, timeout=10)
            voltage = v.stdout.strip() + " Volt"
            log.info("WittyPi Voltage: " + voltage)
            return voltage
        except subprocess.TimeoutExpired as e:
            log.error("helpers.read_voltage(): TimeoutExpired", e)
    return voltage

And to read next scheduled startup:

#!/bin/bash
# Read next startup from wittypi
# run with `bash witty_nextstartup.sh`

readonly I2C_MC_ADDRESS=0x08
readonly I2C_CONF_SECOND_ALARM1=27
readonly I2C_CONF_MINUTE_ALARM1=28
readonly I2C_CONF_HOUR_ALARM1=29
readonly I2C_CONF_DAY_ALARM1=30

i2c_read()
{
  local retry=0
  if [ $# -gt 3 ]; then
    retry=$4
  fi
  local result=$(/usr/sbin/i2cget -y $1 $2 $3)
  if [[ "$result" =~ ^0x[0-9a-fA-F]{2}$ ]]; then
    echo $result;
  else
    retry=$(( $retry + 1 ))
    if [ $retry -ne 4 ]; then
      sleep 1
      i2c_read $1 $2 $3 $retry
    else
      echo "Error reading I2C value" >&2
      return 1
    fi
  fi
}

bcd2dec()
{
  local result=$(($1/16*10+($1&0xF)))
  echo $result
}

sec=$(bcd2dec $(i2c_read 0x01 $I2C_MC_ADDRESS $I2C_CONF_SECOND_ALARM1))
min=$(bcd2dec $(i2c_read 0x01 $I2C_MC_ADDRESS $I2C_CONF_MINUTE_ALARM1))
hour=$(bcd2dec $(i2c_read 0x01 $I2C_MC_ADDRESS $I2C_CONF_HOUR_ALARM1))
date=$(bcd2dec $(i2c_read 0x01 $I2C_MC_ADDRESS $I2C_CONF_DAY_ALARM1))
printf '%02d %02d:%02d:%02d' $date $hour $min $sec
exit 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment