Advertisement
Guest User

RPI Current sensor

a guest
Feb 24th, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import spidev
  4. import time
  5. import os
  6.  
  7. # Schematic values
  8. resVal = 23
  9. ratio = 2000
  10. zeroVal = 1.66
  11.  
  12. # Open SPI bus
  13. spi = spidev.SpiDev()
  14. spi.open(0,0)
  15.  
  16. # Function to read SPI data from MCP3008 chip
  17. # Channel must be an integer 0-7
  18. def ReadChannel(channel):
  19.   adc = spi.xfer2([1,(8+channel)<<4,0])
  20.   data = ((adc[1]&3) << 8) + adc[2]
  21.   return data
  22.  
  23. # Function to convert data to voltage level,
  24. # rounded to specified number of decimal places.
  25. def ConvertVolts(data,places):
  26.   volts = (data * 3.3) / float(1023)
  27.   volts = round(volts,places)
  28.   return volts
  29.  
  30. # Define sensor channels
  31. sensor_channel = 0
  32.  
  33. # Define delay between readings
  34. delay = 1
  35.  
  36. # Define voltage drop
  37. volDif = 0
  38.  
  39. while True:
  40.  
  41.   # Read the current sensor data
  42.   sensor_level = ReadChannel(sensor_channel)
  43.   sensor_volts = ConvertVolts(sensor_level,2)
  44.  
  45.   # Define
  46.   if sensor_volts>1.66:
  47.    volDif = sensor_volts - 1.66
  48.   else:
  49.    volDif = 1.66 - sensor_volts
  50.  
  51.   # Calc Amps secondary
  52.   sensorAmpsec = (volDif / resVal) * 1000
  53.  
  54.   # Calc Amps primary
  55.   sensorAmpsprim = (sensorAmpsec / 1000) * ratio
  56.  
  57.   # Print out results
  58.   print "--------------------------------------------"
  59.   print("Bits: {} ({}V)".format(sensor_level,sensor_volts))
  60.   print("Amps: SEC - {} mA | PRIM - {} A".format(round(sensorAmpsec,2),round(sensorAmpsprim,2)))
  61.  
  62.   # Wait before repeating loop
  63.   time.sleep(delay)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement