Method 8051 bytes in the access int

In use microcontroller, unsigned int 2 bytes, unsigned char one byte. The microcontroller is byte addressable implemented. Byte 16 bit addressing is not good to use,

Can not be used in an array of construction.

In the actual development process, to use DPTR, as well as timer TL0, TH0 nibbles and so on.

We need to define a type int can be used to assign something more natural.

And then to obtain a low 0xff 8, one byte. DPTR can be placed in the low byte or the low byte of the timer.

After eight type int left, and then the high int 0xff 8 bits, a byte, high-byte DPTR moved into or high byte of the timer.

This is very troublesome.

In fact, we can easily struct and union directly obtained in one step int types of high and lower bytes, can also be observed how the microcontroller 51 is stored in an int.

Can be found in, int MCU 51 in two consecutive bytes, high byte stored in low address, high address stored in the low byte. Haha

 

The implementation is:

First, a definition of the structure of INT_BYTE, inside two unsigned char

Then define a union is an unsigned int, and the upper two bytes defined.

Our guide union between variables in the shared memory. That is the first address num, and byte variables where the two are the same!

And num, two bytes are byte, then the byte two bytes h, l is the corresponding num in the high and low bytes.

Experiments to test:

 We define a variable hl U16, giving num hl gave 0xff0f this value.

Then we give P0 port to the low byte, P1 port to the high byte.

Debugger, open ports, run:

Very good, very easy to get the level of type int 8. Of course, added to the variable hl

watch window even glance!

 

By the same token, we can experiment unsigned long type, he occupies four bytes. Also in the high byte of the low address.

This is the small end data storage, it is used when parsing in python struct ah. When using remember as '<', '>' is identified,

It seems to learn microcontroller can dispel misunderstanding.

Finally, we can use this as a self-built code libraries to provide multiplexing. Finally, put the code:

#include <intrins.h>
#include "stc89.h"
/*
This code is written  by H.W. 
at 12969722 at qq.com
*/
struct INT_BYTE {
    unsigned char h;
    unsigned char l;
};
typedef union UINT16 {
    unsigned int num;
    struct INT_BYTE byte;
} U16;

struct BYTE_BIT {
    unsigned char a1;
    unsigned char a2;
    unsigned char a3;
    unsigned char a4;
};
typedef  union UBYTE {
    unsigned long  byte;
    struct BYTE_BIT b;
} U8;

void main(void){
    U16 hl;
    U8 ubit;
    hl.num=0xff0f;
    P0=hl.byte.l;
    P1=hl.byte.h;
    ubit.byte=0xf0f1f2f3;
}

 

 

Guess you like

Origin www.cnblogs.com/yjphhw/p/11352756.html