C语言 STM32 阵列用于控制单个 GPIO



我是嵌入式系统和C编程的新手。我目前正在尝试使用STM32微控制器对PCB进行编程,以便在收到单个通信后控制8个风扇阵列。即00001011将打开风扇 5、7 和 8。总共有 256 种可能的组合,对每个组合进行编程效率不高。

我正在考虑使用一个数组来实现这一点,例如;

fan_array[8] = {fan1, fan2, fan3, fan4, fan5, fan6, fan7, fan8};
printf ("Input fan state"); // user would input binary number as shown above
scanf (%d, fan_array);

这会根据输入到数组中的二进制值设置控制每个风扇的 GPIO 引脚高或低吗?

如果你考虑一下,有 256 种可能的组合,但你只对 8 个风扇感兴趣,所以你需要检查的只是 8 位:

#include <stdio.h>
#define STATE_ON    0x01
#define STATE_OFF    0x00
void enable_relay(unsigned char relay, unsigned char state)
{
/* This is a brute force approach that enables any relay/port combination:
* relay 8: PB2
* relay 7: PB4
* (...)
* relay 1: PA1
*/
switch(relay)
{
case 8:
if(state == STATE_ON)
GPIOB->ODR |= 0x0004;
else
GPIOB->ODR &= ~0x0004;
break;
case 7:
if(state == STATE_ON)
GPIOB->ODR |= 0x0010;
else
GPIOB->ODR &= ~0x0010;
break;
case 1:
if(state == STATE_ON)
GPIOA->ODR |= 0x0002;
else
GPIOA->ODR &= ~0x0002;
break;
}
}
void check_relay(unsigned char fan_map)
{
int i;
unsigned char bit;
unsigned char state;
for(i=0; i < 8; i++) {
bit = (fan_map&(0x01<<i));
state = ((bit != 0)? STATE_ON : STATE_OFF);
enable_relay( (8-i), state);
}
}
int main(void)
{
unsigned char fan_map = 0x0B; /* 0x0B = 00001011 */
check_relay(fan_map);
}

您需要8-i部分,因为您的位顺序与值顺序相反(fan1 作为最左边的位((MSB 是最左边的位(。

最新更新