目录
spi.h
spi.c
main.c
实验效果
spi.h
#ifndef __SPI_H__
#define __SPI_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
//spi初始化
void spi_init();
//spi写入数据
void spi_write(unsigned char data);
#endif
spi.c
#include "spi.h"
extern void delay_us(void);
//spi初始化
void spi_init(){
//使能GPIOE时钟
RCC->MP_AHB4ENSETR |= (0x1<<4);
//PE11配置为输出、推挽输出、无上拉下拉、高速输出
GPIOE->MODER &= (~(0x3<<22));
GPIOE->MODER |= (0x01<<22);
GPIOE->OTYPER &= (~(0x1<<11));
GPIOE->PUPDR &= (~(0x3<<22));
GPIOE->OSPEEDR &= (~(0x3<<22));
//PE12配置为输出、推挽输出、无上拉下拉、高速输出
GPIOE->MODER &= (~(0x3<<24));
GPIOE->MODER |= (0x01<<24);
GPIOE->OTYPER &= (~(0x1<<12));
GPIOE->PUPDR &= (~(0x3<<24));
GPIOE->OSPEEDR &= (~(0x3<<24));
//PE14配置为输出、推挽输出、无上拉下拉、高速输出
GPIOE->MODER &= (~(0x3<<28));
GPIOE->MODER |= (0x01<<28);
GPIOE->OTYPER &= (~(0x1<<14));
GPIOE->PUPDR &= (~(0x3<<28));
GPIOE->OSPEEDR &= (~(0x3<<28));
//PE13配置为输入
GPIOE->MODER &= (~(0x3<<26));
//sck、rck为低电平
GPIOE->ODR &= (~(0x1<<12));
GPIOE->ODR &= (~(0x1<<11));
}
//spi写入数据
void spi_write(unsigned char data){
for (int i = 0; i < 8; i++)
{
//判断发送数据是1或0
if(data & 0x01){
GPIOE->ODR |= (0x1<<14);
}
else{
GPIOE->ODR &= (~(0x1<<14));
}
//data右移1位
data>>=1;
//sck产生一个上升沿
GPIOE->ODR &= (~(0x1<<12));
delay_us();
GPIOE->ODR |= (0x1<<12);
delay_us();
}
}
main.c
#include "gpio.h"
#include "led.h"
#include "uart4.h"
#include "keyip.h"
#include "iic.h"
#include "si7006.h"
#include "ap3216c.h"
#include "spi.h"
/*
0:0xFC
1:0x60
2:0xDA
3:0xF2
4:0x66
5:0xB6
6:0xBE
7:0xE0
8:0xFE
9:0xF6
*/
extern void printf(const char *fmt, ...);
int main()
{
unsigned char led[10] = {0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0, 0xFE, 0xF6};
spi_init();
while (1)
{
int i,j,k;
for (i = 6; i >= 0; i--)
{
for (j = 9; j >= 0; j--)
{
for (k = 0; k < 20; k++)
{
spi_write(0x80);
spi_write(led[i]);
// 数据刷新到锁存寄存器
GPIOE->ODR &= (~(0x1 << 11));
delay_us();
GPIOE->ODR |= (0x1 << 11);
delay_us();
spi_write(0x40);
spi_write(led[j]);
// 数据刷新到锁存寄存器
GPIOE->ODR &= (~(0x1 << 11));
delay_us();
GPIOE->ODR |= (0x1 << 11);
delay_us();
}
}
}
return 0;
}
}