|
楼主
查看: 4777回复: 2
发表于 2021-8-5 20:42:58
只看该作者
求助 想用编码电机实现测速功能,设想是用定时器测频率,看教程和例程自己弄了代码出来,但是单片机死活无法接收。教程是看的其他芯片,怀疑是不是换成了f5529后我自己少设置了什么东西。编码电机没问题,不用定时器中断的时候,输出的PWM波和串口输出都没问题,开启定时器中断后,接收不了中断,PWM波也很不正常,串口发送不了数据。
程序如下:
- #include "msp430.h"
- #include "stdint.h"
- #include <stdio.h>
- int j=1,k=0,l=1;
- void InitSystemClock(void)
- {
- P5SEL |= BIT2|BIT3; //将IO配置为XT2功能
- UCSCTL6 &= ~XT2OFF; //使能XT2
-
- UCSCTL4 = UCSCTL4&(~(SELA_7))|SELA_1; //先将ACLK配置为VLOCLK
- UCSCTL3 |= SELREF_2; //将REFCLK配置为REFCLK
-
- while (SFRIFG1 & OFIFG){
- UCSCTL7 &= ~(XT2OFFG + XT1LFOFFG + DCOFFG); // 清除三类时钟标志位
- // 这里需要清除三种标志位,因为任何一种
- // 标志位都会将OFIFG置位
- SFRIFG1 &= ~OFIFG; // 清除时钟错误标志位
- }
- UCSCTL4 = UCSCTL4&(~(SELS_7|SELM_7))|SELS_5|SELM_5; //将SMCLK和MCLK时钟源配置为XT2
- UCSCTL5 |= DIVS_2;
- }
- void InitUART(void)
- {
- /*复位USCI_Ax*/
- UCA0CTL1 |= UCSWRST;
- /*选择USCI_Ax为UART模式*/
- UCA0CTL0 &= ~UCSYNC;
- /*配置UART时钟源为SMCLK*/
- UCA0CTL1 |= UCSSEL1;
- /*配置波特率为9600@1MHz*/
- UCA0BR0 = 0x68;
- UCA0BR1 = 0x00;
- UCA0MCTL = 1 << 1;
- /*使能端口复用*/
- P3SEL |= BIT3 + BIT4;
- P3DIR |= BIT4;
- P3DIR &= ~BIT3;
- /*清除复位位,使能UART*/
- UCA0CTL1 &= ~UCSWRST;
- }
- void UARTSendString(uint8_t *pbuff,uint8_t num)
- {
- uint8_t cnt = 0;
- for(cnt = 0;cnt < num;cnt ++)
- {
- while(UCA0STAT & UCBUSY);
- UCA0TXBUF = *(pbuff + cnt);
- }
- }
- void PrintFreq(float freq)
- {
- uint32_t temp = (uint32_t)(freq * 1000);
- uint8_t charbuff[] = {0,0,0,0,0,0,0,0,0};//最大999999.999Hz
- int8_t cnt = 0;
- for(cnt = 8;cnt >= 0;cnt --)
- {
- charbuff[cnt] = (uint8_t)(temp % 10) + '0';
- temp /= 10;
- }
- UARTSendString("频率为:",8);
- UARTSendString(charbuff,6);
- UARTSendString(".",1);
- UARTSendString(charbuff + 6,3);
- UARTSendString("Hz",2);
- }
- void main()
- {
- WDTCTL = WDTPW | WDTHOLD;
- InitSystemClock();
- InitUART();
-
- P4DIR |= BIT7;
- P4OUT |= BIT7;
-
- /*设置时钟源为SMCLK*/
- TA0CTL |= TASSEL_2;
- /*设置工作模式为Up Mode*/
- TA0CTL |= MC1;
- /*设置定时间隔*/
- TA0CCR0 = 49999;//50ms
- /*开启TAIFG中断*/
- TA0CTL |= TAIE;
- /*捕捉功能*/
- TA0CCTL2 |= CAP;
- TA0CCTL1 |= CAP;
- /*上升沿捕捉*/
- TA0CCTL1 |= CM_2;
-
- TA0CCTL2 |= CM_2;
- TA0CCTL1 |= SCS;
- TA0CCTL2 |= SCS;
- /*捕捉输入*/
- TA0CCTL1 |= CCIS1;
- TA0CCTL2 |= CCIS1;
- P1SEL |= BIT2+BIT3;
- P1DIR &= ~(BIT2+BIT3);
- /*允许捕捉比较中断*/
- TA2CCTL2 |= CCIE;//输入2口
- TA2CCTL1 |= CCIE;//1口
- _EINT();
- while(1)
- {
- PrintFreq(j);
- PrintFreq(k);
- PrintFreq(l);
- __delay_cycles(5000000);
- }
-
- }
- #pragma vector = TIMER0_A1_VECTOR
- __interrupt void Time_Tick(void)
- {
-
- __bis_SR_register(GIE);
- switch(TA0IV)
- {
- case 0x02://1口
- l^=l;
- j ^= j;
- break;
- case 0x04://2口
-
- P4OUT ^= BIT7;
- break;
- case 0x0A://溢出
-
- k+=1;
- break;
- default:
- break;
- }
- }
复制代码 |
|