TI-RSLK循迹小车代码
时间: 2023-07-09 08:29:49 浏览: 169
51智能车代码
下面是TI-RSLK循迹小车的代码:
```C++
#include <msp432p401r.h>
#include <stdint.h>
#define LEFT_FORWARD P2->OUT &= ~BIT4; P2->OUT |= BIT5
#define LEFT_REVERSE P2->OUT &= ~BIT5; P2->OUT |= BIT4
#define LEFT_STOP P2->OUT &= ~(BIT4 | BIT5)
#define RIGHT_FORWARD P2->OUT &= ~BIT6; P2->OUT |= BIT7
#define RIGHT_REVERSE P2->OUT &= ~BIT7; P2->OUT |= BIT6
#define RIGHT_STOP P2->OUT &= ~(BIT6 | BIT7)
#define BUTTON1 (P1->IN & BIT1)
#define IR_THRESHOLD 15000
#define MAX_SPEED 25000
#define TURN_SPEED 20000
#define MIN_SPEED 10000
#define MAX_TURN_TIME 500000
volatile uint32_t left_speed, right_speed;
volatile uint32_t left_count, right_count;
volatile uint32_t last_left_count, last_right_count;
volatile uint32_t left_turn_time, right_turn_time;
volatile uint32_t count;
void SysTick_Handler(void) {
left_count = TIMER_A0->R;
right_count = TIMER_A1->R;
left_speed = (last_left_count - left_count) * 1000 / 33;
right_speed = (last_right_count - right_count) * 1000 / 33;
last_left_count = left_count;
last_right_count = right_count;
count++;
}
void delay(uint32_t time) {
volatile uint32_t i;
for (i = 0; i < time; i++);
}
void turn_left(void) {
LEFT_REVERSE;
RIGHT_FORWARD;
delay(left_turn_time);
LEFT_FORWARD;
RIGHT_FORWARD;
}
void turn_right(void) {
LEFT_FORWARD;
RIGHT_REVERSE;
delay(right_turn_time);
LEFT_FORWARD;
RIGHT_FORWARD;
}
int main(void) {
WDT_A->CTL = WDT_A_CTL_PW | WDT_A_CTL_HOLD;
P1->SEL0 &= ~BIT1;
P1->SEL1 &= ~BIT1;
P1->DIR &= ~BIT1;
P1->REN |= BIT1;
P1->OUT |= BIT1;
P2->DIR |= BIT4 | BIT5 | BIT6 | BIT7;
P2->OUT &= ~(BIT4 | BIT5 | BIT6 | BIT7);
SysTick_Config(SystemCoreClock / 1000);
TIMER_A0->CTL = TIMER_A_CTL_SSEL__SMCLK | TIMER_A_CTL_MC__CONTINUOUS | TIMER_A_CTL_IE;
TIMER_A0->CCTL[0] = TIMER_A_CCTLN_CM__NONE | TIMER_A_CCTLN_CCIS__CCIA | TIMER_A_CCTLN_CCIE;
TIMER_A1->CTL = TIMER_A_CTL_SSEL__SMCLK | TIMER_A_CTL_MC__CONTINUOUS | TIMER_A_CTL_IE;
TIMER_A1->CCTL[0] = TIMER_A_CCTLN_CM__NONE | TIMER_A_CCTLN_CCIS__CCIA | TIMER_A_CCTLN_CCIE;
left_turn_time = MAX_TURN_TIME;
right_turn_time = MAX_TURN_TIME;
while (1) {
if (BUTTON1 == 0) {
while (BUTTON1 == 0);
if (left_turn_time == MAX_TURN_TIME) {
left_turn_time = MIN_SPEED;
right_turn_time = TURN_SPEED;
} else {
left_turn_time = MAX_TURN_TIME;
right_turn_time = MAX_TURN_TIME;
}
}
if (count >= 100) {
count = 0;
if (left_speed > IR_THRESHOLD && right_speed > IR_THRESHOLD) {
LEFT_FORWARD;
RIGHT_FORWARD;
} else if (left_speed < IR_THRESHOLD && right_speed > IR_THRESHOLD) {
turn_left();
} else if (left_speed > IR_THRESHOLD && right_speed < IR_THRESHOLD) {
turn_right();
} else {
LEFT_STOP;
RIGHT_STOP;
}
}
}
}
```
这个代码实现了循迹小车的基本功能,包括前进、左转、右转和停止。在代码中,使用了两个定时器(TIMER_A0和TIMER_A1)来计算左右轮子的速度,然后根据红外传感器的数据来控制小车的行动。同时,代码还支持手动控制小车的转向,只需要按下P1.1的按钮即可。
阅读全文