demo_spi.h
#include "hw_gpio.h"
#include "hw_uart.h"
#include "hw_spi.h"
#include "osal.h"
#include "resmgmt.h"
#define SPITimeOut ((unsigned int)0x0050)
void demo_spi_init(void);
void spi_write_reg(unsigned char data);
char spi_read_reg(unsigned char Addr);
demo_spi.c
#include "hw_spi.h"
#include "demo_spi.h"
#include <stdint.h>
#include "stdio.h"
void spi_pin_config()
{
hw_gpio_set_pin_function(HW_GPIO_PORT_3,HW_GPIO_PIN_7,HW_GPIO_MODE_OUTPUT_PUSH_PULL,\
HW_GPIO_FUNC_SPI_CLK);
hw_gpio_set_pin_function(HW_GPIO_PORT_1,HW_GPIO_PIN_4,HW_GPIO_MODE_OUTPUT_PUSH_PULL,\
HW_GPIO_FUNC_SPI_DO);
hw_gpio_set_pin_function(HW_GPIO_PORT_1,HW_GPIO_PIN_7,HW_GPIO_MODE_INPUT_PULLUP,\
HW_GPIO_FUNC_SPI_DI);
hw_gpio_set_pin_function(HW_GPIO_PORT_3,HW_GPIO_PIN_5,HW_GPIO_MODE_OUTPUT_PUSH_PULL,\
HW_GPIO_FUNC_GPIO);
}
void demo_spi_init(void)
{
spi_config SPI1;
spi_pin_config();
//multiplexing pin
//configure SPI module
hw_spi_enable(HW_SPI1,0);
SPI1.cs_pad.port=HW_GPIO_PORT_3;
SPI1.cs_pad.pin=HW_GPIO_PIN_5;
SPI1.word_mode = HW_SPI_MODE_MASTER;
SPI1.smn_role = HW_SPI_WORD_8BIT;
SPI1.polarity_mode = HW_SPI_POL_LOW;
SPI1.phase_mode = HW_SPI_PHA_MODE_0;
SPI1.xtal_freq = HW_SPI_FREQ_DIV_8;
SPI1.fifo_mode = HW_SPI_FIFO_NONE;
hw_spi_init(HW_SPI1,&SPI1);
}
void spi_write_reg(unsigned char data)
{
unsigned int TIMEOUT = SPITimeOut;
while(hw_spi_is_busy(HW_SPI1))
{
TIMEOUT--;
if(TIMEOUT==0)
{
printf("write_err!\r\n");
while(hw_uart_is_busy(HW_UART1));
return ;
}
}
hw_spi_fifo_write8(HW_SPI1,data);
}
char spi_read_reg(unsigned char Addr)
{
unsigned int TIMEOUT = SPITimeOut;
char Recchar;
while(hw_spi_is_busy(HW_SPI1))
{
TIMEOUT--;
if(TIMEOUT==0)
{
printf("read_err!\r\n");
while(hw_uart_is_busy(HW_UART1));
return 0;
}
}
while (!hw_spi_get_interrupt_status(HW_SPI1)) {
}
Recchar = hw_spi_fifo_read8(HW_SPI1);
hw_spi_clear_interrupt(HW_SPI1);
return Recchar;
}