This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Msp430 hcsr04 interrupt

#include <msp430.h>

int main()
{
    int echo_pulse_duration;      // time in us
    int distance_cm;

    // Disable watchdog timer
    WDTCTL = WDTPW + WDTHOLD;

    // Make P1.0 a digital output for the LED and P1.6
    // a digital output for the sensor trigger pulses
    P1DIR = BIT1+BIT6;
    P1IN = BIT2;

    // Set up Timer_A1: SMCLK clock, input divider=1,
    // "continuous" mode. It counts from 0 to 65535,
    // incrementing once per clock cycle (i.e. every 1us).
    TA1CTL = TASSEL_2 + ID_0 + MC_2;

    // Now just monitor distance sensor
    while(1)
    {

        // Send a 20us trigger pulse
        P1OUT |= BIT1;                // trigger high
        __delay_cycles(20);           // 20us delay
        P1OUT &= ~BIT1;               // trigger low

        // Measure duration of echo pulse
        while ((P1IN & BIT2) == 0);   // Wait for start of echo pulse
        TA1R = 0;                     // Reset timer at start of pulse
        while ((P1IN & BIT2) > 0);    // Wait for end of echo pulse
        echo_pulse_duration = TA1R;   // Current timer value is pulse length
        distance_cm = 0.017 * echo_pulse_duration; // Convert from us to cm

        if (distance_cm < 50) P1OUT |= BIT6; // LED on
        else P1OUT &= ~BIT6;                 // LED off
    }
}


So I am trying to make projects with hc-sr04. This code above works but I want to make it with interrupt and see distance in serial terminal screen. Can anyone help me?

  • Do you want use to write all the code for you?
    If not, what exactly do you have problems with?
  • I am new with coding with c language and I am not familiar with interrupts. I made a little project with interrupts but it was too easy(toggle led with a button) So I am trying to learn more about interrupts but I dont know how I can manage with the data from the sensor.If you can guide me I would apriciated.

    And also I am trying to use terminal but I feel like I am too far from that ^^
  • Using interrupts typically requires that you organize your program as a state machine, and in the interrupt handler, you do whatever is necessary in the current state. Have a look at the MSP example programs.

    With the LaunchPad, to output something to the terminal, just write it to the UART output. (See the UART examples.) When using interrupts, it's more complex because you write only one byte at a time from the interrupt handler.

**Attention** This is a public forum