msp430f5529超声波测距并用oled显示的代码
时间: 2023-07-02 10:18:38 浏览: 170
超声波测距+oled显示
以下是一个基于msp430f5529的超声波测距并用oled显示的代码示例:
```c
#include <msp430.h>
#include <stdio.h>
#include "oled.h"
#define TRIG BIT3
#define ECHO BIT4
volatile int distance = 0;
volatile int count = 0;
void init_timer(void) {
TA0CTL |= TASSEL_2 + MC_1 + ID_3; // SMCLK, UP, DIV 8
TA0CCR0 = 60000; // 15ms
TA0CCTL0 |= CCIE;
}
void init_gpio(void) {
P2DIR |= TRIG;
P2DIR &= ~ECHO;
P2IE |= ECHO;
P2IES &= ~ECHO;
P2IFG &= ~ECHO;
}
void main(void) {
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
P4SEL |= BIT1 + BIT2; // UART
P4DIR |= BIT1; // TXD
UCA1CTL1 |= UCSWRST; // Reset
UCA1CTL1 |= UCSSEL_2; // SMCLK
UCA1BR0 = 104; // 9600 baud rate
UCA1BR1 = 0;
UCA1MCTL |= UCBRS_1 + UCBRF_0;
UCA1CTL1 &= ~UCSWRST; // Start
OLED_init();
OLED_clear();
OLED_write_string("Distance: ");
init_timer();
init_gpio();
__bis_SR_register(LPM0_bits + GIE);
}
#pragma vector=PORT2_VECTOR
__interrupt void Port_2(void) {
if (P2IFG & ECHO) {
if (P2IES & ECHO) {
TA0CTL |= TACLR;
count = 0;
P2IES &= ~ECHO;
} else {
distance = TA0R / 58;
char str[10];
sprintf(str, "%d", distance);
OLED_set_pos(0, 80);
OLED_write_string(str);
P2IES |= ECHO;
}
P2IFG &= ~ECHO;
}
}
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A(void) {
if (count < 3) {
P2OUT |= TRIG;
__delay_cycles(10);
P2OUT &= ~TRIG;
count++;
} else {
TA0CTL &= ~MC_1;
TA0CTL |= MC_1;
count = 0;
}
}
```
该代码使用定时器和中断实现超声波测距,并将距离信息显示在oled屏幕上。请确保正确连接超声波传感器和oled屏幕,并根据需要调整代码中的引脚和定时器参数。
阅读全文