Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <msp430.h>
- volatile unsigned int distance_in_cm = 0;
- volatile unsigned int rising_edge = 0;
- volatile unsigned int start_time;
- volatile unsigned int total_time;
- void turn_on_timer(){
- P1OUT |= 1;
- }
- void turn_off_timer(){
- P1OUT &= ~(1);
- }
- #pragma vector = TIMER0_A1_VECTOR
- __interrupt void distance(void){ //TIMERA0 interrupt
- if(rising_edge){
- start_time = TACCR0; //checks for rising edge, if so, TACCRO is the start time
- }else{
- total_time = TACCR0 - start_time; //when rising_edge = 0, your saved time the pulse went and came back is TACCR0 - start_time
- distance_in_cm = total_time/58;
- }
- TA0CTL &= TAIFG;
- }
- int main(void){
- DCOCTL = 0;
- BCSCTL1 = CALBC1_1MHZ; //submain clock 1 MHZ
- DCOCTL = CALDCO_1MHZ;
- WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
- TA0CTL = TASSEL_2 | ID_3 | MC_2 | TAIE;
- TA0CCR0 = 100;
- // TASSEL_2 = Timer A clock source select : 2 - SMCLK
- // ID_3 = Timer A input divider : 3 - 100*8 = 800 microseconds = 0,0008 seconds
- // MC_2 = Timer A mode control : 2 - Continous up
- // enable timer interrupt
- __enable_interrupt();
- P1DIR &= ~(1<<1); //echo pin
- P1DIR |= 1; //trig pin
- P1OUT &= ~1;
- P2DIR |= 1<<2;
- P2OUT &= ~(1<<2);
- P2DIR |= (1<<2 | 1<<3 | 1<<4 | 1<<5 | 1<<6 | 1<<7);
- P2OUT &= ~(1<<2 | 1<<3 | 1<<4 | 1<<5 | 1<<6 | 1<<7);
- P1IE |= 1<<1;
- P1IES &= ~1<<1;
- while(1){
- rising_edge = 1; //after pulse has been send rising_edge = 1, TACCR0 detects rising and falling edges
- turn_on_timer();
- __delay_cycles(10); //wait 10 microseconds
- turn_off_timer();
- __delay_cycles(60000); // wait long enough for the interrupt service routine to kick in. 60000 microseconds = 0,06 seconds
- TA0CTL |= TAIFG;
- }
- rising_edge != rising_edge; //after this, the rising_edge needs to be the opposite as it was
- if(distance_in_cm > 32){
- P2OUT |= 1<<3;
- }else if(distance_in_cm < 32 && distance_in_cm > 25){
- P2OUT |= 1<<4;
- }else if(distance_in_cm < 25 && distance_in_cm > 20){
- P2OUT |= 1<<5;
- }else if(distance_in_cm < 20 && distance_in_cm > 15){
- P2OUT |= 1<<6;
- }else if(distance_in_cm < 15 && distance_in_cm > 10){
- P2OUT |= 1<<7;
- }
- while(1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement