Computers, Development Boards & Shields
Educational & Robotics Kits
Electronic Sensors
Motors & Controllers
Communication & Display
Electronic Components
Soldering & Lab Tools


I bought your HC-SR04 Ultrasonic Module to use with my TI MSP430 Micro-controller. Do you have a compatible library or any suggestions as to how I might convert your Arduino library to be most effective for my uses?

2 Answers


Supposedly you can use C code with the MSP430, but I also found an example in native machine code that goes over the details of the process. I prefer the simplicity of the Versalino/Arduino and other C based codes, but the basic principle always holds true with a Virtuabotix Ultrasonic Sensor, and that is that you send out a pulse, and you take a measurement of the time that the echo line is held high. That time is the number of milli or microseconds that it took for the signal to come back in.

That translates to twice the time for a one way trip, so you just divide by two, and then by the speed of sound in the medium you are using and you have a distance to work with.

;***************Start Ultrasonic Bursts and take measurements *****************

clr.w &CCTL1 ; Disable CCTL1
clr.w &TACTL ; Disable timer_A
bis.b #BIT0,&P1OUT ; LED ON
SetupTimerA mov.w #TASSEL0+TACLR+MC1,&TACTL
; TACLK = ACLK, 16 bit up mode
bis.b #BIT5,&P1SEL ; ACLK o/p on P1.5
mov.w #12,&CCR1 ; 12 cycle 40KHz burst
mov.w #CCIE,&CCTL1 ; Compare mode,interrupt
bis.w #LPM0,SR ; Wait for CCR1 interrupt
bic.b #BIT5,&P1SEL ; ACLK o/p on P1.5 OFF
TimerCLR bis.w #TACLR,&TACTL
mov.w #36,&CCR1 ; Delay for transducer to settle
mov.w #CCIE,&CCTL1 ; Compare mode,interrupt
bis.w #LPM0,SR ; Wait for CCR1 interrupt
bis.b #CAON,&CACTL1 ; Comparator_A ON
bic.b #CAIFG,&CACTL1 ; Enable Comparator_A interrupt flag
; Pos edge, CCIB,Cap,interrupt
push &TAR ; TOS = TAR at Start of measurement
bis.w #LPM0,SR ; Wait for CCR1 interrupt (Echo)
clr.w &CCTL1 ; Disable CCTL1
bic.b #BIT0,&P1OUT ; LED OFF
bit.b #CAIFG,&CACTL1 ; Check for Echo not received
jz Next ; ‘out of range’ condition
mov.w &CCR1,Result ; Result = TAR (CCR1) at EOC
sub.w @SP+,Result ; Result = time taken
add.w #48,Result ; compensate 12Clks for the burst
; transmission time + 36Clks delay

;****************** Measurement Done ******************************************

call #Math_calc ; Call Math subroutine
swpb DIGITS ; Shift left by two digits for /100
jmp Mainloop ; next measurement cycle
Next mov.w #0beh,DIGITS ; No echo received display ‘E’ error
jmp Mainloop

The full code is available here:


Thanks for your quick response. This looks fantastic.

Your Answer

No comments yet.

Leave a Reply