天天看点

51单片机资源扩展:扩展片外RAM

    ​​ 51单片机资源扩展:从片内ROM跳转到片外ROM​​ 一文中扩展了单片机的程序存储器,4KB存储空间提升到64KB。其实,4K的代码空间还凑合,但是51自带的256B数据存储空间使用起来还真紧张,其中留给用户的连128B都不到,所以不得不扩展片外RAM。扩展RAM方法和扩展ROM差不多,都是占用P0/P2口做地址线,同时P0用锁存器74373分时复用地址和数据信号。

    以前扩展RAM是用汇编语言访问存储器,好处是定位精准,指哪打哪,坏处就是:程序规模一大就有点难维护了,所以还得改用C实现。

    对应于汇编语言用R1,R0/DPTR访问外部RAM,keil C扩展了存储类型,增加了如pdata(等同用movx @Rn访问方式)/xdata(等同于movx @DPTR访问方式)存储类型用于访问片外ram。同时,还提供了绝对地址访问的宏,如PBYTE/XBYTE,查看定义:

#define PBYTE((unsigned char volatile pdata*)0);
#define XBYTE((unsigned char volatile xdata*)0);      

其实,也还是定义相应存储类型的指针~。

上仿真图和代码前,整理一下keil c提供访问绝对地址的方法:

1._at_定义变量:

变量类型 [存储类型] 变量名 _at_ 常数,指定变量存放在常数所指定的ram位置,注意bit型变量不能使用_at_指定位置;

2.绝对地址访问:

头文件absacc.h提供了绝对地址访问宏,用于字节/字寻址,如

val=XBYTE[0x0000];读片外ram 0x00处内存值 

XBYTE[0x0200]=val;写片外ram 0x0200处内存值

扩展ram仿真图:

51单片机资源扩展:扩展片外RAM

上段去年用汇编写的访问ram的代码:

ORG  0
SJMP  START
ORG  10H
START:
;1456是要访问的内存地址
MOV  DPTR,#1456H;
MOV  A,  #0FFH;
;0xFF移入[1456]
MOVX @DPTR,A;

CLR  A;
MOVX  A, @DPTR; 
;对外部RAM 1456H读出数据到A
NOP
MOV  A, #0A0H;
INC  DPL
MOVX @DPTR,A; 
;将0xA0写入外部RAM 1457H
NOP
;从外部RAM [1457]H读出数据到A
MOVX  A, @DPTR; 
NOP
SJMP START
END      

c语言版本:

#include <reg51.h>
#include <absacc.h>

#define OFFRAMBASE 0x100

unsigned char xdata offRamVal0 _at_ OFFRAMBASE*2;
unsigned char xdata offRamVal1 _at_ 0x00;
int main()
{
  unsigned char idata index = 0;
  offRamVal0 = 0xAA;
  offRamVal1 = 0xCC;
  for(index=0;index<0x10;index++)
  {
    XBYTE[index+OFFRAMBASE] = 0x55; 
  }   
  return 0;
}      

最后看下程序运行后6264内部存储的数据:

0000: <span style="color:#FF0000;">CC</span> 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
0010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
0020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
0090: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00A0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00B0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00C0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00D0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00E0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00F0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
0100:<span style="color:#FF0000;"> 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 | UUUUUUUUUUUUUUUU</span>
0110: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
0120: 00 00 00 00 00 00 00 00 00 00 00
01E0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
01F0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
0200: <span style="color:#FF0000;">AA</span> 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................