以kl25z为主控,3144霍尔传感器,液晶显示器DV12864G计算轮子速度及距离的代码
时间: 2024-02-01 16:16:23 浏览: 133
以下是基于kl25z主控、3144霍尔传感器和液晶显示器DV12864G的代码,用于计算轮子速度和距离:
```c
#include "MKL25Z4.h"
#include "stdio.h"
#include "math.h"
#define PI 3.14159265358979323846
#define CLOCKS_PER_SEC 1000
volatile int cnt = 0;
volatile int speed = 0;
volatile int distance = 0;
void PORTA_IRQHandler(void)
{
if ((PORTA->PCR[13] & 0x01000000) != 0)
{
cnt++;
PORTA->PCR[13] |= 0x01000000;
}
}
void TPM0_IRQHandler(void)
{
TPM0->SC |= 0x80;
speed = (cnt * 60 * CLOCKS_PER_SEC) / (2 * 20 * TPM0->MOD);
distance += 2 * PI * 0.05 / 20;
cnt = 0;
}
void init_hall_sensor(void)
{
SIM->SCGC5 |= 0x200;
PORTA->PCR[13] |= 0x00000110;
NVIC_EnableIRQ(PORTA_IRQn);
}
void init_tpm(void)
{
SIM->SCGC6 |= 0x01000000;
SIM->SOPT2 |= 0x01000000;
TPM0->SC = 0;
TPM0->SC = 0x07;
TPM0->MOD = 5000;
TPM0->SC |= 0x80;
NVIC_EnableIRQ(TPM0_IRQn);
}
void init_lcd(void)
{
SIM->SCGC5 |= 0x1000;
PORTD->PCR[0] |= 0x00000100;
PORTD->PCR[1] |= 0x00000100;
PORTD->PCR[2] |= 0x00000100;
PORTD->PCR[3] |= 0x00000100;
PORTD->PCR[4] |= 0x00000100;
PORTD->PCR[5] |= 0x00000100;
PORTD->PCR[6] |= 0x00000100;
PORTD->PCR[7] |= 0x00000100;
PTD->PDDR = 0xff;
PTD->PDOR = 0xff;
PTD->PDOR = 0x3f;
PTD->PDOR = 0x1f;
PTD->PDOR = 0x0f;
PTD->PDOR = 0x07;
PTD->PDOR = 0x03;
PTD->PDOR = 0x01;
PTD->PDOR = 0x00;
}
void lcd_cmd(unsigned char cmd)
{
PTD->PDOR = cmd;
PTD->PDOR = cmd | 0x80;
PTD->PDOR = cmd;
}
void lcd_data(unsigned char data)
{
PTD->PDOR = data;
PTD->PDOR = data | 0x80;
PTD->PDOR = data;
}
void lcd_clear(void)
{
lcd_cmd(0x01);
for (int i = 0; i < 10000; i++);
}
void lcd_putc(unsigned char c)
{
lcd_data(c);
}
void lcd_puts(char *s)
{
while (*s)
{
lcd_putc(*s++);
}
}
void init_sys(void)
{
init_hall_sensor();
init_tpm();
init_lcd();
}
int main()
{
init_sys();
lcd_clear();
lcd_puts("Speed: ");
lcd_puts("Distance: ");
while (1)
{
char buf[16];
sprintf(buf, "%d", speed);
lcd_cmd(0x80 + 7);
lcd_puts(buf);
sprintf(buf, "%d", distance);
lcd_cmd(0x80 + 17);
lcd_puts(buf);
for (int i = 0; i < 1000000; i++);
}
}
```
代码中使用了两个中断,一个用于检测霍尔传感器的计数器,另一个用于更新速度和距离。在初始化函数中,初始化了霍尔传感器、计时器和液晶显示器。在主循环中,将速度和距离输出到液晶显示器上。
阅读全文