XPT2046驱动代码
时间: 2023-08-05 11:02:09 浏览: 197
XPT2046触摸屏实验过程详解与STM32代码解析
以下是XPT2046触摸屏控制器的驱动代码示例,供参考:
```c
#include "stm32f10x.h"
#include "stm32f10x_spi.h"
#include "xpt2046.h"
#define XPT2046_CS_LOW() GPIO_ResetBits(GPIOB, GPIO_Pin_12)
#define XPT2046_CS_HIGH() GPIO_SetBits(GPIOB, GPIO_Pin_12)
static void XPT2046_SPI_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_SPI2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI2, &SPI_InitStructure);
SPI_Cmd(SPI2, ENABLE);
}
static uint8_t XPT2046_SPI_ReadWrite(uint8_t data)
{
while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
SPI_I2S_SendData(SPI2, data);
while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET);
return SPI_I2S_ReceiveData(SPI2);
}
void XPT2046_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
XPT2046_CS_HIGH();
XPT2046_SPI_Init();
}
int16_t XPT2046_GetData(uint8_t addr)
{
uint8_t tx_data[3], rx_data[3];
uint16_t data = 0;
XPT2046_CS_LOW();
tx_data[0] = addr;
tx_data[1] = 0x00;
tx_data[2] = 0x00;
XPT2046_SPI_ReadWrite(tx_data[0]); // Start bit
rx_data[0] = XPT2046_SPI_ReadWrite(tx_data[1]); // High byte
rx_data[1] = XPT2046_SPI_ReadWrite(tx_data[2]); // Low byte
XPT2046_CS_HIGH();
data = ((rx_data[0] << 5) | (rx_data[1] >> 3)) & 0xFFF;
return data;
}
void XPT2046_GetCoordinates(uint16_t *x, uint16_t *y)
{
*x = XPT2046_GetData(0xD0);
*y = XPT2046_GetData(0x90);
}
```
使用时可调用`XPT2046_Init()`进行初始化,然后调用`XPT2046_GetCoordinates()`获取坐标数据。其中,`XPT2046_GetData()`函数用于读取指定地址的16位数据。
阅读全文