第三期-代码编写(文末有工程源码和接线示意)
首先得搞清楚循迹原理,光电模块能够反馈当前检测的是黑线还是白的区域,那么我们就可以知道当左边的循迹模块检测到黑线时,这个时候车就得像左转,同理右边检测到的时候向右转。大家可以动脑想想是不是这样。
转向实现
转向就比较简单了,左右两边的轮子转速不一样就可以实现转速,通过改变左右两边的轮子pwm就可以实现。或者一个正转一个反转。
电机转向代码:
#include "motor.h"
void car_go_straight(void)//直走
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_RESET);//左电机正转
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_RESET);//右电机正转
}
void car_go_right(void)//右转
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_RESET);//左电机正转
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_SET);//右电机正转
}
void car_go_left(void)//左转
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_SET);//左电机反转
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_SET);//右电机正转
}
void car_go_ahead(void)//后走
{
HAL_GPIO_WritePin(motor11_GPIO_Port,motor11_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(motor12_GPIO_Port,motor12_Pin,GPIO_PIN_SET);//左电机反转
HAL_GPIO_WritePin(motor21_GPIO_Port,motor21_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(motor22_GPIO_Port,motor22_Pin,GPIO_PIN_RESET);//右电机反转
}
头文件:
#ifndef __MOTOR_H_
#define __MOTOR_H_
#include "main.h"
void car_go_straight(void);
void car_go_right(void);
void car_go_left(void);
void car_go_ahead(void);
#endif
循迹代码:
#include "Track.h"
#include "motor.h"
uint8_t tra;
void Tracking(void)
{
if(HAL_GPIO_ReadPin(sensor1_GPIO_Port,sensor1_Pin)){
tra=1;
}else if (HAL_GPIO_ReadPin(sensor2_GPIO_Port,sensor2_Pin))
{
tra=2;
}else
{
tra=0;
}
switch (tra)
{
case 1:
car_go_left();
break;
case 2:
car_go_right();
case 0:
car_go_straight();
default:
break;
}
}
头文件:
#ifndef __TRACK_H_
#define __TRACK_H_
#include "main.h"
void Tracking(void);
#endif
在主函数加入:
#include "Track.h"//包含头文件
TIM1->CCR1=TIM1->CCR2=500;//两个电机的速度范围(0-1000),越大越快。
Tracking();
工程源码:
链接:https://pan.baidu.com/s/17eUDzx6iF1KF1z879YLilw
提取码:ph2q
接线示意:
链接:https://pan.baidu.com/s/19mZJmORUjtLdUl9BgOezCA
提取码:0cwu