基於MSP430F5529的超聲波測距原始碼,自己寫的可能不對,僅供參考
阿新 • • 發佈:2018-11-13
超聲波的原理大家百度一下就應該知道了,因此基於MSP430的超聲波主要是調整時鐘就行了。
程式碼如下
#include "msp430f5529.h" #include "usart.h" #include "stdio.h" double a = 1.111; //距離 long long next; //暫存器值 /* * P3.6與TB0.6相連線,輸出訊號 */ int tim = 0; //溢位次數 void SetVcoreUp (unsigned int level) { PMMCTL0_H = PMMPW_H; SVSMHCTL = SVSHE + SVSHRVL0 * level + SVMHE + SVSMHRRL0 * level; SVSMLCTL = SVSLE + SVMLE + SVSMLRRL0 * level; while ((PMMIFG & SVSMLDLYIFG) == 0); PMMIFG &= ~(SVMLVLRIFG + SVMLIFG); PMMCTL0_L = PMMCOREV0 * level; if ((PMMIFG & SVMLIFG)) while ((PMMIFG & SVMLVLRIFG) == 0); SVSMLCTL = SVSLE + SVSLRVL0 * level + SVMLE + SVSMLRRL0 * level; PMMCTL0_H = 0x00; } void set(void) { volatile unsigned int i; WDTCTL = WDTPW+WDTHOLD; // Stop WDT P1DIR |= BIT1; // P1.1 output P1DIR |= BIT0; // ACLK set out to pins P1SEL |= BIT0; P2DIR |= BIT2; // SMCLK set out to pins P2SEL |= BIT2; P7DIR |= BIT7; // MCLK set out to pins P7SEL |= BIT7; // Increase Vcore setting to level3 to support fsystem=25MHz // NOTE: Change core voltage one level at a time.. SetVcoreUp (0x01); SetVcoreUp (0x02); SetVcoreUp (0x03); UCSCTL3 = SELREF_2; // Set DCO FLL reference = REFO UCSCTL4 |= SELA_2; // Set ACLK = REFO __bis_SR_register(SCG0); // Disable the FLL control loop UCSCTL0 = 0x0000; // Set lowest possible DCOx, MODx UCSCTL1 = DCORSEL_7; // Select DCO range 50MHz operation UCSCTL2 = FLLD_0 + 762; // Set DCO Multiplier for 25MHz __bic_SR_register(SCG0); // Enable the FLL control loop __delay_cycles(782000); do { UCSCTL7 &= ~(XT2OFFG + XT1LFOFFG + DCOFFG); // Clear XT2,XT1,DCO fault flags SFRIFG1 &= ~OFIFG; // Clear fault flags }while (SFRIFG1&OFIFG); // Test oscillator fault flag P6DIR |= BIT0; } void main() { set(); WDTCTL = WDTPW+WDTHOLD; // Stop WDT UART_Init(); //串列埠初始化 P3DIR |= BIT6; P3OUT &=~ BIT6; P3DIR &=~ BIT5; P3IN &=~ BIT5; P2DIR |= 0X00; P2IFG = 0X00; P2IE = BIT0; P2IES = BIT0; P2IN = BIT0; P2OUT = BIT0; P2REN = BIT0; __enable_interrupt(); P1SEL |= BIT4; P1DIR |= BIT4; P1DS |= BIT4; P1OUT &=~ BIT4; while(1) { P3OUT = BIT6; __delay_cycles(4); P3OUT &=~ BIT6; P2OUT &=~ BIT0; __delay_cycles(40000); } } #pragma vector=PORT2_VECTOR __interrupt void Port2_ISR(void) { unsigned int temp; if((P2IN&0X01)!=0X01) { temp=P2IFG; P2IFG=0x00; if(temp==0x01) { P2OUT = BIT0; //開始計時 TA0CCTL0 = CCIE; TA0CCR0 = 20000; TA0CTL = TASSEL_2 + MC_1 + TACLR; __bis_SR_register(GIE); while((P3IN&0X20) == 0X20); //a + TA0R TA0CTL = MC0; //next = TA0R; printf("next = %ld\n",TA0R); } } } #pragma vector = TIMER0_A0_VECTOR __interrupt void TIMER0_A0_ISR(void) { tim++; if(a>10) { tim = 0; P3OUT = BIT6; __delay_cycles(4); P3OUT &=~ BIT6; } }