PCF8563T.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. --- 模块功能:PCF8563T
  2. -- @module PCF8563T
  3. -- @author JWL
  4. -- @license MIT
  5. -- @copyright OpenLuat.com
  6. -- @release 2021.10.16
  7. module(...,package.seeall)
  8. require"utils"
  9. require"bit"
  10. pm.wake("PCF8563T")
  11. local i2cid = 2 --i2cid
  12. local i2cslaveaddr = 0X51 --slave address
  13. local REG_SEC = 0X02
  14. local function i2c_send(data)
  15. i2c.send(i2cid, i2cslaveaddr, data)
  16. end
  17. local function i2c_recv(data,num)
  18. i2c.send(i2cid, i2cslaveaddr, data)
  19. local revData = i2c.recv(i2cid, i2cslaveaddr, num)
  20. return revData
  21. end
  22. local function bcd_to_hex(data)
  23. local hex = bit.rshift(data,4)*10+bit.band(data,0x0f)
  24. return hex;
  25. end
  26. local function hex_to_bcd(data)
  27. local hex = bit.lshift(data/10,4)+data%10
  28. return hex;
  29. end
  30. local function PCF8563T_read_time()
  31. -- read time
  32. local time_data = {}
  33. local data = i2c_recv(REG_SEC,7)
  34. time_data.tm_year = bcd_to_hex(data:byte(7)) + 2000
  35. time_data.tm_mon = bcd_to_hex(bit.band(data:byte(6),0x7f))
  36. time_data.tm_wday = bcd_to_hex(data:byte(5))
  37. time_data.tm_mday = bcd_to_hex(data:byte(4))
  38. time_data.tm_hour = bcd_to_hex(data:byte(3))
  39. time_data.tm_min = bcd_to_hex(data:byte(2))
  40. time_data.tm_sec = bcd_to_hex(data:byte(1))
  41. log.info("data:toHex()", data:toHex())
  42. return time_data
  43. end
  44. local function PCF8563T_set_time(time)
  45. -- set time
  46. local data7 = hex_to_bcd(time.tm_year - 2000)
  47. local data6 = hex_to_bcd(time.tm_mon)
  48. local data5 = hex_to_bcd(time.tm_wday)
  49. local data4 = hex_to_bcd(time.tm_mday)
  50. local data3 = hex_to_bcd(time.tm_hour)
  51. local data2 = hex_to_bcd(time.tm_min)
  52. local data1 = hex_to_bcd(time.tm_sec)
  53. log.info("set time:",data7,data6,data5,data4,data3,data2,data1)
  54. i2c_send({REG_SEC, data1,data2,data3,data4,data5,data6,data7})
  55. end
  56. local function PCF8563T()
  57. sys.wait(4000)
  58. if i2c.setup(i2cid,i2c.SLOW) ~= i2c.SLOW then
  59. log.error("I2c.init","fail")
  60. return
  61. end
  62. local set_time = {tm_year=2021,tm_mon=10,tm_mday=16,tm_wday=6,tm_hour=11,tm_min=19,tm_sec=9}
  63. PCF8563T_set_time(set_time)
  64. while true do
  65. local time = PCF8563T_read_time()
  66. log.info("PCF8563T_read_time",time.tm_year,time.tm_mon,time.tm_mday, time.tm_hour,time.tm_min,time.tm_sec, "week=".. time.tm_wday)
  67. -- log.info("PCF8563T_read_time",time.tm_year,time.tm_mon,time.tm_mday,time.tm_hour,time.tm_min,time.tm_sec)
  68. sys.wait(1000)
  69. end
  70. end
  71. sys.taskInit(PCF8563T)