Skip to content

Instantly share code, notes, and snippets.

@galexite
Last active June 14, 2024 16:59
Show Gist options
  • Select an option

  • Save galexite/12c9e4a5b21070d05619b31a1c970933 to your computer and use it in GitHub Desktop.

Select an option

Save galexite/12c9e4a5b21070d05619b31a1c970933 to your computer and use it in GitHub Desktop.
Read the concentration of CO2 in ppm from a K30 sensor connected to a Linux board over I2C.
#!/usr/bin/env python
""" vim: set ai tw=80:
Accessing the K30 10,000ppm CO2 sensor via I2C, rather than UART, upon Linux
(such as for the Raspberry Pi and other similar embedded systems).
Copyright (c) 2019 George White.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
I2C_SLAVE = 0x0703
CMD_READ_REG = 0x22
REG_CO2_PPM = 0x08
import io
import fcntl
class K30Sensor:
def __init__(self, bus, addr=0x68):
self.fr = io.open(bus, "rb", buffering=0)
self.fw = io.open(bus, "wb", buffering=0)
fcntl.ioctl(self.fr, I2C_SLAVE, addr)
fcntl.ioctl(self.fw, I2C_SLAVE, addr)
def write(self, *data):
if type(data) is list or type(data) is tuple:
data = bytes(data)
self.fw.write(data)
def read(self, count):
s = self.fr.read(count)
l = []
if len(s) != 0:
for n in s:
l.append(ord(n))
return l
def read_co2_ppm(self):
checksum = (CMD_READ_REG + REG_CO2_PPM) & 0xFF
self.write(CMD_READ_REG, 0, REG_CO2_PPM, checksum)
response = self.read(4)
return ((response[1] & 0xFF) << 8) | (response[2] & 0xFF)
def close(self):
self.fw.close()
self.fr.close()
if __name__ == "__main__":
"""
Demonstrate the use of the K30Sensor class by simply reading the
concentration from the sensor, and printing it to the screen.
"""
with K30Sensor("/dev/i2c-0") as k30:
print("Concentration of CO2: {} ppm".format(k30.read_co2_ppm()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment