|
利用freescale s08单片机SPI模块读写at93c46
[复制链接]
原文见:http://blog.ednchina.com/bluehacker/228284/message.aspx这个例子是在我做的开发板NSS08Kit-R1上测试通过的,采用的是MC9S08AC16,但是应该可以应用于其他型号的S08单片机上。
/*****************************
@ Nicrosystem Freescale S08 DevKit(NSS08Kit-R1)
@ author:bluehacker<nicrosystem@gmail.com>
@ date:2009-04-08
******************************/
/*********************
@AT93C46的驱动
*********************/
#include "at93c46.h"
#include "derivative.h"
#define AT93C46_CS PTED_PTED4
void init_spi()
{
SPI1C1=0x5c;//CPOL=1,CPHA=1
SPI1C2=0x00;
SPI1BR=0x11;//0.5MHZ clock rate
PTEDD_PTEDD4=1;//output
AT93C46_CS=1;
}
unsigned char do_spi(unsigned char dat) {
while(!SPI1S_SPTEF);
SPI1D=dat;
while(!SPI1S_SPRF);
return SPI1D;
}
//等待write或erase操作完成
void wait_finish()
{
while(PTED_PTED5==0){
asm(NOP);
}
}
//读保存在at93c46存储器中地址为addr处的数据
unsigned char at93c46_read(unsigned char addr)
{
unsigned char cmd[2];
AT93C46_CS=0;
cmd[0]=0x06;
cmd[1]=addr<<1;
AT93C46_CS=1;
do_spi(cmd[0]);
do_spi(cmd[1]);
cmd[0]=do_spi(0); ;
AT93C46_CS=0;
return cmd[0];
}
//使能写/删除操作
void enable_write(void)
{
unsigned char cmd[2];
AT93C46_CS=0;
cmd[0]=0x02;
cmd[1]=0x60;
AT93C46_CS=1;
do_spi(cmd[0]);
do_spi(cmd[1]);
AT93C46_CS=0;
}
//禁止写/删除操作
void disable_write(void)
{
unsigned char cmd[2];
AT93C46_CS=0;
cmd[0]=0x02;
cmd[1]=0x00;
AT93C46_CS=1;
do_spi(cmd[0]);
do_spi(cmd[1]);
AT93C46_CS=0;
}
//擦除地址为addr的存储单元
void at93c46_erase(unsigned char addr)
{
unsigned char cmd[2];
enable_write();
AT93C46_CS=0;
cmd[0]=0x03;
cmd[1]=addr|0x80;
AT93C46_CS=1;
do_spi(cmd[0]);
do_spi(cmd[1]);
AT93C46_CS=0;
asm(NOP);
AT93C46_CS=1;
wait_finish();
AT93C46_CS=0;
disable_write();
}
//往at93c46 addr地址写数据dat
void at93c46_write(unsigned char addr,unsigned char dat)
{
unsigned char cmd[2];
enable_write();
AT93C46_CS=0;
cmd[0]=0x02;
cmd[1]=addr|0x80;
AT93C46_CS=1;
do_spi(cmd[0]);
do_spi(cmd[1]);
do_spi(dat);
AT93C46_CS=0;
asm(NOP);
AT93C46_CS=1;
wait_finish();
AT93C46_CS=0;
disable_write();
}
//往at93c46所有存储单元写入dat
void at93c46_writeall(unsigned char dat)
{
unsigned char cmd[2];
enable_write();
AT93C46_CS=0;
cmd[0]=0x02;
cmd[1]=0x20;
AT93C46_CS=1;
do_spi(cmd[0]);
do_spi(cmd[1]);
do_spi(dat);
AT93C46_CS=0;
asm(NOP);
AT93C46_CS=1;
wait_finish();
AT93C46_CS=0;
disable_write();
}
//擦除at93c46
//erase ALL chip
void at93c46_eraseall(void)
{
unsigned char cmd[2];
enable_write();
AT93C46_CS=0;
cmd[0]=0x02;
cmd[1]=0x40;
AT93C46_CS=1;
do_spi(cmd[0]);
do_spi(cmd[1]);
AT93C46_CS=0;
AT93C46_CS=1;
wait_finish();
AT93C46_CS=0;
disable_write();
}
类别:freescale | 编辑 | 删除 | 评论(0) | 阅读(306)
|
|