Close

Let's talk some code: Glob Module

A project log for Raspberry Pi Wet Incubator/Sous Vide/Slow Cooker

A web and locally controlled sous vide and slow cooker, now turned in to a laboratory water bath/DNA PCR cycler.

staticdet5staticdet5 07/16/2015 at 01:560 Comments

Anyone that really knows me, knows that I'm a bit of a spaz. I like to get in to things, see how things work, how they could fit together, try new things, find trouble, get in to it, run, and learn something new. HOWEVER, at the core, I'm lazy. I hate repetitive efforts, duplicate work.

One of my goals, when I started this project, was to make a system that took care of the "crap" for the user. I knew I wanted to be able to incorporate multiple thermal sensing elements in the design. With the selection of the DS18B20 thermometers, I knew I could potentially have an unknowable number of sensors available. I wanted to set the program up to scan for sensors within the linux file structure (one of the cool aspects of this particular sensor, and the Raspberry Pi).

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
thermometers = (glob.glob(base_dir + '28*'))
print(thermometers) 

The code snippet above is how I get the list of DS18B20 thermometers that are attached to the Pi.
The first two lines use the python OS module to initialize the thermometers.

The "base_dir" variable contains the directory where the thermometers "live". Checking the "contents" of the thermometers is how we read the temperature. The cool thing about this is that the thermometers and the Pi update the "contents" with temperature data. We just need to check the files occasionally.

The next line uses the Glob module to find all of the items in the "base_dir" location that start with "28", what our thermometers identifiers start with. We don't really care what the identifiers are, or how many of them there are. All Glob does (in this instance) is return everything that meets the criteria (Criteria being: In the directory, "base_dir"; and starting with "28"). In the past, I would have written some PITA code that would have iterated over things within the directory, with manual checks written to make sure the code didn't get confused halfway through a string.

Python's great, but sometimes it's a bit tough knowing about all the great modules out there.... (hint: awesome site: Python Module of the Week: Glob)

The "print(thermometers)" line is simply a program check, to make sure things are working.

Four to Five lines of code to check what DS18B20's are hooked up. The next thing I need to do is also play back what temperatures the thermometers are currently reading. This could help distinguish thermometers, making assignments easier. This will keep the user from having to dig into the Pi's file structure, write down detected devices, and then manually alter a configuration file. This should automate that process completely.

Discussions