</pre></p><span style="font-size:18px;">今天看到同事用STM里位操作时候觉得挺像51的,额,挺怀念51编写程序的风格了今天跟大家分享下stm32位操作的实现方法.</span><p></p><pre code_snippet_id="575904" snippet_file_name="blog_20150109_2_5404986" name="code" class="cpp"><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="cpp">#ifndef __LED_H
#define __LED_H
#define BITBAND(addr, bitnum) ((addr & 0xF0000000)+0x2000000+((addr &0xFFFFF)<<5)+(bitnum<<2))
#define MEM_ADDR(addr) *((volatile unsigned long *)(addr))
#define BIT_ADDR(addr, bitnum) MEM_ADDR(BITBAND(addr, bitnum))
#define GPIO_ODR_OFFSET 12
#define GPIO_IDR_OFFSET 8
//IO口地址映射
#define GPIOA_ODR_Addr (GPIOA_BASE+GPIO_ODR_OFFSET)
#define GPIOB_ODR_Addr (GPIOB_BASE+GPIO_ODR_OFFSET)
#define GPIOC_ODR_Addr (GPIOC_BASE+GPIO_ODR_OFFSET)
#define GPIOD_ODR_Addr (GPIOD_BASE+GPIO_ODR_OFFSET)
#define GPIOE_ODR_Addr (GPIOE_BASE+GPIO_ODR_OFFSET)
#define GPIOF_ODR_Addr (GPIOF_BASE+GPIO_ODR_OFFSET)
#define GPIOG_ODR_Addr (GPIOG_BASE+GPIO_ODR_OFFSET)
#define GPIOA_IDR_Addr (GPIOA_BASE+GPIO_IDR_OFFSET)
#define GPIOB_IDR_Addr (GPIOB_BASE+GPIO_IDR_OFFSET)
#define GPIOC_IDR_Addr (GPIOC_BASE+GPIO_IDR_OFFSET)
#define GPIOD_IDR_Addr (GPIOD_BASE+GPIO_IDR_OFFSET)
#define GPIOE_IDR_Addr (GPIOE_BASE+GPIO_IDR_OFFSET)
#define GPIOF_IDR_Addr (GPIOF_BASE+GPIO_IDR_OFFSET)
#define GPIOG_IDR_Addr (GPIOG_BASE+GPIO_IDR_OFFSET)
//IO口操作,只对单一的IO口!
//确保n的值小于16!
#define PAout(n) BIT_ADDR(GPIOA_ODR_Addr,n) //输出
#define PAin(n) BIT_ADDR(GPIOA_IDR_Addr,n) //输入
#define PBout(n) BIT_ADDR(GPIOB_ODR_Addr,n) //输出
#define PBin(n) BIT_ADDR(GPIOB_IDR_Addr,n) //输入
#define PCout(n) BIT_ADDR(GPIOC_ODR_Addr,n) //输出
#define PCin(n) BIT_ADDR(GPIOC_IDR_Addr,n) //输入
#define PDout(n) BIT_ADDR(GPIOD_ODR_Addr,n) //输出
#define PDin(n) BIT_ADDR(GPIOD_IDR_Addr,n) //输入
#define PEout(n) BIT_ADDR(GPIOE_ODR_Addr,n) //输出
#define PEin(n) BIT_ADDR(GPIOE_IDR_Addr,n) //输入
#define PFout(n) BIT_ADDR(GPIOF_ODR_Addr,n) //输出
#define PFin(n) BIT_ADDR(GPIOF_IDR_Addr,n) //输入
#define PGout(n) BIT_ADDR(GPIOG_ODR_Addr,n) //输出
#define PGin(n) BIT_ADDR(GPIOG_IDR_Addr,n) //输入
#define LED1 PFout(6)
#define LED2 PFout(7)
#define LED3 PFout(8)
#define LED4 PFout(9)
#define LED5 PFout(10)
#endif
我的开发板的GPF6~10是LED灯.
建立一个工程.LED端口初始化为输出模式.
我们通常的写法是:
<span style="white-space:pre"> </span>while(1)
{
GPIO_SetBits(GPIOF, GPIO_Pin_9);
delay(100);
GPIO_ResetBits(GPIOF, GPIO_Pin_9);
delay(100);
}
有的人说我用宏写可以写成:
LED1_On();
LED1_Off();
但是我想说的是用了我上面的头文件你就可以这样写了:
<span style="white-space:pre"> </span>while(1)
{
LED1=1;
delay(100);
LED1=0;
delay(100);
}
是不是很有51的风味啊~