element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      • Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Raspberry Pi
  • Products
  • More
Raspberry Pi
Raspberry Pi Forum need .py code for reading Max31855 A/D temp converter
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Raspberry Pi to participate - click to join for free!
Featured Articles
Announcing Pi
Technical Specifications
Raspberry Pi FAQs
Win a Pi
Raspberry Pi Wishlist
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Verified Answer
  • Replies 32 replies
  • Answers 2 answers
  • Subscribers 678 subscribers
  • Views 4918 views
  • Users 0 members are here
  • raspberry_pi
  • raspberrypi
  • adafruit
Related

need .py code for reading Max31855 A/D temp converter

donb
donb over 11 years ago

Thru this site I got info on a Adafruit Max31855 module. Now does anyone have the code necessary to read the digital output of this fine little module? I don't have the experience to write the code, but truly need the code to save a very long and steep learning curve.   Don

  • Sign in to reply
  • Cancel
  • mconners
    0 mconners over 11 years ago

    While I don't have that particular module I went to the Adafruit site and checked it out. It looks like it is a simple SPI device.

     

    Check here for python instructions Simple SPI on Raspberry Pi - 100RandomTasks

     

    From Adafruit's arduino example it looks like to read celsius temperature, you do a 32 bit read of the SPI data, shift right 18 bits and multiply by .25 and you've got celcius temperature.

     

    https://github.com/adafruit/Adafruit-MAX31855-library/blob/master/Adafruit_MAX31855.cpp

     

    You'll be surprised at how easy this really is.

     

    Good luck,

     

    Mike

     

    Edited bad link

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • mconners
    0 mconners over 11 years ago in reply to mconners

    Taking a second look at the RasPi SPI library, you may have to make your own 32 bit read, but everything is in the .cpp file linked above.

     

    Take a stab at it, if you can't figure it out, post your code here and we can suggest some fixes.

     

    Mike

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • donb
    0 donb over 11 years ago in reply to mconners

    Thanks Michael, I will take a stab at it. I am assuming that the .ccp code is similar to the .py code.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • mconners
    0 mconners over 11 years ago in reply to donb

    There are definitely syntactical differences between the 2, but the ideas will be similar.

     

    The Adafruit example is good because she commented out alot of the fluff. It is really simplified to show only what is necessary.

     

    Like I said, give it a stab, just a simple read from the device, there are plenty of folks on here who are willing to help debug code.

     

    Mike

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • iagorubio
    0 iagorubio over 11 years ago

    You can even compile that code to work with the raspberry with the arduPi library Cooking Hacks - Documentation - Raspberry Pi to Arduino shields connection bridge or may be with the WiringPi library.

     

    You just will need to add a main() function as entry point for you progra, initialize one Adafruit_MAX31855 instance and call the readCelsius() or readFarenheit() methods.

     

    There is one thing I would double check before to connect it, from the description you can read "This breakout board has the chip itself, a 3.3V regulator with 10uF bypass capacitors and level shifting circuitry". Take care, the Raspberrry is a 3.3V device itself, you don't need level shifting at all.

     

    Before to start I would input 3.3V in both VIN and V3.3 and check if the output is 3.3V or you risk a fried Pi.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • donb
    0 donb over 11 years ago in reply to iagorubio

    Thanks Michael, I will take a stab at it. I am assuming that the .ccp code is similar to the .py code.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • donb
    0 donb over 11 years ago in reply to iagorubio

    Thanks Iago for the info. I will look into these things.

    Don

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • donb
    0 donb over 11 years ago in reply to donb

    I found this code from Tuckie on Github and am trying to use it and having problems:
    https://github.com/Tuckie/max31855/blob/master/max31855.py
    I am using only one chip so how much of the
    bottom few lines of the code can I eliminate since that is
    where one of the errors seems to be comming from?

    Another error is comming from line 39. I am using the SPI
    pins as follows:
    sclk- GP11
    miso- GP9
    cs-   GP8
    3.3v from buss on Gert board
    gnd  from buss on Gert board

    I don't understand how the code knows where to find these pins
    and assign them correctly and I don't see lines to input them.
    I have very limited knowledge on how to read this code but it looks like the pins are being initlized
    in lines 9 thru 32. please explain!


    following is the error message I got when I ran the code:

    Python 2.7.3 (default, Jan 13 2013, 11:20:46)

    [GCC 4.6.3] on linux2

    Type "copyright", "credits" or "license()" for more information.

    >>> ================================ RESTART ================================

    >>>

     

    Traceback (most recent call last):
      File "/home/pi/read_display  Max_31855 thermocouple_amp.txt", line 176, in <module>
     
      thermocouples.append(MAX31855(cs_pin, clock_pin, data_pin, units))

      File "/home/pi/read_display  Max_31855 thermocouple_amp.txt", line 39, in __init__
     
      GPIO.setup(self.cs_pin, GPIO.OUT)
    RuntimeError: No access to /dev/mem.  Try running as root!
    >>>

     

    entire list of code follows, Thank you Tuckie:

    #!/usr/bin/python
    import RPi.GPIO as GPIO

    class MAX31855(object):
        '''Python driver for [MAX38155 Cold-Junction Compensated Thermocouple-to-Digital Converter](http://www.maximintegrated.com/datasheet/index.mvp/id/7273)
         Requires:
         - The [GPIO Library](https://code.google.com/p/raspberry-gpio-python/) (Already on most Raspberry Pi OS builds)
         - A [Raspberry Pi](http://www.raspberrypi.org/)


        '''
    def __init__(self, cs_pin, clock_pin, data_pin, units = "c", board = GPIO.BCM):
            '''Initialize Soft (Bitbang) SPI bus


            Parameters:
            - cs_pin:    Chip Select (CS) / Slave Select (SS) pin (Any GPIO) 
            - clock_pin: Clock (SCLK / SCK) pin (Any GPIO)
            - data_pin:  Data input (SO / MOSI) pin (Any GPIO)
            - units:     (optional) unit of measurement to return. ("c" (default) | "k" | "f")
            - board:     (optional) pin numbering method as per RPi.GPIO library (GPIO.BCM (default) | GPIO.BOARD)


            '''
            self.cs_pin = cs_pin
            self.clock_pin = clock_pin
            self.data_pin = data_pin
            self.units = units
            self.data = None
            self.board = board


            # Initialize needed GPIO
            GPIO.setmode(self.board)
            GPIO.setup(self.cs_pin, GPIO.OUT)
            GPIO.setup(self.clock_pin, GPIO.OUT)
            GPIO.setup(self.data_pin, GPIO.IN)


            # Pull chip select high to make chip inactive
            GPIO.output(self.cs_pin, GPIO.HIGH)

        def get(self):
            '''Reads SPI bus and returns current value of thermocouple.'''
            self.read()
            self.checkErrors()
            return getattr(self, "to_" + self.units)(self.data_to_tc_temperature())


        def get_rj(self):
            '''Reads SPI bus and returns current value of reference junction.'''
            self.read()
            return getattr(self, "to_" + self.units)(self.data_to_rj_temperature())


        def read(self):
            '''Reads 32 bits of the SPI bus & stores as an integer in self.data.'''
            bytesin = 0
            # Select the chip
            GPIO.output(self.cs_pin, GPIO.LOW)
            # Read in 32 bits
            for i in range(32):
                GPIO.output(self.clock_pin, GPIO.LOW)
                bytesin = bytesin << 1
                if (GPIO.input(self.data_pin)):
                    bytesin = bytesin | 1
                GPIO.output(self.clock_pin, GPIO.HIGH)
            # Unselect the chip
            GPIO.output(self.cs_pin, GPIO.HIGH)
            # Save data
            self.data = bytesin


        def checkErrors(self, data_32 = None):
            '''Checks error bits to see if there are any SCV, SCG, or OC faults'''
            if data_32 is None:
                data_32 = self.data
            anyErrors = (data_32 & 0x10000) != 0    # Fault bit, D16
            noConnection = (data_32 & 1) != 0       # OC bit, D0
            shortToGround = (data_32 & 2) != 0      # SCG bit, D1
            shortToVCC = (data_32 & 4) != 0         # SCV bit, D2
            if anyErrors:
                if noConnection:
                    raise MAX31855Error("No Connection")
                elif shortToGround:
                    raise MAX31855Error("Thermocouple short to ground")
                elif shortToVCC:
                    raise MAX31855Error("Thermocouple short to VCC")
                else:
                    # Perhaps another SPI device is trying to send data?
                    # Did you remember to initialize all other SPI devices?
                    raise MAX31855Error("Unknown Error")


        def data_to_tc_temperature(self, data_32 = None):
            '''Takes an integer and returns a thermocouple temperature in celsius.'''
            if data_32 is None:
                data_32 = self.data
            tc_data = ((data_32 >> 18) & 0x3FFF)
            return self.convert_tc_data(tc_data)


        def data_to_rj_temperature(self, data_32 = None):
            '''Takes an integer and returns a reference junction temperature in celsius.'''
            if data_32 is None:
                data_32 = self.data
            rj_data = ((data_32 >> 4) & 0xFFF)
            return self.convert_rj_data(rj_data)


        def convert_tc_data(self, tc_data):
            '''Convert thermocouple data to a useful number (celsius).'''
            if tc_data & 0x2000:
                # two's compliment
                without_resolution = ~tc_data & 0x1FFF
                without_resolution += 1
                without_resolution *= -1
            else:
                without_resolution = tc_data & 0x1FFF
            return without_resolution * 0.25


        def convert_rj_data(self, rj_data):
            '''Convert reference junction data to a useful number (celsius).'''
            if rj_data & 0x800:
               without_resolution = ~rj_data & 0x7FF
               without_resolution += 1
               without_resolution *= -1
            else:
                 without_resolution = rj_data & 0x7FF
            return without_resolution * 0.0625


        def to_c(self, celsius):
            '''Celsius passthrough for generic to_* method.'''
            return celsius


        def to_k(self, celsius):
            '''Convert celsius to kelvin.'''
            return celsius + 273.15


        def to_f(self, celsius):
            '''Convert celsius to fahrenheit.'''
            return celsius * 9.0/5.0 + 32


        def cleanup(self):
            '''Selective GPIO cleanup'''
            GPIO.setup(self.cs_pin, GPIO.IN)
            GPIO.setup(self.clock_pin, GPIO.IN)

    class MAX31855Error(Exception):
         def __init__(self, value):
             self.value = value
         def __str__(self):
             return repr(self.value)


    if __name__ == "__main__":


        # Multi-chip example
        import time
        cs_pins = [4, 17, 18, 24]
        clock_pin = 23
        data_pin = 22
        units = "f"
        thermocouples = []
        for cs_pin in cs_pins:
            thermocouples.append(MAX31855(cs_pin, clock_pin, data_pin, units))
        running = True
        while(running):
            try:
                for thermocouple in thermocouples:
                    rj = thermocouple.get_rj()
                    try:
                        tc = thermocouple.get()
                    except MAX31855Error as e:
                        tc = "Error: "+ e.value
                        running = False
                    print("tc: {} and rj: {}".format(tc, rj))
                time.sleep(1)
            except KeyboardInterrupt:
                running = False
        for thermocouple in thermocouples:
            thermocouple.cleanup()

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • mconners
    0 mconners over 11 years ago in reply to donb

    Hey Don, good to see you are trying

     

    First thing, cs_pins = [4, 17, 18, 24]

     

    bring that array down to one element, that is how many thermocouples you are using

     

    I think you want to change it to:

    cs_pins = [24]


    second change:

    clock_pin = 23

    data_pin = 21


    and give that a shot


    Mike


    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • mconners
    0 mconners over 11 years ago in reply to mconners

    Going by this page:

     

    RPi Low-level peripherals - eLinux.org

     

    in the Python section

    # use P1 header pin numbering convention

    GPIO.setmode(GPIO.BOARD)

     

    That would give you the pins as above, it looks like he defaults to GPIO.BCM, you could hardcode GPIO.BOARD into the code, where he does the set mode, or you can pass that in, or figure out the BCM equivalents.

     

    Also, the error about running as root, run it as root by doing

    sudo <commandname>

     

    Mike

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
>
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube