单片机|GPIO相关寄存器

1. STM32的GPIO相关寄存器 【单片机|GPIO相关寄存器】GPIOx_BRR
GPIOx_BSRR
GPIOx_CRH
GPIOx_CRL
GPIOx_IDR
GPIOx_LCKR
GPIOx_ODR
1.1 输入输出方向的设置
涉及到两个32位的配置寄存器(Configuration Register),CRH,CRL。

GPIOB->CRL &= 0x0FFFFFFF; GPIOB->CRL|=0x30000000; //3<<28; //配置PB7为输出 GPIOB->CRL &= 0x0FFFFFFF; GPIOB->CRL|=0x80000000; //8<<28; //配置PB7为输入GPIOB->CRH &= 0xFFFFFFF0; GPIOB->CRH|=3<<0; //配置PB8为输出 GPIOB->CRH &= 0xFFFFFFF0; GPIOB->CRH|=8<<0; //配置PB8为输入

单片机|GPIO相关寄存器
文章图片

/* Check if the current bit belongs to first half or last half of the pin count number in order to address CRH or CRL register*/ configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL: &GPIOx->CRH; registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2u) : ((position - 8u) << 2u); /* Apply the new configuration of the pin to the register */ MODIFY_REG((*configregister), ((GPIO_CRL_MODE0 | GPIO_CRL_CNF0) << registeroffset), (config << registeroffset));

1.2 读取引脚高低电平值
涉及到两个32位数据寄存器(Data Register),IDR,ODR。
#define I2C_SDA_READ()(GPIO_PORT_I2C->IDR & I2C_SDA_PIN)// 读取SDA电平

单片机|GPIO相关寄存器
文章图片

void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) { uint32_t odr = GPIOx->ODR; /* Set selected pins that were at low level, and reset ones that were high */ GPIOx->BSRR = ((odr & GPIO_Pin) << GPIO_NUMBER) | (~odr & GPIO_Pin); }

GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) { GPIO_PinState bitstatus; if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET) { bitstatus = GPIO_PIN_SET; } else { bitstatus = GPIO_PIN_RESET; } return bitstatus; }

1.3 置位和复位的设置
涉及到一个32位置位/复位寄存器(Bit Set/Reset Register),BSRR;一个32位复位寄存器(Bit Reset Register),BRR。
GPIOB->BSRR = GPIO_PIN_7; // PB7 Set GPIOB->BSRR = (uint32_t)GPIO_PIN_7<< 16U// PB7 Reset GPIOB->BRR= GPIO_PIN_7; // PB7 Reset

单片机|GPIO相关寄存器
文章图片

void HAL_GPIO_WritePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState) { if (PinState != GPIO_PIN_RESET) { GPIOx->BSRR = GPIO_Pin; } else { GPIOx->BSRR = (uint32_t)GPIO_Pin << 16u; } }

1.4 锁定IO
TTL施密特触发器有开/关,相应的一个32位锁定寄存器(GPIOx_LCKR)可以控制开关让输入数据寄存器保持当前的状态,达到一个锁定的效果,在某些应用场合很有效果。
要使用该寄存器,需要先激活“锁定”功能。
单片机|GPIO相关寄存器
文章图片

HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) { __IO uint32_t tmp = GPIO_LCKR_LCKK; /* Apply lock key write sequence */ SET_BIT(tmp, GPIO_Pin); /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ GPIOx->LCKR = tmp; /* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */ GPIOx->LCKR = GPIO_Pin; /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ GPIOx->LCKR = tmp; /* Read LCKK register. This read is mandatory to complete key lock sequence */ tmp = GPIOx->LCKR; /* read again in order to confirm lock is active */ if ((uint32_t)(GPIOx->LCKR & GPIO_LCKR_LCKK)) { return HAL_OK; } else { return HAL_ERROR; } }

2. HHD 未完待续。

    推荐阅读