current position:Home>5.15 comprehensive case 2.0 - gas detection system

5.15 comprehensive case 2.0 - gas detection system

2022-05-15 07:47:41Zhiyunfu

brief introduction

Natural gas is the main fuel for household cooking and heating , Its main component is methane (CH4), It also contains a small amount of propane , Ethane 、 Butane and other small amounts of gas . Natural gas itself is colorless and tasteless , Less dense than air . Natural gas leakage is difficult to detect , Its concentration in the air reaches 5%~15% when , It will explode in case of open fire . The popularity of household natural gas , Every year due to improper use 、 Human factors cause gas leakage and explosion accidents one after another .
This case is to teach developers to build a gas leakage detection system step by step against this background .

MQ2 Gas sensors

MQ-2 Gas leakage monitoring devices commonly used in homes and factories , Suitable for liquefied gas 、 benzene 、 Alkane 、 alcohol 、 hydrogen 、 Detection of smoke, etc . So ,MQ-2 To be exact, it is a multi gas detector .

principle
MQ-2 The smoke sensor belongs to tin oxide semiconductor gas sensing material , It belongs to surface ionic formula N Type semiconductor . be in 200~300 Degree Celsius , Tin dioxide adsorbs oxygen in the air , Form negative ion adsorption of oxygen , Reduce the electron density in semiconductors , So as to increase its resistance value . When in contact with smoke , If the potential barrier at the grain boundary changes due to the adjustment of smoke , It will cause the change of surface conductivity . Using this, we can obtain the information of the existence of this kind of smoke , The higher the concentration of smoke , The greater the conductivity , The lower the output resistance , The larger the output analog signal .

characteristic

  • MQ-2 The sensor is sensitive to natural gas 、 Smoke such as liquefied petroleum gas has high sensitivity , Especially sensitive to alkane smoke , It has good anti-interference , It can accurately eliminate the interference information with irritating non combustible smoke .
  • MQ-2 The sensor has good repeatability and long-term stability . Initial stability , Short response time , Good working performance for a long time . It should be noted that : It must be heated for a period of time before use , Otherwise, the output resistance and voltage are not accurate .
  • The detection range of combustible gas and smoke is 100~10000ppm(ppm Is the volume concentration . 1ppm=1 Cubic centimeter /1 Cubic meters )
  • The circuit design has a wide voltage range ,24V Any of the following , Heating voltage 5±0.2V

Be careful : If the heating voltage is too high , It will cause excessive input current , Fuse the internal signal wire , Thus, the device is scrapped .

Get ready

The hardware required for this case

equipment Number
HaaS506 Development board 1
MQ2 Gas sensors 1
SIM card 1
DuPont line A number of

Hardware connection diagram

 Insert picture description here

Code flow

1、 Connect to Alibaba cloud platform .
2、 Duplicate read MQ2 Gas voltage sensor , Upload data to Alibaba cloud .
3、 Use Mobile application function , Show weather 、MQ2 Gas sensor voltage change 、 Equipment alarm .

Function realization

1、 Internet of things platform development

Readers who use the Internet of things platform for the first time , You need to use the Internet of things platform function after opening the instance . You can also use free public instances for development , stay Alibaba cloud Internet of things platform in , In the upper left corner, choose ‘ East China 2- Shanghai ’, Click on ‘ Public examples ’, It can be opened .

1、 Platform product creation can refer to haas506 2.0 Development tutorial -aliyunIoT
2、 Create product attributes ( Additive model )

  • Choose products Function definition Edit draft
     Insert picture description here
  • Add custom features
  • add to identifier And data type ( The identifier should be consistent with the code )
  • Click on Published online
     Insert picture description here
  • Click ok
     Insert picture description here

2、 Device side development

  • Readers who use the development board for the first time can follow haas5062.0 Development tutorial - Introduction Build development environment .
  • Copy the following code to Visual Studio Code, Copy the product certificate to the corresponding location of the code .
     Insert picture description here
  • main.py
# coding=utf-8
from driver import ADC
from driver import GPIO
import network
import ujson
import utime as time
import modem
from  aliyunIoT import Device
import kv

 
# When iot Triggered when the device is connected to the Internet of things platform 'connect'  event 
def on_connect(data):
    global module_name,default_ver,productKey,deviceName,deviceSecret,on_trigger,on_download,on_verify,on_upgrade
    print('***** connect lp succeed****')
    data_handle = {
    }
    data_handle['device_handle'] = device.getDeviceHandle()


# When the connection is disconnected , Trigger 'disconnect' event 
def on_disconnect():
    print('linkkit is disconnected')

# Upload alarm light status 
warning_data = {
    }
# When iot When setting the cloud distribution properties , Trigger 'props' event 
def on_props(request):
    params=request['params']
    params=eval(params)
    warn = params["alarmLight"]
    warning_data["alarmLight"]= warn
    warning_data_str=ujson.dumps(warning_data)
    data1={
    
        'params':warning_data_str
        }      
    device.postProps(data1)



# When iot Cloud call device service when , Trigger 'service' event 
def on_service(id,request):
    print('clound req id is {} , req is {}'.format(id,request))
# When the device follows iot When an error is encountered during platform communication , Trigger 'error' event 
def on_error(err):
    print('err msg is {} '.format(err))

# Callback function of network connection 
def on_4g_cb(args):
     global g_connect_status
     pdp = args[0]
     netwk_sta = args[1]
     if netwk_sta == 1:
         g_connect_status = True
     else:
         g_connect_status = False

# network connections 
def connect_network():
     global net,on_4g_cb,g_connect_status
     #NetWorkClient This class is a singleton class , Realize the functions related to network management , Include initialization , Connected to the Internet , Status information, etc .
     net = network.NetWorkClient()
     g_register_network = False
     if net._stagecode is not None and net._stagecode == 3 and net._subcode == 1:
         g_register_network = True
     else:
         g_register_network = False
     if g_register_network:
    # Register the callback function of network connection on(self,id,func); 1 For connection ,func  Callback function  ;return 0  success 
         net.on(1,on_4g_cb)    
         net.connect(None)
     else:
         print(' Network registration failed ')
     while True:
         if g_connect_status:
             print(' Network connection successful ')
             break
         time.sleep_ms(20)

# Dynamically register callback functions 
def on_dynreg_cb(data):
     global deviceSecret,device_dyn_resigter_succed
     deviceSecret = data
     device_dyn_resigter_succed = True


 #  Connect to the Internet of things platform 
def dyn_register_device(productKey,productSecret,deviceName):
    global on_dynreg_cb,device,deviceSecret,device_dyn_resigter_succed
    key = '_amp_customer_devicesecret'
    deviceSecretdict = kv.get(key)
    print("deviceSecretdict:",deviceSecretdict)
    if isinstance(deviceSecretdict,str):    
        deviceSecret = deviceSecretdict 

    if deviceSecretdict is None or deviceSecret is None:
        key_info = {
    
            'productKey': productKey  ,
            'productSecret': productSecret ,
            'deviceName': deviceName
            }
        #  Dynamically register a device , Acquiring equipment deviceSecret
        # Below if Prevent multiple registrations , If you have registered once , Restart the device and re register will get stuck ,
        if not device_dyn_resigter_succed:
            device.register(key_info,on_dynreg_cb)   



def upload_value(n):
    global value_data
    value_data["gasVoltage"]= n
    value_data_str=ujson.dumps(value_data)
    data={
    
        'params':value_data_str
        }      
    device.postProps(data)





if __name__ == '__main__':
    ICCID=None
    g_connect_status = False
    net = None
    device = None
    deviceSecret = None
    deviceName = None
    productKey = "a1JuD7ay6Pj"
    productSecret = "yV68ScGy5DgEczVx"
    device_dyn_resigter_succed = False

    #  Connect to the network 
    connect_network()
     #  Acquiring equipment IMEI  As deviceName  Dynamic registration 
    deviceName = modem.getDevImei()
    # Acquiring equipment ICCID
    ICCID=modem.sim.getIccid()
    # Initialize the Internet of things platform Device class , obtain device example 
    device = Device()
    if deviceName is not None and len(deviceName) > 0 :
     # Dynamically register a device 
        dyn_register_device(productKey,productSecret,deviceName)
    else:
        print(" Get the device IMEI Failure , Unable to register dynamically ")
    while deviceSecret is None:
        time.sleep(0.2)
    print(' Dynamic registration succeeded :' + deviceSecret)

    key_info = {
    
        'region' : 'cn-shanghai' ,
        'productKey': productKey ,
        'deviceName': deviceName ,
        'deviceSecret': deviceSecret ,
        'keepaliveSec': 60,
        }
    # Print device information 
    print(key_info)

    #device.ON_CONNECT  Is the event ,on_connect It's an event handler / Callback function 
    device.on(device.ON_CONNECT,on_connect)
    device.on(device.ON_DISCONNECT,on_disconnect)
    device.on(device.ON_PROPS,on_props)
    device.on(device.ON_SERVICE,on_service)
    device.on(device.ON_ERROR,on_error)
    device.connect(key_info)

    # The main program 
    # Gas sensors 
    adc=ADC()
    adc.open("ADC1")
    value_data = {
    }
    while True:
        value=adc.readVoltage()
        print('v:',value)
        print('--------------------------------------------')
        upload_value(value)
        time.sleep(1)

    adc.close()

  • Use 485 Serial port read log, To configure “replPort”: 2, A serial port TTL Read to 0 .
  • board.json
{
    
    "version": "2.0.0",
    "io": {
    
        "ADC0": {
    
                "type": "ADC",
                "port": 0,
                "sampling": 12000000
            },
        "ADC1": {
    
                  "type": "ADC",
                  "port": 1,
                  "sampling": 12000000
            },
        "serial1":{
    
                "type":"UART",
                "port":0,
                "dataWidth":8,
                "baudRate":115200,
                "stopBits":1,
                "flowControl":"disable",
                "parity":"none"
            },
        "serial2":{
    
                "type":"UART",
                "port":1,
                "dataWidth":8,
                "baudRate":115200,
                "stopBits":1,
                "flowControl":"disable",
                "parity":"none"
            },
        "serial3":{
    
                "type":"UART",
                "port":2,
                "dataWidth":8,
                "baudRate":115200,
                "stopBits":1,
                "flowControl":"disable",
                "parity":"none"
            }
        },
    "debugLevel": "ERROR",
    "repl": "enable",
    "replPort": 2
    }
    

debugging

  • Debug serial port to use 485 port , Open the device manager to view the debugging port number .
     Insert picture description here
  • Serial port debugging tool use putty
     Insert picture description here

Debugging results

1、 Serial debugging tools log, Network connection successful Dynamic registration succeeded Print per second MQ2 Gas voltage sensor
 Insert picture description here
2、 There is data coming into the cloud , Turn on real-time refresh , The display data will be updated automatically .
 Insert picture description here

3、 Internet of things application development

The following is the Internet of things application development process , Next, the development of mobile application is introduced according to the following process .
 Insert picture description here

3.1 newly build ‘ Common projects ’

  • Use alicloud IoTStudio Create project .
  • Create a new blank project in project management
     Insert picture description here

3.2 Associated products and equipment

 Insert picture description here
 Insert picture description here

3.3 newly build ‘ Mobile application ’

 Insert picture description here
 Insert picture description here
 Insert picture description here

Click... In the red box above ‘ Components ’, You can see the list of available components . Please refer to... For the instructions of each component Component description

3.4 Page design

The case uses three components :

  • Real time curve Display sensor real-time data
  • Indicator light Display alarm status
  • The weather Used to display destination weather

Drag the three components to the middle canvas area
 Insert picture description here

3.5 Register target objects

The associated data source is divided into the following three steps
Related products
Associated devices
Association attribute
Each component is set separately
1、‘ Indicator light ’ Component settings
 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here
After setting it up , Set alarm
 Insert picture description here
2、 The same way to set ‘ Real time curve ’.
 Insert picture description here
3、 Set up ‘ The weather ’ Components , Choose the location you need .

 Insert picture description here

3.6 Business logic development

The main purpose of business logic is to facilitate users to set the behavior logic of Internet of things devices , Conventional Internet of things systems are fixed line behavior logic at the device end , If the equipment behavior needs to be modified after leaving the factory , You need to do OTA upgrade .
Create a new rule to alarm when the gas exceeds the threshold .
 Insert picture description here
The system automatically enters the business logic page , Click on the left side of the ‘ node ’, On the right is the introduction of business logic .
 Insert picture description here
1、 Select the target node
This logic needs to judge the gas voltage value uploaded by the equipment , When the voltage value exceeds the threshold, the alarm is turned on , Otherwise, turn off the alarm . Four nodes are required :

  • Device trigger node
  • Condition judgment node
  • Turn on the alarm lamp node
  • Turn off the alarm lamp node

Drag out the required nodes from the left .

 Insert picture description here
2、 Establish the association relationship between nodes , Drag the mouse to connect the nodes
 Insert picture description here
3、 Business logic editing

  • Device trigger node
     Insert picture description here
  • Condition judgment node
     Insert picture description here
    Device node behavior settings
     Insert picture description here
     Insert picture description here
    Save and deploy business logic
     Insert picture description here

3.7 Launch preview and launch

After the business logic is set , Can be in “ Gas monitoring and alarm system ” page ‘’ preservation ‘’ And click the ‘ preview ’ To preview .
 Insert picture description here
Cell phones scan QR codes , You can view the data on your mobile phone .
 Insert picture description here

copyright notice
author[Zhiyunfu],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/135/202205142335456386.html

Random recommended