#ifndef __SPI_H_
#define __SPI_H_
#include "common.h"
#include "delay.h"
// cs p1.21
//sck p1.20
//miso p1.23
//mosi p1.24
#define SPI_CLOCK 12000000
void spi0_select_cs(void);
void spi0_disSelect_cs(void);
u8 spi0_rw_data(u8 writeByte);
void spi0_set_speed(u8 speed);
void spi0_init(u8 divide);
#endif
#include "spi.h"
void spi0_select_cs(void)
{
P1low(21) = 1;
}
void spi0_disSelect_cs(void)
{
P1high(21) = 1;
}
u8 spi0_rw_data(u8 writeByte)
{
u8 retry = 200;
u8 readByte;
while(!(LPC_SSP0->SR&0x01))//等待发送完成
{
retry--;
DelayUs(1);
if(retry == 0)return 1;
}
LPC_SSP0->DR = (u16)writeByte;
retry = 200;
while(!(LPC_SSP0->SR&0x04))
{
retry--;
DelayUs(1);
if(retry == 0)return 1;
}
readByte = (u8)LPC_SSP0->DR;
return readByte;
}
void spi0_set_speed(u8 divide)
{
LPC_SSP0->CR1 &= ~(1<<1);//停止spi
LPC_SSP0->CR0 |= ((SPI_CLOCK/(divide-1))<<8);
LPC_SSP0->CR1 |= (1<<1);//启动spi
}
void spi0_init(u8 divide)
{
//打开SPI时钟和io口时钟
LPC_SC->PCONP |= (1<<15)|(1<<21);//打开时钟
//配置cs
LPC_IOCON->P1_21 = 0x00;//选择gpio功能,禁止迟滞 不反向 正常推挽
LPC_IOCON->P1_21 |= (2<<3);//上拉
P1dir(21) = 1;//输出
P1high(1) = 1;//为高
LPC_IOCON->P1_20 = 0x00;//选择禁止迟滞 不反向 正常推挽
LPC_IOCON->P1_20 |= (2<<3)|(5<<0);//上拉 ssp clk
LPC_IOCON->P1_23 = 0x00;//选择禁止迟滞 不反向 正常推挽
LPC_IOCON->P1_23 |= (2<<3)|(5<<0);//上拉 ssp miso
LPC_IOCON->P1_24 = 0x00;//选择禁止迟滞 不反向 正常推挽
LPC_IOCON->P1_24 |= (2<<3)|(5<<0);//上拉 ssp mosi
//spi接口初始化
LPC_SSP0->CR0 = 0x0000;
LPC_SSP0->CR1 = 0x00000000;//正常操作,主机模式
LPC_SSP0->CR0 |= (7<<0)|(1<<6)|(1<<7)|((SPI_CLOCK/(divide-1))<<8);//8位数据 cpol cpoa
LPC_SSP0->CPSR = ApbClock/SPI_CLOCK;
LPC_SSP0->IMSC = 0x00000000;//禁止中断
LPC_SSP0->CR1 |= (1<<1);//启动spi
}