luat_spi_device.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "luat_base.h"
  2. #include "luat_gpio.h"
  3. #include "luat_spi.h"
  4. #define LUAT_WEAK __attribute__((weak))
  5. #define LUAT_SPI_CS_SELECT 0
  6. #define LUAT_SPI_CS_CLEAR 1
  7. // luat_spi_device_t* 在lua层看到的是一个userdata
  8. LUAT_WEAK int luat_spi_device_setup(luat_spi_device_t* spi_dev) {
  9. luat_spi_bus_setup(spi_dev);
  10. if (spi_dev->spi_config.cs != 255)
  11. luat_gpio_mode(spi_dev->spi_config.cs, Luat_GPIO_OUTPUT, Luat_GPIO_DEFAULT, Luat_GPIO_HIGH); // CS
  12. return 0;
  13. }
  14. //关闭SPI设备,成功返回0
  15. LUAT_WEAK int luat_spi_device_close(luat_spi_device_t* spi_dev) {
  16. return luat_spi_close(spi_dev->bus_id);
  17. }
  18. //收发SPI数据,返回接收字节数
  19. LUAT_WEAK int luat_spi_device_transfer(luat_spi_device_t* spi_dev, const char* send_buf, size_t send_length, char* recv_buf, size_t recv_length) {
  20. luat_spi_device_config(spi_dev);
  21. if (spi_dev->spi_config.cs != 255)
  22. luat_gpio_set(spi_dev->spi_config.cs, LUAT_SPI_CS_SELECT);
  23. int ret = luat_spi_transfer(spi_dev->bus_id, send_buf, send_length, recv_buf, recv_length);
  24. if (spi_dev->spi_config.cs != 255)
  25. luat_gpio_set(spi_dev->spi_config.cs, LUAT_SPI_CS_CLEAR);
  26. return ret;
  27. }
  28. //收SPI数据,返回接收字节数
  29. LUAT_WEAK int luat_spi_device_recv(luat_spi_device_t* spi_dev, char* recv_buf, size_t length) {
  30. luat_spi_device_config(spi_dev);
  31. if (spi_dev->spi_config.cs != 255)
  32. luat_gpio_set(spi_dev->spi_config.cs, LUAT_SPI_CS_SELECT);
  33. int ret = luat_spi_recv(spi_dev->bus_id, recv_buf, length);
  34. if (spi_dev->spi_config.cs != 255)
  35. luat_gpio_set(spi_dev->spi_config.cs, LUAT_SPI_CS_CLEAR);
  36. return ret;
  37. }
  38. //发SPI数据,返回发送字节数
  39. LUAT_WEAK int luat_spi_device_send(luat_spi_device_t* spi_dev, const char* send_buf, size_t length) {
  40. luat_spi_device_config(spi_dev);
  41. if (spi_dev->spi_config.cs != 255)
  42. luat_gpio_set(spi_dev->spi_config.cs, LUAT_SPI_CS_SELECT);
  43. int ret = luat_spi_send(spi_dev->bus_id, send_buf, length);
  44. if (spi_dev->spi_config.cs != 255)
  45. luat_gpio_set(spi_dev->spi_config.cs, LUAT_SPI_CS_CLEAR);
  46. return ret;
  47. }