######################################## battery_energy.py ##################################
# Halverson 5/25/2015
# Simple program to record battery voltage and calculate battery energy

import sys
mypath=sys.path[0]
if mypath.find('my_python') == -1:       #If true, then "my_python" could not be found
  print "Sorry.  You need to be in my_python for Halverson's program to work."
  print "(That''s because I am assuming that the oscopegraphlib.py and ezu3.py libraries are there.)"
  exit()
sys.path[0]=mypath[0:mypath.find('my_python')]+'my_python'

from oscopegraphlib import *
import math
import u3
from ezu3 import *
from accurate_sleep import *

def power(V,R):
  return 1.0*V*V/R    # Watts

print "Simple program to record battery voltage and calculate energy"
print "I will assume the battery is on FIO6, but you can change this."
load_resistance = input("What is the load resistance (Ohms)? ")
my_sample_period = input("What is the sample period (seconds)? ")

d = u3.U3() # Opens the first LabJackU3 found on the USB
u3setup(d,['ain','ain','din','din','ain','ain','ain','ain'])


print "Press buttons 2 and 3 to quit."

energy_Joules = 0.0
elapsed_time=0.0
while True:
  V=ain6(d)       #Read analog input
  power_Watts = power(V,load_resistance)
  energy_Joules = energy_Joules + power_Watts*my_sample_period
  print "elapsed_time=",elapsed_time,
  print " V=%5.3f Volts" % V,
  print "  P=%8.6f Watts" % power_Watts,
  print "  E=%7.5f Joules" % energy_Joules
  #   oscope(user_y,smallest_y=0.0,biggest_y=2.5,sample_period=0.1,samples_per_sweep=20, \
  #       record_for_xgraph=False,use_seconds_since_midnight=False):
  oscope(V,smallest_y=0.0,biggest_y=2.5,sample_period=my_sample_period,record_for_xgraph=True)
  accurate_sleep(my_sample_period)
  elapsed_time=elapsed_time+my_sample_period
  if din2(d) and din3(d):
    break
    
