手把手叫你用cubemx配置寻迹小车(附源码和接线教程)

第三期-代码编写(文末有工程源码和接线示意)

第一期(器件选择)
第二期(pwm,gpio配置)

首先得搞清楚循迹原理,光电模块能够反馈当前检测的是黑线还是白的区域,那么我们就可以知道当左边的循迹模块检测到黑线时,这个时候车就得像左转,同理右边检测到的时候向右转。大家可以动脑想想是不是这样。

转向实现

转向就比较简单了,左右两边的轮子转速不一样就可以实现转速,通过改变左右两边的轮子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

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bear_Fly-008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值