IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 嵌入式 -> 自制树莓派PICO RP2040开发板+例程(I2C读取LM75和AHT20 温度数据) -> 正文阅读

[嵌入式]自制树莓派PICO RP2040开发板+例程(I2C读取LM75和AHT20 温度数据)

1.原理图

在这里插入图片描述

2.PCB

晶振的焊盘有点大,怕和外壳短路,找了个东西垫高了下
来自嘉立创免费打样PCB
在这里插入图片描述

3.焊接完成

这颗QFN封装芯片比较考验焊接功底,手残的不建议自己弄。
在这里插入图片描述

4.代码实现

参考https://pico.org.cn/

1.main.py

from machine import Pin ,I2C
from utime import sleep
import utime
import lm75a
import ahtx0



i=machine.unique_id()#获取芯片ID
led = Pin(25, Pin.OUT) 
print("你好。。。" , i)
KEY2 = Pin(16, Pin.IN, Pin.PULL_UP)
KEY2.irq(lambda pin: external_interrupt(),Pin.IRQ_FALLING)#按键中断

i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=100000)
#根据已有挂载i2c设备增减i2c.scan()[] 我挂载了3个就打印3个,否则报错
print("所有I2C Address : ", hex(i2c.scan()[0]).upper(),
                            hex(i2c.scan()[1]).upper(),
                            hex(i2c.scan()[2]).upper()) # Display device address

sensor_LM75 = lm75a.LM75A(i2c)
sensor_AHT20 = ahtx0.AHT20(i2c)


def external_interrupt():
        
        led.toggle()
        print('按键中断',led.value())
        print("AHT20实时温度: %0.2f C" % sensor_AHT20.temperature)
        print("AHT20实时湿度: %0.2f %%" % sensor_AHT20.relative_humidity)
 


if __name__ == '__main__':
    while True:
        
        led.value(1)# led off  
        utime.sleep_ms(1000)
        led.value(0)# led on
        utime.sleep_ms(1000)
        print("LM75实时温度检测:%0.2f C" % sensor_LM75.temp())
        #print("AHT20实时温度: %0.2f C" % sensor_AHT20.temperature)
        #print("AHT20实时湿度: %0.2f %%" % sensor_AHT20.relative_humidity)


2. AHTX0.PY

# The MIT License (MIT)
#
# Copyright (c) 2020 Kattni Rembor for Adafruit Industries
# Copyright (c) 2020 Andreas Bühl
#
# 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.
"""
MicroPython driver for the AHT10 and AHT20 Humidity and Temperature Sensor
Author(s): Andreas Bühl, Kattni Rembor
"""

import utime
from micropython import const


class AHT10:
    """Interface library for AHT10/AHT20 temperature+humidity sensors"""

    AHTX0_I2CADDR_DEFAULT = const(0x38)  # Default I2C address
    AHTX0_CMD_INITIALIZE = 0xE1  # Initialization command
    AHTX0_CMD_TRIGGER = const(0xAC)  # Trigger reading command
    AHTX0_CMD_SOFTRESET = const(0xBA)  # Soft reset command
    AHTX0_STATUS_BUSY = const(0x80)  # Status bit for busy
    AHTX0_STATUS_CALIBRATED = const(0x08)  # Status bit for calibrated

    def __init__(self, i2c, address=AHTX0_I2CADDR_DEFAULT):
        utime.sleep_ms(20)  # 20ms delay to wake up
        self._i2c = i2c
        self._address = address
        self._buf = bytearray(6)
        self.reset()
        if not self.initialize():
            raise RuntimeError("Could not initialize")
        self._temp = None
        self._humidity = None

    def reset(self):
        """Perform a soft-reset of the AHT"""
        self._buf[0] = self.AHTX0_CMD_SOFTRESET
        self._i2c.writeto(self._address, self._buf[0:1])
        utime.sleep_ms(20)  # 20ms delay to wake up

    def initialize(self):
        """Ask the sensor to self-initialize. Returns True on success, False otherwise"""
        self._buf[0] = self.AHTX0_CMD_INITIALIZE
        self._buf[1] = 0x08
        self._buf[2] = 0x00
        self._i2c.writeto(self._address, self._buf[0:3])
        self._wait_for_idle()
        if not self.status & self.AHTX0_STATUS_CALIBRATED:
            return False
        return True

    @property
    def status(self):
        """The status byte initially returned from the sensor, see datasheet for details"""
        self._read_to_buffer()
        return self._buf[0]

    @property
    def relative_humidity(self):
        """The measured relative humidity in percent."""
        self._perform_measurement()
        self._humidity = (
            (self._buf[1] << 12) | (self._buf[2] << 4) | (self._buf[3] >> 4)
        )
        self._humidity = (self._humidity * 100) / 0x100000
        return self._humidity

    @property
    def temperature(self):
        """The measured temperature in degrees Celcius."""
        self._perform_measurement()
        self._temp = ((self._buf[3] & 0xF) << 16) | (self._buf[4] << 8) | self._buf[5]
        self._temp = ((self._temp * 200.0) / 0x100000) - 50
        return self._temp

    def _read_to_buffer(self):
        """Read sensor data to buffer"""
        self._i2c.readfrom_into(self._address, self._buf)

    def _trigger_measurement(self):
        """Internal function for triggering the AHT to read temp/humidity"""
        self._buf[0] = self.AHTX0_CMD_TRIGGER
        self._buf[1] = 0x33
        self._buf[2] = 0x00
        self._i2c.writeto(self._address, self._buf[0:3])

    def _wait_for_idle(self):
        """Wait until sensor can receive a new command"""
        while self.status & self.AHTX0_STATUS_BUSY:
            utime.sleep_ms(5)

    def _perform_measurement(self):
        """Trigger measurement and write result to buffer"""
        self._trigger_measurement()
        self._wait_for_idle()
        self._read_to_buffer()


class AHT20(AHT10):
    AHTX0_CMD_INITIALIZE = 0xBE  # Calibration command

3.LM75A.PY

"""
MicroPython LM75A Digital Temperature Sensor
https://github.com/mcauser/micropython-lm75a
MIT License
Copyright (c) 2019 Mike Causer
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.
"""

__version__ = '0.0.3'

# registers
_LM75A_TEMP  = const(0x00) # Temperature register (r) 16-bit
_LM75A_CONF  = const(0x01) # Configuration register (r/w) 8-bit, default: enabled, comparator, os active low, single fault
_LM75A_THYST = const(0x02) # Hysteresis register (r/w) 16-bit, default: 75°C
_LM75A_TOS   = const(0x03) # Overtemperature shutdown register (r/w) 16-bit, default: 80°C

class LM75A:
	def __init__(self, i2c, address=0x49):
		self._i2c = i2c
		self._address = address # 0x48-0x4F
		self._config = 0x00
		self._buf1 = bytearray(1)
		self._buf2 = bytearray(2)
		self.check()
		self.config()

	def check(self):
		if self._i2c.scan().count(self._address) == 0:
			raise OSError('LM75A not found at I2C address {:#x}'.format(self._address))

	def config(self, shutdown=None, os_mode=None, os_polarity=None, os_fault_queue=None):
		if shutdown is not None:
			self._config = (self._config & ~1) | (shutdown & 1)

		if os_mode is not None:
			self._config = (self._config & ~2) | ((os_mode << 1) & 2)

		if os_polarity is not None:
			self._config = (self._config & ~4) | ((os_polarity << 2) & 4)

		if os_fault_queue is not None:
			self._config = (self._config & ~24) | ((os_fault_queue << 3) & 24)

		self._buf1[0] = self._config
		self._i2c.writeto_mem(self._address, _LM75A_CONF, self._buf1)

	def temp(self):
		self._i2c.readfrom_mem_into(self._address, _LM75A_TEMP, self._buf2)
		val = (self._buf2[0] << 3) | (self._buf2[1] >> 5)
		return self._twos_comp(val, 11) * 0.125

	def tos(self, temp):
		self._temp_to_9bit_reg(temp)
		self._i2c.writeto_mem(self._address, _LM75A_TOS, self._buf2)

	def thyst(self, temp):
		self._temp_to_9bit_reg(temp)
		self._i2c.writeto_mem(self._address, _LM75A_THYST, self._buf2)

	def _twos_comp(self, val, bits):
		mask = 2 ** (bits - 1)
		return -(val & mask) + (val & ~mask)

	def _rev_twos_comp(self, val, bits):
		return val & ((1 << bits) -1)

	def _temp_to_9bit_reg(self, temp):
		val = self._rev_twos_comp(int(temp / 0.5), 9)
		self._buf2[0] = val >> 1
		self._buf2[1] = val << 7

5.Thonne IDE

将代码保存到pico里
在这里插入图片描述

在这里插入图片描述

6.注意事项

WIN7 下需要额外装CDC驱动,不想找驱动的的可以复制下面另存为xxx.inf文件 然后进设备管理器里更新。

; Windows 2000, XP, Vista, 7 and 8 (x32 and x64) setup file for Atmel CDC Devices
; Copyright (c) 2000-2013 ATMEL, Inc.

[Version] 
Signature   = "$Windows NT$" 
Class       = Ports 
ClassGuid   = {4D36E978-E325-11CE-BFC1-08002BE10318} 

Provider    = %Manufacturer% 
LayoutFile  = layout.inf 
CatalogFile = atmel_devices_cdc.cat
DriverVer   = 01/08/2013,6.0.0.0 

;----------------------------------------------------------
; Targets
;----------------------------------------------------------
[Manufacturer] 
%Manufacturer%=DeviceList, NTAMD64, NTIA64, NT 

[DeviceList] 
%PI_CDC_PICO%=DriverInstall, USB\VID_2E8A&PID_0005&MI_00

[DeviceList.NTAMD64]
%PI_CDC_PICO%=DriverInstall, USB\VID_2E8A&PID_0005&MI_00 

[DeviceList.NTIA64]
%PI_CDC_PICO%=DriverInstall, USB\VID_2E8A&PID_0005&MI_00 

[DeviceList.NT]
%PI_CDC_PICO%=DriverInstall, USB\VID_2E8A&PID_0005&MI_00

;----------------------------------------------------------
; Windows 2000, XP, Vista, Windows 7, Windows 8 - 32bit
;----------------------------------------------------------
[Reader_Install.NTx86] 


[DestinationDirs] 
DefaultDestDir=12 
DriverInstall.NT.Copy=12 

[DriverInstall.NT] 
include=mdmcpq.inf
CopyFiles=DriverInstall.NT.Copy 
AddReg=DriverInstall.NT.AddReg 

[DriverInstall.NT.Copy] 
usbser.sys 

[DriverInstall.NT.AddReg]
HKR,,DevLoader,,*ntkern 
HKR,,NTMPDriver,,usbser.sys 
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider" 

[DriverInstall.NT.Services] 
AddService = usbser, 0x00000002, DriverService.NT 

[DriverService.NT] 
DisplayName = %Serial.SvcDesc% 
ServiceType = 1 ; SERVICE_KERNEL_DRIVER 
StartType = 3 ; SERVICE_DEMAND_START 
ErrorControl = 1 ; SERVICE_ERROR_NORMAL 
ServiceBinary = %12%\usbser.sys 
LoadOrderGroup = Base 

;----------------------------------------------------------
; Windows XP, Vista, Windows 7, Windows 8 - 64bit
;----------------------------------------------------------

[DriverInstall.NTamd64]
include=mdmcpq.inf
CopyFiles=DriverCopyFiles.NTamd64
AddReg=DriverInstall.NTamd64.AddReg

[DriverCopyFiles.NTamd64]
usbser.sys,,,0x20

[DriverInstall.NTamd64.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,usbser.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"

[DriverInstall.NTamd64.Services]
AddService=usbser, 0x00000002, DriverService.NTamd64

[DriverService.NTamd64]
DisplayName=%Serial.SvcDesc%
ServiceType=1
StartType=3
ErrorControl=1
ServiceBinary=%12%\usbser.sys

;----------------------------------------------------------
; String
;----------------------------------------------------------

[Strings] 
Manufacturer = "ATMEL, Inc." 
PI_CDC_PICO = "Pi Pico Serial Port" 

Serial.SvcDesc = "Pi Pico Serial Driver"


7.参考

1.https://pico.org.cn 树莓派pico 中文站
2.https://awesome-micropython.com/ Awesome MicroPython库
3.https://www.runoob.com/python/python-tutorial.html Python基础教程
4.https://docs.singtown.com/micropython/zh/latest/pyboard/library/index.html MicroPython教程

8.放角落吃灰

  嵌入式 最新文章
基于高精度单片机开发红外测温仪方案
89C51单片机与DAC0832
基于51单片机宠物自动投料喂食器控制系统仿
《痞子衡嵌入式半月刊》 第 68 期
多思计组实验实验七 简单模型机实验
CSC7720
启明智显分享| ESP32学习笔记参考--PWM(脉冲
STM32初探
STM32 总结
【STM32】CubeMX例程四---定时器中断(附工
上一篇文章      下一篇文章      查看所有文章
加:2022-03-30 18:41:35  更:2022-03-30 18:42:57 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 6:38:53-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码