luat_spi_device.c 1.8 KB

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