1.主函数代码部分:
#include "stm32f10x.h" // Device header #include "Delay.h" #include "OLED.h" #include "Motor.h" #include "Key.h" uint8_t KeyNum; int8_t Speed; int main(void) { OLED_Init(); Motor_Init(); Key_Init(); OLED_ShowString(1, 1, "Speed:"); while (1) { KeyNum = Key_GetNum(); if (KeyNum == 1) { Speed += 20; if (Speed > 100) { Speed = -100; } } Motor_SetSpeed(Speed); OLED_ShowSignedNum(1, 7, Speed, 3); } }
2.直流电机封装部分:
#include "stm32f10x.h" // Device header #include "PWM.h" void Motor_Init(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); PWM_Init(); } void Motor_SetSpeed(int8_t Speed) { if (Speed >= 0) { GPIO_SetBits(GPIOA, GPIO_Pin_4); GPIO_ResetBits(GPIOA, GPIO_Pin_5); PWM_SetCompare3(Speed); } else { GPIO_ResetBits(GPIOA, GPIO_Pin_4); GPIO_SetBits(GPIOA, GPIO_Pin_5); PWM_SetCompare3(-Speed); } }
#ifndef __MOTOR_H #define __MOTOR_H void Motor_Init(void); void Motor_SetSpeed(int8_t Speed); #endif