#include stm32f10xh IO#define MOTOR1A_PIN GPIO_Pin_0#define MOTOR1B_PIN GPIO_Pin_1#define MOTOR2A_PIN GPIO_Pin_2#define MOTOR2B_PIN GPIO_Pin_3#define MOTOR3A_PIN GPIO_Pin_4#define MOTOR3B_PIN GPIO_Pin
#include <stm32f10x.h>
// 定义IO口 #define MOTOR1A_PIN GPIO_Pin_0 #define MOTOR1B_PIN GPIO_Pin_1 #define MOTOR2A_PIN GPIO_Pin_2 #define MOTOR2B_PIN GPIO_Pin_3 #define MOTOR3A_PIN GPIO_Pin_4 #define MOTOR3B_PIN GPIO_Pin_5 #define MOTOR4A_PIN GPIO_Pin_6 #define MOTOR4B_PIN GPIO_Pin_7
// 配置IO口 void GPIO_Configuration(void) { GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB,
ENABLE);
GPIO_InitStructure.GPIO_Pin = MOTOR1A_PIN | MOTOR1B_PIN | MOTOR2A_PIN | MOTOR2B_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = MOTOR3A_PIN | MOTOR3B_PIN | MOTOR4A_PIN | MOTOR4B_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
// 控制小车运动 void Car_Move(uint8_t motor1a, uint8_t motor1b, uint8_t motor2a, uint8_t motor2b, uint8_t motor3a, uint8_t motor3b, uint8_t motor4a, uint8_t motor4b) { GPIO_WriteBit(GPIOA, MOTOR1A_PIN, (BitAction)motor1a); GPIO_WriteBit(GPIOA, MOTOR1B_PIN, (BitAction)motor1b); GPIO_WriteBit(GPIOA, MOTOR2A_PIN, (BitAction)motor2a); GPIO_WriteBit(GPIOA, MOTOR2B_PIN, (BitAction)motor2b); GPIO_WriteBit(GPIOB, MOTOR3A_PIN, (BitAction)motor3a); GPIO_WriteBit(GPIOB, MOTOR3B_PIN, (BitAction)motor3b); GPIO_WriteBit(GPIOB, MOTOR4A_PIN, (BitAction)motor4a); GPIO_WriteBit(GPIOB, MOTOR4B_PIN, (BitAction)motor4b); }
// 主函数 int main(void) { // 配置GPIO GPIO_Configuration();
while (1) {
// 读取传感器状态
uint8_t sensor1 = GPIO_ReadInputDataBit(SENSOR_PORT, SENSOR_PIN1);
uint8_t sensor2 = GPIO_ReadInputDataBit(SENSOR_PORT, SENSOR_PIN2);
uint8_t sensor3 = GPIO_ReadInputDataBit(SENSOR_PORT, SENSOR_PIN3);
uint8_t sensor4 = GPIO_ReadInputDataBit(SENSOR_PORT, SENSOR_PIN4);
uint8_t sensor5 = GPIO_ReadInputDataBit(SENSOR_PORT, SENSOR_PIN5);
// 根据传感器状态控制小车运动
if (sensor3 == 0) {
// 传感器3触发
Car_Move(1, 0, 1, 0); // 前进
} else if (sensor2 == 0) {
// 传感器2触发
Car_Move(1, 0, 0, 0); // 停止
} else if (sensor4 == 0) {
// 传感器4触发
Car_Move(0, 0, 1, 0); // 后退
} else if (sensor1 == 0) {
// 传感器1触发
Car_Move(1, 1, 0, 0); // 左转
} else if (sensor5 == 0) {
// 传感器5触发
Car_Move(0, 0, 0, 0); // 停止
}
}
}
原文地址: https://www.cveoy.top/t/topic/imr6 著作权归作者所有。请勿转载和采集!