Hi all,
I have a problem with a code that i am developing and need your help. Next, the information about the problem:
I have a PWM signal from a range sensor (MaxBotix EZ3) with a period of 20Hz as an input into the Timer0 in capture mode into P4.0. I have to measure the pulse width (147us/inch) to calculate the proximity of the sensor to the ground.
For the microcontroller I have a 8MHz xtal and MCLK = ACLK = SMCLK = 8MHz. For the timer i used the ACLK clock source. The value of the capture result is sent via USART0 to the PC.
The problem is that i receive bad data. Whith the sensor in horizontal position pointing to the roof and using the osciloscope to check the PWM signal, the output are pulses of 13ms (147us/inch) that corresponds to 210cm, that is correct. Always the same. But when i capture the signal with the Timer0 capture module, i receive random values allways arround 60cm. I think the problem is related to frequencies of both the clock and the PWM signal or to the synchronization, but i tried all kind of posible solutions but allways receive the same random data.
Could you guys help me and tell me where is my error. Next i add my code:
#include <msp430x16x.h>
unsigned int range;
unsigned char index = 0;
unsigned int measure;
unsigned int measure_1;
unsigned int measure_2;
main()
{
WDTCTL = WDTPW + WDTHOLD; // Stop WDT
P3SEL |= 0x30; // P3.4,5 = USART0 TXD/RXD
BCSCTL1 |= XTS; // ACLK= LFXT1= HF XTAL
do
{
IFG1 &= ~OFIFG; // Clear OSCFault flag
for (i = 0xFF; i > 0; i--); // Time for flag to set
}
while ((IFG1 & OFIFG)); // OSCFault flag still set?
BCSCTL2 |= SELM_3; // MCLK = LFXT1 (safe)
//USART configuration
ME1 |= UTXE0 + URXE0; // Enable USART0 TXD/RXD
U0CTL |= CHAR; // 8-bit character
U0TCTL |= SSEL0; // UCLK= ACLK
U0BR0 = 0x45; // 8MHz 115200
U0BR1 = 0x00; // 8MHz 115200
U0MCTL = 0x00; // 8MHz 115200 modulation
U0CTL &= ~SWRST; // Initialize USART state machine
IE1 |= URXIE0; // Enable USART0 RX interrupt
//TimerB capture configuration
TBCCTL0 |= CM_3 + SCS + CCIS_1 + CAP + CCIE;
TBCTL |= CNTL_0 + TBSSEL_1 + MC_2;
_BIS_SR(GIE); // interrupt
P2DIR = 0x01; // P2.0=ACLK
P2SEL = 0x01;
P4DIR = 0x00; // Set P4.0 input dir
P4SEL = 0x01; // Set P4.0 to TB0
while (1)
{ }
}
#pragma vector=TIMERB0_VECTOR
__interrupt void TimerB0(void)
{
unsigned int rangeH;
unsigned char rangeHrot;
unsigned int rangeL;
measure= TBCCR0;
index++;
if (index == 1)
{
measure_1 = measure;
}
if (index == 2)
{
measure_2 =measure;
range = (measure_2 - measure_1);
rangeH = (0xFF00 & range); //USART needs unsigned char --> I need to separate range in rangeH and rangeL
rangeHrot = (unsigned char)(rangeH/256); //rotate 8 bits
rangeL= (unsigned char)(0x00FF & range);
TXBUF0= rangeHrot;
while (!(IFG1 & UTXIFG0));
TXBUF0= rangeL;
while (!(IFG1 & UTXIFG0));
TBCCTL0 &= ~CCIFG;
index=0;
}
}
Thank you for your help in advance. I wait for your suggestions.
Greetings!!!