今天小编给大家带来是上次AM2120温湿度传感器数据用tpyb V202发送
到阿里云服务器的完善版demo。为此小编重构了函数,用到了面向对象的方法
,让刚入门的我不停的学习python3,到现在我也对列表,元组,字典都能熟练
使用。
        在实际使用这门语言时,要注意!这是在硬件中编程,我为此犯了很多错误
,我用了PC端的方法在tpyb里使用有很多库都是用不了的。其一就有copy函数的
使用,然后是硬件本身有SPI通信,但是怎么用都不成功,我看了很多demo都差
多然而就是我的SPI不行,配置后一直低电压,通信时没有任何时序,最后我就
不使
用硬件本身的库了,自己用输出模式的引脚编写了个模拟SPI驱动,既然成功
了,
让我有了成就感,最后小编也加上了C/F切换按键,说真的V202定时器只有一
个,
让整个项目的代码量和复杂度都需要评估。V202没有按键判断的函数,只能自
己编
写。
        python有它的好处,代码规范且代码量少。但python想把16进制以01方式的
二进制输出,就需要做个算法。你会发现python想要做底层的驱动或者以硬件思维
编写时与PC端编程有挺大差别的。
        小编用的LCD驱动IC是ht16l21,源码里有SPI驱动。驱动的lcd小编就不放出来
了。主要的还是看驱动IC,剩下的LCD编码要看你用什么LCD了。

现在附上实物图,与APP效果图:


APP图:




效果还不错,这是小编队友做的。
现在要附上源码:

        
main.py

# -*- conding:utf-8 -*-

import machine

from machine import Pin,SPI,Timer

import time  #声明用到的类库

import sys

import ht16l21

import networkdata

import thalgorithm

import lcdencoding

global c_f 
global te_hu
global locke

locke = 0
c_f = 0
countes = 0
te_hu = {}
machine.freq(80000000)#初始化时钟频率


am2120 = thalgorithm.DHT_TAM2120_GORITHM([4, 5])

display = ht16l21.HT16L21_SPI(Pin(16), Pin(14), Pin(13))

#ELCD-TMW013BL显示屏列表编码,ps(根据LCD的段位来编写。)
data_byte = [0x00,  
             0x40, 
             0x40, 
             0x40, 
             0x40, 
             0x40, 
             0x40, 
             ];

data_bytes = [0xFF,  
              0xFF, 
              0xFF, 
              0xFF, 
              0xFF, 
              0xFF, 
              0xFF, 
             ];

#声明用到类库中的函数
led = Pin(2, Pin.OUT)
key0 = Pin(0, Pin.IN, Pin.PULL_UP)
display.init_display()
display.write_data(0, data_bytes)

mac = networkdata.do_connect()  # 获取MAC地址,与连接WF
mac = networkdata.mac_format_conversion(mac) #mac格式算法
print(mac)
time.sleep(4)


def lcd_dynamic(t_h):
    """lcd数据动态解码"""
    data_s = [  0x00,  
                0x40, 
                0x40, 
                0x40, 
                0x40, 
                0x40, 
                0x40, 
                ];
    if t_h[0]['probe'] == 'Zero':
        if c_f == 0:
            data_s[0] = 0x52
        else:
            data_s[0] = 0x32
    else:
        if c_f == 1:
            data_s[0] = 0x31
        else:
            data_s[0] = 0x51
        teda = t_h[0]['temp']
        teda = int(float(teda))
        data_s[6],data_s[5],data_s[4] = lcdencoding.lcd_data_encoding(teda)
        huda = str(t_h[0]['hum'])
        huda = huda.strip('%')
        huda = int(float(huda))
        data_s[3],data_s[2],data_s[1] = lcdencoding.lcd_data_encoding(huda)

    return data_s

def cfquchu(thu):
	teda0 = ''
	teda1 = ''
	if thu[0]['probe'] == 'Zero':
		pass
	elif thu[0]['probe'] == 'One':
		teda0 = thu[0]['temp']
	try:
		teda1 = thu[1]['temp']
	except:
		pass
	return teda0, teda1

def cfsocket(tardata, ted0, ted1):
	if c_f == 0:
		if tardata[0]['probe'] == 'Zero':
			pass
		elif tardata[0]['probe'] == 'One':
			tardata[0]['temp'] = str(float(ted0))
		try:
			tardata[1]['temp'] = str(float(ted1))
		except:
			pass
	else:
		if tardata[0]['probe'] == 'Zero':
			pass
		elif tardata[0]['probe'] == 'One':
			tardata[0]['temp'] = str((1.8 * float(ted0)) + 32.0)
		try:
			tardata[1]['temp'] = str((1.8 * float(ted1)) + 32.0)
    	except:
			pass


def sockerda():
    """C_F切换时发送数据"""
    try:
        data = networkdata.connection("TPYBoard v202", mac, c_f, te_hu)
        networkdata.data_sent(host, port, data)
    except:
        print("Unable to connect to the server.......")  

def lcdsocek(t):
    try:
        data = networkdata.connection("TPYBoard v202", mac, c_f, te_hu)
        networkdata.data_sent(host, port, data)
    except:
        print("Unable to connect to the server.......")

tim = Timer(-1)
tim.init(period=15000, mode=Timer.PERIODIC, callback=lcdsocek)


buut = am2120.dht_probes()
tem0, tem1 = cfquchu(buut)
te_hu = buut
print(te_hu)
while True:
    """主循环"""

    if countes > 20:
        buut = am2120.dht_probes()
        tem0, tem1 = cfquchu(buut)
        te_hu = buut
        cfsocket(te_hu, tem0, tem1)
        countes = 0
    countes += 1

    if key0.value() == 0 and locke == 0: #按键判断
        if c_f == 0:
            c_f = 1
        else:
            c_f = 0
        locke = 1
        cfsocket(te_hu, tem0, tem1)
        display.write_data(0, lcd_dynamic(te_hu))
        tim.init(period=15000, mode=Timer.PERIODIC, callback=lcdsocek)
        sockerda()
    elif key0.value() == 1:
        locke = 0

    #data  = lcd_dynamic(te_hu)
    #te_hu = lcd_dynamic(te_hu)
    display.write_data(0, lcd_dynamic(te_hu))
    time.sleep_ms(20)


ht16l21.py

# MicroPython ht16l21 SPI interfaces
# -*- conding:utf-8 -*-

import time

#指令集
RESET_COMMAND               = const(0xAA) #软件复位命令
DRIVE_MODE_COMMAND          = const(0x82) #驱动模式命令
DISPLAY_DATA_INPUT_COMMAND  = const(0x80) #显示数据输入指令
SYSTEM_MODE_COMMAND         = const(0x84) #系统模式命令
FRAME_FREQUENCY_COMMAND     = const(0x86) #帧频率指令
BLINK_FREQUENCY_COMMAND     = const(0x88) #闪烁频率指令
LED_OUTPUT_COMMAND          = const(0x8C) #LED输出命令
IVA_SETTING_COMMAND         = const(0x8A) #内部电压调整(IVA)设置命令
CLEAR_RAM                   = const(0x01) #Clear display RAM



class HT16L21(): #ht16l21父类
    def __init__(self):
        """初始化"""
        self.resetht16l21()
        self.init_display()

    def init_display(self):
        """指令集初始化"""
        self.write_cmd(DRIVE_MODE_COMMAND, 0x00)
        self.write_cmd(SYSTEM_MODE_COMMAND, 0x03)
        self.write_cmd(FRAME_FREQUENCY_COMMAND, 0x02)
        self.write_cmd(IVA_SETTING_COMMAND, 0x04)
        self.write_data(CLEAR_RAM, 0)
    
    #def write_datas(self, )



class HT16L21_SPI(HT16L21): #模拟SPI子类
    def __init__(self, cs, clk, mo):
        """初始化模拟SPI口"""
        # base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
        self.base = [
                str(x) for x in range(10)] + [
                chr(x) for x in range(ord('A'), ord('A') + 6)]
        cs.init(cs.OUT, value=1)
        clk.init(clk.OUT, value=1)
        mo.init(mo.OUT, value=1)
        self.cs = cs
        self.clk = clk
        self.mo = mo
        super().__init__()  # 超类

    def dec2bin(self, string_num, bit):
        """十进制转二进制"""
        num = int(string_num)
        mid = []
        x = 0
        while x 99 or data < -99: #百位判断
        byte0 = data_byte[int(data_conversion(data)[0])]
    elif data < 100 and data > 0:
        byte0 = data_byte[NOTHING]
    else:
        print(data)
        if data == 0:
            byte0 = data_byte[NOTHING]       
        else:
            byte0 = data_byte[MINUS]
    
    if data > 99 or data < -99: #十位判断
        byte1 = data_byte[int(data_conversion(data)[1])]
    elif (data > 9 and data < 100) or (data > -100 and data < 0):
        byte1 = data_byte[int(data_conversion(data)[0])]
    else:
        byte1 = data_byte[NOTHING]

    if data > 99 or data <-99: #个位判断
        byte2 = data_byte[int(data_conversion(data)[2])]
    elif (data < 100 and data > 0) or (data > -100 and data < 0):
        byte2 = data_byte[int(data_conversion(data)[1])]
    else:
        byte2 = data_byte[int(data_conversion(data)[0])]

    return byte0, byte1, byte2


def data_conversion(data):
    """负数转化为正数"""
    if data < 0:
        data = str(data)
        if int(data) < 10 and int(data) > -10:
            bat = data[1]
        elif (int(data) > 9 and int(data) < 100) or (
                int(data) > -100 and int(data) < 0):
            bat = data[1] + data[2]
        else:
            bat = data[1] + data[2] + data[3]
    else:
        bat = str(data)
    return bat


networkdata.py

# MicroPython, The (metwork,socket,data processing) interfaces
# -*- conding:utf-8 -*-
import urllib



def connection(name, mac, symbol, tem_hum):
    """建立总数据表格"""
    data = {
        'devicename': name, #设备名
        'deviceaddre': mac, #设备MAC
        'devicesymbol': symbol, #C/F显示状态位0/1
        'devicedata': tem_hum, #温湿度数据列表
    }
    return data



def do_connect():
    """定义开发板连接无线网络的函数"""
    import network
    wlan = network.WLAN(
        network.STA_IF)  # 设置开发板的网

    wlan.active(True)  # 打开网络连接

    if not wlan.isconnected():  # 判断是否有网络连接

        print('connecting to network...')

        # 设置想要连接的无线网络
        wlan.connect('name', 'password')

        while not wlan.isconnected():  # 等待连接上无线网络

            pass
    mac = wlan.config('mac')      # 获取模块MAC地址
    print('network config:', wlan.ifconfig())
    return mac



def data_sent(host, port, data):
    """连接服务器发送数据模块"""
    import socket
    import json

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 建立套接字
    s.connect((host, port))  # 链接地址

    json_str = json.dumps(data)  # 数据转换为json数据

    print(json_str)
    s.send(bytes('%s
' % (json_str), 'utf8'))

    s.close()  # 关闭套接字


def mac_format_conversion(mac):
    """MAC格式算法函数"""
    mac = [hex(x) for x in bytes(mac)]  # 将读取后的乱码转换为列表格式的16进制数
    y = 0  # 初始化
    mac_data = ''

    while y < 6:
        if len(mac[y]) == 4:  # 判断是否有0
            pass
        else:
            mac[y] = '0x0' + mac[y][2]  # 把0补上

        if y < 5:  # 将数据转换为5c:cf:7f:0d:85:65
            mac_data = mac_data + mac[y][2] + mac[y][3] + ':'
        else:
            mac_data = mac_data + mac[y][2] + mac[y][3]
        y += 1

    return mac_data.upper()


thalgorithm.py

# MicroPython AM2120 gorithm interfaces
# -*- conding:utf-8 -*-
import machine
import dht
from machine import Pin



class DHT_TAM2120_GORITHM(): #AM2120传感器类 PS(可根据不同型号进行修改)

    def __init__(self, prot):
        """初始化端口算法"""
        self.prot = prot
        self.num = len(prot) #测量有多少个端口


    def dht_probes(self):
        """传感器探头判断函数"""
        dat = self.tem_hum_data(0, 0, 0)
        bit = 0  # 初始化算法函数
        i = 0
        cib = 0 #自锁
        while i < self.num:  # 端口计数
            print
            data = self.dht_collect(self.prot[i])
            if data[0] == 1:
                bit += 1
            else:
                pass
            if data[0] != 0:
                if dat['probe'] == 'Zero': #判断单个传感器
                    dat = self.tem_hum_data(data[1], data[2], bit)
                else:
                    # 传感器数量,数据列表,PS(这里有个问题你是否能发现)
                    dat = [dat, self.tem_hum_data(data[1], data[2], bit)]
                    cib = 1 #多个传感器状态位
            i += 1
        try:
            if (cib == 0) or dat['probe'] == 'Zero':
                dat = [dat]
        except:
            pass

        return dat


    def dht_collect(self, prots):
        """DHT传感器模块"""
        try:
            d = dht.DHT22(machine.Pin(prots)) # AM2120接口函数
            d.measure()  # 调用DHT类库中测量数据的函数

            temp = str(d.temperature())  # 读取measure()函数中的温度数据
            hum = str(d.humidity())  # 读取mesure()函数中的湿度数据
            num = 1  # 有数据
        except:  # 没有传感器时的报错
            temp = 0
            hum = 0
            num = 0  # 没数据
        return num, temp, hum


    def tem_hum_data(self, temp, hum, count):
        """编辑温湿度表格"""
        Port_number = ['Zero',
                       'One',
                       'Two',
                       'Three',
                       'Four'];
        if count == 0:  # 判断是否有传感器参数
            bat = {'probe': Port_number[count]}
        else:
            bat = {
                'probe': Port_number[count],
                'temp': str(temp),
                'hum': (str(hum) + '%')
            }
        return bat
        
最后就是本章百度云资源,小编就分享给大家里面有ht16l21数据手册:https://pan.baidu.com/s/1sngFFD7