# GPIO
###### tags: `firmware_hardware` `electrical_system` `NTURT`
In the world of computers, all data are written in 1s and 0s. In the physical world, these binary data can be represented by many different things, but high and low voltages in a certain node of a circuit is the most common way. GPIO is the simplest way an electronic chip can change a logical 1 to a physical high voltage or read a physical high voltage to a logical 1.
## HAL Cheatsheet
### Function
#### Reading digital states of a Pin
```c=
//prototype
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
//application example
uint8_t state = HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_2);
```
#### Writing the digital state of a pin
```c=
//prototype
void HAL_GPIO_WritePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState)
//application example
HAL_GPIO_WrtiePin(GPIOC,GPIO_PIN_13,GPIO_PIN_RESET);
```
#### Flipping the State of a Pin
```c=
//prototype
void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
//application example
HAL_GPIO_TogglePin(GPIOB,GPIO_PIN_5);
```
### HAL Definitions
#### The State of a Pin
```c=
/*----------------PinStates----------------*/
//pinstates reported by HAL is a enum that can be implicitly casted to 0 and 1
typedef enum
{
GPIO_PIN_RESET = 0u,
GPIO_PIN_SET
} GPIO_PinState;
```
#### GPIO Pin Ports
```c=
//GPIO Ports are a long tree of define and typedefs,
//so we only have to call the defined names
#define GPIOC ((GPIO_TypeDef *)GPIOC_BASE)
//etc
```
#### GPIO Pin Numbers
```c=
//The pin number is actually the content directly put into the registers,
//though we only have to use the defined aliases when calling functions
#define GPIO_PIN_0 ((uint16_t)0x0001)
#define GPIO_PIN_1 ((uint16_t)0x0002)
//etc
```