Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2017
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.26 KB | None | 0 0
  1. #!/usr/bin/python
  2. import RPi.GPIO as GPIO
  3. import string
  4.  
  5. class MAX31855(object):
  6.     '''Python driver for [MAX38155 Cold-Junction Compensated Thermocouple-to-Digital Converter](http://www.maximintegrated.com/datasheet/index.mvp/id/7273)
  7.     Requires:
  8.     - The [GPIO Library](https://code.google.com/p/raspberry-gpio-python/) (Already on most Raspberry Pi OS builds)
  9.     - A [Raspberry Pi](http://www.raspberrypi.org/)
  10.  
  11.    '''
  12.  
  13.     def __init__(self, cs_pin, clock_pin, data_pin, units = "c", board = GPIO.BCM):
  14.         '''Initialize Soft (Bitbang) SPI bus
  15.  
  16.        Parameters:
  17.        - cs_pin:    Chip Select (CS) / Slave Select (SS) pin (Any GPIO)  
  18.        - clock_pin: Clock (SCLK / SCK) pin (Any GPIO)
  19.        - data_pin:  Data input (SO / MOSI) pin (Any GPIO)
  20.        - units:     (optional) unit of measurement to return. ("c" (default) | "k" | "f")
  21.        - board:     (optional) pin numbering method as per RPi.GPIO library (GPIO.BCM (default) | GPIO.BOARD)
  22.  
  23.        '''
  24.         self.cs_pin = cs_pin
  25.         self.clock_pin = clock_pin
  26.         self.data_pin = data_pin
  27.         self.units = units
  28.         self.data = None
  29.         self.board = board
  30.  
  31.         # Initialize needed GPIO
  32.         GPIO.setmode(self.board)
  33.         GPIO.setup(self.cs_pin, GPIO.OUT)
  34.         GPIO.setup(self.clock_pin, GPIO.OUT)
  35.         GPIO.setup(self.data_pin, GPIO.IN)
  36.  
  37.         # Pull chip select high to make chip inactive
  38.         GPIO.output(self.cs_pin, GPIO.HIGH)
  39.  
  40.     def get(self):
  41.         '''Reads SPI bus and returns current value of thermocouple.'''
  42.         self.read()
  43.         self.checkErrors()
  44.         return getattr(self, "to_" + self.units)(self.data_to_tc_temperature())
  45.  
  46.     def get_rj(self):
  47.         '''Reads SPI bus and returns current value of reference junction.'''
  48.         self.read()
  49.         return getattr(self, "to_" + self.units)(self.data_to_rj_temperature())
  50.  
  51.     def read(self):
  52.         '''Reads 32 bits of the SPI bus & stores as an integer in self.data.'''
  53.         bytesin = 0
  54.         # Select the chip
  55.         GPIO.output(self.cs_pin, GPIO.LOW)
  56.         # Read in 32 bits
  57.         for i in range(32):
  58.             GPIO.output(self.clock_pin, GPIO.LOW)
  59.             bytesin = bytesin << 1
  60.             if (GPIO.input(self.data_pin)):
  61.                 bytesin = bytesin | 1
  62.             GPIO.output(self.clock_pin, GPIO.HIGH)
  63.         # Unselect the chip
  64.         GPIO.output(self.cs_pin, GPIO.HIGH)
  65.         # Save data
  66.         self.data = bytesin
  67.  
  68.     def checkErrors(self, data_32 = None):
  69.         '''Checks error bits to see if there are any SCV, SCG, or OC faults'''
  70.         if data_32 is None:
  71.             data_32 = self.data
  72.         anyErrors = (data_32 & 0x10000) != 0    # Fault bit, D16
  73.         noConnection = (data_32 & 1) != 0       # OC bit, D0
  74.         shortToGround = (data_32 & 2) != 0      # SCG bit, D1
  75.         shortToVCC = (data_32 & 4) != 0         # SCV bit, D2
  76.         if anyErrors:
  77.             if noConnection:
  78.                 raise MAX31855Error("No Connection")
  79.             elif shortToGround:
  80.                 raise MAX31855Error("Thermocouple short to ground")
  81.             elif shortToVCC:
  82.                 raise MAX31855Error("Thermocouple short to VCC")
  83.             else:
  84.                 # Perhaps another SPI device is trying to send data?
  85.                 # Did you remember to initialize all other SPI devices?
  86.                 raise MAX31855Error("Unknown Error")
  87.  
  88.     def data_to_tc_temperature(self, data_32 = None):
  89.         '''Takes an integer and returns a thermocouple temperature in celsius.'''
  90.         if data_32 is None:
  91.             data_32 = self.data
  92.         tc_data = ((data_32 >> 18) & 0x3FFF)
  93.         return self.convert_tc_data(tc_data)
  94.  
  95.     def data_to_rj_temperature(self, data_32 = None):
  96.         '''Takes an integer and returns a reference junction temperature in celsius.'''
  97.         if data_32 is None:
  98.             data_32 = self.data
  99.         rj_data = ((data_32 >> 4) & 0xFFF)
  100.         return self.convert_rj_data(rj_data)
  101.  
  102.     def convert_tc_data(self, tc_data):
  103.         '''Convert thermocouple data to a useful number (celsius).'''
  104.         if tc_data & 0x2000:
  105.             # two's compliment
  106.             without_resolution = ~tc_data & 0x1FFF
  107.             without_resolution += 1
  108.             without_resolution *= -1
  109.         else:
  110.             without_resolution = tc_data & 0x1FFF
  111.         return without_resolution * 0.25
  112.  
  113.     def convert_rj_data(self, rj_data):
  114.         '''Convert reference junction data to a useful number (celsius).'''
  115.         if rj_data & 0x800:
  116.            without_resolution = ~rj_data & 0x7FF
  117.            without_resolution += 1
  118.            without_resolution *= -1
  119.         else:
  120.              without_resolution = rj_data & 0x7FF
  121.         return without_resolution * 0.0625
  122.  
  123.     def to_c(self, celsius):
  124.         '''Celsius passthrough for generic to_* method.'''
  125.         return celsius
  126.  
  127.     def to_k(self, celsius):
  128.         '''Convert celsius to kelvin.'''
  129.         return celsius + 273.15
  130.  
  131.     def to_f(self, celsius):
  132.         '''Convert celsius to fahrenheit.'''
  133.         return celsius * 9.0/5.0 + 32
  134.  
  135.     def cleanup(self):
  136.         '''Selective GPIO cleanup'''
  137.         GPIO.setup(self.cs_pin, GPIO.IN)
  138.         GPIO.setup(self.clock_pin, GPIO.IN)
  139.  
  140. class MAX31855Error(Exception):
  141.      def __init__(self, value):
  142.          self.value = value
  143.      def __str__(self):
  144.          return repr(self.value)
  145.  
  146. if __name__ == "__main__":
  147.     def unixtime(t):
  148.         return t * 1000
  149.     # Multi-chip example
  150.     import time
  151.     from datetime import datetime
  152.     import pyodbc
  153.     cs_pins = [2, 4, 17]
  154.     clock_pin = 22
  155.     data_pin = 27
  156.     units = "f"
  157.     thermocouples = []
  158.     tempresults = []
  159.     for cs_pin in cs_pins:
  160.         thermocouples.append(MAX31855(cs_pin, clock_pin, data_pin, units))
  161.     running = True
  162.     while(running):
  163.         try:
  164.             count = 0
  165.             holdTCs = []
  166.             for thermocouple in thermocouples:
  167.                 rj = thermocouple.get_rj()
  168.                 try:
  169.                    
  170.                     tc = thermocouple.get()
  171.                     temptc = "{:.2f}".format(tc)
  172.                     newtc = temptc.split('\n')
  173.                     temp1 = newtc[0]
  174.                     holdTCs[count] = tc
  175.                     count += 1
  176.                 except MAX31855Error as e:
  177.                     tc = "Error: "+ e.value
  178.                     running = False
  179.                
  180.                 print holdTCs[0]
  181.    
  182.                 dsn = 'SQLServer2016'
  183.                 user = 'sa'
  184.                 password = 'sqlpassword1'
  185.                 database = 'DevDB'
  186.                 connString = 'DSN={0};UID={1};PWD={2};DATABASE={3};'.format(dsn,user,password,database)
  187.                 conn = pyodbc.connect(connString)
  188.                 cursor = conn.cursor()
  189.                 SQLCommand = ("INSERT INTO MultiReadingTestDB " "(temp1, DateTime, Time, NewTime) " "Values (?, ?, ?, ?)")
  190.                 Values = [tc, datetime.now(), time.time(), unixtime(time.time())]
  191.                 cursor.execute(SQLCommand, Values)
  192.                 conn.commit()
  193.                 conn.close()    
  194.             time.sleep(10)
  195.         except KeyboardInterrupt:
  196.             running = False
  197.     for thermocouple in thermocouples:
  198.         thermocouple.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement