elleny

[Training Camp_Advanced Class] Smart Socket Based on Alibaba Cloud

 
Overview

The demonstration video is at the end!

# Chapter 1 Introduction

## 1.1 Project Background and Significance

In recent years, with the continuous improvement of people's living and technological levels, smart switches have taken the lead in the fields of homes and villas, allowing this part of people to enjoy the smart experience brought by modern technology first, which will inevitably drive the comprehensive upgrading of users. The use of smart switches in public spaces such as homes, factories, offices, and schools meets customers' service needs for personalization, intelligence, interactivity, and security, and also improves the grade of these application places. As a trend product, smart switches are the key development direction of major home furnishing markets.

Therefore, the purpose of this project is to design and make a smart switch based on Alibaba Cloud that can wirelessly remotely control the relay switch through a mobile phone app, and upload the current indoor temperature to the app for real-time display. (I show my cards, freeloading makes me happy)

# Chapter 2 Solution Design and Hardware Selection

## 2.1 Design Tasks and Requirements for This Article

### 2.1.1 Design Tasks

Design and make a set of smart switches based on STM32 and EMW3050 modules. With Alibaba Cloud public version app, the function of remote control of relay switch by mobile phone is realized, and real-time temperature is uploaded to app for display.

### 2.2.2 Main functions realized

(1) Remote start and stop control of relay.

(2) Realize timed measurement and upload of temperature.

(3) Re-network function.

## 2.2 Overall design of the system

The system adopts STM32F103C8T6 as the control core of the intelligent switch, EMW3080 module as the WiFi communication device of the system, ds18b20 module detects the system temperature, and remotely controls the relay and displays the temperature through app. The hardware consists of power supply circuit, stm32 minimum system, EMW3080 module, relay drive circuit, etc. The software mainly consists of serial communication, temperature reading, IO port reading and writing, etc. The overall system block diagram is shown in the figure below.

![image.png]
**Figure 2-1 System block diagram**

## 2.3 Selection of main chip

The STM32F103C8T6 chip is adopted. STM32F103C8T6 has many advantages. Its core is ARM 32-bit Cortex™-M3 CPU with a maximum operating frequency of 72MHz. It has 64K bytes of flash program memory and up to 20K bytes of SRAM. It has 3 16-bit timers, input capture/output comparison and incremental encoder input. It supports up to 2 I2C interfaces and 3 USART interfaces. The convenient and efficient development environment makes the operation easier. The low power consumption is difficult to match with other types of microcontrollers. It has a high degree of integration and is relatively simple to program. In addition, the STM32 series has very rich resources on the Internet, which is very conducive to learning and development.

![image.png]
**Figure 2-2. STM32F103C8T6 is available in LiChuang Mall**

## 2.4 Selection of temperature sensor

DS18B20 is a commonly used digital temperature sensor with a temperature measurement range of -55℃ to +125℃, an inherent temperature measurement error of 1℃, and an accuracy of 0.5. It has the characteristics of small size, low hardware cost, strong anti-interference ability and high precision. The DS18B20 digital temperature sensor is easy to wire and can be used in various occasions after packaging, such as pipeline type, threaded type, magnet adsorption type, stainless steel packaging type, and various models, including LTM8877, LTM8874, etc. It is wear-resistant and collision-resistant, small in size, easy to use, and has various packaging forms. It is suitable for digital temperature measurement and control fields of various narrow space equipment.

![image.png]
**Figure 2-4.DS18B20 temperature sensor**

 

## 2.5 Selection of WIFI communication module

Select Qingke's [EMW3080](http://www.mxchip.com/product/wifi_product/69) module. [EMW3080](http://www.mxchip.com/product/wifi_product/69) is an embedded Wi-Fi module based on MX1290V2 SOC with single 3.3V power supply, integrated Wi-Fi and Cortex-M4F MCU, supporting up to 62.5M main frequency and 256K RAM, powerful floating point operation, rich memory and peripheral interface resources, and can meet most application needs and multi-cloud requirements. The module is officially certified by Alibaba Cloud and is safe and reliable. AT commands directly connect to Alibaba Cloud platform to simplify development, and commercial modules are reliable. Why not use esp8266? I searched on Baidu and found that the performance is far superior! !


![image.png] ![image.png]
In fact, it is mainly because I have used esp8266 before, and developed it with arduino and paired with the blinker platform. [\\\https://www.bilibili.com/video/BV16b411B7wd?p=1\\\](https://www.bilibili.com/video/BV16b411B7wd?p=1) (Don't click this link) To be honest, it is really simple and convenient. . This time I wanted to try something new, and fortunately I didn't fail.

## 2.6 Selection of relays and driver chips

The relay is selected from Huike's HK4100F-DC5V-SHG. The coil voltage of this relay is 5V, and it is paired with the relay driver chip NUD3105LT1G. Simplify the circuit design and enhance the circuit stability at the same time, killing two birds with one stone.

![image.png] ![image.png]
**Figure 2-8. Relay and driver chip**

# Chapter 3 Schematic design and PCB drawing

## 3.1 Circuit schematic design

The circuit design based on Alibaba Cloud smart socket designed in this project mainly includes the minimum system circuit of STM32F103C8T6, emw3080 module circuit, key circuit, DS18B20 driver circuit, download circuit, voltage regulator circuit, relay driver circuit, LED indicator circuit, etc. The main control circuit of the system is shown in the figure below:

![image.png]
**Figure 3-1. Control circuit schematic**

### 3.1.1 Minimum system circuit

The minimum system block diagram of STM32F103C8T6 is shown in the figure below. It mainly includes the enable circuit of crystal oscillator, reset and BOOT selection, and the MCU is the STM32F103C8T6 chip.

![image.png]
**Figure 3-2. Minimum system block diagram of STM32F103C8T6**

### 3.1.2 emw3080 module circuit

The main function of the emw3080 module circuit is to transmit data with stm32 through the serial port. In addition, the boot pin needs to be brought out to facilitate firmware flashing. Connect the EN pin to stm32 to facilitate module reset through the program. At the same time, according to the data sheet, pull up the module's GPIO23. The emw3080 module circuit is shown in the figure below.

![image.png]
**Figure 3-3.EMW3080 module circuit**

### 3.1.3 Key circuit

In addition to the reset button of the stm32 minimum system, the key circuit part is also composed of another light touch button. Since the IO port of STM32 has its own pull-up resistor to constrain the current, the other end of the button can be grounded. The main function of this button is to re-configure the network for the emw3080 module.

![image.png]
**Figure 3-4. Key circuit**

### 3.1.4 ds18b20 drive circuit

According to the ds18b20 official manual, the temperature sensor has two circuit connection modes. In addition to the traditional external power supply, DS18B20 can also work in "parasitic power mode", and the following figure shows the circuit connection diagram of DS18B20 working in "parasitic power mode", so that DS18B20 can work in parasitic power mode, and temperature information can be collected in real time without additional power supply. In addition, this module adopts a single bus data format, which only needs to occupy one IO port of stm32 for reading and writing.

![image.png]
**Figure 3-5. ds18b20 drive circuit**

### 3.1.5USB communication power supply circuit

The 5V voltage of the micro_usb external power supply is converted into the 3.3V voltage required by the chip through the ams1117-3.3 linear regulator. In addition to the power supply circuit, the CH340E USB chip is also used to connect the data line of the mirco_usb female head, as well as the rx and tx ports of the stm32 serial port 1.

![image.png]
**Figure 3-6. USB communication power supply circuit**

### 3.1.6 LED indicator circuit

design Four LED indicators are used to display the current operating status of the device, so as to better transmit information and interact with human-computer interaction.

![image.png]
**Figure 3-7. LED indicator circuit**

### 3.1.7 Relay drive circuit

Select the relay module HK4100F-DC5V-SHG with a coil voltage of 5V, and add the relay drive chip [NUD3105LT1G](https://item.szlcsc.com/15566.html "NUD3105LT1G "), which saves the trouble of building the relay drive circuit by yourself, and works more stably.

![image.png]
**Figure 3-8. Relay drive circuit**

## 3.2 PCB drawing

### 3.2.1 Basic design process

The basic design process of general PCB circuit board design is as follows: preliminary preparation-> schematic design-> PCB structure design-> PCB layout-> wiring-> wiring optimization-> network and DRC inspection and structure inspection.
First: preliminary preparation

This includes preparing component libraries and schematics. "If you want to do your work well, you must first sharpen your tools." To make a good board, in addition to designing the principle, you must also draw well. Before designing PCB, you must first prepare the component library of the schematic SCH and the component library of the PCB. **But!! The awesome LiChuang EDA saves you this troublesome step and has created more than 1 million components that are updated in real time, allowing you to focus more on design! **
![image.png]

Second: PCB structure design

In this step, according to the determined plane size of the circuit board and various mechanical positioning, draw the PCB board surface in the PCB design environment, and place the required connectors, buttons/switches, digital tubes, indicator lights, inputs, outputs, screw holes, assembly holes, etc. according to the positioning requirements. And fully consider and determine the wiring area and non-wiring area (such as how much area around the screw hole belongs to the non-wiring area).
It is necessary to pay special attention to the fact that when placing components, the actual size of the components (occupied area and height), the relative position between components - the spatial size, and the surface where the components are placed must be considered to ensure the electrical performance of the circuit board and the feasibility and convenience of production and installation. At the same time, the placement of the components should be appropriately modified to make them neat and beautiful, while ensuring that the above principles can be reflected. For example, the same components should be placed neatly and in the same direction.

Third: PCB layout

1. Ensure the correctness of the schematic diagram before layout.
Schematic diagram is drawn. Check items: power network, ground network, etc.

2. When laying out, pay attention to the surface where the device is placed (especially plug-ins, etc.) and the placement of the device (whether the direct plug-in is placed horizontally or vertically) to ensure the feasibility and convenience of installation.

3. To put it simply, layout is to place the device on the board. At this time, if the preparations mentioned above are done, you can generate a network table on the schematic diagram (Design->CreateNetlist), and then import the network table on the PCB diagram (Design->LoadNets).

The general layout is carried out according to the following principles:

When laying out, the surface where the device is placed should be determined: Generally speaking, the patch should be placed on the same side, and the plug-in depends on the specific situation.

① Reasonable zoning according to electrical performance, generally divided into: digital circuit area (i.e. afraid of interference, and also generates interference), analog circuit area (afraid of interference), power drive area (interference source);

② Circuits that complete the same function should be placed as close as possible, and the components should be adjusted to ensure the simplest connection; at the same time, the relative positions between the functional blocks should be adjusted to make the connection between the functional blocks the simplest;

③ For components with large mass, the installation position and installation strength should be considered; heating components should be placed separately from temperature-sensitive components, and thermal convection measures should be considered if necessary;

④ I/O driver devices should be as close to the edge of the printed circuit board as possible and close to the lead-out connector;

⑤ Clock generators (such as crystal oscillators or clock oscillators) should be as close as possible to the devices that use the clock;

⑥ The layout requirements should be balanced, dense and orderly, and should not be top-heavy or one-sided.

Fourth: Wiring

Wiring is the most important process in the entire PCB design. This will directly affect the performance of the PCB board. In the design process of PCB, wiring is generally divided into three realms: the first is wiring, which is the most basic requirement for PCB design. If the circuits are not connected and there are flying wires everywhere, it will be an unqualified board, which can be said to be not yet started. The second is the satisfaction of electrical performance. This is the standard for measuring whether a printed circuit board is qualified. This is after the wiring is connected, carefully adjust the wiring so that it can achieve the best electrical performance, and then the appearance. The wiring should be neat and uniform, and cannot be criss-crossed without any rules. All of this must be achieved while ensuring the electrical performance and meeting other individual requirements.

The wiring is mainly carried out according to the following principles:

① In general, the power line and ground line should be wired first to ensure the electrical performance of the circuit board. Within the scope permitted by conditions, try to widen the width of the power and ground lines. It is best that the ground line is wider than the power line. Their relationship is: ground line>power line>signal line. Usually the signal line width is: 0.2~0.3mm, the thinnest width can reach 0.05~0.07mm, and the power line is generally 1.2~2.5mm. For the PCB of the digital circuit, a wide ground wire can be used to form a loop, that is, to form a ground network for use (the ground of the analog circuit cannot be used in this way);

② Pre-wire the lines with more stringent requirements (such as high-frequency lines). The edge lines of the input and output ends should avoid being adjacent and parallel to avoid reflection interference. Ground isolation should be added when necessary. The wiring of two adjacent layers should be perpendicular to each other. Parallel wiring is prone to parasitic coupling;

③ The oscillator casing is grounded, and the clock line should be as short as possible and should not be led everywhere. Under the clock oscillator circuit and special high-speed logic circuit, the ground area should be increased, and other signal lines should not be routed to make the surrounding electric field approach zero;

④ Use 45° zigzag wiring as much as possible, and do not use 90° zigzag wiring to reduce the radiation of high-frequency signals; (high requirements should also use double arc lines);

⑤ No signal line should form a loop. If it is unavoidable, the loop should be as small as possible; the vias of the signal line should be as few as possible;

⑥ The key lines should be as short and thick as possible, and protective ground should be added on both sides;

⑦ When transmitting sensitive signals and noise field band signals through flat cables, they should be led out in the form of "ground wire-signal-ground wire";

⑧ Test points should be reserved for key signals to facilitate debugging, production and maintenance inspection;

⑨ After the schematic wiring is completed, the wiring should be optimized; at the same time, after the preliminary network check and DRC check are correct, the ground wire is filled in the unwired area, and a large area of ​​copper layer is used as the ground wire. On the printed circuit board, all unused areas are connected to the ground as the ground wire. Or make a multilayer board, with the power supply and ground wire occupying one layer each.

Fifth: Add teardrops

Sixth: The first item to check is to check the Keepout layer, top layer, bottom layer topoverlay, bottomoverlay in turn.

Seventh: Electrical rule check: vias (0 vias - incredible; 0.8 dividing line), whether there is a disconnected netlist, minimum spacing (10mil), short circuit

Eighth: Check the power line and ground line - interference. (The filter capacitor should be close to the chip)

Ninth: After the PCB is completed, reload the netlist to check whether the netlist has been modified - it works very well.

Tenth: After the PCB is completed, check the lines of the core components to ensure accuracy.


### 3.2.2 Final PCB display

In this article, after the schematic design and related circuit simulation are completed, the rules are set according to the circuit schematic and the actual working conditions of the smart socket. After that, the network table is input, the components are reasonably laid out, and the wiring and inspection are carried out according to the relevant principles of wiring during PCB board design, and finally the PCB board of the smart socket is completed.

![image.png] ![image.png]
**Figure 3-9. Smart socket PCB**

# Chapter 4 Algorithms and Programming

## 4.1 EMW3080 AT Commands

The best way to understand how to use a module is to consult its technical documentation. So we first open the public documents on Qingke's official website.

![image.png]
Because the emw3080 we bought has been flashed with the firmware of the Feiyan platform, click on the direct connection to the Ali ILOP Feiyan platform command interaction process example. After clicking in, it will present three process diagrams for setting triples, network configuration process, and control command sending and receiving. According to the process picture, the above functions can be successfully realized by reading and writing AT commands through the stm32 serial port.

![image.png]
### 4.1.1 Set triplet

![image.png]
### 4.1.2 Network configuration process

![image.png]
### 4.1.3 Control command sending and receiving

![image.png]
After creating a project on the Ali Life IoT platform and adding a device, you can get the device-specific triplet (actually a quadruple) and start the above process.

## 4.2 DS18B20 temperature reading

The typical temperature reading process of DS18B20 is:

1. Reset  

2. Send SKIP ROM command (0XCC)  

3. Send start conversion command (0X44)

4. Delay

5. Reset

6. Send SKIP ROM command (0XCC)

7. Send read memory command (0XBE)

8. Continuously read two

bytes of data (i.e. temperature)

9. End.

Reset pulse and response pulse All communications on the single bus start with an initialization sequence. According to the ds18b20 initialization timing diagram, we can know that the host outputs a low level and maintains the low level for at least 480us to generate a reset pulse. Then the host releases the bus, and the 4.7K pull-up resistor pulls the single bus high, delays 15~60us, and enters the receiving mode (Rx). Then the DS18B20 pulls the bus low for 60~240us to generate a low-level response pulse. If it is a low level, it will delay for another 480us.

![image.png]
**Initialization timing diagram**

The write timing includes the write 0 timing and the write 1 timing. All write timings require at least 60us, and at least 1us recovery time is required between 2 independent write timings. Both write timings start with the host pulling the bus low. Write 1 timing: the host outputs a low level, delays 2us, and then releases the bus, delays 60us. Write 0 timing: the host outputs a low level, delays 60us, and then releases the bus, delays 2us.

The single bus device transmits data to the host only when the host issues a read sequence. Therefore, after the host issues a read data command, the read sequence must be generated immediately so that the slave can transmit data. All read sequences require at least 60us, and at least 1us recovery time is required between 2 independent read sequences. Each read sequence is initiated by the host, which pulls the bus down for at least 1us. The host must release the bus during the read sequence and sample the bus state within 15us after the start of the sequence. The typical read sequence process is: the host outputs a low level delay of 2us, then the host switches to input mode for a delay of 12us, then reads the current level of the single bus, and then delays for 50us.

![image.png]
**Read and write time slot timing diagram**

## 4.3 LED, relay, button part

STM32 only needs to perform simple IO port read and write operations.

## 4.4 Serial communication part

Serial communication is the main part of the program. In this system, two serial ports, USART1 and USART2, are opened. USART1 is connected to the PC and is responsible for burning the microcontroller program and echoing important information. USART2 is connected to EMW3080W and is responsible for reading and writing AT commands, including the above-mentioned triplet writing, WiFi configuration, and sending and receiving control commands.
STM32 only needs to perform simple IO port read and write operations.
The echo of serial port 1 can directly call the function printf, which can conveniently display whether the program runs according to your logic on the serial port assistant on the computer, such as whether ds18b20 is initialized successfully, whether the emw3080 triplet is written, and whether the network configuration is successful, etc. It is extremely convenient in the debugging stage of the program.

Secondly, serial port 2 is responsible for communicating with EMW3080 and reading and writing AT commands. You can customize the function u2_printf, which is similar to the sending function of serial port 1 printf, but its main function is to write AT commands. Since emw3080 is not directly connected to the computer through the serial port module, in order to better understand the information returned by emw3080 after receiving the AT command, a function is needed to display the information received by serial port 2 to the PC through serial port 1 to facilitate program debugging.

//Return the received AT command response data to the computer serial port

//mode:0, do not clear USART2\_RX\_STA;

// 1, clear USART2\_RX\_STA;

void emw3080\_at\_response(u8 mode)

{

if(USART2\_RX\_STA&0X8000) //Received data once

{

USART2\_RX\_BUF[USART2\_RX\_STA&0X7FFF]=0; //Add terminator

printf("%s",USART2\_RX\_BUF); //Send to the serial port

if(mode)USART2\_RX\_STA=0;

}

}

In addition, for the EMW3080 control instructions received by the serial port 2, because the project is not complicated, I took a shortcut and did not use json parsing, but directly used a strstr function to solve it.

//After EMW3080 sends a command, check the received response

//str: expected response result

//Return value: 0, did not get the expected response result

//Others, the position of the expected response result (the position of str)

u8* emw3080\_check\_cmd(u8 *str)

{



char *strx=0;

if(USART2\_RX\_STA&0X8000) //Received data once

{

USART2\_RX\_BUF[USART2\_RX\_STA&0X7FFF]=0;//Add terminator

strx=strstr((const char*)USART2\_RX\_BUF,(const char*)str);

}

return (u8*)strx;

}

Then in the loop, just determine whether the received string contains the information you want. To be honest, it doesn't seem very good, but isn't it nice?

if(emw3080\_check\_cmd(":0"))

{

printf("key off
");

relay=0;

LED4=1;



}

if(emw3080\_check\_cmd(":1"))

{

printf("key on
");

relay=1;

LED4=0;

}

if(emw3080\_check\_cmd("CONNECT"))

{

printf("Network configuration successful
");

LED2=1;

}

 

****One more thing I want to remind you is that sometimes when you wonder why there is a problem with the AT command, you can first check whether you have reset the EMW3080 before reading or writing the AT command. I couldn't write it before, but later I tried it. After resetting the EN pin of the emw3080 through the IO port program, everything went smoothly. ********

 

 

# Chapter 5 Debugging process and results

## 5.1 Soldering and inspection of circuit boards

I soldered two boards in total. I was thinking about what to do if I didn’t have a soldering iron at home. I didn’t expect to win the yellow flower 907 during the live broadcast. However, I hardly soldered boards during college. I quickly watched the soldering iron patch soldering tutorial on LiChuang EDA B station, bought a cutter head online, and started my first work. . . .

After the first board was soldered, the serial port could be detected. After a while of joy, I found that the LED light was not on. . . My mentality exploded. I tried the relay and it worked, but this LED did not light up. I didn’t know what went wrong, after all, I was a novice in soldering. So I started to solder the second board. Fortunately, I bought two sets of components, otherwise I would be dead. After the second board was soldered, the LED light was on!! But one of them was not on, so I started to tinker with it. After all, I only had this board. I checked and found that the resistor next to the LED light was soldered on one side, and the other side was not soldered to the pad. After the LED light problem was solved, I found that the button was not working. . . . A closer look showed that it was a cold solder joint again, but it was fixed after rework. After the board circuit was adjusted, I felt relieved.

![image.png]
**The first failed product and the second finished product**

## 5.2 Program debugging

After the components of the circuit board are soldered and checked, the actual program debugging begins. Program debugging is divided into the following steps:

1. Debug each module individually

2. Debug module combination

3. Debug the entire system

Debug each module individually, including: LED light control, relay control, key input, temperature data acquisition, serial communication, etc. After confirming that each part works normally individually. Start module combination debugging, including: key input control module network configuration, send temperature data through AT commands, control relay switches according to received strings, etc. After the

module combination debugging is completed, the functions are organically combined, and the overall debugging of the system begins, the program is improved, errors are corrected, and the required functions are realized according to the task requirements of the design scheme in this article.

# Summary

The work completed in this paper mainly includes the following:

1. Introduced the development of smart sockets, described the background of smart fan research and its practical engineering significance

2. Introduced the design of the scheme and hardware selection

3. Introduced the design principles related to PCB, and completed the drawing of PCB while designing the circuit schematic.

4. Analyzed the process of the main program and explained the principle of the main algorithm.

5. Built the hardware circuit and debugged the burning program to complete the following functions:

(1) Remote start and stop control of the relay.

(2) Realize the timed measurement and upload of temperature.

(3) Key re-networking function.

This course design - the smart switch based on Alibaba Cloud has been completed. Although there are still many shortcomings and deficiencies in the design, I have learned a lot from it. In this course design, under the professional guidance of LiChuang EDA teacher and personal learning, I applied knowledge such as circuit design and embedded software development, and had a deeper understanding of designing an IoT control system. I exercised my hands-on ability and the ability to develop engineering projects, and closely combined theory with practice. It will be of great help in the future work, study and life.


**Finally, I suddenly had the idea to use this PCB on the computer heat sink. **
**For detailed production process and effect, please see the video below~**
**If you are interested, there are also various functions to add, such as remote computer startup, remote monitoring of computer performance, or adding an oled to display computer performance temperature, etc. Hahahaha**

![QQ图片20200822235323.png]
参考设计图片
×
 
 
Search Datasheet?

Supported by EEWorld Datasheet

Forum More
Update:2024-11-14 23:49:04
  • Best RP2040 Development Boards of 2021
  • Working principle of electronic tags
  • Sell some idle SSDs Samsung 850 and 860evo
  • 50Ω
  • TI's Buck Converter Selection Reference Guide
  • stm8

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号