1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- /*
- * hc-sr04.c
- *
- * Copyright 2022 dh33ex <dh33ex@riseup.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
- * MA 02110-1301, USA or see <http://www.gnu.org/licenses/>.
- *
- *
- */
- #ifndef __msp430_h_
- #include <msp430.h>
- #endif
- #include "hc-sr04.h"
- void HC_SR04_init(unsigned char trig, unsigned char echo) {
- /* setup ports */
- P1DIR |= trig; /* set TRIGER to output */
- P1OUT &= ~trig; /* clear TRIGER port initially */
- P1DIR &= ~echo; /* set ECHO to input */
- P1REN &= ~echo; /* disable resistor */
- /* setup timer */
- TA0CTL |= TACLR; /* reset timer */
- TA0CTL |= MC_2; /* continuous mode */
- TA0CTL |= TASSEL_2; /* choose SCMLK */
- TA0CTL |= ID_0; /* div-by-1 in prescalar */
- }
- float HC_SR04_mesure(unsigned char trig, unsigned char echo) {
- float distatnce;
- P1OUT |= trig;
- __delay_cycles(15);
- P1OUT &= ~trig;
- TA0R = 0;
- while (!(P1IN & echo)) {
- if (TA0R > 16384) { /* timeout */
- return -1;
- }
- }
- TA0R = 0;
- while (P1IN & echo);
- distatnce = TA0R * 0.017;
- return distatnce;
- }
|