#include <reg51.h>
#include<intrins.h>//包含_nop_()函数
//定义命令
#define READ 0x03
#define WRITE 0x02
#define WREN 0x06
#define WRDI 0x04
#define RDSR 0x05
#define WRSR 0x01
#define PE 0x42
#define SE 0xd8
#define CE 0xc7
#define RDID 0xab
#define DPD 0xb9
//端口定义
sbit SCK = P1^4;
sbit MOSI = P1^5;
sbit MISO = P1^6;
sbit CS = P1^7;
//延时程序
void delay_ms(int n)
{
int i, j;
for(i=0;i<n;++i)
for(j=0;j<1000;++j);
}
//延时程序
void delay_ns(void) //延时>4us
{
_nop_();//空指令
_nop_();
_nop_();
_nop_();
}
//SPI写一个byte
void SPI_byte_write(const char *dat)
{
char tmp = *dat, i;
for(i=0;i<8;++i){
SCK = 0;
MOSI = (bit)(tmp >> 7); //先输出高bit
tmp <<= 1; //数据左移一位
SCK = 1; //SCK为高发送bit
delay_ns(); //延时防止芯片为响应
}
}
//SPI读一个byte
void SPI_byte_read(char *dat)
{
char tmp = 0, i;
for(i=0;i<8;++i){
SCK = 0;
tmp <<= 1; //左移一位
tmp |= MISO; //接收最高位
SCK = 1;//SCK为高接收bit
delay_ns();
}
*dat = tmp;
}
//SPI写多个byte
void SPI_nbyte_write(const char *addr, const char *dat, char num)
{
char inst_wren = WREN, inst_write = WRITE, i;
CS = 0;
SPI_byte_write(&inst_wren); //写使能
CS = 1;
delay_ms(1);
CS = 0;
SPI_byte_write(&inst_write); //写指令
for(i=0;i<3;++i){
SPI_byte_write(addr + i);//写地址
}
for(i=0;i<num;++i){
SPI_byte_write(dat + i);//写数据
}
CS = 1;
}
//SPI读多个byte
void SPI_nbyte_read(const char *addr, char *dat, char num)
{
char inst = READ, i;
CS = 0;
SPI_byte_write(&inst); //读指令
for(i=0;i<3;++i){
SPI_byte_write(addr + i);//写地址
}
for(i=0;i<num;++i){
SPI_byte_read(dat + i);//写数据
}
CS = 1;
}
char dat[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,
0x77,0x7c,0x39,0x5e,0x79,0x71};//0~F的字形码
char save[16] = {0};
const char addr[3] = {0x00, 0x00, 0x00};//读写的地址
int main(void)
{
int i;
SPI_nbyte_write(addr, dat, 16);//写入数据
delay_ms(30);
SPI_nbyte_read(addr, save, 16);//读出数据
for(i=0;i<16;i++)
{
P3=save[i];//数码管显示
delay_ms(60);
}
return 0;
}
- 1
- 2
- 3
前往页