perl interface to 18B20 1-wire temperature sensor

raspberry pi zero interfacing with 18B20 1-wire temperature sensor

I am pretty impressed with the responsiveness and accuracy of the 1-wire 18B20 temperature sensor. This is the first 1-wire sensor I have ever used. To get it going on the pi zero, I had to enable the 1-wire protocol via raspi-config, and edit the /boot/config.txt file to tell it what pin to use. Like gpio, 1-wire has a file system interface, which makes perl a great tool to interface to 1-wire devices.

Interestingly, each 1-wire device has a unique serial number, so it is possible to have literally thousands of 1-wire devices on a single bus; certainly far more than i2c allows. Here is the command line output of a manual reading from the 18B20:

file system interface on pi zero for a 1-wire 18B20 temperature sensor
file system interface on pi zero for a 1-wire 18B20 temperature sensor

The part of the output that says t=26500 is the temperature reading in celsius i.e. 26.500 or 79.7F.

Here is my perl code for interfacing with the 18B20 ->

#!/usr/bin/perl -w
use strict;

=pod
reads a 1wire 18B20
include this in your script, 
returns fahrenheit
=cut

#my $temp = read_18b20();
#print "temp: $temp\n";

sub read_18b20{
	`ls /sys/bus/w1/devices > 1w.txt`;
	open OW, "1w.txt" or die $!;
	my $temp_sensor = '';
	while(<OW>){
		if($_ =~ /(28-............)/){
			#print "serial number:  $1\n";
			$temp_sensor = $1;	
		}#end if
	}#end while
	close OW;

	my ($tempC, $tempF) = (0,0);
	`cat /sys/bus/w1/devices/$temp_sensor/w1_slave > 1w_reading.txt`;	
	open RD, "1w_reading.txt" or die $!;
	while(<RD>){
		if($_ =~ /t=(\d\d)(\d\d\d)/){
			$tempC = $1.".".$2;
			#print "celsius: $tempC\n";	
		}#end if
	}#end while
	close RD;
	$tempF = $tempC * (1.8) + 32;
	#print "farenheit: $tempF\n";
	
	return $tempF; 
}#end read_18b20

1;

Here is sample output from a script that samples the sensor every 2 seconds. I breathed on the 18B20 to demonstrate the responsiveness.

samples from a 1-wire 18B20 temperature sensor using perl interface
samples from a 1-wire 18B20 temperature sensor using perl interface

Leave a Reply

Your email address will not be published. Required fields are marked *