51 single-chip microcomputer program skills

Source: Internet
Author: User

The topics discussed in this series are completed in the Keil UVision3 Integrated compilation environment, for the 51 series MCU.

The following is an introduction to my microcontroller program must contain a header file----"Const.h", the full content is as follows:

#ifndef _const_h_

#define _const_h_

#include <intrins.h>

#define TRUE 1

#define FALSE 0

typedef unsigned char BYTE;

typedef unsigned int WORD;

typedef unsigned long DWORD;

typedef float FLOAT;

typedef char CHAR;

typedef unsigned char UCHAR;

typedef int INT;

typedef unsigned int UINT;

typedef unsigned long ULONG;

typedef UINT WPARAM;

typedef ULONG LPARAM;

typedef ULONG LRESULT;

typedef void void;

typedef const CONST;

typedef void *pvoid;

typedef bit BOOL;

#define Makeword (lo, HI) ((WORD) (((BYTE) (LO) | ((WORD) ((BYTE) (HI))) << 8))

#define Makedword (lo, HI) ((DWORD) (((WORD) (lo)) | ((DWORD) ((WORD) (HI)) << 16))

#define LOWORD (DW) ((WORD) (DW)

#define HIWORD (DW) ((WORD) ((DWORD) (DW) >>) & 0xFFFF)

#define Lobyte (W) ((BYTE) (W))

#define Hibyte (W) ((BYTE) ((WORD) (W) >> 8) & 0xFF)

#define MAX (A, B) ((a) > (b))? (a): (b))

#define MIN (A, B) ((a) < (b))? (a): (b))

#define SET_STATE_FLAG (State, mask) (state) |= (mask)

#define RESET_STATE_FLAG (State, mask) (state) &= ~ (mask))

#define TEST_STATE_FLAG (State, mask) (state) & (Mask)

Offset starting from 0

#define TEST_BIT (b, offset) (1 & ((b) >> (offset))

#define SET_BIT (b, offset) ((b) |= (1 << (offset))

#define RESET_BIT (b, offset) ((b) &= (~ (1 << (offset)))

Change the BCD code to decimal, such as turning 0x23 into 23

Note: High four-bit and low four-bit cannot be greater than 9

#define BCD_TO_DECIMAL (BCD) ((Byte) (((Byte) (BCD) >> 4) * + ((((Byte) (BCD) & 0x0f))

#define DECIMAL_TO_BCD (decimal) ((Byte) (((((Byte)) << 4) | ((BYTE) (decimal))% 10))

#define NOP () _nop_ ()

#define BYTE_ROTATE_LEFT (b, N) _crol_ (b, N)

#define Byte_rotate_right (b, N) _cror_ (b, N)

#define WORD_ROTATE_LEFT (w, N) _irol_ (W, N)

#define Word_rotate_right (w, N) _iror_ (W, N)

#define DWORD_ROTATE_LEFT (DW, N) _lrol_ (DW, N)

#define Dword_rotate_right (DW, N) _lror_ (DW, N)

#define ENABLE_ALL_INTERRUPTS () (EA = 1)

#define DISABLE_ALL_INTERRUPTS () (EA = 0)

#endif

In fact, most of the content is from the VC's header files copied from nothing innovative, and from the name is also better to judge the realization of the function, it is not introduced. Here are a few common:

1, Lobyte () and Hibyte (). As you can see from the name, take a low byte and a high byte of the word length. These two macros are often used in the initial load of the timer. Almost all programs on the Internet or in books are like this:

TH0 = (65536-x)/256;

TL0 = (65536-x)% 256;

In fact, this assignment is very non-intuitive, why should high-byte divided by 256? Low byte Why do you want to take 256 redundancy? Is it not clear that you should change the following wording?

TH0 = Hibyte (65536-x);

TL0 = Lobyte (65536-x);

2, Test_bit (), Set_bit () and Reset_bit (). Single-chip computer resources are relatively tense, often used to "bit" as the unit. These three macros are for convenient bit operation.

3, Bcd_to_decimal () and DECIMAL_TO_BCD (). Friends who have used ds1302 know that the information from the BCD format is often required to be converted to decimal.

Of course, this header file just plays a role, always add the required functions. The benefit of this is to refine the functionality that is often used, increasing the reuse rate of the code. What's more, all of your own library files will be written in this header file in the future. Just as all Windows programs need to contain windows.h header files.

MCU serial port is one of the most commonly used functions, packaging it is relatively simple, let us slowly understand the C language packaging meaning ...

#ifndef _serial_config_h_#define_serial_config_h_#include"const.h"#ifndef osc_frequency#errorUndefined osc_frequency#endif /****************************************************************************** is limited to: Serial port mode 1 of the operating mode, that is, 1-bit starting bit, 8-bit data bit and 1-bit stop bit, no parity bit, baud rate does not multiply ******************************************************************************/ #defineOsc_frequency 11.0592typedefenumtagbaud{b_2400=2400, b_4800=4800, b_9600=9600, b_19200=19200, Invalid_baud,} BAUD; typedefvoid(*recvproc) (BYTEbyte); BOOL openserial (BAUD BAUD, Recvproc precvfunc); BOOL SendData (Constbyte*PData, BYTE nSize); voidcloseserial ();#endif 

I write the principle of single-chip computer program is very simple, is to look good ~_~ but this "good-looking" meaning is very broad, basically can be summed up as code must be concise, beautiful, efficient .

One might ask, why did you come up with a header file that doesn't know the details of the function, rather than just giving it a concrete implementation? This problem actually need to use "encapsulation" the Nature to answer: encapsulation is to let the caller not care about the specific implementation, so as to achieve the hidden information . Note: the "encapsulation" here is a logical implication and a programming specification or guideline. No one can bind you not to obey. A look at the header file will immediately understand what functionality the package provides, because the writing process requires a reasonable structure to connect the functional modules together to achieve a coordinated operation.

Well, the sermon said a lot, look at the specific things.. c files are as follows:

#include"serialconfig.h"#include"chiptypedef.h"Ecvproc G_pfnrecvfunc=NULL; BOOL openserial (BAUD BAUD, Recvproc precvfunc) {BYTE Loadvalue=0; if(Precvfunc = =NULL)returnFALSE; G_pfnrecvfunc=Precvfunc; Switch(Baud)//ensure that the baud rate entered is correct    {          Caseb_1200: Caseb_2400: Caseb_4800: Caseb_9600: Break; default:returnFALSE;  Break; }        /***************************************************************************** LoadValue = 256-osc_frequency * 10^6/(384 * Baud) has been transformed by the upper limit of the result of each operation ***************************************************************************** */Loadvalue= the-(BYTE) ( +*1.0f* (float) Osc_frequency/384* +*1.0f/Baud); Tmod|= t1_m1_;//Timer T1 mode of Operation 2TH1 =Loadvalue; TL1= Loadvalue;//non-TL1 = TH1 AssignmentPCON =0x00;//baud rate does not multiplySCON =0x50;//serial communication mode 1, allow receivingSM1 =1;//REN =1; TR1=1;//Start Timer 1ES =1;//Open Serial InterruptEA =1;//Open Total Interrupt    returnTRUE;} voidcloseserial () {TR1=0;//off timer 1ES =0;//off serial interrupt} BOOL SendData (Constbyte*PData, BYTE nSize) {BYTE I=0; if(PData = = NULL | | nSize = =0)                 returnFALSE;  for(i =0; I &lt; NSize; i++) {Sbuf=Pdata[i];  while(! TI); TI =0; }     returnTRUE;} voidSERIALISR () interrupt Sio_vector {RI=0; (*G_pfnrecvfunc) (SBUF); }
 #include  serialconfig.h   " void  recvproc (BYTE byte ); Span style= "color: #008000;" >//  void   Main () {openserial (b_9600, Recvproc);  while   (TRUE) { //  after doing some processing, call SendData () to send data   Span style= "color: #0000ff;" >void  recvproc (BYTE byte  ) { //  

Let's take a look at the serial port after the package main () function of the program flow, is not very clear? More importantly, from the main function can not see the single-chip implementation of the bottom, it is completely like writing the host computer program, the advantage is to focus on the process of implementation of the program, and do not care about the specific implementation details. Otherwise, the intricacies of the complex are mixed into a piece that affects the implementation of the program function. After all, the human mind is limited in thinking at the same time.

My understanding is that the process is the combination of the variable and the hard-to-change by abstraction. We can think of programs like this: every single-chip microcomputer program itself needs to complete a lot of relatively independent functions. So, what is variable? Clearly, the sequential flow of functions is variable, and each program is different. So what is not easy to change? is a relatively independent function module, such as: serial function, timer function, LDC display function ... Well, now that we have separated the serial function, that is, the function of the non-change is not easy to separate out. But think about the concrete implementation will find that there are still volatile factors in the inside, such as: different baud rate, crystal oscillator frequency. So, we think of the baud rate can be used as the parameters of the function to adapt to different requirements, the crystal frequency separation of the individual header file for all the files under the project. Finally, all of the variable factors have been identified, and become a factor that is not easy to change, such a functional package is basically to achieve the purpose of "reuse". So, I realized this serial package can adapt to all 51 series of single-chip microcomputer, the reason lies in this.

Through a small serial function package to realize the profound "encapsulation" thought is still very good ~_~

http://blog.csdn.net/jiqiang01234/article/details/5132522

51 single-chip microcomputer program skills

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.