Arduino and OneWire
In preparation for my DIY BrewPi project, I picked up a few DS18B20 temperature sensors from Amazon. These sensors use something called the OneWire protocol; this allows you to connect multiple sensors so the same wire, simplifying the wiring.
That simplicity comes at a cost, and the cost in this case is complexity in code. I found a number of explanations for how “simple” it is to use these, and then they’d proceed with some example code that is 100+ lines. While not terribly challenging, I’d avoid tagging this with “simple”.
The challenge with having more than one sensor on the same data wire is knowing which sensor you’re interacting with. The steps needed in your code following something like this:
- Identify the addresses on the bus (commone wire used for data).
- Request a temperature reading from each sensor.
- Read the reading from each sensor.
That doesn’t sound so bad, and it’s not. However, the benefit of moving the complexity into the code is that you can use libraries to do the heavy lifting; someone else can figure out the gritty details, publish an API and an example, and we can have something simple and functional.
Finding the addresses
The first thing you need to do is find the addresses of the sensors you’ll be using. You could do this dynamically with the code, but there is a practical problem with this – I need to know which sensor is giving each reading for my project. With this contraint, there’s no getting around hardcoding the addresses.
This sketch continually loops through all addresses found on the bus and prints the 8-byte hex addresses.
Obtaining temperature readings
Once you have the addresses, the code for obtaining the temperature readings is fairly simple. Declare the number of sensors at the array of device addresses toward the top. From there, the
setup function will start the serial monitor and set the resolution of the sensors. I chose
12, the most precise. It costs a small amount of extra time, which is fine for the application I have in mind.
loop function just loops over the sensors, requests and obtains readings, and prints them to the serial monitor.
I did a fair of amount of
Googling research for figuring out how all of this works. Some of the useful sites I found:
- Datasheet from Maxim Integrated.
- The Arduino Playground describes the ideas behind working with a DS18B20 device.
- The PJRC site has a nice, brief overview of the OneWire library.
- Henry Bench’s manual provided a simple explanation and code snippet for using the OneWire and DallasTemperature libraries together.