LPC2478的spi使用
LPC2748具有一个SPI控制器,可以当做SPI主机或者从机使用,有以下特性
其使用起来很方便,并且支持中断,使用的寄存器如下
基本上,使用起来就是设置控制为,CPOL CPOA等等,数据长度的配置等,设置分频率,发送数据,等待状态或者中断,发送完成,就OK了
官方给出的流程如下
操作过程见以下代码
#ifndef __SPI0_H_ #define __SPO0_H_ #include "common.h" #include "lpc24xx.h" #include "clock.h" typedef enum SPI0_SPEED { SPI_SPEED1 = 100000, SPI_SPEED2 = 500000, SPI_SPEED3 = 1000000, SPI_SPEED4 = 1500000, SPI_SPEED5 = 2000000, SPI_SPEED6 = 3125000 }SPI0_SPEED; typedef enum SPI_BITFRIST { msbFrist = 0, lsbFrist = 1 }SPI_BITFRIST; void Spi0SelectCs(void); void Spi0DisSelectCs(void); u8 Spi0RwData(u8 writeByte,u8* readByte); void Spi0SetSpeed(SPI0_SPEED speed); void Spi0Init(SPI0_SPEED speed,SPI_BITFRIST bitFrist); #endif
#include "spi.h" #define BIT_ENABLE_POSITION 2 #define CPHA_POSITION 3 #define CPOL_POSITION 4 #define MSTR_POSITION 5 #define LSBF_POSITION 6 #define SPIE_POSITION 7 #define BITS_POSITION 8 void Spi0Init(SPI0_SPEED speed,SPI_BITFRIST bitFrist) { u32 spiClock = (SystemCoreClock/4)/speed; PCONP |= (1 << 8);//打开SPI时钟 SCS |= (1<<0);//设置高速寄存器组方式访问端口 //sck PINSEL0 &= ~(0x03u<<30); PINSEL0 |= (0x03u<<30); PINMODE0 &= ~(0x03u<<30); //csn 普通GPIO 不用硬件CSN PINSEL1 &= ~(0x03<<0); PINMODE1 &= ~(0x03<<0); FIO0DIR |= (1<<16); //miso PINSEL0 &= ~(0x03<<2); PINSEL0 |= (0x03<<2); PINMODE0 &= ~(0x03<<2); //mosi PINSEL0 &= ~(0x03<<4); PINSEL0 |= (0x03<<4); PINMODE0 &= ~(0x03<<4); //spi接口初始化 S0SPCR = (0<<BIT_ENABLE_POSITION)|(1<<CPHA_POSITION)|(1<<CPOL_POSITION)|(1<<MSTR_POSITION)|(bitFrist<<LSBF_POSITION) |(0<<SPIE_POSITION)|(0x08<<BITS_POSITION); //八位数据,主模式 关中断 S0SPCCR = spiClock; } void Spi0SelectCs(void) { FIO0CLR |= (1<<16); } void Spi0DisSelectCs(void) { FIO0SET |= (1<<16); } u8 Spi0RwData(u8 writeByte,u8* readByte) { u8 retry = 200; if((S0SPSR&0x80)) { retry = S0SPDR; return 1; } S0SPDR = writeByte; retry = 200; while(!(S0SPSR&0x80)) { retry--; if(retry == 0)return 1; } *readByte = S0SPDR; return 0; } void Spi0SetSpeed(SPI0_SPEED speed) { u32 spiClock = (SystemCoreClock/4)/speed; S0SPCCR = spiClock; }