You want to log data measured with a sensor onto a USB flash drive.
Write a Python program that writes the data to a file on a USB flash drive. By writing the file in CSV (comma-separated values), you can import directly into a spreadsheet, including Gnumeric on the Raspberry Pi (Recipe 4.2).
The example program will log temperature readings recorded from a DS18B20. So, if you wish to try this out, first build Recipe 12.9.
Open an editor (nano or IDLE) and paste in the following code. As with all the program examples in this book, you can also download the program from the Code section of the Raspberry Pi Cookbook website, where it is called temp_log.py.
import os, glob, time, datetime log_period = 600 # seconds logging_folder = glob.glob(‘/media/*’)[0] dt = datetime.datetime.now() file_name = “temp_log_{:%Y_%m_%d}.csv”.format(dt) logging_file = logging_folder + ‘/’ + file_name os.system(‘modprobe w1-gpio’) os.system(‘modprobe w1-therm’) base_dir = ‘/sys/bus/w1/devices/’ device_folder = glob.glob(base_dir + ’28*’)[0] |
The program is set to log the temperature every 10 minutes (600 seconds). You can alter this by changing the value of log_period.
Discussion
When you plug a USB flash drive in to a Raspberry Pi, it automatically installs it under /media. If there is more than one drive, then the program uses the first folder it finds inside /media. The name of the logging file is constructed from the current date.
If you open the file in a spreadsheet like Open Office, you will be able to edit it directly. Your spreadsheet may ask you to specify the separator for the data, which will be a comma.
Figure 12-20 shows a set of data captured using this recipe, and the resulting file has been opened with the Gnumeric spreadsheet running on the Raspberry Pi.
See Also
This program could easily be adapted for use with other types of sensor, such as light (Recipe 12.2) or acceleration (Recipe 12.8).