current position:Home>5.14 comprehensive case 2.0 - automatic induction door

5.14 comprehensive case 2.0 - automatic induction door

2022-05-15 07:39:07Zhiyunfu

brief introduction

Many public places use automatic induction doors , The door opens automatically when someone approaches , Close the door automatically when you are far away ; Sometimes it is necessary to keep the door open, such as handling goods , It's inconvenient to close the door ; Or the place needs to be closed frequently when it closes at night , No one is allowed to enter .
This case simulates the corresponding scenario , Design a mobile phone that can use APP To control the automatic induction door system .

Infrared obstacle avoidance sensor

  • Infrared obstacle avoidance is a kind of obstacle avoidance sensor , It has a pair of infrared transmitting and receiving tubes , The transmitting tube emits infrared rays of a certain frequency , When the detection direction encounters an obstacle ( The interface outputs a low-level signal , The detection distance can be adjusted through the potentiometer knob ).

  • Specifications :

    1. Working voltage :DC 3.3V-5V
    2. Working current :≥20mA
    3. working temperature :-10℃—+50℃
    4. Detection distance :2-30cm
    5. The output signal : There are obstacles or reflected to the ground output low level , Barrier free high level
    6. Regulation mode : Multi turn resistance regulation
    7. Effective angle :35°

Get ready

The hardware required for this case

equipment Number
HaaS506 Development board 1
Infrared obstacle avoidance sensor 1
SG90 The steering gear 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、 Enable two threads , The obstacle avoidance sensor uploads the detection status to Alibaba cloud every second ; The steering gear judges whether to open the door according to the conditions .
3、 establish ‘ Mobile application ’ function , Access control is normal 、 Normally closed 、 Normally open mode , And real-time detection of accumulated traffic .
4、 Upload the access control status to Alibaba cloud platform .

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
1、 Add custom features
2、 According to the plan 2 Show add identifier And data type ( The identifier should be consistent with the code )
3、 Click on Published online
 Insert picture description here

  • Click ok
     Insert picture description here

2、 Device side development

main.py

# coding=utf-8

from driver import GPIO
from driver import PWM
import network
import ujson
import utime as time
import modem
from  aliyunIoT import Device
import kv
import _thread

 
# 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')


servo_data={
    }
# When iot When setting the cloud distribution properties , Trigger 'props' event 
def on_props(request):
    global servo_data,door_status
    params=request['params']
    params=eval(params)
    door_status=params["door_status"]
    servo_data["door_status"]= door_status
    servo_data_str=ujson.dumps(servo_data)
    data={
    
        'params':servo_data_str
        }       
    device.postProps(data)

# 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)   


count_data = {
    }
def upload_count():
    global count_data
    count_data["person_count"]= count
    count_data_str=ujson.dumps(count_data)
    data1={
    
        'params':count_data_str
        }      
    device.postProps(data1)


def setOptionSero(duty_cycle):
    global servo
    param2 = {
    'freq':50, 'duty': duty_cycle }
    servo.setOption(param2) 


def operatorDoor():
    global detected, closed,door_status
    closed = True
    #  After opening the door, judge whether there is anyone else 
    while True:
        time.sleep_ms(50)
        if door_status == 1:
            openDoor()
        elif door_status == -1:
            closeDoor()
        else:
            if detected == True:
                 openDoor()
            else:
                 closeDoor()


def openDoor():
    global closed,servo
    if closed == True:
        print("open the door")
        setOptionSero(12)
        # TODO  Door opening operation 
        closed = False

def closeDoor():
    global closed,servo
    if closed == False:
        time.sleep_ms(200)
        print("close the door")
        #  Operate the door closing 
        setOptionSero(5)
        closed = True

def infrared_status():
     global detected, count, door_status
     while True:             #  Infinite loop 
        time.sleep_ms(50)
        status = infrared.read()
        #  Object detected 
        if status == 0:
            detected = True
            #  Only those in a very closed state will report 
            if door_status != -1:
                count = count + 1
                print("object detected, count = " + str(count))
                upload_count()
            #  Stop when people are detected 5 Second retest , It is equivalent to the time of simulating pedestrian passing 
            time.sleep(5)
        #  Not detected 
        elif status == 1:
            detected = False
            print('no object detected')
            #  No one was detected , Then interval 500ms Test once 
            time.sleep_ms(500)

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)

    #  Initialize infrared 
    infrared = GPIO()
    print(infrared,'---------------------------')
    infrared.open("infrared")
    #  Initialize the steering gear 
    servo = PWM()
    servo.open("pwm_lpg")
    # Initialization data 
    count = 0
    detected = False
    door_status = 0
    upload_count()
    time.sleep(2)
    try:
        #  Start infrared detection 
        _thread.start_new_thread(infrared_status, ())
        #  Start the steering gear to simulate door opening / Door closing operation thread 
        _thread.start_new_thread(operatorDoor, ())
    except Exception as e:
        print(e)
        print("Error: unable to start thread")

    while True:
        time.sleep_ms(1000)



Use 485 Serial port read log, To configure “replPort”: 2, A serial port TTL Read to 0 .
board.json

{
    
  "name": "haas506",
  "version": "2.0.0",
  "io": {
    
    "pwm_lpg": {
    
      "type": "PWM",
      "port": 3
      },   
    "infrared":{
    
      "type":"GPIO",
      "port": 20,
      "dir": "input",
      "pull":"pullup"
    },         
    "SPI0": {
    
      "type": "SPI",
      "port": 0,
      "mode": "master",
      "freq": 2000000
    },
    "serial1": {
    
      "type": "UART",
      "port": 0,
      "dataWidth": 8,
      "baudRate": 115200,
      "stopBits": 1,
      "flowControl": "disable",
      "parity": "none",
      "timeout": 1000
    },
    "serial2": {
    
      "type": "UART",
      "port": 1,
      "dataWidth": 8,
      "baudRate": 9600,
      "stopBits": 1,
      "flowControl": "disable",
      "parity": "none",
      "timeout": 1000
    },
    "serial3": {
    
      "type": "UART",
      "port": 2,
      "dataWidth": 8,
      "baudRate": 115200,
      "stopBits": 1,
      "flowControl": "disable",
      "parity": "none",
      "timeout": 1000
    }
  },
  "debugLevel": "ERROR",
  "repl": "enable",
  "replPort": 2
}

3、 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 the status of infrared obstacle avoidance sensor every second , When someone enters the print ‘open the door’, Control the steering gear to open the door , And display the current number of people uploaded to the cloud ; When no one enters the print ‘no object detected’.
 Insert picture description here
2、 Alicloud platform , open Real time refresh , The current Number of entrants .
 Insert picture description here

4、 Create mobile app

establish ‘ Common projects ’

 Insert picture description here
 Insert picture description here
After creating the auto jump home page , Associated with the corresponding product
 Insert picture description here
 Insert picture description here
Back to home , Create a new mobile app
 Insert picture description here
 Insert picture description here
Automatically jump to the application editing interface , Select the component → Basic components → Chart → Real time curve , Or search directly .
When I'm done , Configure component information .
 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here
add to ‘ The radio ’ Components , And configure component information .
 Insert picture description here
 Insert picture description here
Configure interaction information .
 Insert picture description here
 Insert picture description here
Save after configuration , Click preview to view the set mobile application .
 Insert picture description here
Cell phones scan QR codes , You can select automatic door mode on your mobile phone , And check the traffic in real time .
 Insert picture description here

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

Random recommended