Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save XtendedGreg/3b46a6dc6792eedce1451768cddbfbf6 to your computer and use it in GitHub Desktop.
Save XtendedGreg/3b46a6dc6792eedce1451768cddbfbf6 to your computer and use it in GitHub Desktop.
Alpine Linux on Raspberry Pi Basics: Using I2C Sensors

Alpine Linux on Raspberry Pi Basics: Using I2C Sensors

As featured in the XtendedGreg YouTube Live Stream: https://youtube.com/live/L9yt2NOktGs Alpine Linux on Raspberry Pi Basics: Using I2C Sensors

Introduction

This Gist is a procedure on how to enable I2C functionality on Alpine Linux running on a Raspberry Pi. I2C is a high speed communications interface that allows interacting with sensors and periferals efficiently. In this example, we will be connecting an SHT31-D temperature and humidity sensor to create a basic logger using Python. Follow these steps and you will be well on your way to integrating it into your next project!

Setup Procedure

  1. Enable I2C bus in usercfg.txt file on the root of the boot drive
  • From the console remount the boot drive for read/write
mount -o remount,rw /media/mmcblk0p1
  • Create or edit the usercfg.txt file
vi /media/mmcblk0p1/usercfg.txt
  • Press i to enter edit mode and enter the following line at the end of usercfg.txt
dtparam=i2c_arm=on
  • Press esc then :wq and press enter to save and exit the editor
  • Remount the boot drive as read-only
mount -o remount,ro /media/mmcblk0p1
  1. Add the I2C module to load on boot
  • Enter the following command into the console
echo 'i2c-dev' > /etc/modules-load.d/i2c.conf
  1. Install needed packages from APK package manager
apk add python3 py3-pip py3-rpigpio py3-smbus
  1. Add the Python library from Adafruit for the SHT31-D
    • Note: This is not available as a package on Alpine Linux so cannot be installed using APK Package Manager, so we will need to add an override flag to allow this install
pip3 install --break-system-packages adafruit-circuitpython-sht31d
  1. Add the path where the Python library from Adafruit is installed to LBU to persist on reboot
lbu add /usr/lib/python*/site-packages/adafruit*
  1. Commit the changes to LBU and Reboot
  • lbu commit -d
  • reboot

Temperature and Humidity Logger Script

  1. Using a text editor, create a new file an open it for editing in the current directory
vi sht31.py
  1. Enter edit mode by pressing i and enter the following code and then esc followed by :wq and hit enter to save and exit
#!/usr/bin/python
import board
import busio
import adafruit_sht31d
import time
import datetime

# Initialize I2C bus
i2c = busio.I2C(board.SCL, board.SDA)

# Create sensor object
sensor = adafruit_sht31d.SHT31D(i2c)

# Modify this for your desired file path
output_file = "temperature_humidity_data.txt"

while True:
    temperature = sensor.temperature
    humidity = sensor.relative_humidity

    # Get current timestamp
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # Format data for output
    data_string = f"{timestamp},{temperature},{humidity}\n"

    # Print to terminal
    print(data_string.strip()) 

    # Write to file
    with open(output_file, "a") as f:
        f.write(data_string)

    time.sleep(1)  # Take measurements every second
  1. Give the file executable permissions
chmod +x sht31.py
  1. Add the file to LBU so that it saves past reboots
lbu add $(pwd)/sht31.py
  1. Commit the changes using LBU
lbu commit -d

Run the Program and Enjoy!

./sht31.py
  • Use CTRL+c to exit back to the terminal

Explanation of the Output

  • If everything is running correctly, you will see output that looks like this:
2024-03-31 03:53:28,24.89585717555505,31.270313572899976
  • The parts are separated by commas (,) and represent the following values
    • Datestamp
    • Temperature in Celcius
    • Relative Humidity as a Percent
  • You can use these values to graph changes in the temperature and humidity over time

Code Modifications

  • You can covert the temperature Celcius to Fahrenheit by inserting the following code before the line # Format data for output inside of the while loop
# Convert Celcius to Fahrenheit
temperature = (temperature * 9/5) + 32
  • You can change the interval of the measurements to be longer so that it is easier to track the data over time by changing the number in the following line in the while loop to the number of seconds to wait between measurements
time.sleep(1)  # Take measurements every second

Additional Information

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment