关于SPI和芯片配置,求大神看看,哪里出问题了?
写了段spi与芯片通信的代码,不知到哪里出错,求大神看看
附件有代码和芯片资料
#include "REG51.h"
#include "intrins.h"
#include <stdio.h>
#include <string.h>
#define uchar unsigned char
/*************************
模拟SPI接口I/O定义
*************************/
sbit spi_cs=P2^7;
sbit spi_di=P4^4;
sbit spi_clk=P4^1;
sbit spi_do=P4^5;
void SomeNOP()
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
/*******************************
向SPI器件写入一个字节数据
*******************************/
void spi_write(unsigned char spi_dat)
{
unsigned char i;
spi_cs=0;
for (i=0;i<8;i++)
{
spi_clk=0;
if((spi_dat & 0x80)==0x80)
{
spi_di=1; //写入最高位
}
else
spi_di=0;
SomeNOP();
spi_clk=1;
spi_dat=(spi_dat<<1); //左移一位,依次写入
}
spi_clk=0;
//spi_cs=1;
}
/********************************
从SPI器件读出一个字节数据
********************************/
unsigned char spi_read()
{
unsigned char i,spi_dat;
spi_cs=0;
spi_clk=1;
for (i=0;i<8;i++)
{
spi_clk=0;
spi_dat=(spi_dat<<1); //xxxxxxx0
spi_clk=1;
if(spi_do==1)
{
spi_dat|=0x01; //xxxxxxx0|00000001
}
else
{
spi_dat&=~0x01; //xxxxxxx0&11111110
}
spi_clk=0; //从高到低位依次移入
//spi_cs=1;
}
return spi_dat;
}
void spiwrite_start()
{
EA = 0;
spi_cs = 0;
spi_clk = 0;
spi_di = 1;
SomeNOP();
spi_clk = 1;
SomeNOP();
spi_clk = 0;
spi_di = 0 ;
SomeNOP();
spi_clk = 1;
//spi_cs = 1;
}
void spiread_start()
{
EA = 0;
spi_cs = 0;
spi_clk = 0;
spi_do = 1;
SomeNOP();
spi_clk = 1;
SomeNOP();
spi_clk = 0;
spi_do = 1;
SomeNOP();
spi_clk = 1;
//spi_cs = 1;
}
//写一个数据
void Write_OneByte(unsigned char addr,unsigned char ddata)
{
spiwrite_start();
SomeNOP();
spi_write(addr);
SomeNOP();
spi_write(ddata);
spi_cs = 1;
SomeNOP();
}
//读一个数据
unsigned char Read_OneByte(unsigned char addr)
{
uchar temp;
spiread_start();
SomeNOP();
spi_write(addr); //先写入地址,设置写
SomeNOP();
//spiread_start();
//SomeNOP();
temp = spi_read();
spi_cs = 1;
SomeNOP();
return temp;
}