(一)选择PB10与PB11 为高速输出模式,模拟I2C协议;
(二)选择PB6与PB7为输入,检测按键;
(三)其它平常配置;
添加工程文件 -> Game文件
添加头文件:
#include "stdlib.h"
#include "oled.h"
#include "dinogame.h"
/* USER CODE BEGIN PV */
int get_key_val()
{
if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_6)== GPIO_PINSET)
{
HAL_Delay(50);
if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_6)==GPIO_PIN_SET)
{
return 2;
}
}
if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7)==GPIO_PIN_SET)
{
HAL_Delay(50);
if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7)==GPIO_PIN_SET)
{
return 1;
}
}
return 0;
}
/* USER CODE END PV */
变量:
/* USER CODE BEGIN 1 */
unsigned char key_num = 0;
unsigned char cactus_category = 0;
unsigned char cactus_length = 8;
unsigned int score = 0;
unsigned int highest_score = 0;
int height = 0;
int cactus_pos = 128;
unsigned char cur_speed = 30;
char failed = 0;
char reset = 0;
/* USER CODE END 1 */
准备:
/* USER CODE BEGIN 2 */
OLED_Init();
OLED_ShowString(0,0,"Test",4);
/* USER CODE END 2 */
OLED_DrawCover();
while(get_key_val()!=2);
HAL_Delay(100);
OLED_Clear();
/* Infinite loop */
/* USER CODE BEGIN WHILE */
主函数:
if (failed == 1)
{
OLED_DrawRestart();
key_num = get_key_val();
if (key_num == 2)
{
if(score > highest_score) highest_score = score;
score = 0;
failed = 0;
height = 0;
reset = 1;
OLED_DrawDinoJump(reset);
OLED_DrawCactusRandom(cactus_category, reset);
OLED_Clear();
}
continue;
}
score ++;
if (height <= 0) key_num = get_key_val();
OLED_DrawGround();
OLED_DrawCloud();
if (height>0 || key_num == 1) height = OLED_DrawDinoJump(reset);
else OLED_DrawDino();
cactus_pos = OLED_DrawCactusRandom(cactus_category, reset);
if(cactus_category == 0) cactus_length = 8;
else if(cactus_category == 1) cactus_length = 16;
else cactus_length = 24;
if (cactus_pos + cactus_length < 0)
{
cactus_category = rand()%4;
OLED_DrawCactusRandom(cactus_category, 1);
}
if ((height < 16) && ( (cactus_pos>=16 && cactus_pos <=32) || (cactus_pos + cactus_length>=16 && cactus_pos + cactus_length <=32)))
{
failed = 1;
}
OLED_ShowString(0, 0, "I LOVE China", 12);
//OLED_ShowNum(58, 0, highest_score, 5, 12);
OLED_ShowNum(98, 0, score, 5, 12);
reset = 0;
cur_speed = score/20;
if (cur_speed > 29) cur_speed = 29;
HAL_Delay(30 - cur_speed);
// HAL_Delay(500);
key_num = 0;
(四)将OLED与按键接好即可。(按键接3.3V)