{"id":163477,"date":"2025-01-15T16:30:02","date_gmt":"2025-01-15T16:30:02","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=163477"},"modified":"2025-01-16T10:22:24","modified_gmt":"2025-01-16T10:22:24","slug":"raspberry-pi-pico-microsd-card-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-microsd-card-micropython\/","title":{"rendered":"Raspberry Pi Pico: MicroSD Card Guide with Datalogging Example (MicroPython)"},"content":{"rendered":"\n<p>In this guide, we\u2019ll show you how to interface a microSD card with the Raspberry Pi Pico, how to create, write, read, and delete files, and we\u2019ll also create a datalogging project example. The Raspberry Pi Pico will be programmed using MicroPython.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-microsd-card-guide-Micropython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico MicroSD Card Guide with Datalogging Example MicroPython\" class=\"wp-image-166633\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-microsd-card-guide-Micropython.jpg?w=1920&amp;quality=100&amp;strip=all&amp;ssl=1 1920w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-microsd-card-guide-Micropython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-microsd-card-guide-Micropython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-microsd-card-guide-Micropython.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-microsd-card-guide-Micropython.jpg?resize=1536%2C864&amp;quality=100&amp;strip=all&amp;ssl=1 1536w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p>Using a microSD card can be useful in different scenarios. For example, to log a large amount of data over an extended period. <\/p>\n\n\n\n<p>Additionally, you can easily extract the card from the microcontroller and transfer the data to another system for later analysis. <\/p>\n\n\n\n<p>It might also be useful to save configuration files that need to be changed occasionally, without the need to modify the code running on the Raspberry Pi Pico.<\/p>\n\n\n\n<p><strong>Table of Contents:<\/strong><\/p>\n\n\n\n<p>In this tutorial, we&#8217;ll cover the following topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#intro-microsd-card\" title=\"\">Introducing the MicroSD Card Module<\/a><\/li>\n\n\n\n<li><a href=\"#pinout\" title=\"\">MicroSD Card Module Pinout &#8211; SPI Communication<\/a><\/li>\n\n\n\n<li><a href=\"#sdcard-module\" title=\"\">Uploading the <em>sdcard.py<\/em> Module<\/a><\/li>\n\n\n\n<li><a href=\"#testing-microsd-card\" title=\"\">Testing the MicroSD Card<\/a><\/li>\n\n\n\n<li><a href=\"#create-write-read-files\" title=\"\">Create, Write, and Read Files on a MicroSD Card<\/a><\/li>\n\n\n\n<li><a href=\"#delete-files\" title=\"\">Deleting Files<\/a><\/li>\n\n\n\n<li><a href=\"#datalogging\" title=\"\">Datalogging Temperature to the MicroSD Card<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">Prerequisites &#8211; MicroPython Firmware<\/h2>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board. <\/p>\n\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\" title=\"\">Programming Raspberry Pi Pico using MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"intro-microsd-card\">Introducing the MicroSD Card Module<\/h1>\n\n\n\n<p>The easiest way to interface a microSD card with a microcontroller is by using a <a href=\"https:\/\/makeradvisor.com\/tools\/sd-card-module\/\" target=\"_blank\" rel=\"noopener\" title=\"\">microSD card module<\/a>. These modules typically include all the necessary components like voltage regulators, level shifters, and pull-up resistors, making it easier to connect the microSD card to a microcontroller.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/makeradvisor.com\/tools\/sd-card-module\/\" target=\"_blank\" rel=\"noreferrer noopener\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"317\" height=\"288\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/microSD-card-module-ESP32-ESP8266-Arduino.png?resize=317%2C288&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"microSD card module\" class=\"wp-image-102297\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/microSD-card-module-ESP32-ESP8266-Arduino.png?w=317&amp;quality=100&amp;strip=all&amp;ssl=1 317w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/microSD-card-module-ESP32-ESP8266-Arduino.png?resize=300%2C273&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 317px) 100vw, 317px\" \/><\/a><\/figure><\/div>\n\n\n<p>You can communicate with the microSD card using SPI or SDMMC protocols. SDMMC protocol is usually faster than SPI, but requires more GPIOs and is usually more complex. At the moment, there isn\u2019t great support for SDMMC communication with the Raspberry Pi Pico. So, we\u2019ll prioritize using SPI protocol with the microSD card.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/microSD-card-module-ESP32-Arduino-ESP8266.jpg?resize=750%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"microSD card module for Raspberry Pi Pico Arduino SPI\" class=\"wp-image-102279\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/microSD-card-module-ESP32-Arduino-ESP8266.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/microSD-card-module-ESP32-Arduino-ESP8266.jpg?resize=300%2C168&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>There are different microSD card modules compatible with the Raspberry Pi Pico. We\u2019re using the microSD card module shown in the figure above\u2014it communicates using SPI communication protocol. You can use any other microSD card module with an SPI interface. Some microSD card modules even support both SPI and SDMMC protocols.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Parts Required<\/h2>\n\n\n\n<p>For this tutorial, you\u2019ll need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-pico-w\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/sd-card-module\/\" target=\"_blank\" rel=\"noopener\" title=\"\">MicroSD card module<\/a><\/li>\n\n\n\n<li>MicroSD card that can be formatted as FAT32<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Jumper wires<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"pinout\">MicroSD Card Module Pinout &#8211; SPI Communication<\/h2>\n\n\n\n<p>You can wire the microSD card to any combination of Raspberry Pi Pico SPI pins. We\u2019ll use the pins shown in the following table.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><td><strong>MicroSD Card Module<\/strong><\/td><td><strong>Raspberry Pi Pico<\/strong><\/td><\/tr><tr><td>3V3*<\/td><td>3V3(OUT)<\/td><\/tr><tr><td>CS<\/td><td>GPIO 5<\/td><\/tr><tr><td>MOSI (TX)<\/td><td>GPIO 3<\/td><\/tr><tr><td>CLK\/SCK<\/td><td>GPIO 2<\/td><\/tr><tr><td>MISO (RX)<\/td><td>GPIO 4<\/td><\/tr><tr><td>GND<\/td><td>GND<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>* <em>The microSD card module we\u2019re using only requires 3V3. Some modules might need 5V. In that case, you need to power them using the VBUS pin<\/em>.<\/p>\n\n\n\n<p>You can also use the following schematic diagram as a reference.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"918\" height=\"542\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Wiring-Raspberry-Pi-Pico-microSD-card-module.png?resize=918%2C542&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Wiring Raspberry Pi Pico to microSD Card Module\" class=\"wp-image-163482\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Wiring-Raspberry-Pi-Pico-microSD-card-module.png?w=918&amp;quality=100&amp;strip=all&amp;ssl=1 918w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Wiring-Raspberry-Pi-Pico-microSD-card-module.png?resize=300%2C177&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Wiring-Raspberry-Pi-Pico-microSD-card-module.png?resize=768%2C453&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 918px) 100vw, 918px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Formatting the MicroSD Card<\/h2>\n\n\n\n<p>Before proceeding with the tutorial, make sure you&nbsp;format your microSD card as FAT32. Follow the next instructions to format your microSD card or use a software tool like&nbsp;<a href=\"https:\/\/www.sdcard.org\/downloads\/formatter\/\" target=\"_blank\" rel=\"noreferrer noopener\">SD Card Formatter<\/a>&nbsp;(compatible with Windows and Mac OS).<\/p>\n\n\n\n<p><strong>1.<\/strong>&nbsp;Insert the microSD card into your computer. Go to&nbsp;<em>My Computer<\/em>&nbsp;and right-click on the SD card. Select&nbsp;<strong>Format\u2026<\/strong>&nbsp;as shown in the figure below.<\/p>\n\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\"><div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"431\" height=\"573\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/format-SD-card-1.png?resize=431%2C573&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"format microSD card\" class=\"wp-image-61731\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/format-SD-card-1.png?w=431&amp;quality=100&amp;strip=all&amp;ssl=1 431w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/format-SD-card-1.png?resize=226%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 226w\" sizes=\"(max-width: 431px) 100vw, 431px\" \/><\/figure><\/div><\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\"><div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"254\" height=\"463\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/format-SD-card-2.png?resize=254%2C463&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"format microsd card fat32 windows\" class=\"wp-image-61732\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/format-SD-card-2.png?w=254&amp;quality=100&amp;strip=all&amp;ssl=1 254w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/format-SD-card-2.png?resize=165%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 165w\" sizes=\"(max-width: 254px) 100vw, 254px\" \/><\/figure><\/div><\/div>\n<\/div>\n\n\n\n<p><strong>2.<\/strong>&nbsp;A new window pops up. Select&nbsp;FAT32, press&nbsp;Start&nbsp;to initialize the formatting process, and follow the onscreen instructions. After a few seconds, the process will be completed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"sdcard-module\">Uploading the <em>sdcard.py<\/em> Module<\/h2>\n\n\n\n<p>At the moment, there isn\u2019t much support in terms of libraries to use the microSD card with the Raspberry Pi Pico. We\u2019ve found the <em>sdcard.py<\/em> module that seems to work just fine to handle files on the microSD card. Follow the next steps to install the library.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/refs\/heads\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/sd_card\/sdcard.py\" target=\"_blank\" rel=\"noopener\" title=\"\"><strong>Click here to download the <em>sdcard.py<\/em> library code.<\/strong><\/a><\/li>\n\n\n\n<li>Create a new file in Thonny IDE and copy the library code.<\/li>\n\n\n\n<li>Go to&nbsp;<strong>File<\/strong>&nbsp;&gt;&nbsp;<strong>Save&nbsp;as<\/strong> and select&nbsp;<strong>Raspberry Pi Pico<\/strong>.<\/li>\n\n\n\n<li>Name the file&nbsp;<a href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/refs\/heads\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/sd_card\/sdcard.py\" target=\"_blank\" rel=\"noopener\" title=\"\">sdcard.py<\/a>&nbsp;and click&nbsp;<strong>OK<\/strong>&nbsp;to save the file on the Raspberry Pi Pico.<\/li>\n<\/ol>\n\n\n\n<p>And that\u2019s it. The library was uploaded to your board. Now, you can use the library functionalities in your code by importing the library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"testing-microsd-card\">Testing the MicroSD Card<\/h2>\n\n\n\n<p>Upload the following code to your Raspberry Pi Pico to check if it can communicate with the microSD card.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-microsd-card-micropython\/\r\n\r\nfrom machine import SPI, Pin\r\nimport sdcard, os\r\n\r\n# Constants\r\nSPI_BUS = 0\r\nSCK_PIN = 2\r\nMOSI_PIN = 3\r\nMISO_PIN = 4\r\nCS_PIN = 5\r\nSD_MOUNT_PATH = '\/sd'\r\n\r\ntry:\r\n    # Init SPI communication\r\n    spi = SPI(SPI_BUS,sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))\r\n    cs = Pin(CS_PIN)\r\n    sd = sdcard.SDCard(spi, cs)\r\n    # Mount microSD card\r\n    os.mount(sd, SD_MOUNT_PATH)\r\n    # List files on the microSD card\r\n    print(os.listdir(SD_MOUNT_PATH))\r\n    \r\nexcept Exception as e:\r\n    print('An error occurred:', e)<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/sd_card\/test_microsd_card.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>The previous code starts SPI communication on the pins that the microSD card is connected to, tries to mount the microSD card, and then, tries to list the files there.<\/p>\n\n\n\n<p>If you\u2019re using different SPI pins, you should modify the code accordingly. Also notice that depending on the pins used, you might need to change the SPI bus. On the Raspberry Pi Pico pinout, you can see which pins are on SPI bus 1 or 0.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>SPI_BUS = 0\nSCK_PIN = 2\nMOSI_PIN = 3\nMISO_PIN = 4\nCS_PIN = 5<\/code><\/pre>\n\n\n\n<p class=\"rntbox rntclgreen\">Related content: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Testing the Code<\/h3>\n\n\n\n<p>Run the previous code on your Raspberry Pi Pico by clicking on the Thonny IDE run green button.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"470\" height=\"114\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?resize=470%2C114&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Run code in Thonny IDE\" class=\"wp-image-144594\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?w=470&amp;quality=100&amp;strip=all&amp;ssl=1 470w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?resize=300%2C73&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 470px) 100vw, 470px\" \/><\/figure><\/div>\n\n\n<p>You should get a similar message on the Shell (see the screenshot below). If that\u2019s the case, it means everything is working as expected. If not, check the wiring, if the microSD card is properly inserted, and if you\u2019re using the right SPI Bus number for the pins you\u2019re using.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"702\" height=\"242\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/mount-micro-sd-card-successful-thonny-ide.png?resize=702%2C242&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"microsd card mount successfully Thonny IDE RPI Pico - Testing\" class=\"wp-image-163484\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/mount-micro-sd-card-successful-thonny-ide.png?w=702&amp;quality=100&amp;strip=all&amp;ssl=1 702w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/mount-micro-sd-card-successful-thonny-ide.png?resize=300%2C103&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 702px) 100vw, 702px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"create-write-read-files\">Create, Write, and Read Files on a MicroSD Card<\/h2>\n\n\n\n<p>Now that you know that the Raspberry Pi Pico is properly connected to the microSD card, let\u2019s test some basic file operations.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Pico-microsdcard.jpg?resize=750%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico with microSD Card\" class=\"wp-image-163485\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Pico-microsdcard.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Pico-microsdcard.jpg?resize=300%2C168&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>The following code mounts the microSD card, creates a new file, writes to it, and then reads its content.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-microsd-card-micropython\/\r\n \r\nfrom machine import SPI, Pin\r\nimport sdcard, os\r\n\r\n# Constants\r\nSPI_BUS = 0\r\nSCK_PIN = 2\r\nMOSI_PIN = 3\r\nMISO_PIN = 4\r\nCS_PIN = 5\r\nSD_MOUNT_PATH = '\/sd'\r\nFILE_PATH = 'sd\/sd_file.txt'\r\n\r\ntry:\r\n    # Init SPI communication\r\n    spi = SPI(SPI_BUS,sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))\r\n    cs = Pin(CS_PIN)\r\n    sd = sdcard.SDCard(spi, cs)\r\n    # Mount microSD card\r\n    os.mount(sd, SD_MOUNT_PATH)\r\n    # List files on the microSD card\r\n    print(os.listdir(SD_MOUNT_PATH))\r\n    \r\n    # Create new file on the microSD card\r\n    with open(FILE_PATH, &quot;w&quot;) as file:\r\n        # Write to the file\r\n        file.write(&quot;Testing microSD Card \\n&quot;)\r\n        \r\n    # Check that the file was created:\r\n    print(os.listdir(SD_MOUNT_PATH))\r\n    \r\n    # Open the file in reading mode\r\n    with open(FILE_PATH, &quot;r&quot;) as file:\r\n        # read the file content\r\n        content = file.read()\r\n        print(&quot;File content:&quot;, content)  \r\n    \r\nexcept Exception as e:\r\n    print('An error occurred:', e)<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/sd_card\/micro_sd_card_create_write_read.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>First, import the required modules and classes. We need to import <span class=\"rnthl rntliteral\">SPI<\/span> and <span class=\"rnthl rntliteral\">Pin<\/span> classes from the <span class=\"rnthl rntliteral\">machine<\/span> module, the <span class=\"rnthl rntliteral\">os<\/span> module to use operations on the filesystem, and the <span class=\"rnthl rntliteral\">sdcard<\/span> to interact with the microSD card.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from machine import SPI, Pin\nimport sdcard, os<\/code><\/pre>\n\n\n\n<div class=\"wp-block-group rntbox rntclgray is-vertical is-layout-flex wp-container-core-group-is-layout-8cf370e7 wp-block-group-is-layout-flex\">\n<p><strong>The <span class=\"rnthl rntliteral\">os<\/span> module<\/strong><\/p>\n\n\n\n<p>In MicroPython, there\u2019s a module called <span class=\"rnthl rntliteral\">os<\/span> that includes a wide range of functions to manage file operations. Additionally, it also comes with methods for tasks like managing directories, accessing environment variables, and executing system commands. The <span class=\"rnthl rntliteral\">os<\/span> module comes included by default on MicroPython firmware. More details about the os module <a href=\"https:\/\/docs.micropython.org\/en\/latest\/library\/os.html\" target=\"_blank\" rel=\"noopener\" title=\"\">can be found here<\/a>.<\/p>\n<\/div>\n\n\n\n<p>Define the SD card pins and SPI bus number you\u2019re using on the following lines.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>SPI_BUS = 0\nSCK_PIN = 2\nMOSI_PIN = 3\nMISO_PIN = 4\nCS_PIN = 5<\/code><\/pre>\n\n\n\n<p>Create variables to hold the SD card path and the file path that we\u2019ll create.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>SD_MOUNT_PATH = '\/sd'\nFILE_PATH = 'sd\/sd_file.txt'<\/code><\/pre>\n\n\n\n<p>Then, initialize SPI communication and mount the microSD card.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    # Init SPI communication\n    spi = SPI(SPI_BUS,sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))\n    cs = Pin(CS_PIN)\n    sd = sdcard.SDCard(spi, cs)\n    # Mount microSD card\n    os.mount(sd, SD_MOUNT_PATH)<\/code><\/pre>\n\n\n\n<p>List all files on the SD card filesystem.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># List files on the microSD card\nprint(os.listdir(SD_MOUNT_PATH))<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Creating a File<\/h4>\n\n\n\n<p>Creating a file in MicroPython is as easy as using the <span class=\"rnthl rntliteral\">open()<\/span> function and passing as argument the filename and the file opening mode. The <span class=\"rnthl rntliteral\">open()<\/span> function will open the file if it already exists, or it will create a new file if it doesn\u2019t.<\/p>\n\n\n\n<p>The different modes for opening a file are <span class=\"rnthl rntliteral\">&#8216;w&#8217;<\/span>, <span class=\"rnthl rntliteral\">&#8216;r&#8217;<\/span>, and <span class=\"rnthl rntliteral\">&#8216;a&#8217;<\/span>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">&#8216;w&#8217;<\/span>: writing mode \u2014 allows writing to a file, overwriting existing content;<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">&#8216;r&#8217;<\/span>: reading mode \u2014 enables reading from an existing file;<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">&#8216;a&#8217;<\/span>: appending mode \u2014 appending new data to the end of an existing file.<\/li>\n<\/ul>\n\n\n\n<p>To create a new file, we can use the writing mode (<span class=\"rnthl rntliteral\">&#8216;w&#8217;<\/span>). The following line of code will create a new file on the Raspberry Pi Pico filesystem using the <span class=\"rnthl rntliteral\">open()<\/span> method. The file is called <span class=\"rnthl rntliteral\">sd_file.txt<\/span> (defined previously on the <span class=\"rnthl rntliteral\">FILE_PATH<\/span> variable), but you can rename it to whatever you want.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Create new file on the microSD card\nwith open(FILE_PATH, \"w\") as file:<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>The \u2018with\u2019 Keyword for File Operations<\/strong><\/h5>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">with<\/span> keyword is used in conjunction with file operations to ensure proper handling of resources and to simplify code. Specifically, it&#8217;s often used with the <span class=\"rnthl rntliteral\">open()<\/span> function when dealing with files.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>with open(FILE_PATH, \"w\") as file:<\/code><\/pre>\n\n\n\n<p>This syntax automatically handles opening and closing the file, ensuring that the file is properly closed when you&#8217;re done with it, even if an exception occurs during file operations.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Writing to the File<\/h4>\n\n\n\n<p>Writing to a file is very straightforward. You just need to use the <span class=\"rnthl rntliteral\">write()<\/span> method on the <span class=\"rnthl rntliteral\">file<\/span> object and pass as argument the data you want to write (it must be a string). In our example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>with open(FILE_PATH, \"w\") as file:\n    # Write to the file\n    file.write(\"Testing microSD Card \\n\")<\/code><\/pre>\n\n\n\n<div class=\"wp-block-group rntbox rntclgray is-vertical is-layout-flex wp-container-core-group-is-layout-8cf370e7 wp-block-group-is-layout-flex\">\n<h4 class=\"wp-block-heading\">The Newline Character<\/h4>\n\n\n\n<p>In the previous code, notice that we use a <strong>\\n<\/strong> at the end of our first line:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>file.write(\"Writing my first line <strong>\\n<\/strong>\")<\/code><\/pre>\n\n\n\n<p>In Python\/MicroPython, the <span class=\"rnthl rntliteral\">\\n<\/span> represents a newline character. It is used to represent the end of a line in a text file. It is a control character that signifies the beginning of a new line of text.&nbsp; When working with files, the newline character is useful for formatting text. When writing multiple lines to a file, you use <span class=\"rnthl rntliteral\">\\n<\/span> to separate each line.<\/p>\n<\/div>\n\n\n\n<h4 class=\"wp-block-heading\">Reading a File<\/h4>\n\n\n\n<p>After writing to the file, let\u2019s open it in reading mode to check that it was actually written. To read the file, use the <span class=\"rnthl rntliteral\">read()<\/span> method as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Open the file in reading mode\nwith open(FILE_PATH, \"r\") as file:\n    # read the file content\n    content = file.read()\n    print(\"File content:\", content)  <\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Testing the Code<\/h2>\n\n\n\n<p>Run the previous code on your Raspberry Pi Pico. You should get a similar message on the Shell.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"733\" height=\"229\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/micro-sd-card-file-created-thonny-ide.png?resize=733%2C229&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"microsd card file created thonny IDE\" class=\"wp-image-163486\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/micro-sd-card-file-created-thonny-ide.png?w=733&amp;quality=100&amp;strip=all&amp;ssl=1 733w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/micro-sd-card-file-created-thonny-ide.png?resize=300%2C94&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 733px) 100vw, 733px\" \/><\/figure><\/div>\n\n\n<p>The first line means that there aren\u2019t any files on the microSD card filesystem. The second line shows the file we created with the code called <em><strong>sd_file.txt<\/strong><\/em>. Finally, the last line shows the contents of the <strong><em>sd_file.txt<\/em><\/strong> file.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"delete-files\">Deleting Files<\/h2>\n\n\n\n<p>Deleting a file on the microSD card is as easy as using the command <span class=\"rnthl rntliteral\">os.remove()<\/span> and passing as an argument the file path.<\/p>\n\n\n\n<p>For example, you can simply add the following line to the previous example to delete the <strong><em>sd_file.txt<\/em><\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Delete file from the microSD card\nos.remove(FILE_PATH)<\/code><\/pre>\n\n\n\n<p>The complete code can be found below:<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-microsd-card-micropython\/\r\n\r\nfrom machine import SPI, Pin\r\nimport sdcard, os\r\n\r\n# Constants\r\nSPI_BUS = 0\r\nSCK_PIN = 2\r\nMOSI_PIN = 3\r\nMISO_PIN = 4\r\nCS_PIN = 5\r\nSD_MOUNT_PATH = '\/sd'\r\nFILE_PATH = 'sd\/sd_file.txt'\r\n\r\ntry:\r\n    # Init SPI communication\r\n    spi = SPI(SPI_BUS,sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))\r\n    cs = Pin(CS_PIN)\r\n    sd = sdcard.SDCard(spi, cs)\r\n    # Mount microSD card\r\n    os.mount(sd, SD_MOUNT_PATH)\r\n    # List files on the microSD card\r\n    print(os.listdir(SD_MOUNT_PATH))\r\n    \r\n    # Create new file on the microSD card\r\n    with open(FILE_PATH, &quot;w&quot;) as file:\r\n        # Write to the file\r\n        file.write(&quot;Testing microSD Card \\n&quot;)\r\n        \r\n    # Check that the file was created:\r\n    print(os.listdir(SD_MOUNT_PATH))\r\n    \r\n    # Open the file in reading mode\r\n    with open(FILE_PATH, &quot;r&quot;) as file:\r\n        # read the file content\r\n        content = file.read()\r\n        print(&quot;File content:&quot;, content)\r\n    \r\n    # Delete file from the microSD card\r\n    os.remove(FILE_PATH)\r\n    \r\n    # Check that the file was deleted\r\n    print(os.listdir(SD_MOUNT_PATH))    \r\n    \r\nexcept Exception as e:\r\n    print('An error occurred:', e)\r\n\r\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/sd_card\/micro_sd_card_create_write_read_delete.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>We also list the contents of the microSD card again to make sure the file was removed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Testing the Code<\/h3>\n\n\n\n<p>Run the previous code on your Raspberry Pi. You should see that the microSD card filesystem is empty in the end. It means we successfully removed the <strong><em>sd_file.txt<\/em><\/strong> file.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"624\" height=\"229\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/delete-file-from-sd-card-success-thonny-ide.png?resize=624%2C229&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Delete file from microSD card - Thonny IDE\" class=\"wp-image-163488\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/delete-file-from-sd-card-success-thonny-ide.png?w=624&amp;quality=100&amp;strip=all&amp;ssl=1 624w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/delete-file-from-sd-card-success-thonny-ide.png?resize=300%2C110&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 624px) 100vw, 624px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"datalogging\">Datalogging Temperature to the MicroSD Card<\/h2>\n\n\n\n<p>Datalogging to the microSD card with the Raspberry Pi Pico is simple. You just need to mount the microSD card, and then, use the right file paths to create files and save the data.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-log-data-microsd-card.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico log data to microsd card\" class=\"wp-image-163504\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-log-data-microsd-card.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-log-data-microsd-card.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>To show you how it\u2019s done, we\u2019ll create a simple project that saves the Raspberry Pi Pico internal temperature to the microSD card every 30 seconds. <strong>Note that you need the <span class=\"rnthl rntliteral\">picozero<\/span> package installed on your board (<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-internal-temperature-micropython\/#reading-temperature-picozero\" title=\"\">check this tutorial<\/a>).<\/strong><\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-microsd-card-micropython\/\r\n\r\nfrom time import sleep\r\nfrom machine import Timer, SPI, Pin\r\nfrom picozero import pico_temp_sensor\r\nimport sdcard, os\r\n\r\n# Constants\r\nSPI_BUS = 0\r\nSCK_PIN = 2\r\nMOSI_PIN = 3\r\nMISO_PIN = 4\r\nCS_PIN = 5\r\nSD_MOUNT_PATH = '\/sd'\r\nFILE_PATH = '\/sd\/temperature.txt'\r\n\r\n# Init SPI communication\r\nspi = SPI(SPI_BUS, sck=Pin(SCK_PIN), mosi=Pin(MOSI_PIN), miso=Pin(MISO_PIN))\r\ncs = Pin(CS_PIN)\r\n\r\ndef mount_sdcard(spi, cs_pin):\r\n    try:\r\n        sd = sdcard.SDCard(spi, cs_pin)\r\n        # Mount microSD card\r\n        os.mount(sd, SD_MOUNT_PATH)\r\n        # List files on the microSD card\r\n        print(os.listdir(SD_MOUNT_PATH))\r\n    \r\n    except Exception as e:\r\n        print('An error occurred mounting the SD card:', e)\r\n\r\ndef log_temperature(timer):\r\n    try:\r\n        # Read the internal temperature sensor value\r\n        temperature = pico_temp_sensor.temp\r\n        # Format temperature\r\n        temperature_string = &quot;{:.2f} \u00b0C\\n&quot;.format(temperature)\r\n        \r\n        # Write to the file\r\n        with open(FILE_PATH, 'a') as file:\r\n            file.write(temperature_string)\r\n            print(&quot;Temperature logged successfully.&quot;)\r\n    except Exception as e:\r\n        print('An error occurred accessing the file or getting temperature', e)\r\n\r\n# Mount SD card\r\nmount_sdcard(spi, cs)\r\n\r\n# Log temperature when the program first runs\r\nlog_temperature(None)\r\n\r\n# Create a timer that calls log_temperature every 30 seconds\r\nlog_timer = Timer(period=30000, mode=Timer.PERIODIC, callback=log_temperature)\r\n\r\n# Keep the program running\r\ntry:\r\n    while True:\r\n        sleep(0.1)\r\nexcept KeyboardInterrupt:\r\n    # Clean up and stop the timer on keyboard interrupt\r\n    log_timer.deinit()\r\n    print(&quot;Keyboard Interrupt&quot;)<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/sd_card\/temperature_data_logger.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>We start by including the required libraries<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from time import sleep\nfrom machine import Timer, SPI, Pin\nfrom picozero import pico_temp_sensor\nimport sdcard, os<\/code><\/pre>\n\n\n\n<p>We create a function called <span class=\"rnthl rntliteral\">log_temperature()<\/span> that will be responsible for getting the internal temperature reading and logging the value to a file on the filesystem. This function will then be called by a <a href=\"https:\/\/randomnerdtutorials.com\/micropython-timer-interrupts-ep32-esp8266\/\" title=\"\">timer interrupt<\/a> (that\u2019s why we need the function to have one parameter for the time).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def log_temperature(timer):\n    try:\n        # Read the internal temperature sensor value\n        temperature = pico_temp_sensor.temp\n        # Format temperature\n        temperature_string = \"{:.2f} \u00b0C\\n\".format(temperature)\n        \n        # Write to the file\n        with open(FILE_PATH, 'a') as file:\n            file.write(temperature_string)\n            print(\"Temperature logged successfully.\")\n    except Exception as e:\n        print('An error occurred accessing the file or getting temperature', e)<\/code><\/pre>\n\n\n\n<p>Inside that function, we start by getting the Pico\u2019s internal temperature sensor:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Read the internal temperature sensor value\ntemperature = pico_temp_sensor.temp<\/code><\/pre>\n\n\n\n<p>Then, create a new variable to save the temperature as a string with two decimal places and with the Celsius degrees unit. We also add a newline character <span class=\"rnthl rntliteral\">\\n<\/span>, so that new data is appended to the next line.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Format temperature\ntemperature_string = \"{:.2f} \u00b0C\\n\".format(temperature)<\/code><\/pre>\n\n\n\n<p>Open the new file in appending mode, <span class=\"rnthl rntliteral\">&#8216;a&#8217;<\/span> ,(we want to append new data to the file, not overwriting it). We write the temperature reading to the file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Write to the file\n        with open(FILE_PATH, 'a') as file:\n            file.write(temperature_string)\n            print(\"Temperature logged successfully.\")<\/code><\/pre>\n\n\n\n<p>Then, we want to call that function as soon as the code starts running, so we don\u2019t have to wait 60 seconds for the first log triggered by the timer. Because this function is expecting a value referring to the timer, we can simply pass <span class=\"rnthl rntliteral\">None<\/span> to run that function right away.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Log temperature when the program first runs\nlog_temperature(None)<\/code><\/pre>\n\n\n\n<p>Set a periodic timer interrupt that calls the <span class=\"rnthl rntliteral\">log_temperature()<\/span> function every minute, thus logging data continuously until you stop the program.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>log_timer = Timer(period=60000, mode=Timer.PERIODIC, callback=log_temperature)<\/code><\/pre>\n\n\n\n<p>To keep our program running, we add an empty while loop, but you can add any other tasks to the loop, and it will still log the temperature when it\u2019s the right time.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Keep the program running\ntry:\n    while True:\n        sleep(0.1)<\/code><\/pre>\n\n\n\n<p>Additionally, we also added the <span class=\"rnthl rntliteral\">KeyboardInterrupt<\/span> exception to stop the timer when the program is interrupted by the user.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except KeyboardInterrupt:\n    # Clean up and stop the timer on keyboard interrupt\n    log_timer.deinit()\n    print(\"Keyboard Interrupt\")<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Testing the Code<\/h3>\n\n\n\n<p>Let the code run for a considerable amount of time until you get some data. When you\u2019re happy, stop the program.<\/p>\n\n\n\n<p>Remove the microSD card from the Raspberry Pi Pico and open it on your computer to check the file and its content. You should have a <strong><em>temperature.txt<\/em><\/strong> file with the record of the Raspberry Pi Pico internal temperature.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"589\" height=\"534\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/logging-rpi-pico-temperature-microsd-card.png?resize=589%2C534&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Datalogging temperature to microSD Card - Raspberry Pi Pico\" class=\"wp-image-163489\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/logging-rpi-pico-temperature-microsd-card.png?w=589&amp;quality=100&amp;strip=all&amp;ssl=1 589w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/logging-rpi-pico-temperature-microsd-card.png?resize=300%2C272&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 589px) 100vw, 589px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this guide you learned how to interface a microSD card with the Raspberry Pi Pico programmed with Micropython.We covered how to create a file, write data to it, read data from a file, and how to log data periodically using a timer.<\/p>\n\n\n\n<p>We hope you&#8217;ve found this guide useful. Instead of logging the Pico&#8217;s internal temperature, you may want to log data from other sensors. We have guides for other sensors you may find useful:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bh1750-micropython\/\">Raspberry Pi Pico: <strong>BH1750 Ambient Light Sensor<\/strong> (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bme680-micropython\/\">Raspberry Pi Pico: <strong>BME680 Environmental Sensor<\/strong> (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bme280-micropython\/\">Raspberry Pi Pico: <strong>BME280 Get Temperature, Humidity, and Pressure<\/strong> (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-motion-pir-micropython\/\">Raspberry Pi Pico: <strong>Detect Motion using a PIR Sensor<\/strong> (MicroPython)<\/a><\/li>\n<\/ul>\n\n\n\n<p>If you&#8217;d like to learn more about programming the Raspberry Pi Pico with MicroPython, take a look at our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\">Learn Raspberry Pi Pico\/Pico W with MicroPython (eBook)<\/a><\/strong><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\">Free Raspberry Pi Pico Projects and Tutorials<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, we\u2019ll show you how to interface a microSD card with the Raspberry Pi Pico, how to create, write, read, and delete files, and we\u2019ll also create a &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico: MicroSD Card Guide with Datalogging Example (MicroPython)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-microsd-card-micropython\/#more-163477\" aria-label=\"Read more about Raspberry Pi Pico: MicroSD Card Guide with Datalogging Example (MicroPython)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":166633,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[324,326],"tags":[],"class_list":["post-163477","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-micropython"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/10\/Raspberry-Pi-Pico-microsd-card-guide-Micropython.jpg?fit=1920%2C1080&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/163477","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=163477"}],"version-history":[{"count":12,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/163477\/revisions"}],"predecessor-version":[{"id":166651,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/163477\/revisions\/166651"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/166633"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=163477"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=163477"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=163477"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}