Raspberry Pi Pico data logger
Turn Raspberry Pi Pico into a temperature data-logging device and untether it from the computer to make it fully portable
Gareth Halfacree @ghalfacree
Throughout our Raspberry Pi Pico tutorials, you’ve been using your Pico connected to a Raspberry Pi or other computer via its micro USB port. Like all microcontrollers, though, there’s no reason your Pico has to be tethered in this way: it’s a fully functional self-contained system, with processing capabilities, memory, and everything it needs to work on its own. In this guide you’ll learn how to use the file system to create, write to, and read from files, allowing you to put your Pico anywhere you like and have it record data for later access – turning it into what is known as a data logger. For this you’ll only need your Pico and, if you want to use it away from your Raspberry Pi, a micro USB charger or battery pack; once you have finished the tutorial, you can connect additional analogue sensors if you want to expand your project.
With a passion for open-source software and hardware, Gareth was an early adopter of the Raspberry Pi platform and has written several publications on its capabilities and flexibility.
The file system is where your Pico stores all the programs you’ve been writing. It’s equivalent in function to the microSD card in your Raspberry Pi, or the hard drive or solid-state drive in your laptop or desktop computer: it’s a form of non-volatile storage, which means that whatever you save there stays in place even when you unplug your Pico’s micro USB cable. Connect your Pico to your Raspberry Pi and load Thonny, if you don’t already have it open. Click the Open icon, and click ‘Raspberry Pi Pico’ in the pop-up which appears. You’ll see a list of all the programs you’ve been writing so far, stored on your Pico’s file system. You’re not going to open one right now, so click Cancel. Click at the bottom of the Shell area to start working with your Pico in interactive mode. Type: `file = open("test.txt", "w")` This tells MicroPython to open a file called test.txt for writing – the "w" part of the instruction. You won’t see anything print to the Shell area when you press ENTER at the end of the line, because although you’ve opened the file, you haven’t done anything with it yet. Type: `file.write("Hello, File!")` When you press ENTER at the end of this line, you’ll see the number 12 appear (Figure 1). That’s MicroPython confirming to you that it has written 12 bytes to the file you opened. Count the number of characters in the message you wrote: including the letters, comma, space, and exclamation mark, there are twelve – each of which takes up a single byte. When you’ve written to a file, you need to close it – this ensures that the data you’ve told MicroPython to write is actually written to the file system. If you don’t close the file, the data might not have been written yet – a bit like writing a letter in LibreOffice Writer or another word processor and forgetting to save it. Type: `file.close()`
Your file is now safely stored on your Pico’s file system. Click the Open icon on Thonny’s toolbar, click ‘Raspberry Pi Pico’, and scroll through the list of files until you find **test.txt**. Click on it, then click OK to open it: you’ll see your message pop up in a new Thonny tab. You don’t have to use the Open icon to read files, though: you can do it directly in MicroPython itself. Click back into the bottom of the Shell area and type:
You’ll notice that this time around there’s no **“w”**: that’s because instead of writing to the file, you’re going to be reading it. You could replace the **“w”** with an **“r”**, but MicroPython defaults to opening a file in read mode – so it’s fine to simply leave that part of the instruction off. Next, type:
You’ll see the message you wrote to the file print to the Shell area (**Figure 2**). Congratulations: you can read and write files on your Pico’s file system! Before you finish, remember to close the file – it’s not as important to properly close a file after reading it as it is when writing to it, but it’s a good habit to get into anyway:
Now write something to the file – the reading from the temperature sensor
Now you know how to open, write to, and read from files, you have everything you need to build a data logger on your Pico. Click the New icon to start a new program in Thonny, and start your program by typing:
You might recognise this code: it’s the same as you used in The MagPi #107 (magpi.cc/107) to read from your Pico’s on-board temperature sensor. The readings from the sensor are the data you’re going to be logging to the file system, so you don’t want to simply print them out as you did before. Start by opening a file for writing by adding the following line at the bottom:
If the file doesn’t already exist on the file system, this creates it; if it does, it overwrites it – emptying its contents ready for you to write new data. Now you need to write something to the file – the reading from the temperature sensor:
Rather than writing a fixed string in quotes, as you did before, this time you’re converting the variable temperature – which is a floating-point number, in other words one with a decimal point in it – to a string, then writing that to the file. As before, to make sure the data is written you need to close the file:
Click the Run icon and save your program to the Raspberry Pi Pico as Datalogger.py. The program will only take a few seconds to run; when the >>> prompt reappears at the bottom of the Shell area, click into it and type the following to open and read your new file:
You’ll see the temperature reading your program took appear in the Shell (**Figure 3**). Congratulations: your data logger works! A data logger that only logs a single reading – a datum – isn’t that useful, though. To make your data logger more powerful, you need to modify it so it takes lots of readings. Click Run again, and read the file again:.
Notice how there’s still only one reading in the file. When your program opened the file for writing again, it automatically wiped its previous contents – meaning that each time your program runs, it will wipe the file and store a single reading. To fix that, you need to modify your program. Start by clicking and dragging your mouse cursor to highlight the lines:
When you’ve highlighted both lines – making sure not to miss any parts – let go of the mouse button and press CTRL+X on your keyboard to cut the lines; you’ll see them disappear from the program. Next, go to the bottom of your program and delete everything after:
To make your data logger more powerful, you need to modify it
Now type:
After pressing ENTER at the end of that line, hold down the CTRL key and press the V key to paste the two lines you cut earlier. You’ll see them appear, which saves you having to type them in – but only the first line will be properly indented so it’s nested as part of the infinite loop you just opened. Put your cursor at the start of the line below by clicking and press the SPACE bar four times to indent the line properly, then move your cursor to the end of the line and press ENTER. Type the following line, making sure it’s properly indented:
Now, though, you’re going to need to do something new. If you close the file as you did before, you won’t be able to write to it again without reopening it and wiping its contents. If you don’t close the file, the data will never actually get written to the file system. The solution: flush the file, rather than close it. Type:
When you’re writing to a file but the data isn’t actually being written to the file system, it’s stored in what’s known as a buffer – a temporary storage area. When you close the file, the buffer is written to the file in a process known as flushing. Using file.flush() is equivalent to file.close(), in that it flushes the contents of the buffer into the file – but unlike file.close(), the file remains open for you to write more data to it later. Now you just need to pause your program between readings:
Your finished program will look like this:
Click the Run icon and count to 60, then click the Stop icon. Now open and read your file in the script area:
The good news is that your program has worked, and you’ve recorded multiple readings in a single file – around six, give or take a few depending on how quickly you counted. The bad news is that they’re all mushed together on a single line (**Figure 4**) – making it difficult to read. To fix that problem, you need to format the data as it’s written to the file. Go back to the file.write() line in your program, and modify it so it looks like:
The plus symbol (+) tells MicroPython that you want to append what follows, concatenating the two strings together, “\n” is a special string known
as a control character – it acts as the equivalent of pressing the ENTER key, meaning that each line in your data log should be on its own separate line. Click the Run icon, count to 60 again, and click Stop. Open and read your file:
You’ve made progress, but it’s still not right: the \n control character isn’t acting like a press of ENTER, but printing as two visible characters (**Figure 5**, previous page). That’s because **file.read()** is bringing in the raw contents of the file, and making no attempt at formatting it for the screen. To fix the formatting problem, you need to wrap the file read in a **print()** function:
This time you’ll see each reading print out on its own line, neatly formatted and easy to read (**Figure 6**). Congratulations: you’ve built a data logger which can take multiple readings and store them on your Pico’s file system! Your Pico’s file system works regardless of whether or not it’s connected to your Raspberry Pi or another computer. If you have a micro USB
You can take your data logger to any room and have it run by itself
mains charger or a USB battery pack with a micro USB cable, you can take your data logger to any room in your house and have it run by itself – but you’ll need a way to get your program running without having to click the Run icon in Thonny. For use without a connected computer – known as headless operation – you can save your program under a special file name: **main.py**. When MicroPython finds a file called **main.py** in its file system, it runs that automatically every time it’s powered on or reset – without you having to click Run. In Thonny, after stopping the program if running, click the File menu then Save As. Click ‘Raspberry Pi Pico’ in the pop-up that appears, then type ‘main.py’ as the file name before clicking Save. At first, nothing will seem to happen: that’s because Thonny puts your Pico into interactive mode, which stops it from automatically running the program you just saved. To force the program to run, click into the bottom of the Shell area and hold down the CTRL key, press the D key, then let go of the CTRL key. This sends your Pico a soft reset command, which will break it out of interactive mode and start the program running. Find something else to do for five minutes or so, then press the Stop icon and open your data log:
You’ll see a list of temperature readings, even though you didn’t click the Run icon – because your program ran automatically when your Pico reset. If you have a micro USB charger or USB battery pack, disconnect your Pico from your Raspberry Pi, take it to another room, and connect it to the charger or battery pack. Leave it there for ten minutes, then come back and unplug it. Take it back to your Raspberry Pi, plug it back in, and read your file again: you’ll see the readings from the other room, proving that your Pico can run perfectly well without your Raspberry Pi helping it along. Congratulations: your data logger is now fully functional and wholly portable, ready to go with you wherever you need to record data!