STC12C5A60S2_SPI
综述
测试中发现硬件SPI在传输的时候容易出bug,有时候MOSI不会被拉低,导致数据错误,不知道如何解决。
这里只展示最简单发送数据。
SPI所涉及寄存器
SPCTL
SPSTAT
例程
SPI.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include "SPI.h"
sbit LED = P3^0;
void delay3us(void) { unsigned char a; for(a=5;a>0;a--); _nop_(); }
void SPI_Init() { SPDAT = 0x00; //clear dat SPSTAT = SPIF|WCOL; SPCTL = SPEN|MSTR|SPDHH|CPHA|CPOL; //master CPOL = 1 CPHA = 1 IE2|=ESPI; EA = 1; }
void SPI_WR_Byte(unsigned char dat) // 1 dat 0 cmd { SPDAT=dat; delay3us(); //need some delay }
void SPI_Interrupt() interrupt 9 { SPSTAT = SPIF|WCOL; SPISS = 1; }
|
SPI.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #ifndef __SPI_OLED12864_H #define __SPI_OLED12864_h
#include <reg52.h> #include <intrins.h>
sfr SPCTL = 0xce; sfr SPSTAT = 0xcd; sfr SPDAT = 0xcf; sfr AUXR = 0xa2;
sfr IE2 = 0xaf;
sbit SPISS = P1^3;
#define SPIF 0x80 #define WCOL 0x40
#define SSIG 0x80 #define SPEN 0x40 #define DORD 0x20 #define MSTR 0x10 #define CPOL 0x08 #define CPHA 0x04
#define SPDHH 0x00 #define SPDH 0x01 #define SPDL 0x02 #define SPDLL 0x03
#define ESPI 0x02
/**********
MOSI = P1^5 MISO = P1^6 SPICLK = P1^7
**********/
void SPI_Init(); void SPI_WR_Byte(unsigned char dat);
#endif
|
main.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include "main.h"
void main() { SPI_Init(); while(1) { SPI_WR_Byte(0x66); SPI_WR_Byte(0x76); SPI_WR_Byte(0x86); SPI_WR_Byte(0x96); } }
|
main.h
1 2 3 4 5 6 7 8 9 10
| #ifndef __MAIN_H #define __MAIN_H
#include <reg52.h> #include "SPI.h" #include <intrins.h>
#endif
|