芯片的外设一般按照这么几个流程来进行,GPIO,外部中断,定时器,串口,ADC,IIC,SPI,下面我就按照各个模式来写
首先是GPIO,STM8的GPIO拥有复用功能,这句话告诉我们必然需要配置IO的复用功能才能使用,看这张表
DDR决定输入输出方向,CR1 CR2决定输入输出模式,上拉,下拉,推挽,开漏等
主要依靠这几个寄存器
还有一个控制寄存器2,懒得传了
按照这张表,输出写输出寄存器,输入读输入寄存器,就能完成GPIO的操作了
以下是操作代码
#include "key.h" u8 keyValue = 0;
#define KEY1_IN (GPIOD->IDR&0X80)
#define KEY2_IN (GPIOE->IDR&0X08) static void Delay(u16 nCount)
{
/* Decrement nCount value */
while (nCount != 0)
{
nCount--;
} } void KeyInit(void)
{
//D7初始化
GPIOD->DDR &= ~(1<<7);//设置为输入
GPIOD->CR1 |= (1<<7);
GPIOD->CR2 &= ~(1<<7);//10 上拉输入 //E3初始化
GPIOE->DDR &= ~(1<<3);//设置为输入
GPIOE->CR1 |= (1<<3);
GPIOE->CR2 &= ~(1<<3);//10 上拉输入
} u8 KeyScan(void)
{
if(KEY1_IN == 0)
{
Delay(16000);
if(KEY1_IN == 0)
{
keyValue = KEY_VALUE1;
return KEY_VALUE1;
}
}
if(KEY2_IN == 0)
{
Delay(16000);
if(KEY2_IN == 0)
{
keyValue = KEY_VALUE2;
return KEY_VALUE2;
}
}
return 0;
}
#ifndef __KEY_H_
#define __KEY_H_
#include "stm8s.h" //按键使用D7 E3
//按键按下低电平,按键松开高电平 #define KEY_VALUE1 1
#define KEY_VALUE2 2 extern u8 keyValue; void KeyInit(void); u8 KeyScan(void); #endif
#include "led.h" void LedInit(void)
{ //D1初始化
GPIOD->DDR |= (1<<1);//设置为输出
GPIOD->CR1 |= 1<<1;
GPIOD->CR2 &= ~(1<<1);//10 推挽输出 //d0
GPIOD->DDR |= (1<<0);//设置为输出
GPIOD->CR1 |= 1<<0;
GPIOD->CR2 &= ~(1<<0);//10 推挽输出 //c3
GPIOC->DDR |= (1<<3);//设置为输出
GPIOC->CR1 |= 1<<3;
GPIOC->CR2 &= ~(1<<3);//10 推挽输出
LedSet(1,1);
LedSet(2,1);
LedSet(3,1);
} void LedSet(u8 ch,u8 value)
{ switch(ch)
{
case 1:
if(value)GPIOD->ODR |= 1<<1;
else GPIOD->ODR &= ~(1<<1);
break;
case 2:
if(value)GPIOD->ODR |= 1<<0;
else GPIOD->ODR &= ~(1<<0);
break;
case 3:
if(value)GPIOC->ODR |= 1<<3;
else GPIOC->ODR &= ~(1<<3);
break;
}
}
#ifndef __LED_H_
#define __LED_H_
#include "stm8s.h" //led1 PD1 swim
//led2 pd0
//led3 pc3 d12_cs void LedInit(void); void LedSet(u8 ch,u8 value); #endif