main.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "w25q_spi_demo"
  3. VERSION = "1.0.1"
  4. --spi编号,请按实际情况修改!
  5. local spiId = 1 --这里使用SPI 1
  6. --GPIO2<----> SCK
  7. --GPIO3<----> CS
  8. --GPIO4<----> MOSI
  9. --GPIO5<----> MISO
  10. local cs = 3 -- CS使用GPIO3
  11. local cspin = gpio.setup(cs, 1) --配置CS为输出
  12. --收发数据
  13. local function sendRecv(data,len)
  14. local r = ""
  15. cspin(0)
  16. if data then spi.send(spiId,data) end
  17. if len then r = spi.recv(spiId,len) end
  18. cspin(1)
  19. return r
  20. end
  21. sys.taskInit(function()
  22. local result = spi.setup(
  23. spiId,--串口id
  24. nil,
  25. 0,--CPHA
  26. 0,--CPOL
  27. 8,--数据宽度
  28. 1000000--,--频率
  29. -- spi.MSB,--高低位顺序 可选,默认高位在前
  30. -- spi.master,--主模式 可选,默认主
  31. -- spi.full--全双工 可选,默认全双工
  32. )
  33. print("open",result)
  34. if result ~= 0 then--返回值为0,表示打开成功
  35. print("spi open error",result)
  36. return
  37. end
  38. --检查芯片型号
  39. local chip = sendRecv(string.char(0x9f),3)
  40. if chip == string.char(0xef,0x40,0x17) then
  41. log.info("spi", "chip id read ok 0xef,0x40,0x17")
  42. else
  43. log.info("spi", "chip id read error")
  44. for i=1,#chip do
  45. print(chip:byte(i))
  46. end
  47. return
  48. end
  49. local data = "test data 123456"
  50. --enable write
  51. sendRecv(string.char(0x06))
  52. --写页数据到地址0x000001
  53. sendRecv(string.char(0x02,0x00,0x00,0x01)..data)
  54. log.info("spi","write",data)
  55. sys.wait(500)--等写入操作完成
  56. --读数据
  57. local r = sendRecv(string.char(0x03,0x00,0x00,0x01),data:len())
  58. log.info("spi","read",r)
  59. --disable write
  60. sendRecv(string.char(0x04))
  61. spi.close(spiId)
  62. end)
  63. -- 结尾总是这一句哦
  64. sys.run()