Hardware design and implementation of wireless electronic ordering system based on single chip microcomputer

Publisher:心若澄明Latest update time:2011-10-29 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

Chapter 1 Introduction
1.1 Research Background and Significance

Human beings have been using wireless communication technology for thousands of years. The beacon towers used in ancient times were the most primitive form of wireless communication. However, wireless communication technology was still in its infancy at that time. It was not until the end of the 19th century when Italian Marconi invented the wireless telegraph that humans really began to use wireless communication technology on a large scale [1]. In recent decades, with the development of computer technology and electronic technology, wireless communication technology has been advancing at a rapid pace and has become a key research direction in the field of communications.
Modern wireless communication technology is based on hardware circuits, so the development of microelectronics technology [2] directly restricts the development of wireless communication technology. Looking back on the development of integrated circuits, we can see that in the more than 40 years since the invention of integrated circuits, the phrase "from circuit integration to system integration" is the best summary of the development process of IC products from SSI (Small Scale Integrated) to VLSI (Very Large Scale Integrated) and today's very large-scale integrated circuits. That is, the development of the entire integrated circuit product has gone through a process from the traditional system-on-board to the system-on-a-chip. With the increase in the degree of integration, the size, energy consumption and cost of chips are gradually decreasing. This has also led to the development of electronic products towards the portable and low-end markets.
Although the development history of microelectronics has been more than half a century, the development of radio frequency chips [1][2] has only been in recent years. From a classification point of view, radio frequency chips belong to application-specific integrated circuits. There are many companies specializing in the production of radio frequency chips in the world, such as Nordic and Chipcon. These chips generally work in free frequency bands, use special modulation and demodulation technology, and integrate many circuits inside. For example, Nordic's NRF2401 chip is a single-chip radio frequency transceiver chip that works in the 2.4-2.5GHz ISM (Industry Science Medicine) frequency band. The chip has built-in frequency synthesizers, power amplifiers, crystal oscillators, modulators and other functional modules. The output power and communication channel can be configured through the program. The chip has very low energy consumption. When transmitting at a power of -5dBm, the operating current is only 10.5mA, and when receiving, the operating current is only 18mA. There are multiple low-power working modes, and energy-saving design is more convenient. Its DuoCeiverTM technology enables nRF2401 to use the same antenna to receive data from two different channels at the same time.
The wireless electronic ordering system is a typical application of wireless communication technology. In recent years, with the improvement of people's living standards and the change of lifestyle, the catering industry has a huge investment market and is known as China's golden industry. People have higher requirements for service quality during consumption. At the same time, the fierce competition among restaurants has also promoted the application of wireless communication technology in the catering industry. The purpose of the wireless electronic ordering system is to use the most advanced 2.4GRF wireless communication technology, embedded mobile database technology [3][4], and touch screen handheld computer technology to provide a complete solution for the catering industry to move towards full digitalization. The system can improve the grade of restaurants, improve efficiency, automatically check out, avoid human errors, avoid missing orders, monitor restaurant conditions in real time, provide various statistical information, streamline staff, manage inventory, improve service quality, etc. It brings new management concepts and service methods to the catering industry, optimizes business processes, provides better services to customers, maximizes corporate value while minimizing costs, and is an important symbol of the catering industry's development towards informatization. Since wireless communication technology is used, there is no need for complex wiring, which greatly reduces the construction cost of the restaurant and the cost of line maintenance. At the same time, the mobility of wireless communication also allows waiters to contact the bar at any time.
The wireless electronic ordering system is based on the currently popular technology - embedded technology [3], relying on a certain hardware platform. Therefore, the development of microelectronics technology has a great limitation on the performance of the system. At present, microelectronics technology has developed to SOC (System On Chip), and the integration has been greatly improved. At the same time, the price, size and energy consumption of chips have been further reduced, all of which have made the wireless electronic ordering system develop in the direction of mobility and popularization. It can be said that with the further development of microelectronics technology, the wireless electronic ordering system still has a lot of room for development.

1.2 Current Development Status of Wireless Communication Technology

According to the different transmission power, wireless communication technology can be divided into short-range wireless communication technology and long-range wireless communication technology. The hardware platforms and communication protocols they rely on are also very different. Several common long-range wireless communication systems, such as the GPRS system and the 3G system that will be put into use in China, have some common characteristics: they use dedicated frequency bands and require dedicated companies to operate. Since this system requires a limited transmission distance and has cost restrictions, long-range wireless communication protocols are not within the scope of consideration. The following focuses on several common short-range wireless communication protocols:
1 Bluetooth [5]
In 1994, Ericsson began to study a wireless module that enables mobile phones and their accessories (such as headphones) to communicate with each other. Four years later, Ericsson, Nokia, IBM and other companies jointly launched Bluetooth technology, which is mainly used for wireless connection of communication and information equipment. The operating frequency of Bluetooth is 2.4 GHz, and the effective range is about 10m radius. Within this range, multiple devices using Bluetooth technology, such as mobile phones, microcomputers, laser printers, etc., can be wirelessly connected, transmit data to each other at a rate of about 1Mb/s, and can easily access the Internet. At present, the development focus of Bluetooth technology is multi-point connection, that is, one device can be connected to multiple (up to 7) other devices at the same time. In the future, Bluetooth products from different manufacturers on the market will be able to connect to each other.
The application of Bluetooth technology mainly includes the following three categories:
1 Voice/data access refers to connecting a computer to a communication device through a secure wireless link to complete the connection with the wide area network.
2 Peripheral device interconnection refers to connecting various devices to the host through a Bluetooth link.
3 PAN (Personal Area Net) is shown in Figure 1, which is mainly used for sharing and exchanging personal networks and information.
The Bluetooth protocol has the following technical features:
(1) Bluetooth works in the globally open 2.4GHz ISM band;
(2) It uses frequency hopping spectrum expansion technology to divide the frequency band into several hop channels. In one connection, the radio transceiver continuously jumps from one channel to another according to a certain code sequence;
(3) A Bluetooth device can establish a connection with seven other Bluetooth devices at the same time;
(4) The data transmission rate can reach 1Mbit/s;
(5) Low power consumption and good communication security;
(6) It can connect across obstacles within the effective range without special communication viewing angle and direction requirements;
(7) It supports voice transmission;
(8) Networking is simple and convenient
It is precisely because of the above characteristics of the Bluetooth protocol that Bluetooth products involve information devices such as PCs, laptops, mobile phones, and A/V equipment, automotive electronics, home appliances, and industrial equipment. Bluetooth supporters predict that once chips that support Bluetooth become very cheap, Bluetooth will be in almost all products, from microwave ovens to buttons on clothes.
However, the transmission distance of Bluetooth is relatively short, and Bluetooth is not a fully mature technology. Although it is described as promising, it still needs to be strictly tested in actual use. The data transmission rate of Bluetooth is not very high, which may also affect its development in today's era of data explosion. Currently, mainstream software and hardware platforms do not provide support for Bluetooth, which increases the application cost of Bluetooth and makes it more difficult to popularize it. Considering all the above points, the Bluetooth protocol is not suitable for this system.
2 Ultra Wide Band Technology UWB (Ultra Wide band) [6]
Ultra Wide Band Technology UWB (Ultra Wide band) is another newly developed wireless communication technology. UWB sends data by acting on the antenna with baseband pulses. Narrow pulses (less than 1ns) produce signals with extremely large bandwidth. The pulses are modulated using pulse position modulation (PPM) or binary phase shift keying (BPSK). UWB is allowed to operate in the 3.1-10.6 GHz band. It is mainly used in small-range, high-resolution radar and imaging systems that can penetrate walls, ground and bodies. In addition, this new technology is suitable for LANs (Local Area Nets) or PANs that require very high speeds (greater than 100Mb/s).
The military has been researching UWB for many years and has developed a radar with extremely high resolution. It was not until February 14, 2002 that the Federal Communications Commission of the United States approved the technology for civilian use. Therefore, UWB is still a new thing in the commercial and consumer fields. UWB has the potential to support data transmission rates of up to 110Mb/s within a range of 10m, without the need to compress data, and can complete video data processing quickly, simply and economically. Although the data transmission distance of UWB technology has been greatly improved compared to Bluetooth technology, it still cannot meet the technical requirements of this system.
3 ZigBee [1][7]
Zigbee is a short-range, low-power wireless communication technology. The name comes from the bee's eight-shaped dance. Its characteristics are short distance, low complexity, low power consumption, low data rate and low cost. It is mainly suitable for use in the fields of automatic control and remote control and can be embedded in various devices.
The technical characteristics and application prospects of the ZigBee protocol will be described in detail in the next chapter.
4 IrDA (infrared data association) technology [5][6]
Infrared is an electromagnetic wave with a wavelength between 750nm and 1mm. Its frequency is higher than microwaves but lower than visible light. It is a type of light that is invisible to the human eye. Since infrared has a short wavelength and poor diffraction ability against obstacles, it is more suitable for use in situations where short-distance wireless communication is required, for point-to-point linear data transmission, with a transmission rate of up to 16Mbps. IRDA limits the wavelength range of light waves used in infrared data communication to within 850nm to 900nm. IRDA technology has the following characteristics:
(1) It is a wireless connection technology that is currently widely used worldwide and is supported by many hardware and software platforms;
(2) Wireless data transmission and reception is achieved through the mutual conversion between data electrical pulses and infrared light pulses.
(3) It is mainly used to replace point-to-point cable connections;
(4) The new communication standard is compatible with the earlier communication standards;
(5) Small angle (within 30 degrees cone angle), short distance, point-to-point linear data transmission, strong confidentiality
(6) High transmission rate, currently 4M rate FIR technology has been widely used, and 16M rate VFIR technology has been released.
Although the IRDA technology is now very mature, and many companies' products support this protocol. However, due to the short wavelength of infrared rays and poor diffraction ability against obstacles, it can only be used for line-of-sight transmission, and the transmission distance is relatively short, so it is not suitable for the technical requirements of this system.
Comprehensively comparing the technical characteristics of the above short-range wireless communication protocols and the requirements of this system, only the ZigBee protocol can basically meet the requirements. In addition, there are many manufacturers that support the ZigBee protocol, and the technology is also mature, which can be made into low-cost embedded products.

1.3 Research content of the paper

The implementation of the wireless electronic ordering system is based on hardware circuits. In order to reduce the bit error rate and improve the utilization of frequency resources, data must be transmitted according to a certain protocol. At the sending end, the data is encoded in a certain format, and then modulated to an agreed frequency and sent; the receiving end demodulates and decodes the received signal to restore the data.
The research content of this paper mainly consists of two parts:
1. After discussing the characteristics of various wireless communication protocols and the development status of electronic technology, a hardware platform based on the ZigBee protocol is proposed on this basis. The principles and functions of each component of the platform are analyzed in detail.
2. The programming rules of the platform are analyzed and the corresponding driver is developed.

1.4 Content Arrangement

This paper conducts an in-depth study on the hardware design of wireless electronic food system. The full text is divided into five chapters, and the content of each chapter is arranged as follows:
Chapter 1 introduces the research background of this paper and the content arrangement of each chapter. Chapter
2 introduces the details of the ZigBee protocol and a chip based on the ZigBee protocol.
Chapter 3 proposes its own hardware platform based on the previous chapter, and introduces the components and functions of the platform in detail.
Chapter 4 corresponds to Chapter 3, mainly talking about the driver of the hardware platform and the development of the serial port debugging tool on the PC side, and briefly introduces the corresponding software development tools.
Chapter 5 is a summary and outlook. It summarizes the work of this paper and explores
the direction for further in-depth research.
Chapter 2 ZigBee [7] Protocol Analysis
ZigBee protocol is a short-range, low-complexity, low-power, low-data-rate, low-cost wireless network technology.
In terms of standard specification formulation, the main two organizations are the IEEE 802.15.4 group and the ZigBee Alliance, which formulate hardware and software standards respectively. In terms of IEEE 802.15.4, the IEEE established the 802.15.4 group in December 2000 to develop MAC (Media Access Control) and physical layer specifications. The 802.15.4 standard was passed in May 2003. In terms of the ZigBee Alliance, the ZigBee Alliance[7] was jointly established by Honeywell, Mitsubishi, Motorola, Philips and Invensys in October 2002. The ZigBee Alliance is responsible for developing network layer, security management, and application interface specifications, and is also responsible for interoperability testing. Currently, the ZigBee Alliance has launched Version 1.0 and has more than 150 members.
The ZigBee protocol is based on the 802.15.4 standard[8][9] and coordinates communication between thousands of tiny sensors. These sensors require very little energy and transmit data from one sensor to another via radio waves in a relay manner, so their communication efficiency is very high. The IEEE802.15.4 specification is an economical, efficient, low data rate (<250 kbps) wireless technology that works at 2.4 GHz and 868/915 MHz. It is the basis of the ZigBee application layer and network layer protocols.
Compared with various existing wireless communication technologies, ZigBee technology will be the technology with the lowest power consumption and cost. At the same time, due to the low data rate and small communication range of ZigBee technology, ZigBee technology is also suitable for carrying services with small data traffic. Therefore, the main application areas predicted by the ZigBee Alliance include industrial control, consumer electronic devices, automotive automation, agricultural automation and medical equipment control.

2.1 ZigBee Protocol Framework

The ZigBee protocol, like other network communication protocols, uses a layered model, clearly dividing the functions implemented by each layer and the role it plays in the entire protocol. Each layer provides a set of specific services for its upper layer. The ZigBee protocol architecture is roughly as listed in Table 2.1.

Table 2.1 ZigBee protocol architecture
Layer 4 Application layer
Layer 3 Network layer
Layer 2 Media Access Layer (MAC)
Layer 1 Physical layer

Although the ZigBee protocol is based on the standard seven-layer OSI (Open System Interconnect) model [10], only those layers related to ZigBee are defined. The IEEE802.15.4-2003 standard defines the bottom two layers: the physical layer and the MAC. The ZigBee Alliance provides protocols for the network layer and application layer framework.
Compared with common wireless communication standards, the ZigBee protocol suite is compact and simple, and the requirements for specific implementation are very low. The following is an estimate of the requirements for the ZigBee protocol suite: the hardware requires an 8-bit processor, such as the widely used 80C51 series microcontroller [12]; the software requires 32KB of ROM (Read Only Memory), and the minimum software requires 4KB of ROM; the network master node requires more ROM to accommodate the device information of all nodes in the network, the data packet forwarding table, the device association table, and the key storage related to security.
1 Physical layer
The IEEE802.15.4 standard is designed for low cost and higher level integration requirements in the physical layer. The working frequency bands used are 2.4 GHz and 868/915 MHz. The number of channels available in each frequency band is 16, 10, and 1, respectively, providing transmission rates of 250 kbps, 40 kbps, and 20 kbps, respectively, and the transmission range is between 10-100 meters.
In order to avoid interference, DSSS (Direct Sequence Spread Spectrum) [13] is used in each frequency band to divide a signal into multiple signals in a way of breaking the whole into pieces, and then transmit the signal through a coded method to avoid interference. For most low-end implementations, the application of direct sequence can make the analog circuit simpler and have higher fault tolerance performance.
2 Media Access Layer
In terms of the media access layer (MAC), the IEEE802.15.4 standard mainly uses the CSMA/CA (Carrier Sense Multiple Access/Collision Avoidance) method of the IEEE802.11 series of standards in the wireless local area network WLAN to improve the compatibility of the system. This MAC layer design not only simplifies the application of various topology networks, but also achieves very effective power consumption control.
3 Network layer
Network function is an important feature of the ZigBee protocol and is also different from other wireless local area network standards. In terms of the network layer, its main work is to be responsible for the establishment and management of the network mechanism, and it has self-configuration and self-repair functions. In the network layer, the ZigBee protocol defines three roles: the first is the network coordinator, which is responsible for the establishment of the network and the allocation of network locations; the second is the router, which is mainly responsible for finding and repairing the routing path of the information packet, and is responsible for forwarding the information packet; the third is the terminal device, which can only choose to join the network already formed by others, can send and receive information packets, but cannot forward, and does not have the routing function. Usually, routers and network coordinators are implemented by full-function devices (FFDs), while terminal devices are implemented by reduced-function devices (RFDs). In terms of networking, ZigBee mainly adopts three methods as shown in Figure 2.1: the first is a master-slave star network, which requires a network coordinator responsible for managing and maintaining the network and no more than 65,535 slave devices; the second is a cluster network, which can be an extended single star network or multiple interconnected star networks; the third is a mesh network, in which each FFD in the network can be used as a router to optimize the shortest and most reliable path according to the AD hoc network routing protocol.

Figure 2.1 Three network topologies

4 Application layer
For the application layer, there are three main parts: application support (APS) connected to the network layer, ZigBee device object (ZDO) and device application rules. The most important thing about ZigBee's application layer architecture is that it has covered the concept of service.
For ZigBee devices, when they join a WPAN (Wireless Personal Area Net), the ZMO of the application layer will initiate a series of initialization actions. First, they will search for devices and services through APS, and then record the related devices or services in the binding table in APS according to the pre-defined description information; all subsequent service usage must query the service or rules of the data through this binding table. The device application rules are different description information designed according to different products, as well as the parameter settings of each layer of ZigBee protocol.
5 Security layer
The security layer is not a separate protocol. ZigBee provides a set of security classes and software based on the 128-bit AES algorithm, and integrates the security elements of the IEEE802.15.4 standard to ensure the confidentiality, consistency and authenticity of the MAC layer frame.
In addition, the ZigBee Alliance is also responsible for the formulation of ZigBee product interoperability testing and certification rules, so that manufacturers who develop ZigBee products have an open place to test interoperability with each other. In the certification part, the ZigBee Alliance has defined three levels of certification. The first level certifies the physical layer and MAC, which has the most direct relationship with the chip factory; the second level certifies the ZigBee protocol stack; and the third level certifies the ZigBee product. Only products that pass the third level certification can be labeled with the ZigBee logo, so it is also called ZigBee registered certification.

2.2 Advantages and Disadvantages of ZigBee Protocol and Its Application Prospects

The ZigBee protocol is developed from WLAN. After the continuous modification and improvement of the standard by ZigBee Alliance members [7] in recent years, it has shown strong vitality. However, it still has some shortcomings, which also limits the scope of application of the ZigBee protocol.
2.2.1 Advantages of the ZigBee protocol
Low power consumption: Since the working cycle of ZigBee network node devices is short, the power consumption of sending and receiving information is low, and the sleep mode is adopted (when not transmitting data, they are in sleep state, and when they need to receive data, the coordinator device in the ZigBee network is responsible for waking them up), it can ensure that two No. 5 batteries can support up to six months to two years of use. Frequent battery replacement or charging is avoided, thereby reducing the burden of network maintenance.
High data transmission reliability: The collision avoidance mechanism is adopted, and dedicated time slots are reserved for communication services that require fixed bandwidth, avoiding competition and conflicts when sending data. In addition, the MAC layer adopts a fully confirmed data transmission mechanism. Each data packet sent must wait for the confirmation information of the receiver, thereby fundamentally ensuring the reliability of data transmission and minimizing the probability of information loss.
Large network capacity: A Zigbee network can accommodate up to 65,536 slave devices and one master device [14], and up to 100 Zigbee networks can exist in one area at the same time.
Low latency: Optimized for latency-sensitive applications, the communication latency and the latency of sleep state activation are very short. The typical device search latency is 30ms, the typical sleep activation latency is 15ms, and the active device channel access latency is 15ms.

Table 2.2 Zigbee and Bluetooth protocol latency comparison
Device search latency typical value (ms) Sleep activation latency typical value (ms) Active device channel access latency (ms)
ZigBee technology 30 15 15
Bluetooth technology >= 3000 3000 2

Compatibility: Seamless integration with existing control network standards. The network is automatically established through the network coordinator, and the CSMA-CA method is used for channel access. A full handshake protocol is provided for reliable transmission.
Security: Zigbee provides data integrity check and authentication functions, and the encryption algorithm uses AES-128. At the same time, each application can flexibly determine its security attributes, which effectively guarantees network security.
Low implementation cost: The initial cost of the module is estimated to be around US$6, which will soon drop to US$1.5~2.5, and the Zigbee protocol is free of patent fees.
The protocol suite is compact and simple: The requirements for its specific implementation are very low. Estimated requirements for the Zigbee protocol suite: 8-bit microprocessor, such as 80C51[10]; full protocol suite software requires 32K bytes of ROM; minimum protocol suite software requires about 4K bytes of ROM.
2.2.2 Problems and solutions of ZigBee protocol The
802.15.4 standard is the basis of ZigBee protocol. There are two main problems in using it to realize wireless data collection:
1. The clocks of sensor nodes in the network need to be synchronized. When the multi-sensor information of the monitoring system is integrated, the host computer needs to know when each raw data is collected. The trigger of sampling requires each node to have a unified clock;
2. Its communication rate is low, and it is limited by the interface communication rate. In addition, it is affected by the coding efficiency of the error correction code, so the actual data transmission volume is very low.
This problem can be solved in the following ways: The sensor node uses a DSP processor, and as much data processing work as possible is done at the sensor node level, so as to minimize the amount of raw data sent and only send useful information. For example, the raw data in a stable state can be sent to the host computer without sending it. Only the raw data before and after the suspicious state can be sent, which greatly reduces the amount of data communication.
2.2.3 Application Prospects of ZigBee Protocol
ZigBee protocol is particularly suitable for occasions with low data throughput, low network construction investment, high network security requirements, and inconvenient to frequently replace batteries or charge. It is expected to be widely used in consumer electronic devices, home intelligence, industrial control, medical equipment control, agricultural automation and wireless ordering systems. Consumer electronics
and home intelligence will be the most promising markets for ZigBee technology. Home devices that can be connected to the Internet include TVs, video recorders, PC peripherals, children's toys, game consoles, access control systems, windows and curtains, lighting equipment, air conditioning equipment and other household appliances. The introduction of ZigBee protocol to household devices will greatly improve people's living environment and comfort.
In the field of industrial control, the use of sensors and ZigBee networks can make automatic data collection, analysis and processing easier; it can be used as an important part of decision-making support systems, such as the detection of hazardous chemical components, early detection and prediction of fire alarms, and detection and maintenance of high-speed rotating machines. These applications do not require high data throughput and continuous status updates, and focus on low power consumption, which can maximize battery life and reduce the maintenance cost of ZigBee networks.
In the medical field, sensors and ZigBee networks can accurately and in real time monitor each patient's blood pressure, heart rate, etc., which helps doctors respond quickly and reduces the workload of doctors' ward rounds. It is particularly suitable for monitoring and treating seriously ill and critically ill patients.
In modern agriculture, sensors can transmit soil temperature, nitrogen concentration, pH value, precipitation, temperature, air pressure and the geographical location of the collected information to the central control part via the ZigBee network, so that farmers can find problems early and accurately, which helps to maintain and increase crop yields and reduce the probability of disasters.
This system uses the ZigBee protocol for the wireless ordering system of restaurants, which can improve the grade of restaurants, improve efficiency, automatically check out, avoid human errors, avoid running orders, monitor the status of restaurants in real time, provide various statistical information, streamline staff, manage inventory, improve service quality, etc., bringing new management concepts and service methods to the catering industry, optimizing business processes, providing better services to customers, maximizing corporate value while minimizing costs, and is an important symbol of the development of the catering industry towards informatization.

2.3 Chips based on ZigBee protocol[1][4][5]

When the ZigBee Alliance was founded in August 2002, Honeywell, Invensys, Mitsubishi Electric, Motorola and Philips, and other internationally renowned companies, were supporters of the ZigBee protocol. At present, ZigBee has attracted hundreds of chip R&D companies and wireless equipment manufacturing companies, and new companies are constantly joining the alliance. Now many companies in the world produce chips based on the ZigBee protocol, and the integration of chips is getting higher and higher. For example, the nRF series chips of Nordic in Norway, and the wireless data transmission chips of Chipcon. The chip principles of each company are basically the same, and the programming rules are roughly the same. Therefore, Nordic's nRF2401 is selected. The characteristics of the nRF2401 chip are described in detail below. The
nRF2401 wireless transceiver chip, like Bluetooth, works in the 2.4GHZ free frequency band and can be unimpeded in the global wireless market. nRF2401 supports multi-point communication, with a maximum transmission rate of more than 1Mbit/s, and has a higher transmission speed than Bluetooth. It is designed using the SOC method, and only a small number of peripheral components are needed to form a radio frequency transceiver circuit. Unlike Bluetooth, nRF2401 does not have a complex communication protocol. It is completely transparent to the user, and the same products can communicate freely. More importantly, nRF2401 is cheaper than Bluetooth products. Therefore, nRF2401 is the industry's smallest, lowest power, and lowest peripheral component low-cost radio frequency system-level chip.
The pinout of nRF2401 is shown in Figure 2.2 (top view). It uses a 5mm×5mm 24-pin QFN package. The main features of nRF2401 are as follows:
Figure 2.2 Pinout of nRF2401

(1) It uses the globally open 2.4 GHZ frequency band with 125 channels to meet the needs of multi-frequency and frequency hopping.
(2) The speed (1 Mbps) is higher than Bluetooth and has high data throughput.
(3) There are very few peripheral components. Only a crystal oscillator and a resistor are needed to design the RF circuit.
(4) All operating parameters such as transmission power and operating frequency can be set by software.
(5) The power supply voltage range is 1.9-3.6 V, and the power consumption is very low.
(6) The current consumption is very small. The typical peak current at -5 dBm output power is 10.5 mA.
(7) A dedicated voltage regulator circuit is set inside the chip. Therefore, any power supply (including DC/DC switching power supply) can achieve good communication effect.
(8) Each chip can set a maximum of 40 bits of address through software, and data will only be output when the local address is received (providing an interrupt indication). It is also very convenient to program.
(9) It has a built-in CRC (Cyclic Redundancy Check) [16] error correction hardware circuit and protocol.
(10) Using DuoCever technology, data from two nRF2401s can be received simultaneously;
(11) When using ShockBurst TM mode, it can be used for extremely low power operation and non-strict MCU execution;
(12) No external SAW filter is required;
(13) 100% RF inspection is possible;
(14) With data time slot and data clock recovery functions.
The internal structure principle and external component block diagram of nRF2401 are shown in Figure 2.3. The working principle is introduced below.

Figure 2.3 Internal structure principle and external composition block diagram of nRF2401

1 ShockBurst TM[16] Mode
The ShockBurst TM mode of nRF2401 uses the on-chip FIFO (First-In First-Out) to perform low data rate clock synchronization and high data rate transmission, thereby greatly reducing power consumption.
ShockBurst TM transmission is mainly completed through the MCU interface pins CE, CLK1 and DATA. When the MCU requests to send data, CE is set to a high level. At this time, the receiver address and payload data are used as the internal clock of nRF2401. The rate can be adjusted to 1Mbps by the request protocol or MCU; setting CE to a low level can activate ShockBurst TM transmission.
ShockBurst TM reception is mainly implemented using the MCU interface pins CE, DR1, CLK1, and DATA. After the address and size of the RF packet input payload are correctly set, setting CE to a high level can activate RX. After that, the nRF2401 can monitor the information input for 200μs. If a valid data packet is received, an interrupt is given to the MCU and DR1 is set to a high level, so that the MCU outputs the effective load data in the form of a clock. After the system receives all the data, nRF2401 sets DR1 to a low level. At this time, if CE remains high, it waits for a new data packet. If CE is set to a low level, it starts receiving a new sequence.
The DuoCeiver TM[17] technology of nRF2401 provides two independent dedicated digital channels for RX, which can replace two separate receiving systems. Figure 4 shows the structure diagram of the DuoCeiver TM simultaneous dual receiving channel. nRF2401 can receive data from two 1Mbps receivers separated by 8MHZ through an antenna interface. At the same time, the output of the two digital channels is fed back to two separate MCU interfaces. The specific two channels are as follows:
Figure 2.4 DuoCeiver TM simultaneous dual receiving channel structure diagram

Digital channel 1: CLK1, DATA, DR1;
digital channel 2: CLK2, DOUT2, DR2;
It should be noted that normal reception can only be guaranteed when the frequency of digital channel 2 is 8MHZ higher than that of digital channel 1.

Chapter 3 Design and Implementation of Hardware System Based on ZigBee Protocol
At present, the 51 series single-chip microcomputer is very popular and has a lot of information. Therefore, the 51 series single-chip microcomputer is selected as the MCU of the development board. After adding certain peripheral circuits, it communicates with the wireless data transmission module to realize wireless data transmission.

3.1 Overview of STC89C58RD+[10] MCU

STC89C58RD+ series MCU is a new generation of super anti-interference, high-speed, low-power MCU launched by Hongjing Technology. The instruction code is fully compatible with the traditional 8051 MCU. 12 clocks/machine cycle and 6 clocks/machine cycle can be selected at will.
It has the following features:
1. Enhanced 6 clocks/machine cycle, 12 clocks/machine cycle 8051 CPU (Central Process Unit).
2. Working voltage: 5.5V - 3.4V (5V MCU)
3. Working frequency range: 0 - 40 MHz, equivalent to 0 ~ 80MHz of ordinary 8051. The actual working frequency can reach 48MHz.
4. 32K bytes of user application space
5. 1280 bytes of RAM (Random Access Memory) integrated on chip.
6. There are 32 general I/O ports. After reset, P1/P2/P3 are quasi-bidirectional ports/weak pull-up (common 8051 traditional I/O ports). P0 is an open-drain output. When used as a bus extension, a pull-up resistor is not required. When used as an I/O port, a pull-up resistor is required.
7. ISP (In System Programmable) / IAP (In Application Programmable), no special programmer / emulator is required. User programs can be downloaded directly through the serial port (P3.0 / P3.1). 8K program can be completed in 3 seconds.
8. EEPROM function
9. Watchdog
10. A total of 3 16-bit timers / counters, of which timer 0 can also be used as 2 8-bit timers
11. 4 external interrupts, falling edge interrupts or low-level trigger interrupts, Power Down mode can be awakened by external interrupt low-level trigger interrupts
12. Universal UART (Universal Asynchronous Receiver / Transmitter, universal serial interface), multiple UARTs can also be implemented using timer software
14. Operating temperature range: 0 - 75℃ / -40 - +85℃
15. Package: PDIP-40, PLCC-44, PQFP-44
The biggest advantage of using this microcontroller as a development board is that it supports ISP, so there is no need to buy expensive programmers / emulators, and online programming can be achieved directly through the serial port line. Moreover, the watchdog and Flash are integrated inside, which simplifies the production of PCB boards. The instruction code is compatible with 51 single-chip microcomputers, so the driver can be developed with the commonly used 51 single-chip microcomputer software development tools.

3.2 Schematic diagram and functions of each component of the development board

The entire development board is composed of a single-chip microcomputer minimum system and some of its peripheral circuits. The single-chip microcomputer minimum system serves as the control center of the entire development board, controlling the coordinated work of various peripheral circuits to complete the functions of the system design. The schematic diagram of the entire system is shown in Appendix 2. The principles of each component and the functions they implement are described in detail below. The schematic diagram was drawn by Protel 99SE[18][19].
3.2.1 Circuit of the single-chip microcomputer minimum system[page]

The single-chip minimum system is the control center of the entire development board. It consists of a power supply, a reset circuit, and a crystal oscillator. The power supply is 5V and the crystal oscillator is 12MHZ. For the convenience of debugging, P0.4-P0.7 are connected to the light-emitting tube, and the light-emitting tube is connected to a common anode. This is because all I/O ports are high level when the development board is first powered on or reset. Since no external memory is used, EA is connected to a high level. In order to facilitate debugging and reduce costs, USB (Universial Serial Bus) is used for power supply. The plug-and-play feature of USB makes it very convenient to power the development board. Figure 3.1 shows the single-chip minimum system.
Figure 3.1 Single-chip minimum system
3.2.2 Serial port level conversion part
Most PCs have a serial communication port RS-232 for serial communication between two computers. The RS-232 communication interface is a standardized serial interface, which is a physical interface defined for DTE (Data Terminal Equipment) and DCE (Data Communication Equipment). RS-232 uses an unbalanced connection (also known as a single-ended line). In this line, the signal voltage is added to a wire, and all signal voltages use a common ground line. In order to improve the anti-interference ability and increase the transmission distance, the signal and level of each pin of RS-232 are specified to use negative logic levels, DC (-15-5V) is specified as logic "1", DC (+ 5-+15V) is specified as logic "0", and DC (-5-+5V is specified as a transition zone). Since the input and output levels of the microcontroller are TTL levels, which are inconsistent with the electrical specifications of the RS-232 standard serial interface of the PC, level conversion must be performed to realize data reading between the microcontroller and the PC. The selected level conversion chip is MAX232, and its operating voltage is +5V, which is the same as the working power supply of the microcontroller.
Since the STC89C58RD+ microcontroller supports ISP download, this serial port can be used to communicate with the PC and download programs to the microcontroller without purchasing an expensive programmer. Figure 3.2 shows the serial port level conversion part.
Figure 3.2 Serial port level conversion part
3.2.3 LED part
Since the output of each pin is high level after the microcontroller is reset, a common cathode LED digital tube is selected. The enable terminal com1, com2, com3, and com4 of each digital tube are connected to P1.0, P1.1, P1.2, and P1.3 respectively. When a low level is output to the enable terminal, the corresponding digital tube can be selected. 74LS244 is an eight-group buffer and bus driver with three-state output. The selected four-bit eight-segment digital tube has an integrated decoder, which simplifies the connection of the line and reduces the probability of errors. Figure 3.3 is the LED part.
Figure 3.3 LED part

3.2.4 Development board and wireless data transmission module interface
This part consists of two parts: Since the operating voltage of nRF2401 is 1.9V-3.6V, the chip will be burned if the operating voltage exceeds 3.6V. The power supply of the development board is 5V, so in order for the system to work, there must be a part that converts the 5V level to the 3.3V level. In order to achieve this process, LM1117-MAX3.3 is selected as the core chip. LM1117 is a low-dropout voltage regulator series with a dropout of 1.2V output and 1.2V when the load current is 800mA. LM1117 provides current limiting and thermal protection, and the circuit contains a Zener-regulated bandgap reference voltage to ensure that the output voltage accuracy is within ±1%. The LM1117 series has LLP, TO-263, SOT-223, TO-220 and TO-252 D-PAK packages; in addition, in order to connect the two modules directly, some pins of the P2 port are brought together with a pin header, and the pin header spacing is 100mil, standard DIP pin. Figure 3.4 is the interface between the development board and the wireless
data transmission module, and Figure 3.5 is the 5V level conversion to 3.3V level. Figure 3.4 Development board and wireless data transmission module interface
Figure 3.5 5V level conversion to 3.3V level

3.2.5 Keyboard part
Figure 3.6 Keyboard part

The keyboard part is used to realize human-computer communication. It consists of four key switches, namely S5 (P3.3/INT1), S6 (P3.4/T0), S7 (P3.5/T0), S5 (P3.2/INT0), which are all high level under normal circumstances. When the key is pressed, the output is low level. Since the composition of the four keyboards is the same, only the circuit diagram of S5 is drawn here. Figure 3.6 is the keyboard part.

3.3 Wireless Data Transmission Module

After careful comparison and repeated arguments, it was decided to use the nRF2401 chip as the core chip of the wireless module. Its characteristics have been discussed in detail in the previous chapter and will not be repeated here. The typical application circuit of the nRF2401 chip is shown in Figure 3.7.

Figure 3.7 Typical application circuit of nRF2401 chip
As can be seen from Figure 11, only a few peripheral circuits are needed to form a wireless data transmission module.
Its interface circuit with the development board is shown in Figure 3.8.
The requirements of each interface are as follows:
(1) The voltage range of the VCC pin is between 1.9V and 3.6V. It cannot be outside this range. Exceeding 3.6V will burn the module. The recommended voltage is about 3.3V.
(2) Except for the power supply VCC and the ground terminal, the remaining pins can be directly connected to the ordinary 5V microcontroller IO port without level conversion. Of course, it is more suitable for microcontrollers of about 3V.
(3) Microcontrollers without SPI hardware can also control this module. Using ordinary microcontroller IO ports to simulate SPI does not require the intervention of the microcontroller's real serial port. Only ordinary microcontroller IO ports are needed. Of course, serial ports can also be used.
(4) Pins 6 and 12 are ground pins and need to be connected to the logical ground of the development board.
Figure 3.8 Interface circuit of wireless data transmission module and development board

3.4 PCB design of wireless data transmission module and development board

PCB is a piece of insulating material. Various electronic components are placed on the surface reasonably, and copper film wires are arranged to connect the pins of electronic components. There are copper guide holes connecting different surfaces between different surfaces.
With the continuous development and progress of electronic technology, PCB has made great progress in complexity and application scope. According to the complexity, PCB can be divided into 3 categories: 1. Single-sided printed circuit board; 2. Double-sided printed circuit board; 3. Multi-layer printed circuit board. In order to facilitate wiring, the development board and wireless data transmission module used in this system are both double-layer printed circuit boards.
The generation of PCB mainly consists of four processes: the first is the generation of schematic diagram; the second is to generate the corresponding network table according to the generated schematic diagram. The network table is the link between the PCB diagram and the schematic diagram; the third step is to create a new PCB file and import the network table; the fourth step is to reasonably layout the components and connect the pins of the components with wires.
3.4.1 PCB diagram of the development board
Generate the corresponding PCB diagram according to the above steps based on the schematic diagram of the development board. As shown in Figure 3.9:
In all the processes of PCB diagram design, the schematic diagram has been generated in the previous section. The generation of the network table is also relatively simple. Since the PCB diagram uses the component package to represent the component, each component in the schematic diagram must have its own package method, and the package library where the package is used must be imported before drawing the PCB diagram. Otherwise, the error of component missing will occur during the process of importing the network table.

Figure 3.9 PCB diagram of the development board

There are two main package libraries used on the development board: Advpcb.ddb and Miscellaneous.ddb. In addition, since there are no corresponding packages for the USB power interface, power switch, keyboard and four-digit eight-segment digital tube, it is necessary to use the component library editor to create new component packages. Figure 3.10 is the keyboard package, Figure 3.11 is the USB package, Figure 3.12 is the switch package, and Figure 3.13 is the four-digit eight-segment digital tube package.

Figure 3.10 Keyboard package Figure 3.11 USB package

Figure 3.12 Switch package Figure 3.13 Four-digit eight-segment digital tube package

The serial number of the pins of each component package must be consistent with the serial number of the pins in the schematic diagram, otherwise there will be an error of missing pins during the adjustment of the network table.
The following focuses on the analysis of the wiring process.
Wiring is an important step in completing product design. It can be said that the previous preparations are all done for it. In the entire PCB, the design process of wiring has the highest limit, the most delicate skills, and the largest workload. The PCB wiring of this system is double-sided wiring, and there are two ways of wiring: automatic wiring and interactive wiring. However, due to the poor effect of automatic wiring, the actual effect is often very different from the expected effect, so all interactive wiring is used. In the wiring process, full consideration is given to how to reduce the mutual interference between component characters.
First, according to the size of the printed circuit board current, try to increase the width of the power line and reduce the loop resistance. Their relationship is: ground line> power line> signal line. At the same time, make the direction of the power line and ground line consistent with the direction of data transmission, which helps to enhance the anti-noise ability. There are particular lines: if conditions permit, never make them thin; high-voltage and high-frequency lines should be round and smooth, without sharp chamfers, and corners should not be right angles.
Due to the double-layer design, vias will inevitably be used. If there are too many vias, the copper deposition process will bury hidden dangers if it is not careful. Therefore, the vias should be minimized in the design. In addition, the power filter/decoupling capacitors should be arranged reasonably: Generally, only a number of power filter/decoupling capacitors are drawn in the schematic diagram, but it is not indicated where they should be connected. In fact, these capacitors are set for switching devices (gate circuits) or other components that need filtering/decoupling. These capacitors should be arranged as close to these components as possible. If they are too far away, they will be useless.
3.4.2 PCB diagram of wireless data transmission module
Since the core chip of the wireless data transmission module works at 2.4GHZ, special attention should be paid to interference control when designing the PCB diagram. When designing the PCB, various electromagnetic interferences must be taken into account, and attention should be paid to adjusting the positions of resistors, capacitors and inductors, especially the positions of capacitors.
The PCB of nRF2401 is a double-layer board. Generally, no components are placed on the bottom layer, and the vacant space on the top layer is covered with copper. These copper covers are connected to the ground of the bottom layer through vias. The power supply of nRF2401 should be separated by capacitors, which is conducive to providing a stable power supply to nRF2401. In the PCB, make as many through holes as possible so that the top and bottom grounds can fully contact. The PCB of nRF2401 module is shown in Figure 3.14.
Figure 3.14 PCB diagram of wireless data transmission module

Chapter 4 Hardware Driver and Serial Port Debugging Tool
The driver is the soul of the hardware circuit. A hardware circuit without a driver is useless. STC89C58RD+ is a 51-type microcontroller. Its driver can be developed just like other 51 microcontroller drivers. The microcontroller software development platform chooses the more popular Keil uVision2, because there is a lot of information about Keil uVision2 software, so it will be easy to get started.
The serial port debugging tool is used to send data from the PC to the microcontroller through the serial port, and the PC receives data sent from the microcontroller. Visual C++ 6.0 is selected to develop the serial port debugging tool. Visual C++ 6.0 is an excellent development tool launched by Microsoft. It has compact code, fast running speed, and is more suitable for low-level development.

4.1 Hardware Drivers

The entire data transmission system consists of two parts: the development board connected to the PC is the host end, which cannot be moved, receives data sent from the slave end, and sends instructions to the slave end; the movable one is the slave end, which consists of the development board and the wireless data transmission module. Due to the different status and functions of the two ends, the corresponding drivers are also different.
Keil uVision2 is used to develop hardware drivers. It supports chips of MCS51 architecture from many different companies. It integrates editing, compiling, simulation, etc. It also supports PLM, assembly and C language programming. Its interface is similar to the commonly used Microsoft VC++ interface. It has a friendly interface, is easy to learn and use, and has powerful functions in debugging programs and software simulation. Therefore, many engineers who develop 51 applications or ordinary single-chip microcomputer enthusiasts like it very much. There are two commonly used programming languages ​​for 51, one is assembly language and the other is C language. The machine code generation efficiency of assembly language is very high, but the readability is not strong. A more complex program is even more difficult to understand. In most cases, the machine code generation efficiency of C language is comparable to that of assembly language, but its readability and portability far exceed that of assembly language. In addition, C language can be embedded in assembly to solve the problem of high-efficiency code writing. For the development cycle, the development cycle of medium and large software writing using C language is usually much shorter than that of assembly language. Considering the advantages of C language above, C51 language was selected during development.
4.1.1 Host-side hardware driver
The host-side hardware driver has two main functions: to enable the development board to communicate with the PC through the serial port; to enable the development board to communicate with the wireless data transmission module through certain I/O ports.
The serial port of the STC89C58RD+ microcontroller is a full-duplex communication interface, which can send and receive at the same time. It can be used as a UART or a synchronous shift register. Its frame format and baud rate can be set through software programming, which is very convenient to use.
The working mode and baud rate of the serial port of the STC89C58RD+ microcontroller are composed of the control register SCON and the special function register PCON.
Serial port control register SCON:

D7 D6 D5 D4 D3 D2 D1 D0
SM0 SM1 SM2 REN TB8 RB8 TI RI

Special function register PCON:

D7 D6 D5 D4 D3 D2 D1 D0
SMOD

The serial port can be set to four working modes through software. The data format and baud rate of each working mode are different. The four working modes are as follows:
1. Mode 0
When SM1 and SM0 are set to 00, the serial port works in mode 0. In mode 0, RXD is the data input/output terminal, TXD is the synchronous pulse output terminal, and the data sent or received is 8 bits, with the low bit first and the high bit last. The baud rate of mode 0 is fixed at 1/12 of the oscillation frequency, that is, one bit of data is transmitted in each machine cycle. Mode 0 can be connected to an external shift register to expand the serial port to a parallel port, or it can be connected to an external synchronous input/output device. After sending, the hardware automatically sets TI to 1. Before sending data again, the software needs to clear the TI bit to 0.
When REN is 1, the microcontroller allows receiving data. RXD is the data receiving terminal, and the received data is saved in the SBUF receiving buffer. After sending, the hardware automatically sets RI to 1. Before receiving data again, the software needs to clear RI to 0.
2. Mode 1
When SM1 and SM0 are set to 01, the serial port works in mode 1. Mode 1 is an 8-bit asynchronous communication mode with variable baud rate, which is sent by TXD and received by RXD. One frame of data is 10 bits, 1 start bit (low level), 8 data bits (low bit first) and 1 stop bit (high level). The baud rate depends on the T overflow rate of the timer (1/overflow cycle) and the baud rate selection bit SMOD.
3. Mode 2 and Mode 3
When SM0 and SM1 are set to 10 or 11, the serial port works in mode 2 or mode 3. Both modes are 9-bit asynchronous communication, only the baud rate is different, and they are suitable for multi-machine communication. In mode 2 or mode 3, data is sent by TXD and received by RXD. One frame of data is 11 bits, 1 start bit (low level), 8 data bits (low bit first), 1 programmable bit (9th data bit, used for parity or address/data selection), and 1 stop bit (high level). Compared with mode 1, there is one more programmable bit. When sending, the 9th bit of data is TB8, and when receiving, the 9th bit of data is sent to RB8.
Through the comparison of various working modes of the microcontroller serial port above, since a development board and a PC are used for separate communication, working mode 1 is more suitable for the system requirements. By setting the appropriate baud rate and frame format, accurate data transmission between the development board and the PC can be achieved.
Due to the different processing speeds of the PC and the microcontroller, when the PC sends data to the development board, the microcontroller uses an interrupt to receive data. The transmission attribute parameters of the microcontroller are set to "9600, N, 8, 1" through software to achieve synchronization with the serial port transmission rate of the PC. When the development board sends data to the PC, the query method is used, which can save the limited resources of the microcontroller.
The development board also exchanges data with the wireless data transmission module through a special interface. Since the system is designed for point-to-point communication, only one channel of nRF2401 is used. The data transmission mode of nRF2401 is synchronous transmission, so the ordinary I/O port is used to simulate the SPI transmission through software.
nRF2401 has four working modes: transceiver mode, configuration mode, idle mode and shutdown mode[16][17]. The working mode is determined by the three pins PWR_UP, CE, TX_EN and CS, see Table 4.1 for details.

Table 4.1 Setting methods of various working modes of nRF2401
Working mode PWR_UP CE CS
Transceiver mode 1 1 0
Configuration mode 1 0 1
Idle mode 1 0 0
Shutdown mode 0 * *

The previous article has discussed the transceiver mode of nRF2401. Here we will focus on its configuration mode. All configuration work of nRF2401 is completed through the three pins CS, CLK1 and DATA. It takes 15 bytes of configuration words to configure it to ShockBurstTM transceiver mode. The configuration word
of ShockBurstTM can be divided into the following four parts:
(1) Data width: declares the number of bits occupied by the data in the RF data packet. This enables nRF2401 to distinguish between the data and CRC checksum in the received data packet;
(2) Address width: declares the number of bits occupied by the address in the RF data packet. This enables nRF2401 to distinguish between address and data;
(3) Address: The address of the received data, including the address of channel 1 and the address of channel 2;
(4) CRC: enables nRF2401 to generate CRC checksum and decoding.
The configuration word of nRF2401 is shown in Table 4.2:
In configuration mode, keep the PWR_UP pin high and the CE pin low, and write the configuration word to nRF2401 in sequence starting from the highest bit. At the falling edge of the CS pin, the newly input configuration word starts to work.
Table 4.2 Configuration word of nRF2401
Bit Bit Name Function
Shockb
Brst T
M Configuration 143: 120 24 TEST Reserved
119: 112 8 DATA2_W Receive channel 2 valid data length
111: 104 8 DATA1_W Receive channel 1 valid data length
103: 64 40 ADDR2 Receive channel 2 address, up to 5 bytes
63: 24 40 ADDR1 Receive channel 1 address, up to 5 bytes
23: 18 6 ADDR_W Receive channel address bit number
17 1 CRC_L 8-bit or 16-bit CRC check
16 1 CRC_EN Enable CRC check
Common device configuration 15 1 RX2_EN Enable the second channel
14 1 CM Communication mode setting
13 1 RFDR_SB Transmit data rate
12: 10 3 XO_F Crystal oscillator frequency
9: 8 2 RF_PWR Transmitter output power
7: 1 7 RF_CH# Channel setting
0 1 RX_EN Receive or send operation
The flow chart of the development board exchanging data with the PC through the serial port is as follows:
Figure 4.1 Flow chart of the development board exchanging data with the PC through the serial port
The flow chart of the development board exchanging data with the wireless data transmission module through the IO port is Figure 4.2.

Figure 4.2 Flowchart of data exchange between the development board and the wireless data transmission module through the IO port

4.1.2 Mobile Driver
The structure of the mobile development board is exactly the same as that of the PC development board, but it does not need to communicate with the PC, but only needs to communicate with the wireless data transmission module. Therefore, the driver is simpler than the other end. The specific programming rules have been described in detail in the previous section, so I will not go into details here. The specific program is part of the PC program.

4.2 Serial port debugging tool

The serial port debugging tool was developed using Microsoft Visual C++ 6.0[20][21]. Almost all world-class software, from industry-leading web browsers to task-oriented enterprise applications, are developed using the Microsoft Visual C++ development system. Visual C++ is the most efficient tool of choice for developing high-performance applications on Windows and the Web using C++. Visual C++ 6.0 brings a higher level of productivity to C++ without sacrificing flexibility, performance, and control. It has a visual interface and encapsulates a large number of classes, making interface creation very simple. It can be used to quickly and easily develop applications in the Windows environment. Visual C++ 6.0 provides the Mscomm[20][21] control specifically for serial port communication. Using this control, programmers do not have to spend time understanding more complex API functions. By simply modifying the properties of the control and using the methods provided by the control, they can configure the serial port and complete the sending and receiving of serial port data.
4.2.1 Basic principles of serial communication
The essential function of the serial port is to act as a code converter between the CPU and the serial device. When data is sent from the CPU through the serial port, the byte data is converted into serial bits. When receiving data, the serial bits are converted into byte data. In the Windows environment, the serial port is part of the system resources. If an application wants to use the serial port for communication, it must submit a resource request to the operating system before using it (open the serial port), and must release the resources (close the serial port) after the communication is completed. Serial port communication programs under 32 bits can be implemented in two ways: using ActiveX controls; using API communication functions. In this course design, the MSComm control of MFC is used. The following is a brief introduction to this key control.
Microsoft Communications Control (hereinafter referred to as MSComm) is an ActiveX control provided by Microsoft to simplify serial communication programming under Windows. It provides serial communication functions for applications and provides applications with a simple way to send and receive data through a serial interface. The MSComm control is very convenient when programming serial ports. It actually calls API functions, but we don’t have to understand complex API functions to control serial communication. The communication process is actually the operation of properties and the response to control events.
In the Windows operating system, serial communication uses the "event notification" method to support data transmission in blocks. When communicating, Windows opens a user-defined input and output buffer. Each time a character is received, a low-level hardware interrupt is generated. The serial driver immediately takes control and puts the character into the input data buffer, and then returns control to the running application. If the input data buffer is full, the driver uses the currently defined flow control mechanism to notify the sender to stop sending data. Sending data also uses a similar processing method. The application puts the data to be sent into the output data buffer, and each time the serial port sends a character, a low-level hardware interrupt is generated.
Visual C++ 6.0 communication control Mscomm provides a full-featured serial port data sending and receiving function. The Mscomm control has two processing methods: one is event-driven method, and the other is query method.
1) Event-driven method. When a communication event occurs, the MSCOMM control triggers the OnComm event. The caller can capture the event and confirm what kind of event or error occurred by checking its CommEvent property, so as to perform corresponding processing. The advantages of this method are timely response and high reliability.
2) Query method. After each key function of the program, events and errors can be queried by checking the value of the CommEvent property. If the application is small, this approach may be preferable. For example, if you write a simple phone dialer, there is no need to generate an event for each character received, because the only character waiting to be received is the "OK" response from the modem.
When using the MSCOMM control, one MSCOMM control can only correspond to one serial port at a time. If the application needs to access and control multiple serial ports, multiple MSCOMM controls must be used.
In VC++, the MSCOMM control only corresponds to one C++ class - CMSComm. Since the MSCOMM control itself does not provide methods, the CMSComm class, except for the Create() member function, all other functions are Get/Set function pairs used to get or set the properties of the control. The MSCOMM control also has only one OnComm event, which is used to notify the caller that a communication event has occurred.
The MSCOMM control has many important properties, but due to space limitations, only a few of the more important and commonly used properties are given.

Table 4.3 Important properties of the MSCOMM control Property
Description
CommPort Communication port number
Settings Baud rate, parity, data bits expressed in string form
PortOpen The state of the communication port, open or closed
Input Receive data
Output Send data
InputMode The type of received data: 0 is text; 1 is binary

Table 4.4 All controls used in the program, and their IDs
Control ID Title
Button ID_SEND Send
Button ID_CLEAR Clear
Edit box IDC_EDIT_SEND
Edit box IDC_EDIT_RCV
Static text IDC_STATIC Receive buffer
Static text IDC_STATIC Send buffer
Group box IDC_STATIC Port selection
Radio button IDC_1 Port 1
Radio button IDC_2 Port 2
mscomm IDC_MSCOMM

Table 4.5 Used variables and their types
Control IDS Type Member
IDC_EDIT_SEND CString m_str_send
IDC_EDIT_RCV CString m_str_recv
IDC_MSCOMM CMSComm m_mscomm

Object IDS Messages Function
ID_SEND BN_CLICKED OnSend
ID_CLEAR BN_CLICKED OnClr
IDC_1 BN_CLICKED On_Com1
IDC_2 BN_CLICKED On_Com2
IDC_MSComm OnComm OnComm

4.2.2 Programming principles
Step 1: Initialize the serial port. Call the SetCommPort() function, select the port to be used, then set the baud rate, the processing method for sending and receiving, and the data transmission method, and finally open the serial port.
Step 2: Send data. After converting the string to be sent into a specific type, call the SetOutput() function to send the data to the send buffer
Step 3: Receive data. Read the data in the receive buffer through the GetInput() function, convert it to the Cstring type, and display it on the interface.
The main parts of the program and some flow charts:
(1) After logging into the interface, the program first clears the receive buffer and the send buffer The
program is as follows:
m_str_send=" ";
m_str_recv=" ";
UpdateData(FALSE);
(2) Then initialize the serial port, that is, set the various properties of the MSComm control. First, we need to select the port. Since the computer used has only two serial ports, this program only gives two options. The specific program code is as follows:
void CMyDlg::On_Com1()
{
if(m_mscomm.GetPortOpen())
m_mscomm.SetPortOpen(FALSE);
m_mscomm.SetCommPort(1);
m_mscomm.SetSettings(”9600,n,8,1″);
m_mscomm.SetRThreshold(1);
m_mscomm.SetSThreshold(0);
m_mscomm.SetInputLen(0);
m_mscomm.SetInputMode(1);
m_mscomm.SetPortOpen(TRUE);
}
void CMyDlg::On_Com2()
{
if(m_mscomm.GetPortOpen())
m_mscomm.SetPortOpen(FALSE);
m_mscomm.SetCommPort(2);
m_mscomm.SetSettings(”9600,n,8,1″);
m_mscomm.SetRThreshold(1);
m_mscomm.SetSThreshold(0);
m_mscomm.SetInputLen(0);
m_mscomm.SetInputMode(1);
m_mscomm.SetPortOpen(TRUE);
}
1) CommPort: Select 1 and 2 respectively.
2) Setting sets or returns the baud rate of the serial port: 9600, no parity bit, 8 data bits, 1 stop bit.
3) InBufferSize: Set the receive buffer to 1024 bytes.
4) RThreshold: Set that when the number of bytes in the receive buffer is 1, the OnComm event of MSCOMM is triggered, and then the computer reads the data in the receive buffer and clears the receive buffer.
5) InputLen: The value is 0, set INPUT to read the contents of the entire buffer.
6) OutBufferSize: Set the send buffer to 512 bytes.
(3) Source code for sending data
void CMyDlg::OnSend()
{
if(!m_mscomm.GetPortOpen())
m_mscomm.SetPortOpen(TRUE);
UpdateData(TRUE);
m_mscomm.SetOutput(COleVariant(m_str_send)); //Send data
}
Send the string in the text box to the variable m_str_send, then convert the characters into ColeVariant type data, and then send the data to the send buffer through the SetOutput function.
(4) Source program code for receiving data
void CMyDlg::OnComm()
{
VARIANT variant_tmp;
COleSafeArray safearray_tmp;
LONG len,i;
BYTE buf[2048];
CString str_tmp;
if(m_mscomm.GetCommEvent()==2)
{
variant_tmp=m_mscomm.GetInput();
safearray_tmp=variant_tmp;
len =safearray_tmp.GetOneDimSize();
for(i=0;i safearray_tmp.GetElement(&i,buf+i);
for(i=0;i {
BYTE ch=*(char*)(buf+i);
str_tmp.Format(”%c”,ch);
m_str_recv+=str_tmp;
}
}
UpdateData(FALSE);
}
When m_mscomm.GetCommEvent()==2, data arrives, triggering the OnComm event and calling this function. First, read the data in the receiving buffer into the variable variant_tmp through m_mscomm.GetInput(), and then assign variant_tmp to safearray_tmp to realize the data type conversion to ColeSafeArray. Calculate the total length of the received characters through safearray_tmp.GetOneDimSize(), then convert each ColeSafeArray variable into a Byte type variable, and finally convert it into a character type and display it in the text box.
Flowchart of void CMyDlg::OnComm():

Figure 4.3 Flowchart of void CMyDlg::OnComm()

(5) Clear function source code
void CMyDlg::OnClr()
{
m_str_send=” “;
m_str_recv=” “;
UpdateData(FALSE);
}
The overall program flow chart is shown in Figure 4.4
Figure 4.5 is the graphical interface when the PC sends data to the microcontroller through port 1. After entering the interface, you must first select the port to be initialized according to the connected serial port, and then use the keyboard to enter a series of characters in the send buffer. After the microcontroller development board is powered on, click the send button to send the data out.
Figure 4.6 is the graphical interface when the PC receives data sent by the microcontroller through the serial port. The data received in the buffer is in binary form, and the program has converted these binary into strings and displayed on the interface.
Figure 4.7 is the graphical interface of the serial port debugging tool when it is initially running.
In the event-driven mode, it is directly managed by the computer, and the bytes cannot be controlled. In addition, the speed of the microcontroller serial port and the PC serial port is quite different. The receiving program must be carefully and reasonably designed to make the transmission stable and reliable, otherwise unexpected problems are likely to occur. During debugging, if you accidentally set the baud rate of the serial port debugging tool to be different from the baud rate of the development board serial port, an error will occur. The baud rate of the serial port has been set to 9600bps in the program to avoid errors.
Figure 4.5 Graphical interface when sending through port 1

Figure 4.6 Graphical interface when receiving through the serial port
Figure 4.7 Running interface of the serial port debugging tool
Chapter 5 Summary and Outlook
5.1 Summary of the whole article

Through this graduation project, I learned a lot of knowledge that is not in the textbooks, and also exercised my hands-on ability, stringing together the scattered knowledge I had learned before.
First of all, in the initial research stage of the graduation project, I learned how to query relevant information in various ways. Through the study of these materials, I have a general understanding of the current development status and future development trends of wireless communication, and I have realized the various protocols in wireless communication and the competition between them. I have learned about the advanced technologies in wireless communication, which have pointed out the direction for my future study.
My graduation project mainly involves two aspects: hardware and software. Through these, my hardware and software development capabilities have been improved. First of all, in terms of hardware, I have a basic understanding of the development process and work to be done for electronic products. I have basically mastered the methods of designing schematics and simple PCB diagrams with Protel 99 SE, and designed a single-chip minimum system. Through the design of the development board and the process of hardware construction, I have a deeper understanding of the interface of the 51 series single-chip microcomputer, and I am familiar with the pins and connection methods of some commonly used peripheral circuits of single-chip microcomputers, such as LED digital tubes, keyboards, etc.
In terms of software, through the development of serial port debugging tools, I have basically mastered the use of Visual C++ 6.0 and deepened my understanding of class encapsulation. Through the development of the development board driver, I have mastered Keil uVision2, and am familiar with the registers and programming rules inside the 51 series microcontrollers, as well as how to control peripheral circuits.
Of course, due to the limitations of the microcontroller's functions, when facing a very complex system like the wireless ordering system, the microcontroller is not very suitable. This is because the microcontroller has too few pins, the operating system that can be used is too simple, and it cannot perform complex work scheduling, nor can it drive complex peripheral circuits. Therefore, it is difficult to use a microcontroller to fully realize the requirements of the ordering system.
In recent years, processors have developed to 32-bit machines, especially 32-bit processors with ARM (Advanced RISC Machines) as the core, which are favored by more and more embedded developers. ARM processors support complex embedded operating systems, such as Win CE, UClinux, etc. It can perform complex function scheduling and can drive relatively complex peripheral circuits such as touch screens. In this way, the use of ARM processors and embedded operating systems, combined with embedded mobile database technology, can better meet the requirements of the ordering system. Therefore, the graduation project also pointed out a direction for my future study.
As far as this paper is concerned, the main work completed is as follows:
1. Based on the ZigBee protocol, the 51 series single-chip microcomputer is used as the processor, and a certain peripheral circuit is used to build a hardware development platform.
2. The driver is written for the hardware part using C51 language, and the serial port debugging tool is developed using Visual C++6.0.

5.2 Research Prospects

At present, various wireless communication technologies are flourishing. However, with the development of economy and the improvement of people's needs, wireless communication technology still has a lot of room for development. There is still a long way to go in the following aspects.
1 With the development of IP (Internet Protocol) technology, wireless communication network and IP network have a trend of integration. In particular, the increase in demand for multimedia information and the low real-time requirements of multimedia information make the use of wireless communication network to transmit multimedia information a hot topic.
2 With the improvement of people's living standards and the change of lifestyle, wireless communication technology will inevitably develop in the direction of mobility and portability.
3 Due to the limited wireless spectrum resources and the particularity of wireless communication transmission channels, how to improve the utilization rate of spectrum resources and improve anti-interference ability will become a very popular research direction in the future.
4 Modern microelectronics technology is developing rapidly, Moore's theorem is still valid, integrated circuit technology has developed to SOC, and 32-bit ARM processors have been widely used. Therefore, in the development of increasingly complex embedded systems in the future, 32-bit processors and embedded operating systems will be more widely used.

Reference address:Hardware design and implementation of wireless electronic ordering system based on single chip microcomputer

Previous article:MB89163 single chip microcomputer and its application in remote control
Next article:Comprehensive design of new concept of single chip microcomputer controlled motorcycle ignition

Recommended ReadingLatest update time:2024-11-16 23:54

MCU+XPT2046+MQ135 indoor air purification system
If you want to transplant this application project to the development board, you only need to modify the pins according to the circuit diagram of this project, and change them to the pins corresponding to the buttons, LCD and buzzer of our development board. The AD chip uses the same one, so you only need to change t
[Microcontroller]
MCU+XPT2046+MQ135 indoor air purification system
Solution to the problem that the UART of STM8S type microcontroller keeps entering the receiving interruption
Problem Description: In a project, the lower computer uses STM8S003F3 as the main chip. When using RS485 to communicate with the upper computer, it will always enter the receiving interrupt and will not receive the correct data from the upper computer at all. Solution process: At first, I thought that the proble
[Microcontroller]
Calculator assembly language based on 51 single chip microcomputer
The calculators we talked about before were all based on C language. Next, let’s talk about a simple calculator based on assembly language. hardware design The display is still a digital tube, and the MCU is C51, which supports integer calculation. Simulation diagram: programming YJ EQU 50H ;Result storage YJ1 E
[Microcontroller]
Calculator assembly language based on 51 single chip microcomputer
Design and implementation of a simple infrared remote control password lock based on single chip microcomputer
0Introduction With the progress of science and technology and the development of social economy, it has become an inevitable trend for electronic password locks to replace traditional mechanical locks. In the past, the password lock system based on single-chip microcomputer directly stored the compiled pass
[Microcontroller]
Design and implementation of a simple infrared remote control password lock based on single chip microcomputer
Simulation Design of Eight-way Answering Machine Based on 51 Single-chip Microcomputer
First, the referee presses the start button on the right, the buzzer sounds, and the quiz begins. The initial time is 20 seconds. If contestants 1-8 press the button, their quiz is successful and the contestant number is displayed on the screen. If no one takes the quiz after the time (20 seconds), the time is reset t
[Microcontroller]
Simulation Design of Eight-way Answering Machine Based on 51 Single-chip Microcomputer
ADS1212 and SST MCU realize high-precision data acquisition design
0 Introduction Data acquisition technology has been widely used in signal processing, communication, process control, remote sensing and telemetry, and the development of various high-tech technologies has further enhanced the accuracy of data acquisition systems. This article introduces a high-precision da
[Microcontroller]
Temperature Control Between Two Points Based on Single Chip Microcomputer
A feedback control system that uses temperature as the controlled quantity. In the physical processes and chemical reactions of production processes such as chemical, petroleum, and metallurgy, temperature is often a very important quantity that needs to be accurately controlled. In addition to these departments, te
[Microcontroller]
Temperature Control Between Two Points Based on Single Chip Microcomputer
A simple design of electronic password lock based on 51 single chip microcomputer
  1 Background and design features of single chip electronic password lock   With the rapid development of high technology today, people have invented various forms of locks, such as password locks, electronic locks and laser locks. Based on traditional keys, these locks use magnetic fields, sound waves and light be
[Microcontroller]
A simple design of electronic password lock based on 51 single chip microcomputer
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

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号