main.lua 1.7 KB

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