#!/bin/bash

# Assert (active low) GFSHTDN to apply
# power to circuit
devmem2 0x40028008 w 0x80000 > /dev/null

# GF_Test not asserted (GPO_11)
devmem2 0x40028008 w 0x800 > /dev/null

#GF_Test asserted
#devmem2 0x40028004 w 0x800

get_adc_counts(){
  sleep 3
  counts=$(cat /dev/mcp3551-0)
  if [[ "$counts" == Wait* ]] # check to see if the A/D is still reading
  then
    sleep 0.5
    counts=$(cat /dev/mcp3551-0) # And try again if it was
  fi
  echo $counts
}

# Takes count as first arg and offset as second
counts_to_ma() {
  count=$(($1 * 1000))
  result=$((($count - 1048576000) / 660 + $2))
  int=$((result / 1000000))
  dec=$((result % 1000000))
  # Pretty-print negative numbers
  if [ $result -lt 0 ]; then
    printf -- "-%d.%06d" $((-1 * $int)) $((-1 * $dec))
  else
    printf "%d.%06d" $int $dec
  fi
}

while true; do
## A0
echo -e "\nmA:"
# Chan A0 asserted
devmem2 0x40028004 w 0x00000001 > /dev/null
counts=$(get_adc_counts)
printf "CHAN A0 (Batt): %s [%d counts]\n" "$(counts_to_ma $counts -107000)" $counts
##


## A1 
# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null
# Chan A1 asserted 
devmem2 0x40028004 w 0x00000005 > /dev/null
counts=$(get_adc_counts)
printf "CHAN A1 (24V): %s [%d counts]\n" "$(counts_to_ma $counts 28000)" $counts
##


## A2  
# CS assert
#devmem2 0x40028008 w 0x00000010 > /dev/null
# CS de-assert
#devmem2 0x40028004 w 0x00000010 > /dev/null
# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null
# Chan A2 asserted
devmem2 0x40028004 w 0x00000003 > /dev/null
counts=$(get_adc_counts)
printf "CHAN A2 (12V): %s [%d counts]\n" "$(counts_to_ma $counts -67000)" $counts
##


## A3 
# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null
# Chan A3 asserted
devmem2 0x40028004 w 0x00000007 > /dev/null
counts=$(get_adc_counts)
printf "CHAN A3 (5V): %s [%d counts]\n" "$(counts_to_ma $counts -11000)" $counts
##


## B0
# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null
# Chan B0 asserted
devmem2 0x40028004 w 0x00040000 > /dev/null
counts=$(get_adc_counts)
printf "CHAN B0 (3.3V): %s [%d counts]\n" "$(counts_to_ma $counts 2000)" $counts
##


## B1
# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null
# Chan B1 asserted
devmem2 0x40028004 w 0x00040004 > /dev/null
counts=$(get_adc_counts)
printf "CHAN B1 (3.15V_A): %s [%d counts]\n" "$(counts_to_ma $counts 3000)" $counts
##


## B2
# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null
# Chan B2 asserted
devmem2 0x40028004 w 0x00040002 > /dev/null
counts=$(get_adc_counts)
printf "CHAN B2 (3.15V_B): %s [%d counts]\n" "$(counts_to_ma $counts 3000)" $counts
##


## B3
# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null
# Chan B3 asserted
devmem2 0x40028004 w 0x00040006 > /dev/null
counts=$(get_adc_counts)
printf "CHAN B3 (GND): %s [%d counts]\n" "$(counts_to_ma $counts 28000)" $counts
##

# Clear all
devmem2 0x40028008 w 0x00040007 > /dev/null

done
