1+ from machine import Pin , SPI
2+ import utime
3+
4+ class cs5460a (object ):
5+ def __init__ (self , spi , cs = 4 , rst = 2 ):
6+ self .spi = spi
7+ self .cs = Pin (cs , Pin .OUT )
8+ self .rst = Pin (rst , Pin .OUT )
9+ self .FLOAT24 = 16777216.0 # 2^24
10+ self .VOLTAGE_MULTIPLIER = (1 / self .FLOAT24 * 385 )
11+ self .CURRENT_MULTIPLIER = (1 / self .FLOAT24 * 11.66 )
12+ self .POWER_MULTIPLIER = (1 / self .FLOAT24 * 1.024 * 385 * 11.66 * 2 )
13+
14+ def read (self , addr ):
15+ b = bytearray ([0xfe , 0xfe , 0xfe ])
16+ buf = bytearray (3 )
17+ self .cs .value (0 )
18+ self .spi .write (bytearray ([addr ]))
19+ self .spi .write_readinto (b , buf )
20+ self .cs .value (1 )
21+ # print(buf[0],buf[1],buf[2])
22+ return buf
23+
24+ def write (self , addr , data ):
25+ self .cs .value (0 )
26+ self .spi .write (bytearray ([addr ]))
27+ self .spi .write (data )
28+ self .cs .value (1 )
29+ # print('write_ok')
30+
31+ def cs5460a_init (self ):
32+ self .rst .value (0 )
33+ utime .sleep_ms (50 )
34+ self .rst .value (1 ) # reset the cs5460a
35+
36+ self .cs .value (0 )
37+ self .spi .write (bytearray ([0xa0 ]))
38+ self .cs .value (1 ) # the command of the power_up
39+
40+ self .write (0x40 , bytearray ([0x00 , 0x00 , 0x61 ])) # set
41+ self .write (0x48 , bytearray ([0x46 , 0xfa , 0xcb ]))
42+ self .write (0x44 , bytearray ([0x42 , 0x66 , 0xb4 ]))
43+
44+ self .cs .value (0 )
45+ self .spi .write (bytearray ([0xe8 ]))
46+ self .cs .value (1 ) # start to convert
47+
48+ def conv (self , true_power ):
49+ if true_power [0 ] > 0x80 :
50+ a = bytearray ([~ true_power [0 ]])
51+ a [0 ] &= 0x7f
52+ # print(a)
53+ b = bytearray ([~ true_power [1 ]])
54+ # print(b)
55+ c = bytearray ([~ true_power [2 ]])
56+ # print(c)
57+ temp = ((c [0 ] + b [0 ] * 256 + a [0 ] * 65536 ) + 1 )
58+ else :
59+ temp = ((true_power [0 ] + true_power [0 ] * 256 + true_power [0 ] * 65536 ) + 1 )
60+ return temp
61+
62+
63+ def unit_test ():
64+ vspi = SPI (- 1 , sck = Pin (18 ), mosi = Pin (23 ), miso = Pin (19 ), baudrate = 2000000 ) # -1 software spi
65+ ts = cs5460a (vspi )
66+ ts .cs5460a_init () # 初始化
67+
68+ while True :
69+ utime .sleep_ms (1000 )
70+ k = ts .read (0x1e )
71+ print (k )
72+ voltage = ts .read (0x18 )
73+ current = ts .read (0x16 )
74+ true_power = ts .read (0x14 )
75+ temp1 = (current [2 ] + current [1 ] * 256 + current [0 ] * 65536 )
76+ temp2 = (voltage [2 ] + voltage [1 ] * 256 + voltage [0 ] * 65536 )
77+ t = ts .conv (true_power )
78+ A = ts .CURRENT_MULTIPLIER * temp1
79+ V = ts .VOLTAGE_MULTIPLIER * temp2
80+ P = ts .POWER_MULTIPLIER * t
81+ print ('current=%.2f A' % A )
82+ print ('voltage=%.2f V' % V )
83+ print ('ture_power=%.2f W' % P )
84+
85+
86+ if __name__ == '__main__' :
87+ unit_test ()
0 commit comments