gpt4 book ai didi

c - 用于控制单独 GPIO 的 STM32 阵列

转载 作者:行者123 更新时间:2023-11-30 18:11:03 25 4
gpt4 key购买 nike

我是嵌入式系统和 C 编程新手。我目前正在尝试使用 STM32 微 Controller 对 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 部分,因为您的位顺序与值顺序(MSB 是最左边的位)相反(fan1 作为最左边的位)。

关于c - 用于控制单独 GPIO 的 STM32 阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52553508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com