temperature control system

Foreword
With the advent of the "information age", as a means of obtaining information - sensor technology has made significant progress, its application fields are becoming more and more extensive, its requirements are getting higher and higher, and the demand is becoming more and more urgent. Sensor technology has become one of the important symbols to measure the development level of a country's science and technology. Therefore, it is very important to understand and master the basic structure, working principle and characteristics of various sensors.
Because sensors can convert various physical quantities, chemical quantities, and biomass signals into electrical signals, people can use computers to realize automatic measurement, information processing, and automatic control, but they all have influence factors such as temperature drift and nonlinearity to varying degrees. . Sensors are mainly used in measurement and control systems, and their performance directly affects the performance of the system. Therefore, it is necessary not only to master the structure, principle and performance indicators of various sensors, but also to understand that the sensor can meet the requirements of signal processing, display and control through proper interface circuit adjustment, and only through the application of the principle and intelligence of the sensor The analysis and understanding of sensor examples can combine sensors with information communication and information processing to adapt to the production, research, development and application of sensors. On the other hand, the measured signal of the sensor comes from various application fields. In order to reform productivity, improve work efficiency and timeliness, each field is developing sensors suitable for the application, so a wide variety of new sensors and sensor systems continue to emerge. Temperature sensors are one of the most important types of sensors. Its development speed is fast, and its application is wide, and there is still great potential.
In order to improve the knowledge and understanding of sensors, especially the in-depth study of temperature sensors and their use and application, this system is designed based on the principles of practicality, broadness and typicality. In this paper, the temperature monitoring system is developed and designed by using single-chip microcomputer combined with sensor technology. In this paper, the theory of sensors and the practical application of single-chip microcomputers are organically combined, and the process of using thermistors as thermal sensors to detect ambient temperature and the principle process of realizing thermoelectric conversion are described in detail.
This design has strong applicability. The design system can be used as a biological culture fluid temperature monitoring system. If it is slightly modified, it can be used as a water heater temperature adjustment system, a laboratory temperature monitoring system, and so on. The main task of the project is to complete the environmental temperature detection, use the single chip microcomputer to realize the temperature regulation and implement the temperature monitoring through the computer. The designed system has the advantages of convenient operation and flexible control.
The design system includes six parts: temperature sensor, A/D conversion module, output control module, data transmission module, temperature display module and temperature regulation drive circuit. The function and realization process of each part are introduced in detail in this paper. The core of the whole system is to carry out temperature monitoring and complete all the requirements of the project.

1 Design Requirements
1.1 Control Requirements
(1) The temperature of the biological propagation medium should be guaranteed to be within the temperature suitable for cell reproduction, which is mainly considered in the control program design. The temperature control range is 15-25°C, the temperature control accuracy requirement in the heating and cooling stages is 0.5°C, and the temperature control accuracy in the heat preservation stage is 0.5°C.

Figure 1.1.1 Temperature control curve
(2) Microcomputer automatic adjustment Under normal circumstances, the system is automatically put into operation.
(3) Simulate manual operation When an abnormality occurs in the system, it will be put into manual operation.
(4) The microcomputer monitoring function displays the current set value and actual value of the controlled quantity, and the output of the controlled quantity.

1.2 Mathematical model of the controlled object
The culture medium for biological reproduction is mainly used for biological reproduction research, and temperature is an important factor affecting biological reproduction. This system requires monitoring the temperature of the culture medium for a long time and controlling the current temperature. The control object is the culture medium for biological reproduction, which is controlled by a relay.

2 System hardware configuration
2.1 Single-chip microcomputer and system bus
Single-chip microcomputer: PIC16F877A (PIC16F877A is an 8-bit single-chip microcomputer with A/D conversion produced by MICORCHIP Company in the United States).
Display system: commercial computer.
User memory: 256M RAM.
System bus: RS-232-C interface (also known as EIA RS-232-C) RS232 C has 25 lines, divided into 5 functional groups, including 4 data lines, 11 control lines, 3 timing lines, 7 spare lines and undefined lines.
Operating system: Windows 2000.

2.2 Hardware introduction
Peripheral circuit equipment for computer work
(1) Temperature sensor The temperature sensor uses a compensated NTC thermistor
.
The product has good consistency and interchangeability. Suitable for temperature measurement and metering equipment with general accuracy.
②Appearance structure and size:

Figure 2.2.1 Structural Dimensions of Temperature Sensor
③Main Technical Parameters:
Time Constant≤30S  
Measuring Power≤0.1mW
Operating Temperature Range -55~+125℃
Dissipation Coefficient≥6mW/℃
Rated Power 0.5W  
④Power Consumption Curve:

Figure 2.2.2 Temperature sensor power consumption curve
(2) Core processing unit MicroChip PIC16F877A single-chip
microchip PCI16F877A single-chip main performance:
high-performance RISC CPU
only has 35 single-word instructions.
All instructions are single-cycle except for program instructions which are two-cycle.
Operating speed: DC-20M clock input.
DC-200ns instruction cycle.
8K 14 FLASH program memories.
368
8 data memory (RAM) bytes.
Pinout compatible with PIC16C73B/74B/76/77.
Interrupt capability (up to 14 interrupt sources).
8-level deep hardware stack.
Direct, indirect and relative addressing modes.
Power-On Reset (POR).
Power-on timer (PWRT) and shock start timer.
Watchdog Timer (WDT) with on-chip reliable running RC oscillator.
Programmable code protection.
Low power sleep mode.
selectable oscillator.
Low power consumption, high speed CMOS FLASH/EEPROM technology.
Fully static design.
In-Circuit Serial Programming (ICSP).
Separate 5v In-Circuit Serial Programming (ICSP) capability.
Processor read/write access to program memory.
The operating voltage range is 2.0v to 5v.
High input/output current 25mA.
Commercial, industrial temperature range.
Low power consumption:
typical value is less than 2mA at 5v, 4MHz.
Typical value is less than 20uA at 3v, 32KHz.
Typical quiescent current values ​​are less than 1uA.
Peripheral features:
Timer 0: 8-bit timer/counter with prescaler.
Timer 1: 16-bit timer/counter with prescaler,
can still work during SLEEP when using external crystal clock. Timer 2: 8-bit timer/counter 2 captures
with 8-bit period register, prescaler and postscaler , comparator and PWM module. Among them: The catcher is 16 bits, the maximum resolution is 12.5nS. The comparator is 16-bit with a maximum resolution of 200nS. The maximum PWM resolution is 10 bits. 10-bit multi-channel analog-to-digital converter. SSP with SPI (Master mode) and I2C (Master/Slave) modes. Universal Synchronous Asynchronous Receive/Transmit (USART/RCI) with 9-bit address detection. 8-bit parallel slave port with RD, WR and CS controls (40/44 pins only). Reset detection circuit with voltage drop. (3) RS-232-C interface circuit










There are two ways of serial communication and parallel communication for data transmission between computers or between computers and terminals. Because the serial communication method has fewer lines and low cost, especially in long-distance transmission, it avoids the inconsistency of the characteristics of multiple lines and is widely used. In serial communication, both communication parties are required to adopt a standard interface, so that different devices can be easily connected for communication. RS-232-C interface (also known as EIA RS-232-C) is the most commonly used serial communication interface at present. It is a standard for serial communication jointly formulated by the Electronic Industries Association (EIA) in conjunction with Bell System, modem manufacturers and computer terminal manufacturers in 1970. Its full name is "Technical Standard for Serial Binary Data Exchange Interface between Data Terminal Equipment (DTE) and Data Communication Equipment (DCE)", which stipulates that a 25-pin DB25 connector is used, and each pin of the connector The signal content of the pin is specified, and the level of various signals is also specified.
① Signal content of the interface In fact, many of the 25 leads of RS-232-C are rarely used, and generally only 3-9 leads are used in computer communication. The signal of the most commonly used 9 leads of RS-232-C.
②Electrical characteristics of the interface The voltage of any signal line in RS-232-C is a negative logic relationship. Namely: logic. "1", -5~-15V; logic "0" +5~ +15V. Noise margin is 2V. That is, the receiver is required to recognize signals as low as +3V as logic "0" and signals as high as -3V as logic "1".
③ The physical structure of the interface The RS-232-C interface connector generally uses a 25-pin plug socket of the type DB-25, usually the plug is at the DCE end, and the socket is at the DTE end. Some devices are connected to the RS-232-C interface of the PC , because the transmission control signal of the other party is not used, only three interface lines are needed, namely "send data", "receive data" and "signal ground". Therefore, the 9-core socket of DB-9 is adopted, and the transmission line adopts shielded twisted pair.
④The length of the transmission cable is stipulated by the RS-232C standard. When the code element distortion is less than 4%, the transmission cable length should be 50 feet. In fact, this 4% code element distortion is very conservative. In practical applications, there are about 99 % of users work in the range of 10~20% of symbol distortion, so the maximum distance in actual use will be far more than 50 feet.

Figure 2.3.1 Max232 structure diagram
(4) Relay
Relay is an automatic switch with isolation function, which is widely used in remote control, telemetry, communication, automatic control, mechatronics and power electronic equipment, and is one of the most important control components.
The relay is an executive component that plays a role of control and isolation in the automatic control circuit. It is actually an automatic switch that can use low voltage and small current to control high current and high voltage.
In this system, the automatic temperature adjustment circuit controlled by the relay and the program in the PCI16F877A single-chip microcomputer constitute an automatic temperature monitoring circuit to realize the monitoring and automatic control of the temperature of the biological culture
medium The characteristics of thermoelectric effect technology, using special semiconductor material thermopile to cool, can directly convert electric energy into heat energy, with high efficiency. Its working principle is shown in Figure 2.5.1:

Figure 2.5.1 The working principle of the semiconductor cooling sheet
The semiconductor cooling sheet is composed of many N-type and P-type semiconductor particles arranged with each other, and the NPs are connected by common conductors to form a complete circuit, usually copper, aluminum or other The metal conductor is finally sandwiched by two ceramic sheets like sandwich biscuits. The ceramic sheets must be insulated and have good heat conduction. After the power is turned on, the heat from the cold end is moved to the hot end, resulting in a decrease in the temperature of the cold end and an increase in the temperature of the hot end. Its appearance is shown in Figure 2.5.2.

2) This control system monitors the temperature of the biological culture medium, so too fast a temperature change will significantly affect the biological reproduction.

Figure 2.5.2 Appearance of semiconductor cooling sheet
② This control system monitors the temperature of the biological culture solution. Too fast temperature change is obviously unfavorable to biological reproduction. Therefore, high-impedance and low-power heating resistance wire is used in this system. A small range of temperature adjustments is performed.

3 Composition block diagram of the temperature control system
A typical feedback temperature control system is adopted, and the components are shown in Figure 3.1. Among them, the functions of the digital controller are realized by the single-chip microcomputer.

Figure 3.1 Block diagram of the temperature control system

The transfer function of the Petri dish is, where τ1 is the time constant of resistance heating, is the pure lag time of resistance heating, and is the sampling period.
The A/D converter can be classified as a zero-order keeper, so the transfer function of the generalized object is
(3-1-1)

The Z transfer function of the generalized object is
(3-1-2)
, so the closed-loop Z transfer function of the system is
(3-1-3)

The digital controller of the system is

= (3-1-4)
written as a difference equation is

(3-1-5)
order

,
,

(3-1-6)
In the formula - the deviation at the first sampling;
- the deviation at the first sampling;
- the deviation at the first sampling;

4 Structure diagram and overview of temperature control system

                      图4.1温度控制系统结构图

The temperature sensor in Figure 4.1 and the A/D converter in the Micro Chip PIC16F877A microcontroller form an input channel for collecting temperature signals in the petri dish. The temperature sensor output voltage after A/D conversion is compared with the digital value of the given temperature in the petri dish, and then the deviation between the actual temperature and the given temperature can be obtained. The temperature setting value in the petri dish is set by the program in the Micro Chip PIC16F877A single-chip microcomputer. The digital controller composed of Micro Chip PIC16F877A single-chip microcomputer performs comparison operation, and after comparison, the output control value controls the temperature regulation circuit composed of heating and cooling circuits to adjust the temperature of the culture medium in the culture dish. At the same time, the current temperature is transmitted to the serial port of the commercial computer through the level conversion circuit, and the temperature in the petri dish is dynamically displayed by the computer. Under normal circumstances, the temperature control is automatically controlled by the Micro Chip PIC16F877A single-chip microcomputer. When necessary, the computer can also forcefully change the temperature in the petri dish through software.

5 Temperature Control System Software Design
5.1 Microchip PIC16F877A microcontroller temperature control system software structure diagram is shown in Figure 5.1.1.

               图5.1.1单片机温度控制系统软件结构图

5.2 SCM control flow chart

                    图5.2.1单片机控制流程图

5.3 Temperature conversion program module
The temperature sensor outputs 2.52V—1.02V at 12°C to 60°C, the temperature starting point is 12°C, and the full scale is 48°C. The 10-bit A/D converter embedded in the Micro Chip PIC16F877A MCU corresponds to the digital output of 0000000000B 1111111111B (0 5V), and the following conversion formula is used for conversion:
AX=A0+(AM-A0)(NX-N0)/(NM -N0)
In the formula, A0 is the lower limit of a measuring instrument.
AM is the upper limit of a measuring instrument.
AX Actual measured value.
The digital quantity corresponding to the lower limit of the N0 meter.
The digital quantity corresponding to the upper limit of the NM meter.
The digital quantity corresponding to the NX measurement value.
5.4 Temperature Non-Linear Conversion Program Module
Using broken line fitting method for linearization processing
, as shown in Figure 5.4.1, it is divided into the following sections:
when 1.73V≤Ax<2.52V, T℃=0.06 WN+12
when 1.40V≤ When WN<1.73V, T℃=0.03
WN+25
When 1.24V≤WN<1.40V, T℃=0.016*WN+40
When 1.06V≤WN<1.24V, T℃=0.018WN+50

Table 5.4.1 Actual measurement data of temperature curve
Temperature (°C) 12 13 14 15 16 17 18
Voltage (V) 2.52 2.48 2.47 2.44 2.40 2.39 2.37
Temperature (°C) 19 20 21 22 23 24 25
Voltage (V) 2.32 2.28 2.22 2.15 2.09 1.83 1.73
Temperature (°C) 26 27 28 29 30 31 32
Voltage (V) 1.70 1.66 1.64 1.61 1.58 1.56 1.54
Temperature (°C) 33 34 35 36 37 38 39
Voltage (V) 1.53 1.50 1.4 8 1.46 1.45 1.43 1.41
Temperature (℃ ) 40 41 42 43 44 45 46
Voltage (V) 1.40 1.38 1.37 1.35 1.32 1.30 1.29
Temperature (°C) 47 48 49 50 51 52 53
Voltage (V) 1.27 1.26 1.25 1.24 1.22 1.20 1.19
Temperature (°C) 54 55 56 57 58 59 60
Voltage (V) 1.17 1.16 1.12 1.11 1.09 1.07 1.06

                      图5-1

Figure 5.4.1 Equivalent diagram of temperature segment line limit

6 Design of Communication Protocol
Because the temperature acquisition and implementation control are realized through the single-chip microcomputer control system, and the microcomputer completes the temperature monitoring, so the communication protocol between the single-chip microcomputer and the microcomputer needs to be adopted. The application conditions of this design are short-distance data transmission with a transmission distance of no more than 15 meters, and the amount of transmitted data is small, so the RS232C serial communication method, which is widely used in the control field, is adopted.
For short-range and small-batch data communication, the design adopts the zero MODEM mode of 3-wire system (RXD, TXD, GND) soft handshake. That is: cross-connect the "transmitting data line (TXD)" and "receiving data (RXD)" of the PC and the single-chip microcomputer, the ground wire (GND) of the two is directly connected, and other signal lines such as the handshake signal line are not used, but use Software handshake. In this way, the predetermined task can be realized, and the circuit design can be simplified to save the cost.
Since RS232C is an early standard developed to promote data communication in the public telephone network, its logic level is different from TTL and MOS logic levels. The level of logic 0 is specified as between +5~+15V, and the level of logic 1 is between -5~-15V. Therefore, when connecting the RXD and TXD of the PC and the single-chip microcomputer, the level conversion must be carried out.
The figure below is the hardware connection diagram during communication, in which the device MAX232 completes the task of logic level conversion.

Figure 6.1 Level conversion circuit diagram

Note: In the 9-pin RS232 interface of the PC: 2 wires: RXD, 3 wires: TXD, 5 wires: GND
and in the 25-pin RS232 interface: 3 wires: RXD, 2 wires: TXD, 7 wires: GND

6.1 Software Design
In the software design of data communication, two problems must be solved: one is reliability and the other is speed. For these two problems, reliability is the first, and the speed can only be the speed on a reliable basis. The realization of reliable and fast transfer requires the reliability and mutual cooperation between PC-single-chip software and communication protocols.
6.1.1 Overview of communication protocol
When designing the PC-SCM communication protocol, one point needs to be explained: In the actual communication of this system, the PC is the master controller and the SCM is only the passive receiver. Adopting this communication protocol is simpler than when the two parties are mutually mastering each other.
The design idea of ​​this communication protocol is based on the frame transmission mode. That is, when sending command signals, response signals and data signals to the RS232 serial port, they are sent frame by frame. In order to transmit data quickly and reliably, each frame of data is uniquely corresponding to a command frame. At this time, the command to transmit data is executed as follows:
(1) When the PC reads data, follow the "read command-wait data-report", that is, the PC issues a command, waits to receive data, and reports to the application program according to the correctness and error of the received data The execution status of this command.
(2) When the PC writes data, follow the "write command-wait for response-report", that is, the PC issues a write command (the data to be written at this time is included in this command), and waits for the "correctly received" from the MCU , and report to the application that the command is complete.
(3) If there is an error in any frame signal received by the PC or MCU during the transfer process, it will send a request to resend the frame signal to the other party. If three transfers fail in a row, the communication is exited and reported to the application.

6.2 Communication protocol description
6.2.1 Signal frame classification
(1) Read command frame: When PC reads data, PC sends command signal to PIC16F877A.
(2) Write command frame: When the PC writes data, the PC sends a command signal (including the data to be written) to the PIC16F877A.
(3) Data frame: When the PC reads data, the PIC16F877A sends a signal containing data information to the PC.
(4) Positive response frame: When the PC writes data, PIC16F877A reports to the PC that the data has been received correctly.
(5) Resend command frame: When the PC reads/writes data, the signal frame (read/write command frame) received by PIC16F877A is wrong and sends a request to the PC to resend the signal.
(6) Abandon command frame: When the PC reads/writes data, the PC or PIC16F877A sends a notification signal to the other party to exit the communication when the program cannot be executed normally.
6.2.2 Signal frame format
(1) Read command frame format
Frame header flag frame type device address start address
length checksum frame tail flag frame
header flag (1 Bit): Indicates that this data packet belongs to this serial port communication protocol and is Whether to receive the flag of this package data.
Frame type (1 Bit): The identification mark of the signal frame used, that is, the flag byte of each type of signal in 1.2.1 Signal frame classification.
Device address (1Byte): Which external device is the address of the external device that the PC wants to access.
Start address (2Byte): The memory start address of the device to be accessed by the PC.
Length (1Byte): The length of data transferred by one command.
Checksum (1Byte): The checksum byte of this frame signal is exclusive or checksum.
Frame end mark (1Byte): The end mark of this frame signal.
(2) Write command frame
Frame header flag frame type device address start address
length data area check and frame end flag
Data area: the data information to be written. Other analyzes are the same as above.
(3) Data frame
Frame header mark Frame type length Data area check word frame end mark
Length: The length of the transferred data.
Data area: the transferred data information. Other analyzes are the same as above.
(4) Positive response frame
frame header flag frame type null checksum frame tail flag
empty meaningless: added for the convenience of PIC16F877A programming. Other analyzes are the same as above.
(5) Retransmission frame
Frame header flag Frame type Null check word Frame tail flag
Other analysis is the same as above.
(6) Abandon frame
Frame header flag Frame type error code Checkword frame end flag
Error code:
00H Execute PC command to send an abandon frame response to passively exit communication.
01H PIC16F877A The MCU writes into the chip and an error occurs, actively notifying the PC to quit the communication.
6.2.3 Communication protocol processing flow
(1) Data framing and data reassembly

Figure 6.2.1 Serial port data sending process

                      图6.2.2串口数据接受过程

The data sent by the application program is placed in the sending buffer as a data stream, and is framed-cut-sent through the communication protocol. At the receiving end, the framed data is removed from the frame header and reassembled into the receiving buffer, and handed over to the application program for processing. The schematic diagram of the sending process is shown in Figure 6.2.1, and the schematic diagram of the receiving process is shown in Figure 6.2.2.
SCM serial communication software design flow chart

                    图6.2.3单片机串口通信软件流程图

PC receiving data software design process

                      N                        N



       Y                                      Y
          
                       Y
                      
         


                       Y
                       


       Y
                      Y



       N

Figure 6.2.4 Flow chart of PC serial communication software design

6.3 Software design of PC upper computer
6.3.1 Choice of PC software design method
In the development of communication program of PC upper computer, the programming languages ​​commonly used by people can be divided into three categories: (1) Assembly language directly facing the underlying hardware. (2) Advanced programming language under DOS environment, such as: C language, etc. (3) Advanced programming language under Windows environment, such as: VC++, etc. Among these three methods, the serial port programming under Windows environment has been widely used because of its device independence, portability and friendly interface. At the same time, under the condition that the Windows operating system has already occupied a dominant position, it has gradually become an inevitable choice to use the high-level language under the Windows environment to develop a good communication program.
There are mainly two ways to develop serial communication program under Windows environment:
(1) use Windows API (Application Program Interface) user program interface function;
(2) use ActiveX control;
the main feature of the latter is easy to learn, but the former More powerful functions and more flexible control means.

6.3.2 Choice of PC software communication mode
There are two types of serial communication in the Win32 environment: the main mode is the synchronous mode, and the asynchronous mode has its own characteristics. In the software design, the appropriate method should be selected according to the actual situation.
(1) Synchronous mode
In the synchronous mode, the function of reading the serial port tries to read the specified number of data in the receiving buffer of the serial port, and it will not return until the specified number of data has been read or the set timeout time has expired. For example: (Take the C++ Builder programming language as an example, the same below)
………………………………… COMMTIMEOUTS cto; int timeConstant, timeMutiplier; cto.ReadTotalTimeoutConstant = timeConstant; //Set the total timeout
constant cto .ReadTotalTimeoutMultiplier = timeMutiplier; //Set the total timeout coefficient SetCommTimeouts(m_hFile,&cto); //Timeout setting …………………………………… ReadFile (hComport,inBuffer,nWantRead, &nRealRead, NULL);//Read serial port …………………………………………………… COMMTIMEOUTS structure is used to set timeout, specify the waiting time of read and write functions











In the ReadFile function, hComport is the serial port handle to be read; inBuffer is the size of the input buffer; nWantRead is the number of bytes the function tries to read each time ReadFile is called; nRealRead is the actual number of bytes read; the last parameter value is NULL It means that ReadFile will adopt synchronous file reading and writing.
(2) Asynchronous mode In the asynchronous mode
, using the multi-thread structure of Win32, the read and write operations of the serial port can be performed in the background, while other parts of the application program are executed in the foreground. For example:
…………………………
………………………… CreateFile (lpszPort, //Open the serial port
GENERIC_READ |GENERIC_WRITE, 0, 0, ……………………………… OPEN_EXISTING, FILE_FLAG_OVERLAPPED, // Allow asynchronous operation 0); OVERLAPPED lpOverlapped; COMMTIMEOUTS cto; int timeConstant, timeMutiplier; cto.ReadTotalTimeoutConstant = timeConstant; //Set the total timeout constant cto.ReadTotalTimeoutMultiplier = timeMutiplier; //Set the total timeout factor














SetCommTimeouts(m_hFile,&cto); //Timeout setting
lpOverlapped.hEvent=CreateEvent (NULL.TRUE,FALSE,NULL ) ;
……………………………………………………… ReadFile (hComport,inBuffer,nWantRead,&nRealRead,&lp Overlapped); //Read serial port ......…………… lpOverlapped is an OVERLAPPED structure variable, OVERLAPPED structure is used to point out the overlap between read and write operations and other operations in order to implement threads Between synchronization and communication, the above code uses the CreateEvent function to generate a manual reset event, and assigns its handle to the hEvent member of lpOverlapped. In this way, when the asynchronous read and write is completed, Windows95 sends the event signal. (3) Comparison of the two methods The asynchronous method uses the multi-thread structure to monitor the communication equipment, and its biggest advantage is that the program has the ability to perceive the received data independently. Once the communication thread inquires that the data has been sent to the serial port, the thread automatically sends a data received message to the application program, which can be used by the application program to read the data from the communication device. And the use of communication threads does not occupy CPU time, so the system actually has the ability to control multiple communication devices (such as MODEM) at the same time. Therefore, the asynchronous method should be adopted in occasions that require high system robustness.







The advantages of the asynchronous method are also the disadvantages of the synchronous method. When using the synchronous method, it is easy to cause thread blocking, which will degrade the system performance. But in some occasions, this shortcoming can be reduced as much as possible through some measures, but its easy-to-use advantages are well reflected. If you don't consider the process and thread of Win95, just read the serial port buffer when there is data in the serial port. At this time, determining the timing of serial port reading, the implementation of handshake protocol and software error correction are the main issues that programmers should consider, and they are also the main measures to reduce the negative impact caused by thread blocking.
The occasions where synchronous transfer can be used have the following characteristics:
① When to transfer data is determined by the PC, and the lower computer only passively receives and executes commands.
② Within a limited time, the PC command can be executed and the result returned. Without making the PC wait for a long time.
③ The length of the data transferred each time is known, and the amount of data transferred is limited and relatively small.
When we were developing the serial communication program, we applied these two methods to develop successfully. Given the security and ubiquity of applying asynchronous

6.3.3 Specific implementation method
The following takes C++ Builder as an example to describe the implementation process of PC communication software:
(1) Open the serial port
In Win32, the serial port and other communication devices are treated as files. The functions used to open and close the serial port for reading and writing are the same as those for operating files.
The communication session starts by calling the CreateFile function to open the serial port. CreateFile "opens the serial port" with read access, write access or read-write access and sets it as an asynchronous operation mode. The example of calling this function to open the serial port for reading and writing in synchronous operation mode is as follows:
mHandle = CreateFile(lpszPort, //serial port name
GENERIC_READ|GENERIC_WRITE, //allow read/write
0, //exclusive mode serial port cannot share
NULL, // The security attribute is generally set to 0
OPEN_EXISTING, //the serial port already exists and cannot create a new port
lpOverlapped, //asynchronous mode
0 //the serial port has no template file and should be set to 0
);
if the call is successful, the function returns the handle of the serial port and assigns it to Handle, If the call fails the function returns INVALID_HANDLE_VALUE.
(2) Initialize the serial port
The initialization of the serial port includes the setting of parameters such as baud rate, data bit, stop bit, parity bit, I/O buffer size and timeout. When calling the API function to initialize the serial port, the baud rate, data bits, parity check stop bit information is included in a DCB structure, and the timeout information is included in the COMMTIMEOUTS structure,
Generally, after using CreateFile to open the serial port, you can call the GetCommState function to obtain the initial configuration of the serial port. To modify the configuration of the serial port, you should first modify the DCB structure, and then call the SetCommState function to set the serial port with the specified DCB structure. For example: DCB
dcb;
GetCommState(mHandle, &dcb) //Read DCB structure
………………………………… dcb.BaudRate=9600 //Set the baud rate to 9600b/s dcb. ByteSize=8; // Each character has 8 bits dcb.Parity=NOPARITY; // No parity dcb.StopBits=ONESTOPBIT; // One stop bit SetCommState(hCom, &dcb) // Save to DCB structure to make the set value take effect Call the SetupComm function to set the size of the serial port's input and output buffers. If the communication rate is high, a larger buffer should be set. For example: …………………………………………… SetupComm( mHandle , 1024 2, 1024 2 ) //The size of the input and output buffers are both 2K ……………… ……………………………… _












When using ReadFile and WriteFile to read and write the serial port, the timeout problem needs to be considered. If the specified number of characters are not read or written within the specified time, the ReadFile or WriteFile operation ends. To query the current timeout setting should call the GetCommTimeouts function. This function will fill a COMMTIMEOUTS structure and call SetCommTimeouts to set the timeout with the content of a certain COMMTIMEOUTS structure.
……………………………………………
_

TimeOuts.ReadIntervalTimeout=0 //Read interval timeout
TimeOuts.ReadTotalTimeoutMultiplier=10 //Read time coefficient
TimeOuts.ReadTotalTimeoutConstant=100 //Read time constant
TimeOuts.WriteTotalTimeoutMultiplier=10 //Write time coefficient
TimeOuts.WriteTotalTimeoutConstant=100 //Write time constant SetCommTimeouts (hCom ,
&TimeOuts); //Save the set value to take effect
……………………………………………………………… COMMTIMEOUTS The members of the structure are all in milliseconds. The formula for calculating the total timeout is: total timeout = time coefficient × number of characters required to read/write + time constant When reading and writing the serial port in asynchronous mode, although ReadFile() and WriteFile() may return before the operation is completed, the timeout is still effective. In this case, the timeout specifies the completion time of the operation rather than the return time of ReadFile() and WriteFile(). (3) Read and write serial ports After the initialization work is completed, the read/write functions ReadFile() and WriteFile() can be reasonably arranged according to the communication protocol to read and write various handshake information and data information. Among them, when to read the data information and response information sent by the microcontroller is important. At this time, the event-driven method is adopted, that is, the event mask on the communication resource is set to EV_RXCHAR. The application instance is notified when a character is received and put into the buffer. //PC sends a set of commands to the MCU








WriteFile(mHandle, //serial port handle
pDataBuff, //storage data buffer area
iLen, //length of written data
pdwWritten, //write length should be set to 0 before operation
lpOverlapped) //asynchronous mode
//set communication event Mask
DWORD dwMask=EV_RXCHAR;
SetCommMask(m_hFile,dwMask)) //Set communication event mask
//Waiting for communication event
OVERLAPPED os ;
memset( &os, 0, sizeof( OVERLAPPED ) ) ;
os.hEvent=CreateEvent(NULL TRUE FALSE NULL)
if(!WaitCommEvent(m_hFile, &dwEvtMask, &os)) // Overlapping operation
if(GetLastError()==ERROR_IO_PENDING)
{ // Infinitely waiting for overlapping operation result GetOverlappedResult(mHandle, &os, &dwTrans, true); // The event has occurred and the read operation is scheduled ReadFile(mHandle, //serial port handle pDataBuff, //storage data buffer area iLen, //length of the read data pdwRead, //actual read length







lpOverlapped) //Asynchronous mode
}
In the above example, we wait infinitely for the communication event to occur. If the communication event has not occurred, the system will not continue to execute. In actual program design, we can set a time limit, and if the communication event does not arrive after this time limit, the corresponding error handling will be executed. At this time, just replace the GetOverlappedResult function with the WaitForSingleObject function. The declaration form of this function is as follows: WaitForSingleObject( HANDLE hEvent,
//
Event Handle
unsigned long mTimeOuts //Timeout setting
)
(4) Close the serial
port After the communication is completed, call the CloseHandle() function to close the serial port, such as
CloseHandle(mHandle); //Close mHandle is the handle returned when the serial port is opened
6.4 MCU software design
We know that it affects data transfer Factors that cause errors include: transmission line distribution parameters, baud rate errors between upper and lower computers, on-site interference, etc. For short-range small-batch data communication, the baud rate error of the lower computer is the most important factor affecting reliable communication. Therefore, the design of the single-chip software should focus on and set the baud rate.
6.4.1 Baud rate
(1) Analysis of baud rate error sources
① The oscillation circuit of the single chip microcomputer is composed of crystal and capacitors C1 and C2. The frequency of the crystal oscillator is mainly determined by the frequency of the crystal, and also has a certain relationship with the capacitors C1, C2 and the external temperature. In addition, the nominal value and the actual value of the crystal frequency cannot be exactly the same.
②Baud rate maximum allowable error analysis
In the asynchronous serial communication mode 1, the single-chip microcomputer continuously samples the received data (RXD) at a sampling rate of 16 times the baud rate. Once a negative transition from 1 to 0 is detected, the 16-frequency division counter is immediately reset to make it full The moment of the flip is exactly aligned with the edge of the input bit. The 16 frequency division counter divides the time of each receiving bit into 16 parts. The three bits in the middle are 7, 8, and 9. In the state, the bit detector samples the value of the RXD terminal and determines the received bit by 2 out of 3. data bits. It can be seen that when the error of the baud rate causes a certain data bit to be received, the bit will be sampled twice when the sampling point is half a bit away from the midpoint of the bit. That is: to make the received Nth bit the correct bit, the following formula must be met: the
allowable baud rate error N > 0.54,
so when the transmitted frame of data is 10 bits, the maximum allowable baud rate The allowable error is 5% For other commonly used 8-bit, 9-bit, 11-bit, one-frame serial transmission, the maximum baud rate allowable error is 6.25%, 5.56%, and 4.5% respectively.
③Measures to reduce the baud rate error
We know that using a crystal oscillator with a small dispersion is the key to reducing the baud rate error. If the dispersion of the crystal oscillator has exceeded the allowable range, its nominal value should not be used at this time, and the actual crystal baud rate value can be obtained by measuring its baud rate.
(2) Realization of MCU software
① Example of setting the value of communication mode and baud rate ……………………………………………… MOV
SCON , #50H Initialize serial port settings For mode 1 MOV TMOD,#20H Use timer 1 as baud rate generator and set it as mode 2 MOV PCON,#XXH Set SMOD value MOV TH1,#XXH Set timer initial value SETB TR1 Start timer 1 ……… ………………………………………… _









…………………………
②Wait for receiving the signal frame sent by the PC and respond accordingly according to the communication protocol.

6.5 Communication protocol design conclusion
6.5.1 Communication reliability analysis
The reliability of communication is mainly reflected in the reliability of the communication protocol used. The reliability of this communication protocol mainly has two theoretical foundations:
(1) By judging the frame header Characters are used to determine the start of a frame, which prevents some data from entering the internal data processing. This possibility is 1/256, and this possibility can be further reduced by 1/256 through the judgment of the stop bit. In addition, it can be further reduced by judging the frame type byte.
(2) Check word Exclusive OR check of the whole frame signal makes the possibility of wrong reception very small. If this XOR check is changed to CRC check, the possibility of error is even more minimal. The protocol used in this communication has an error correction function, which is reflected in the fact that when the PC sends or receives data, when the received response signal fails, it will resend or receive the frame of data until the correct response is received, specifically in the program. Three consecutive errors are allowed, and the communication will be abandoned after exceeding. In practical application, when using this communication, the transmission distance is only within a few meters and the environmental interference is relatively small, thus further ensuring the reliability of communication from external factors.
6.5.2 Analysis of communication speed
If the occurrence of errors is not considered, the PC needs to add 12 bytes every time it sends a frame of data, 8 bytes of which are used to send and 4 bytes are used to answer the PC. When receiving a frame of data, 13 bytes need to be added, of which 5 bytes are used for receiving and 8 bytes are used for response. For example: if calculated by transmitting 32 bytes per frame, the efficiency of sending and receiving is calculated by ignoring the processing time of PC and PIC16F877A microcontroller. The calculation formula of sending data rate and receiving data rate is as follows:
sending data rate: 9600 32/44=6981bit/s
receiving data rate: 9600
32/45=6826bit/s
This is the theoretical rate, and it should also include the time for processing signal frames and waiting for signal frames of PC and PIC16F877A single-chip microcomputer in practice. In this communication protocol, there will be no phenomenon that a certain signal frame has arrived but the PC or PIC16F877A microcontroller has not yet started to receive. In actual application, due to different specific application environments, the time for PC and PIC16F877A MCU to process signal frames will be different, so the specific rate value will vary according to specific applications.

7 Protel99 Design Schematic Diagram
(1) The first step in circuit board design using Protel is to design the schematic diagram. The schematic diagram determines the basic functions of the entire circuit and is also the basis for generating the netlist and designing the printed circuit board.
① Create a new design library under the initial interface of Protel 99, which is used to manage projects.
File-New-Change the file name-Change the save path-OK
② Enter the folder Document in the design library file.
③ Create new schematic files and printed board files in the Document folder.
File-New-Schematic Document-Ok-Change the file name
File-New-PCB Document-Ok-Change the file name④
Open the schematic file.
⑤ Add a schematic file library.
Design-Add/Remove Library- Browse the required parts library-Add-Ok
⑥ Place various components, drawings, network labels and other components required by the circuit.
Design-Add/Remove Library- Browse the required parts library-Add-Ok
to call up the component Place-part from the parts library
⑦ Layout and route the original components to form a complete schematic diagram.
Place-part
⑧ Edit and adjust. Then archive the output.
Right click - Properties....Designation-Part-Footrit Save
⑨ Print or create a report.

Figure 7.1.1 Flow chart of protel design

(2) Use the PCB system to design the PCB board in the following seven steps:
① Set the relevant parameters. This step mainly sets the automatic layout parameters, automatic wiring parameters, board surface parameters, etc.
② PCB board size design. On the forbidden wiring layer, draw a border line along the designed PCB side, that is, specify the range of automatic layout. This step lays the foundation for Auto Layout. At the same time, copper wires are placed on the upper board surface (ie, the component surface) along the frame line of the forbidden wiring layer, which is necessary for the final molding of the PCB board.
③ The layout is based on the connection relationship between the components on the schematic diagram, and considering the electromagnetic compatibility, the installation space and heat dissipation of the components, etc., and always place the components in the appropriate position on the PCB circuit board. The quality of the layout directly affects the electrical performance of the PCB board and the function of the layout, which is the most time-consuming and cumbersome in the PCB board design process. Layout work requires patience and meticulousness. Although the system provides the function of automatic layout, generally speaking, manual adjustment is required.
Manual layout, first load the network list generated by SCH, and realize the layout by manually moving the arrangement position of the components on the PCB board. For mobile components, it is best to turn on the network connection display, so that you can observe the density of the connections between adjacent components.
Automatic layout, the PCB system environment provides automatic layout function to complete component placement, but it is best to use manual adjustments in details. During the layout, components that require many connections to each other should be placed nearby; components that may cause interference with each other should be kept away: power devices should consider the heat dissipation space.
④ Automatic routing. Routing is the process of placing copper-clad connections between component pins, which can be done manually or automatically. However, the PCB system of Protel99 provides a powerful automatic routing function, and it is recommended to use this function for automatic routing. Before automatic routing, the designer must first design the routing parameters and define the routing rules. If it is not appropriate, it may cause the failure of automatic wiring, that is, the success rate of wiring is not high, so special attention should be paid to this step
⑤ Start the design rule check DRC. This step uses the DRC function provided by the PCB to check the PCB board that has completed the wiring. This step is automatically completed by the software. The inspection results are output in the report file *.rep, and the PCB software will display the errors on the PCB diagram, which is convenient for inspection and modification.
⑥ Panel character adjustment. In order to make the designed PCB board beautiful and to install soldering components conveniently, the names of the components should be changed. Character parameters with design values ​​are moved outside the component box. The size is right and the characters don't want to overlap.
⑦ Save, output, and plate-make the PCB design drawings that have passed the DRC inspection and have adjusted the layout characters.
⑧ After the circuit design of the printed board is completed, the design project of the entire circuit board is basically completed. Archive for later modification and improvement.

Figure 7.1.2 Process of making PCB board

8 Production of hardware circuit board
In this design, two relays are required to control the peripheral temperature adjustment system, two LEDs are used to prompt serial port data indication, there is also a PIC16F877A single-chip microcomputer, a Max232 level converter, an active crystal oscillator and Its peripheral resistors and capacitors, etc. After confirming the correctness and feasibility of the circuit, start to use Protel to layout it.
Protel is a very useful electronic production tool, and it can also perform simulation. In the process of drawing the schematic diagram, the components you are looking for may not be found in the component library in the schematic diagram, such as PIC16F877A, etc., so you have to draw the components yourself. After drawing the schematic diagram, choose to automatically number the components, and then change the numbers of some components as needed. After setting the component number, use the ERC in TOOLS to check, it will prompt whether there are errors such as components with the same number. After the ERC check is correct, the encapsulation can begin. Similarly, the packages of some components cannot be found in the PCB library or have discrepancies, such as key switches and 2-digit DIP switches cannot be found in the PCB library, so you need to adjust the components according to the actual size of the components and the references in the corresponding schematic diagram. Foot numbering, to make the correct package.

Figure 8.1 Complete PCB Diagram
In addition, the pin numbers of the variable resistors in the schematic diagram and the pin numbers in the PCB library are somewhat different (you can double-click the component in the schematic diagram, select HIDDEN PINS, and you can observe the pin numbers of the components. pin number), you can change the pin number of the component to the corresponding number in the schematic diagram in the PCB library. After all the components are packaged, a component report can be generated. In the report, the label and package code of each component can be clearly seen. After further inspection, the network table will be established. Draw a rectangle with the same border as the size of the circuit board in the forbidden wiring layer, and then start to import the network table. After the imported network table has no errors, the formal layout begins. According to the routing of the schematic diagram, pull the devices into the frame and put them in the appropriate position. After the layout is completed, first set the safety spacing to 10mil, select the bottom layer for the wiring layer, select 25 mil for the line width, and change the outer diameter of the pad to 40mil and the inner diameter to 20mil (some points should be changed to smaller or larger as needed). Then start the formal wiring. Wiring cannot rely on automatic wiring alone, especially in this design there are many chips, so the entire circuit is manually wired according to the schematic diagram. This can make the whole circuit look more tidy. When the wiring is not connected sometimes, it can be adjusted by using the short jumper on the top layer, so as to complete the design of the entire PCB circuit board. See Figure 8.1.
After laying out the PCB diagram and checking that it is correct, print the PCB diagram on the transfer paper, then iron it on the circuit board, corrode, and punch holes. Before ironing the board, the copper board should be sanded to remove the oxidized part of the surface. When corroding, use ferric chloride and appropriate amount of boiling water to make ferric chloride solution for corrosion, so that the corrosion will be faster. After the corrosion, clean the circuit board with thinner water, and then start drilling (choose 0.8mm Needle), after punching the hole, use a multimeter to measure whether the circuit is connected, and then apply rosin solution (alcohol + rosin), so that the welding speed will be faster and it can prevent oxidation, and then put it aside to dry. At the same time, measure whether some components (resistors, etc.) are damaged, and after the circuit board is dry, install the components according to the PCB diagram. Then you can start soldering. When welding, it is necessary to prevent false welding and disconnection, so after welding, use a multimeter to measure whether the components and lines are connected. After the inspection is completed, the hardware circuit board assembly is completed.

9 Design Summary
Through the design of this temperature monitoring system, I have learned a lot. During the production process, we must pay attention to the inspection of each work step to ensure the success of the production. For example, if the wiring is reasonable and the assembly is checked correctly, if there is still no output in the circuit, then it is certain that the schematic diagram is wrong. At this time, it is necessary to return to the schematic diagram for inspection. The overall inspection sequence should be schematic diagram, PCB diagram, assembly situation, and welding process. On the whole, this is a complicated process. Be careful, calm, and check repeatedly until you find the reason.
This graduation project lasted at least 3 months. From the determination of the topic at the beginning, to the subsequent information search, theoretical study, and the recent debugging and testing process, all these have further improved my theoretical knowledge and hands-on ability. The topic of synthetic circuit includes some knowledge of communication circuit and single chip microcomputer, which can be said to be a comprehensive synthesis of communication circuit knowledge. It is inevitable to encounter various problems in the process of drawing schematic diagrams, PCB wiring, installation and debugging. This requires keeping calm and thinking actively with the theoretical knowledge in books. If you can’t solve it, you can ask your classmates or instructors. Although many problems were inevitably encountered during the production process, these problems were finally solved satisfactorily with the help of teachers and classmates, and the entire system design and final debugging were realized. The relevant indicators met the expected requirements, and the project was completed well. This design task.
After four years of study and accumulation, I have completed my graduation project in a serious manner after mastering relevant professional knowledge and other aspects of knowledge.
From getting the topic to finding information, from researching the topic to setting the PCB circuit board, from debugging the circuit board to starting again after failure... In this process full of challenges and setbacks, full of enthusiasm and blows In the course, I was deeply touched. It is not only a test of my four-year learning knowledge and my application ability, but also a test of my research spirit, attitude in the face of difficulties, perseverance and patience in doing things. In this process, I deeply felt the significance of doing graduation project, and those who really devoted themselves to doing it like me will definitely have the same feeling.
The key points and difficulties of this course are:
(1) To get in touch with the temperature sensor initially, it is necessary to ponder over the principle, structure, application and other aspects of the sensor from the beginning; (2
) Consider the circuit realization principle from non-electrical signal to electric signal and the interface with the single-chip microcomputer;
(3) Familiar with the pull RS-232-C serial port programming technology;
(4) Pay attention to the realization process of the adjustment circuit and how to indirectly control it through the single-chip microcomputer.
By doing this project, I understand and master the basic theoretical knowledge of sensors, and have a deeper grasp of the development and application of single-chip microcomputers and PC programming control. It has laid a good foundation for the design and development of single-chip microcomputer software and hardware products and PC software development in the future, and established the confidence to independently engage in product research and development, and has been fully trained in this ability.

thank you

In this graduation project, I got the enthusiastic guidance from my instructor Chen Ziqiang. Caring and supervising the graduation design process and progress from beginning to end. Help solve many problems encountered in graduation design. He also constantly taught us the methods of analyzing and solving problems, and pointed out the correct direction of efforts, which saved me a lot of detours during the graduation process. At the same time, he also provides us with various special equipment and places, so that we can have sufficient time during the debugging process. Here I am very grateful to Teacher Zhao for his guidance and help, and I would like to express my sincere thanks!
At the same time, the classmates around me gave me a lot of help. Here, I would like to express my sincere thanks to the classmates who care about me! In addition, the leaders and teachers in the department also gave us the necessary guidance, and I would also like to express my heartfelt thanks to the leaders of the department and grade! Finally, I would like to thank the college for training me over the past few years.

References
[1] He Limin. Single-chip application system design system configuration and interface technology [M]. Beijing: Beijing University of Aeronautics and Astronautics, 1990. [2] Li Xiaoquan. The principle and application of single-chip microcomputer [M]. Beijing: Electronic Industry Press
, 2000.
[3] Liu Heping. The Principle and Application of Single Chip Microcomputer [M]. Chongqing: Chongqing University Press, 2002. [
4] Xu Aijun. Application Programming Design of Single Chip Microcomputer Advanced Language C51 [M]. Beijing: Electronic Industry Press, 2002.
[ 5] Xie Zimei. Electronic Circuit Design. Experiment. Test (Second Edition) [M]. Wuhan: Huazhong University of Science and Technology Press, 2000. [6] Jiang Guoqiang. Modern Digital Logic Circuits. Beijing: Electronic Industry Press,
2002.
[ 7] Zhang Yong. Introduction and Application of PROTEL 99SE Circuit Design Technology (First Edition). Beijing: Electronics Industry Press, 2002. [8]
Fan Changxin. Communication Principles (Fifth Edition) [M]. Beijing: National Defense Industry Press Society, 2001.
[9] Richard c.Dorf.modern conctrol system[M].BEIJING:Science Publishing House, 2002.
[10] Donald A. Neamen. Electronic circuit analysis and design[M].Tsinghua University Press and Springer Verlag .2002.

Appendix 1
(1) The microcontroller program used in this design is as follows:
#include <pic.h>
//**************************
void INIT( )
{ ADCON1=0X07; TRISC=0X80; TRISB=0X00; TRISD=0X00; RD1=0; RD0=0; TRISA=0X0f; TRISE=0X00; } //************ ************* #include <pic.h> #include “init.h” #include “proc.h” //**************** *********** unsigned char i; unsigned int delay; extern unsigned char a; extern unsigned char temph; extern unsigned char templ; ************* void main() { //Initialization INIT();
























for(delay=65536;delay>0;delay–) asm(“clrwdt”);
temph=0x35;
templ=0x30;
do
{
asm(“clrwdt”);
PROCDIANPIN();
RC0=0;
RC1=0;
}while(1);
}
#include <pic.h>
#include “tranpc.h”
//*********************
union adres
{
int y1;
unsigned char adre[2];
}adresult;
extern unsigned int delay;
unsigned int temp;
unsigned int y;
unsigned char receive;
unsigned char a;
extern unsigned char rxbuf[];
unsigned char temph;
unsigned char templ;
extern unsigned char i;
//******************************
void PROCDIANPIN()
{
ADCON0=0X89;
ADCON1=0X84;
ADIF=0;
ADGO=1;
for(delay=0x8ff;delay>0;delay–) asm(“nop”);
while(ADIF0)
{
asm(“clrwdt”);
}
asm(“clrwdt”);
ADIF=0;
adresult.adre[0]=ADRESL;
adresult.adre[1]=ADRESH;
if((adresult.y1<=0x204)&&(adresult.y1>=0xD9))
{
temp=0x10;
for(
y=0x204;adresult.y1<=y;adresult.y1=adresult.y1+0x07)
{
temp++;
if(temp
0x1a) temp=0x20;
if(temp0x2a) temp=0x30;
if(temp
0x3a) temp=0x40;
if(temp0x4a) temp=0x50;
if(temp
0x5a) temp=0x60;
if(temp0x6a) temp=0x70;
if(temp
0x7a) temp=0x80;
if(temp0x8a) temp=0x90;
if(temp
0x9a) temp=0x100;
}
}
TXPC(temp);
RC0=1;
RXDATAS();
if(rxbuf[0]!=0)
{
if((rxbuf[0]==0x10)&&(rxbuf[1]==0xff)) receive=0xff;
else if(rxbuf[0]0x20)
{
templ=rxbuf[1];
temph=rxbuf[2];
}
if(receive
0xff)
{
RC1=1;
a=0xff;
}
}
if(temp<=templ)
{
if(a!=0xff)
RD0=1;
else RD0=0;
}
else if(temp>=temph)
{
if(a!=0xff)
RD1=1;
else RD1=0;
}
else if((temp>=templ)&&(temp<=temph))
{
a=0;
RD0=0;
RD1=0;
}
for(delay=0xFff;delay>0;delay–) asm(“nop”);
}
#include <pic.h>
//*************************
unsigned char txbuf[5];
unsigned char rxbuf[5];
extern unsigned int delay;
unsigned char s_uart_buf;
unsigned char rx_lo_buf;
extern unsigned char i;
//*************************
void TXPC(unsigned char byte)//9600b/s
{
RC6 = 0;//start bit
for(s_uart_buf=0;s_uart_buf<46;s_uart_buf++)continue;
if(byte&0x01)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(byte&0x02)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(byte&0x04)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(byte&0x08)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(byte&0x10)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(byte&0x20)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(byte&0x40)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(byte&0x80)RC6=1;
else RC6=0;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
RC6=1;//stop bit
for(s_uart_buf=0;s_uart_buf<45;s_uart_buf++)asm(“nop”);
}
//*************************************************
unsigned char RXPC(void)//9600b/s
{
rx_lo_buf=0;
while(1)
{
if(!RC7) break;
}
//receive start bit
for(s_uart_buf=0;s_uart_buf<46;s_uart_buf++)continue;
//receive bit
for(s_uart_buf=0;s_uart_buf<17;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x01;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x02;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x04;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x08;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x10;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x20;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x40;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
if(RC7)rx_lo_buf=rx_lo_buf|0x80;
for(s_uart_buf=0;s_uart_buf<35;s_uart_buf++)asm(“nop”);
//receive stop bit
for(s_uart_buf=0;s_uart_buf<10;s_uart_buf++)asm(“nop”);
return rx_lo_buf;
}

void RXDATAS()
{ //Start receiving data for(i=0;i<5;i++) rxbuf[i]=0; for(i=0x04;i>0;i–) { asm("clrwdt"); if (RC7





0) break;
for(delay=65535;delay>0;delay–)
{
asm(“clrwdt”);
if(RC7
0) break;
}
}
if(RC7==1)
{
goto rxend;
}
for(i=0;i<5;i++)
{
rxbuf[i]=RXPC();
if(rxbuf[i]==0x21) break;
}
rxend:
asm(“clrwdt”);
}

Guess you like

Origin blog.csdn.net/ambiguous__/article/details/130907689