hc-sr04.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * hc-sr04.c
  3. *
  4. * Copyright 2022 dh33ex <dh33ex@riseup.net>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. * MA 02110-1301, USA or see <http://www.gnu.org/licenses/>.
  20. *
  21. *
  22. */
  23. #ifndef __msp430_h_
  24. #include <msp430.h>
  25. #endif
  26. #include "hc-sr04.h"
  27. void HC_SR04_init(unsigned char trig, unsigned char echo) {
  28. /* setup ports */
  29. P1DIR |= trig; /* set TRIGER to output */
  30. P1OUT &= ~trig; /* clear TRIGER port initially */
  31. P1DIR &= ~echo; /* set ECHO to input */
  32. P1REN &= ~echo; /* disable resistor */
  33. /* setup timer */
  34. TA0CTL |= TACLR; /* reset timer */
  35. TA0CTL |= MC_2; /* continuous mode */
  36. TA0CTL |= TASSEL_2; /* choose SCMLK */
  37. TA0CTL |= ID_0; /* div-by-1 in prescalar */
  38. }
  39. float HC_SR04_mesure(unsigned char trig, unsigned char echo) {
  40. float distatnce;
  41. P1OUT |= trig;
  42. __delay_cycles(15);
  43. P1OUT &= ~trig;
  44. TA0R = 0;
  45. while (!(P1IN & echo)) {
  46. if (TA0R > 16384) { /* timeout */
  47. return -1;
  48. }
  49. }
  50. TA0R = 0;
  51. while (P1IN & echo);
  52. distatnce = TA0R * 0.017;
  53. return distatnce;
  54. }