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:07【Zhiyunfu】
Comprehensive case 2.0- Automatic induction door
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
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
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
- Click ok
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 .
Use case of steering gear Reference resources
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 .
- Serial port debugging tool use putty
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’.
2、 Alicloud platform , open Real time refresh , The current Number of entrants .
4、 Create mobile app
establish ‘ Common projects ’
After creating the auto jump home page , Associated with the corresponding product
Back to home , Create a new mobile app
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 .
add to ‘ The radio ’ Components , And configure component information .
Configure interaction information .
Save after configuration , Click preview to view the set mobile application .
Cell phones scan QR codes , You can select automatic door mode on your mobile phone , And check the traffic in real time .
copyright notice
author[Zhiyunfu],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/135/202205142335456447.html
The sidebar is recommended
- Financial IT architecture - Analysis of cloud native architecture of digital bank
- [paper notes] lsnet: extreme light weight Siamese network for change detection in remote sensing image
- Mock tool equivalent to Fiddler!
- Write a program, input several integers (separated by commas) and count the number of occurrences of each integer.
- Inventory a voice conversion library
- Technology selection of micro service registration center: which of the five mainstream registration centers is the most popular?
- Summary of root cause analysis ideas and methods | ensuring it system and its stability
- JS custom string trim method
- Web3: the golden age of Creator economy
- Introduction and installation of selenium module, use of coding platform, use of XPath, use of selenium to crawl JD product information, and introduction and installation of sketch framework
guess what you like
Basics: a 5-makefile example
Database connection pool Druid source code learning (V)
Check the box to prevent bubbling
Click on the box to change color
Local style and global style of uniapp
LeetCode. 2233. Maximum product after K increases (math / minimum heap)
Overview, BGP as, BGP neighbor, BGP update source, BGP TTL, BGP routing table, BGP synchronization
Routing policy and routing control
Principle and configuration of IS-IS
C - no AC this summer
Random recommended
- Basic operation of linked list (complete code)
- Thread control - thread waiting, thread termination, thread separation
- Key points of acupuncture and moxibustion
- Module product and problem solution of Luogu p2260 [Tsinghua training 2012]
- Review points of Geodesy
- Summary of review points of Geodesy
- Arrangement of geodetic knowledge points
- Review key points of basic geodesy
- Luogu p2522 [haoi2011] problem B solution
- [app test] summary of test points
- Version management tool - SVN
- JDBC ~ resultset, use of resultsetmetadata, ORM idea, arbitrary field query of any table (JDBC Implementation)
- This article takes you to understand can bus
- Gear monthly update April
- Gear monthly update April
- Convert timestamp to formatted date JS
- The time stamp shows how many minutes ago and how many days ago the JS was processed
- [untitled]
- Luogu p2216 [haoi2007] ideal square problem solution
- Miscellaneous questions [2]
- Which securities company does qiniu school recommend? Is it safe to open an account
- Hyperstyle: complete face inversion using hypernetwork
- What activities are supported by the metauniverse to access reality at this stage?
- P2P swap OTC trading on qredo
- Google | coca: the contrast caption generator is the basic image text model
- SIGIR 2022 | Huawei reloop: self correcting training recommendation system
- Whether you want "melon seed face" or "national character face", the "face changing" technology of Zhejiang University video can be done with one click!
- Sorting of naacl2022 prompt related papers
- Servlet create project
- "Chinese version" Musk was overturned by the original: "if it's true, I want to see him"
- [network security] web security trends and core defense mechanisms
- [intensive reading] object detection series (10) FPN: introducing multi-scale with feature pyramid
- 007. ISCSI server chap bidirectional authentication configuration
- 2021-03-09
- plot_ Importance multi classification, sorting mismatch, image value not displayed
- [intensive reading] object detection series (XI) retinanet: the pinnacle of one stage detector
- How to install MFS environment for ECS
- [intensive reading] the beginning of object detection series (XII) cornernet: anchor free
- Open source sharing -- a record of students passing through time
- MOT:A Higher Order Metric for Evaluating Multi-object Tracking