物联网开发笔记(97)- Micropython ESP32开发之LM75 温度传感器I2C接口

本文介绍了如何使用ESP32开发板,配合MicroPython库与LM75温度传感器进行交互,包括传感器的驱动代码和示例,展示了读取温度并在ILI9341屏幕上显示的实现,还提到了将传感器的OS信号用于LED报警的功能。
摘要由CSDN通过智能技术生成

一、目的

        这一节我们学习如何使用乐鑫的ESP32开发板连接LM75 温度模块,温度相关的操作。

        在早前我们也介绍过其他温度传感器的模块的操作,这里我们来学习新的模块LM75 温度传感器,它精度高。

二、环境

        ESP32(固件:esp32-20220618-v1.19.1.bin) + Thonny(V4.0.1) + LM75 温度传感器模块 + ILI9341屏幕 + Win10 64位商业版

        ILI9341屏幕接线方法,以及屏幕驱动和相关字库,请看这个文章哈:

物联网开发笔记(91)- 使用Micropython开发ESP32开发板之通过串口SPI控制ILI9341 液晶屏显示文字_spi驱动ili9341_魔都飘雪的博客-CSDN博客使用Micropython开发ESP32开发板之通过串口SPI控制ILI9341 液晶屏显示文字https://blog.csdn.net/zhusongziye/article/details/129350419?spm=1001.2014.3001.5501        LM75温度模块接线方法:

 

三、LM75温度传感器驱动

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=0x48):
		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

四、示例代码1

        我们使用下方代码,找出我们LM75温度模块的I2C地址:

from machine import Pin,I2C
import time

#创建I2C对象LM75A
i2c = I2C(0,scl = Pin(22),sda = Pin(21),freq = 400000)

def main():
    # 输出I2C设备地址:73 49,73为十进制,49为十六进制
    print("%s %x"%(i2c.scan()[0],i2c.scan()[0]))  
    
    
if __name__ == "__main__":
    main()

示例效果:

 五、示例代码2

from machine import Pin,SPI,I2C,PWM
from ili9341 import Display,color565
from xglcd_font import XglcdFont
import lm75a
import time

#lm75a I2C地址0x49
addr = 0x49
#创建I2C对象LM75A
i2c = I2C(1,scl = Pin(22),sda = Pin(21),freq = 400000)
#创建lm75a
lm = lm75a.LM75A(i2c,addr)

# 调节显示亮度,初始亮度为400
blk = PWM(Pin(2),duty = (400),freq = (1000))
# 创建SPI对象
spi = SPI(2, baudrate=40000000, polarity=0, phase=0, bits=8, firstbit=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
# 创建屏幕对象
tft = Display(spi,cs=Pin(5,Pin.OUT),dc=Pin(26,Pin.OUT),rst=Pin(27,Pin.OUT),width=240,height=320,rotation=180)
# 字库
font9x11 = XglcdFont("font/ArcadePix9x11.c",9,11)
font12x24 = XglcdFont("font/Unispace12x24.c",12,24)

def main():
    #清屏填充黑色
    tft.clear(color565(0,0,0))
    #写文本标题
    tft.draw_text(10,10,"*** LM75 ***",font12x24,color565(255,255,0),color565(0,0,0))
    #绘画两条横线,白色填充
    tft.draw_hline(0,40,240,color565(255,255,255))
    tft.draw_hline(0,45,240,color565(255,255,255))
    #显示I2C扫描的地址和数量
    tft.draw_text(0,60,"i2c addr: 0x%x num: %d"%(i2c.scan()[0],len(i2c.scan())),font12x24,color565(255,0,0),color565(0,0,0))
    
    print("%s %x"%(i2c.scan()[0],i2c.scan()[0]))  # 输出73 49,73为十进制,49为十六进制
    
    while True:
        #显示温度值
        #print("%.2f"%lm.temp())
        tft.draw_text(60,148,"temp: %.2f"%(lm.temp()),font12x24,color565(0,255,0),color565(0,0,0))
        
        #画两个实心圆绿色红色交替500ms做提示
        tft.fill_circle(235,315,3,color565(0,255,0))
        time.sleep(0.5)
        tft.fill_circle(235,315,3,color565(255,0,0))
        time.sleep(0.5)
        
    
if __name__ == "__main__":
    main()
    

显示效果:

六、示例代码3

        我们把ILI9341屏幕的背光从原来的GPIO2接到GPIO4,返回把LM75温度模块的OS接到GPIO2。因为板载蓝色LED灯是连接到GPIO的,我们可以利用LM75温度模块的OS来输出警示信息。比如,当温度大于或者小于设定值时,进行LED闪烁报警。

from machine import Pin,SPI,I2C,PWM
from ili9341 import Display,color565
from xglcd_font import XglcdFont
import lm75a
import time

#lm75a I2C地址0x49
addr = 0x49
#创建I2C对象LM75A
i2c = I2C(1,scl = Pin(22),sda = Pin(21),freq = 400000)
#创建lm75a
lm = lm75a.LM75A(i2c,addr)

# 调节显示亮度,初始亮度为400
blk = PWM(Pin(4),duty = (400),freq = (1000))
# 创建SPI对象
spi = SPI(2, baudrate=40000000, polarity=0, phase=0, bits=8, firstbit=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
# 创建屏幕对象
tft = Display(spi,cs=Pin(5,Pin.OUT),dc=Pin(26,Pin.OUT),rst=Pin(27,Pin.OUT),width=240,height=320,rotation=180)
# 字库
font9x11 = XglcdFont("font/ArcadePix9x11.c",9,11)
font12x24 = XglcdFont("font/Unispace12x24.c",12,24)

def main():
    #清屏填充黑色
    tft.clear(color565(0,0,0))
    #写文本标题
    tft.draw_text(10,10,"*** LM75 ***",font12x24,color565(255,255,0),color565(0,0,0))
    #绘画两条横线,白色填充
    tft.draw_hline(0,40,240,color565(255,255,255))
    tft.draw_hline(0,45,240,color565(255,255,255))
    #显示I2C扫描的地址和数量
    tft.draw_text(0,60,"i2c addr: 0x%x num: %d"%(i2c.scan()[0],len(i2c.scan())),font12x24,color565(255,0,0),color565(0,0,0))
    
    print("%s %x"%(i2c.scan()[0],i2c.scan()[0]))  # 输出73 49,73为十进制,49为十六进制
    
    while True:
        #显示温度值
        #print("%.2f"%lm.temp())
        tft.draw_text(60,148,"temp: %.2f"%(lm.temp()),font12x24,color565(0,255,0),color565(0,0,0))
        
        #画两个实心圆绿色红色交替500ms做提示
        tft.fill_circle(235,315,3,color565(0,255,0))
        time.sleep(0.5)
        tft.fill_circle(235,315,3,color565(255,0,0))
        time.sleep(0.5)
        
        led = Pin(2,Pin.OUT)
        if(lm.temp() > 15):
            #tft.draw_text(60,200,"temp excption!",font12x24,color565(255,0,0),color565(0,0,0))
            while True:
                tft.draw_text(60,200,"temp excption!",font12x24,color565(255,0,0),color565(0,0,0))
                led.value(1 - led.value())
                time.sleep_ms(500)
                tft.draw_text(60,200,"                      ",font12x24,color565(255,0,0),color565(0,0,0))
    
if __name__ == "__main__":
    main()
    

演示效果:

 

七、LM75 温度传感器购买

https://item.taobao.com/item.htm?spm=a1z09.2.0.0.6ea92e8dbo8yfk&id=591361172562&_u=np01rch9745icon-default.png?t=N176https://item.taobao.com/item.htm?spm=a1z09.2.0.0.6ea92e8dbo8yfk&id=591361172562&_u=np01rch9745

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔都飘雪

您的1毛奖励是我创作的源源动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值