spi.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * spi.c
  3. *
  4. * Copyright 2023 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 "spi.h"
  27. #define CSDIR P1DIR
  28. #define CSOUT P1OUT
  29. #define CSPIN BIT3
  30. void spi_init(void) {
  31. // setup SPI
  32. UCB0CTL1 |= UCSWRST; // put B0 into reset
  33. UCB0CTL1 |= UCSSEL_2; // choose SMCLK
  34. UCB0BR0 = 5; // CLK = SMCLK / 5 = 1 MHz / 5 = 200 kHz
  35. UCB0BR1 = 0;
  36. UCB0CTL0 |= UCSYNC | UCMSB | UCMST | UCCKPH;
  37. // MOSI, MISO and CLK setup
  38. P1SEL |= BIT5; // P1.5 use CLK (11)
  39. P1SEL2 |= BIT5;
  40. P1SEL |= BIT6; // P1.6 use MISO (11)
  41. P1SEL2 |= BIT6;
  42. P1SEL |= BIT7; // P1.7 use MOSI (11)
  43. P1SEL2 |= BIT7;
  44. // CS pin setup
  45. // WARNING: if P2.6 or P2.7 used, additional setup required!
  46. CSDIR |= CSPIN; // set pin to output
  47. CSOUT &= ~CSPIN; // disable pin initially
  48. UCB0CTL1 &= ~UCSWRST;
  49. }
  50. BYTE spi_send(BYTE byte) {
  51. while (UCB0STAT & UCBUSY); // wait until SPI is free
  52. UCB0TXBUF = byte; // send byte
  53. while (UCB0STAT & UCBUSY); // wait until SPI free
  54. return UCB0RXBUF; // return answer
  55. }
  56. BYTE spi_receive(void) {
  57. return spi_send(0xFF);
  58. }
  59. void spi_select(void) {
  60. CSOUT &= ~CSPIN; // active low
  61. }
  62. void spi_deselect(void) {
  63. CSOUT |= CSPIN; // active low
  64. }