CocoPi.py 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. '''
  2. =========================================================
  3. ______ ______
  4. /\ _ \ /\ _ \ __
  5. \ \ \/\_\ ____ ____ ___\ \ \_\ \/\_\
  6. \ \ \/_/_ / __ \ / __ \ / __'\ \ __/\/_/_
  7. \ \ \_\ \/\ \_\ \/\ \__//\ \_\ \ \ \/ /\ \
  8. \ \____/\ \____/\ \____\ \____/\ \_\ \ \_\
  9. \/___/ \/___/ \/____/\/___/ \/_/ \/_/
  10. __
  11. /\ \ __ ----------------
  12. \ \ \ /\_\ ____ __ __ __ _ pi.cocorobo.cn
  13. \ \ \ \/_/_ / _ \/\ \/\ \/\ \/ \ ----------------
  14. \ \ \____ /\ \/\ \/\ \ \ \_\ \/> </ SYSTEM VERSION
  15. \ \_____\\ \_\ \_\ \_\ \____//\_/\_\ -- 24.07.05 ---
  16. \/_____/ \/_/\/_/\/_/\/___/ \//\/_/ ----------------
  17. =========================================================
  18. '''
  19. #########################################################
  20. # ------------------------------------------------------
  21. #| 封装包内容: | 类名称: |
  22. #|-------------------------------|----------------------|
  23. #| 2023.02.16: | |
  24. #| 【添加】 | |
  25. #| 1、AHT20温湿度传感器 | AHT20 |
  26. #| 2、MPU6050陀螺仪六轴传感器 | MPU6050 |
  27. #| 3、板载4颗按钮A、B、C、D | BUTTON |
  28. #| 4、光线强度传感器 | LIGHTINTENSITY |
  29. #| 5、板载LED灯! | LED |
  30. #| 6、直流电机 | DCMOTOR |
  31. #| 7、模拟舵机 | SERVO |
  32. #|------------------------------------------------------|
  33. #| 2023.02.27: | |
  34. #| 【修复完善】 | BUTTON、LED |
  35. #| 【添加】 | WIFI |
  36. #|------------------------------------------------------|
  37. #| 2023.03.09: | |
  38. #| 【修复完善】 | LED |
  39. #|------------------------------------------------------|
  40. #| 2023.03.14: | |
  41. #| 【修复完善】 | SERVO |
  42. #|-------------------------------------------------------
  43. #| 2023.06.01: | |
  44. #| 【替换】 | BUTTON |
  45. #| 【替换】 | LED |
  46. #| 【替换】 | DCMOTOR |
  47. #| 【替换】 | SERVO |
  48. #| 【添加】 | RGB |
  49. #| 【添加】 | ADC |
  50. #| 【添加】 | DAC |
  51. #| 【添加】 | INPUT |
  52. #| 【添加】 | OUT |
  53. #| 【添加】 | UvcVideo |
  54. #|-------------------------------------------------------
  55. #| 2023.06.15: | |
  56. #| 【更改】 | STM8S |
  57. #|-------------------------------------------------------
  58. #| 2023.08.17: | |
  59. #| 【更改】 | DCMOTOR |
  60. #|-------------------------------------------------------
  61. #| 2023.08.25: | |
  62. #| 【更改】 | BUZZER |
  63. #|-------------------------------------------------------
  64. #| 2023.09.28: | |
  65. #| 【更改】 | QMI8658 |
  66. #########################################################
  67. #|-------------------------------------------------------
  68. #| 2024.02.22: | |
  69. #| 【更改】 | QMI8658 |
  70. #########################################################
  71. #| 2024.02.28: | |
  72. #| 【更改】 | STM8S |
  73. #########################################################
  74. #| 2024.03.07: | |
  75. #| 【添加】 | GPTrequest |
  76. #########################################################
  77. #| 2024.03.11: | |
  78. #| 【修改】 | LED |
  79. #| 【修改】 | DCMOTOR |
  80. #########################################################
  81. #| 2024.03.22: | |
  82. #| 【增加】 | RTC |
  83. #| 【增加】 | PCA9685 |
  84. #########################################################
  85. #| 2024.04.10: | |
  86. #| 【修改】 | GPTrequest |
  87. #########################################################
  88. #| 2024.07.05: | |
  89. #| 【增加】 | LazyImport |
  90. #| 【针对】 | GPTrequest |
  91. #| 【针对】 | uuid |
  92. #| 【针对】 | json |
  93. #| 【针对】 | base64 |
  94. #| 【修改】 | STM8S |
  95. #| 【修改】 | DCMOTOR |
  96. #| 【修改】 | multiFuncGpio |
  97. #| 【增加】 | DS3231 |
  98. #| 【增加】 | SPI_WS2812 |
  99. #| 【增加】 | HCSR04 |
  100. #| 【增加】 | extDcMotor |
  101. #| 【增加】 | extServo |
  102. #| 【增加】 | extGpio |
  103. #| 【拆分】 | GPTrequest |
  104. #########################################################
  105. from smbus2 import SMBus
  106. import time
  107. import math
  108. from maix import gpio
  109. import os
  110. import SUNXI_GPIO
  111. from maix import camera
  112. import time
  113. import sys
  114. #20240715
  115. import threading
  116. sys.path.append('/root/preset/server')
  117. ##################################
  118. # 1、AHT20温湿度传感器 #
  119. ##################################
  120. AHT20_I2CADDR = 0x38
  121. AHT20_CMD_SOFTRESET = [0xBA]
  122. AHT20_CMD_INITIALIZE = [0xBE, 0x08, 0x00]
  123. AHT20_CMD_MEASURE = [0xAC, 0x33, 0x00]
  124. AHT20_STATUSBIT_BUSY = 7 # The 7th bit is the Busy indication bit. 1 = Busy, 0 = not.
  125. AHT20_STATUSBIT_CALIBRATED = 3 # The 3rd bit is the CAL (calibration) Enable bit. 1 = Calibrated, 0 = not
  126. class AHT20:
  127. # Usage: AHT20 crc8 checker.
  128. # A total of 6 * 8 bits data need to check. G(x) = x8 + x5 + x4 + 1 -> 0x131(0x31), Initial value = 0xFF. No XOROUT.
  129. N_DATA = 6
  130. # 1 * 8 bits CRC
  131. N_CRC = 1
  132. # Initial value. Equal to bit negation the first data (status of AHT20)
  133. INIT = 0xFF
  134. # Useful value to help calculate
  135. LAST_8_bit = 0xFF
  136. # Devide number retrieve from CRC-8 MAXIM G(x) = x8 + x5 + x4 + 1
  137. CRC_DEVIDE_NUMBER = 0x131
  138. # I2C communication driver for AHT20, using only smbus2
  139. def __init__(self, BusNum=2):
  140. # Initialize AHT20
  141. self.BusNum = BusNum
  142. self.cmd_soft_reset()
  143. # Check for calibration, if not done then do and wait 10 ms
  144. if not self.get_status_calibrated == 1:
  145. self.cmd_initialize()
  146. while not self.get_status_calibrated() == 1:
  147. time.sleep(0.01)
  148. def get_normalized_bit(self,value, bit_index):
  149. # Return only one bit from value indicated in bit_index
  150. return (value >> bit_index) & 1
  151. def cmd_soft_reset(self):
  152. # Send the command to soft reset
  153. with SMBus(self.BusNum) as i2c_bus:
  154. i2c_bus.write_i2c_block_data(AHT20_I2CADDR, 0x0, AHT20_CMD_SOFTRESET)
  155. time.sleep(0.04) # Wait 40 ms after poweron
  156. return True
  157. def cmd_initialize(self):
  158. # Send the command to initialize (calibrate)
  159. with SMBus(self.BusNum) as i2c_bus:
  160. i2c_bus.write_i2c_block_data(AHT20_I2CADDR, 0x0 , AHT20_CMD_INITIALIZE)
  161. return True
  162. def cmd_measure(self):
  163. # Send the command to measure
  164. with SMBus(self.BusNum) as i2c_bus:
  165. i2c_bus.write_i2c_block_data(AHT20_I2CADDR, 0, AHT20_CMD_MEASURE)
  166. time.sleep(0.08) # Wait 80 ms after measure
  167. return True
  168. def get_status(self):
  169. # Get the full status byte
  170. with SMBus(self.BusNum) as i2c_bus:
  171. return i2c_bus.read_i2c_block_data(AHT20_I2CADDR, 0x0, 1)[0]
  172. return True
  173. def get_status_calibrated(self):
  174. # Get the calibrated bit
  175. return self.get_normalized_bit(self.get_status(), AHT20_STATUSBIT_CALIBRATED)
  176. def get_status_busy(self):
  177. # Get the busy bit
  178. return self.get_normalized_bit(self.get_status(), AHT20_STATUSBIT_BUSY)
  179. def get_measure(self):
  180. # Get the full measure
  181. # Command a measure
  182. self.cmd_measure()
  183. # Check if busy bit = 0, otherwise wait 80 ms and retry
  184. while self.get_status_busy() == 1:
  185. time.sleep(0.08) # Wait 80 ns
  186. # TODO: do CRC check
  187. # Read data and return it
  188. with SMBus(self.BusNum) as i2c_bus:
  189. return i2c_bus.read_i2c_block_data(AHT20_I2CADDR, 0x0, 7)
  190. def mod2_division_8bits(self,a, b, number_of_bytes, init_value):
  191. "calculate mod2 division in 8 bits. a mod b. init_value is for crc8 init value."
  192. head_of_a = 0x80
  193. # Processiong a
  194. a = a << 8
  195. # Preprocessing head_of_a
  196. for i in range(0, number_of_bytes):
  197. head_of_a = head_of_a << 8
  198. b = b << 8
  199. init_value = init_value << 8
  200. a = a ^ init_value
  201. while (head_of_a > 0x80):
  202. # Find a 1
  203. if (head_of_a & a):
  204. head_of_a = head_of_a >> 1
  205. b = b >> 1
  206. a = a ^ b
  207. else:
  208. head_of_a = head_of_a >> 1
  209. b = b >> 1
  210. # This will show calculate the remainder
  211. # print("a:{0}\thead of a:{1}\tb:{2}".format(
  212. # bin(a), bin(head_of_a), bin(b)))
  213. return a
  214. def AHT20_crc8_calculate(self,all_data_int):
  215. init_value = INIT
  216. # Preprocess all the data and CRCCode from AHT20
  217. data_from_AHT20 = 0x00
  218. # Preprocessing the first data (status)
  219. # print(bin(data_from_AHT20))
  220. for i_data in range(0, len(all_data_int)):
  221. data_from_AHT20 = (data_from_AHT20 << 8) | all_data_int[i_data]
  222. # print(bin(data_from_AHT20))
  223. mod_value = self.mod2_division_8bits(
  224. data_from_AHT20, CRC_DEVIDE_NUMBER, len(all_data_int), init_value)
  225. # print(mod_value)
  226. return mod_value
  227. def AHT20_crc8_check(self,all_data_int):
  228. """
  229. The input data shoule be:
  230. Status Humidity0 Humidity1 Humidity2|Temperature0 Temperature1 Temperature2 CRCCode.
  231. In python's int64.
  232. """
  233. mod_value = self.AHT20_crc8_calculate(all_data_int[:-1])
  234. if (mod_value == all_data_int[-1]):
  235. return True
  236. else:
  237. return False
  238. def get_measure_CRC8(self):
  239. """
  240. This function will calculate crc8 code with G(x) = x8 + x5 + x4 + 1 -> 0x131(0x31), Initial value = 0xFF. No XOROUT.
  241. return: all_data (1 bytes status + 2.5 byes humidity + 2.5 bytes temperature + 1 bytes crc8 code), isCRC8_pass
  242. """
  243. all_data = self.get_measure()
  244. isCRC8_pass = self.AHT20_crc8_check(all_data)
  245. return all_data, isCRC8_pass
  246. def get_temperature(self):
  247. # Get a measure, select proper bytes, return converted data
  248. measure = self.get_measure()
  249. measure = ((measure[3] & 0xF) << 16) | (measure[4] << 8) | measure[5]
  250. measure = measure / (pow(2,20))*200-50
  251. return measure
  252. def get_temperature_crc8(self):
  253. isCRC8Pass = False
  254. while (not isCRC8Pass):
  255. measure, isCRC8Pass = self.get_measure_CRC8()
  256. time.sleep(80 * 10**-3)
  257. measure = ((measure[3] & 0xF) << 16) | (measure[4] << 8) | measure[5]
  258. measure = measure / (pow(2,20))*200-50
  259. return measure
  260. def get_humidity(self):
  261. # Get a measure, select proper bytes, return converted data
  262. measure = self.get_measure()
  263. measure = (measure[1] << 12) | (measure[2] << 4) | (measure[3] >> 4)
  264. measure = measure * 100 / pow(2,20)
  265. return measure
  266. def get_humidity_crc8(self):
  267. isCRC8Pass = False
  268. while (not isCRC8Pass):
  269. measure, isCRC8Pass = self.get_measure_CRC8()
  270. time.sleep(80 * 10**-3)
  271. measure = (measure[1] << 12) | (measure[2] << 4) | (measure[3] >> 4)
  272. measure = measure * 100 / pow(2,20)
  273. return measure
  274. ##################################
  275. # 2、MPU6050陀螺仪六轴传感器 #
  276. ##################################
  277. SLAVE_ADDR = 0x68
  278. PWR_MGMT_1 = 0x6B
  279. PWR_MGMT_2 = 0x6C
  280. WHO_AM_I = 0x75
  281. GYRO_X = 0x43
  282. GYRO_Y = 0x45
  283. GYRO_Z = 0x47
  284. ACCL_X = 0x3B
  285. ACCL_Y = 0x3D
  286. ACCL_Z = 0x3F
  287. class MPU6050:
  288. def __init__(self, BusNum=2):
  289. # Initialize mpu6050
  290. self.BusNum = BusNum
  291. self.cmd_soft_reset()
  292. def cmd_soft_reset(self):
  293. # Send the command to soft reset
  294. with SMBus(self.BusNum) as bus:
  295. bus.write_byte_data(SLAVE_ADDR, PWR_MGMT_1, 0)
  296. time.sleep(0.04) # Wait 40 ms after poweron
  297. def read_byte(self,addr):
  298. with SMBus(self.BusNum) as bus:
  299. return bus.read_byte_data(SLAVE_ADDR,addr)
  300. def read_word(self,addr):
  301. with SMBus(self.BusNum) as bus:
  302. h = bus.read_byte_data(SLAVE_ADDR, addr)
  303. l = bus.read_byte_data(SLAVE_ADDR, addr+1)
  304. val = (h << 8) + l
  305. return val
  306. def read_word_i2c(self,addr):
  307. val = self.read_word(addr)
  308. if (val >= 0x8000):
  309. return -((65535 - val) + 1)
  310. else:
  311. return val
  312. def dist(self,x, y):
  313. return math.sqrt((x*x) + (y*y))
  314. def get_x_rotat(self,x,y, z):
  315. rad = math.atan2(y,self.dist(x, z))
  316. return math.degrees(rad)
  317. def get_y_rotat(self,x, y, z):
  318. rad = math.atan2(x,self.dist(y, z))
  319. return -math.degrees(rad)
  320. def read_gyro(self):
  321. GYR_X = self.read_word_i2c(GYRO_X)
  322. GYR_Y = self.read_word_i2c(GYRO_Y)
  323. GYR_Z = self.read_word_i2c(GYRO_Z)
  324. #print ("GYRO -> X:{:04.2f} Y:{:04.2f} Z:{:04.2f}".format((GYR_X/131), (GYR_Y/131), (GYR_Z/131)))
  325. return (GYR_X/131), (GYR_Y/131), (GYR_Z/131)
  326. def read_acc(self):
  327. ACC_X = self.read_word_i2c(ACCL_X)
  328. ACC_Y = self.read_word_i2c(ACCL_Y)
  329. ACC_Z = self.read_word_i2c(ACCL_Z)
  330. CALC_ACC_X = ACC_X/16384.0
  331. CALC_ACC_Y = ACC_Y/16384.0
  332. CALC_ACC_Z = ACC_Z/16384.0
  333. #print ("ACCL -> X:{:04.2f} Y:{:04.2f} Z:{:04.2f}".format(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z))
  334. #print("ROTATE -> X:{:04.2f} Y:{:04.2f}\n".format(get_x_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z), get_y_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z)))
  335. return CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z,self.get_x_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z),self.get_y_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z)
  336. def get_gyro_x(self):
  337. return self.read_gyro()[0]
  338. def get_gyro_y(self):
  339. return self.read_gyro()[1]
  340. def get_gyro_z(self):
  341. return self.read_gyro()[2]
  342. def get_acc_x(self):
  343. return self.read_acc()[0]
  344. def get_acc_y(self):
  345. return self.read_acc()[1]
  346. def get_acc_z(self):
  347. return self.read_acc()[2]
  348. def get_angle_x(self):
  349. return self.read_acc()[3]
  350. def get_angle_y(self):
  351. return self.read_acc()[4]
  352. ##################################
  353. # 3、板载4颗按钮A、B、C、D #
  354. ##################################
  355. class BUTTON:
  356. def __init__(self, gpioId):
  357. self.gpio=224+gpioId
  358. SUNXI_GPIO.setcfg(self.gpio, SUNXI_GPIO.IN)
  359. def is_pressed(self):
  360. self.getValue=SUNXI_GPIO.input(self.gpio)
  361. if self.getValue != 1:
  362. return True
  363. else:
  364. return False
  365. ##################################
  366. # 4、光线强度传感器 #
  367. ##################################
  368. class LIGHTINTENSITY:
  369. def __init__(self, addr=b"0x05070080") -> None:
  370. self.addr = addr
  371. self.path = "/sys/class/sunxi_dump/dump"
  372. self.file = open(self.path, "wb+")
  373. self.last = self.value()
  374. def value(self):
  375. self.file.write(b"0x05070080")
  376. self.file.seek(0)
  377. return int(self.file.read()[:-1], 16)
  378. def __del__(self):
  379. try:
  380. if self.file:
  381. self.file.close()
  382. del self.file
  383. except Exception as e:
  384. pass
  385. ##################################
  386. # 5、板载LED灯 #
  387. ##################################
  388. class LED:
  389. def __init__(self, gpioId=69):
  390. self.gpioId=gpioId
  391. SUNXI_GPIO.setcfg(self.gpioId, SUNXI_GPIO.OUT)
  392. SUNXI_GPIO.setcfg(259, SUNXI_GPIO.OUT)
  393. def out(self,value):
  394. if value==0 or value==1:
  395. self.value=1-value
  396. else:
  397. self.value=0
  398. SUNXI_GPIO.output(self.gpioId,self.value)
  399. SUNXI_GPIO.output(259,self.value)
  400. ##################################
  401. # 6、QMI8658 #
  402. ##################################
  403. class QMI8658(object):
  404. def __init__(self, smbus=2, address=0X6B):
  405. self._address = address
  406. import smbus2
  407. self._bus = smbus2.SMBus(smbus)
  408. bRet = self.WhoAmI()
  409. if bRet:
  410. self.Read_Revision()
  411. else:
  412. return None
  413. self.Config_apply()
  414. def _read_byte(self, cmd):
  415. rec = self._bus.read_i2c_block_data(int(self._address), int(cmd), 1)
  416. return rec[0]
  417. def _read_block(self, reg, length=1):
  418. rec = self._bus.read_i2c_block_data(int(self._address), int(reg), length)
  419. return rec
  420. def _read_u16(self, cmd):
  421. LSB = self._bus.read_i2c_block_data(int(self._address), int(cmd), 1)
  422. MSB = self._bus.read_i2c_block_data(int(self._address), int(cmd)+1, 1)
  423. return (MSB[0] << 8) + LSB[0]
  424. def _write_byte(self, cmd, val):
  425. self._bus.write_i2c_block_data(int(self._address), int(cmd), bytes([int(val)]))
  426. def WhoAmI(self):
  427. bRet = False
  428. if (0x05) == self._read_byte(0x00):
  429. bRet = True
  430. return bRet
  431. def Read_Revision(self):
  432. return self._read_byte(0x01)
  433. def Config_apply(self):
  434. self._write_byte(0x02, 0x40)
  435. self._write_byte(0x08, 0x03)
  436. self._write_byte(0x03, 0x04)
  437. self._write_byte(0x04, 0x64)
  438. self._write_byte(0x06, 0x11)
  439. def Read_Raw_XYZ(self):
  440. xyz = [0, 0, 0, 0, 0, 0]
  441. vals={}
  442. raw_timestamp = self._read_block(0x30, 3)
  443. raw_acc_xyz = self._read_block(0x35, 6)
  444. raw_gyro_xyz = self._read_block(0x3b, 6)
  445. raw_xyz = self._read_block(0x35, 12)
  446. timestamp = (raw_timestamp[2] << 16) | (
  447. raw_timestamp[1] << 8) | (raw_timestamp[0])
  448. for i in range(6):
  449. xyz[i] = (raw_xyz[(i*2)+1] << 8) | (raw_xyz[i*2])
  450. if xyz[i] >= 32767:
  451. xyz[i] = xyz[i]-65535
  452. vals["AcX"]=xyz[0]
  453. vals["AcY"]=xyz[1]
  454. vals["AcZ"]=xyz[2]
  455. vals["GyX"]=xyz[3]
  456. vals["GyY"]=xyz[4]
  457. vals["GyZ"]=xyz[5]
  458. return vals
  459. def Read_XYZ(self):
  460. xyz = [0, 0, 0, 0, 0, 0]
  461. raw_xyz = self.Read_Raw_XYZ()
  462. #QMI8658AccRange_8g
  463. acc_lsb_div = (1 << 12)
  464. #QMI8658GyrRange_512dps
  465. gyro_lsb_div = 64
  466. for i in range(3):
  467. xyz[i] = raw_xyz[i]/acc_lsb_div # (acc_lsb_div/1000.0)
  468. xyz[i+3] = raw_xyz[i+3]*1.0/gyro_lsb_div
  469. return xyz
  470. def get_accel(self, samples=10, calibration=None):
  471. result = {}
  472. for _ in range(samples):
  473. v = self.Read_Raw_XYZ()
  474. for m in v.keys():
  475. result[m] = result.get(m, 0) + v[m] / samples
  476. if calibration:
  477. for m in calibration.keys():
  478. if m == "AcZ":
  479. pass
  480. else:
  481. result[m] -= calibration[m]
  482. return result
  483. def calibrate(self, threshold=50):
  484. print('Calibrating QMI8658... ', end='')
  485. while True:
  486. v1 = self.get_accel(100)
  487. v2 = self.get_accel(100)
  488. if all(abs(v1[m] - v2[m]) < threshold for m in v1.keys()):
  489. print('Done.')
  490. return v1
  491. def getPitchYawRollGxGyGz(self,calibration):
  492. caliData=self.get_accel(10, calibration)
  493. pitch=caliData["AcX"]/182.04
  494. yaw=caliData["AcY"]/182.04
  495. roll=caliData["AcZ"]/182.04
  496. groX=caliData["GyX"]
  497. groY=caliData["GyY"]
  498. groZ=caliData["GyZ"]
  499. if roll<0:
  500. if pitch >=0:
  501. pitch=180-pitch
  502. elif pitch <0:
  503. pitch=(180+pitch)*(-1)
  504. if yaw >=0:
  505. yaw=180-yaw
  506. elif pitch <0:
  507. yaw=(180+yaw)*(-1)
  508. return [pitch,yaw,roll,groX,groY,groZ]
  509. ##################################
  510. # 7、STM8S #
  511. ##################################
  512. import smbus2
  513. import time
  514. class stm8s(object):
  515. bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  516. address = 0x50
  517. # 0x00 # 触发配置
  518. # 0x01 # 重置配置
  519. # 0x02 # pwm0 历史配置
  520. # 0x03 # pwm1 历史配置
  521. # 引脚配置模式有 1. pwm 2. gpio ouput gpio input 3. adc 4.ws2812_singe 5 ws2812_multi
  522. def __init__(self):
  523. self.reset()
  524. time.sleep(0.05)
  525. pass
  526. def clear(self):
  527. self.write(1, 1)
  528. self.reset()
  529. time.sleep(0.05)
  530. def write(self, addr, val):
  531. for i in range(0, 3):
  532. try:
  533. self.bus.write_byte_data(self.address, addr, val)
  534. time.sleep(0.001) # 1ms
  535. # print(addr, val) # debug
  536. return True
  537. except Exception:
  538. time.sleep(0.01)
  539. continue
  540. return False
  541. def fastWrite(self,addr,valBlock):
  542. try:
  543. self.bus.write_i2c_block_data(self.address,addr,valBlock)
  544. return True
  545. except Exception:
  546. return False
  547. def read(self, addr):
  548. for i in range(0, 3):
  549. try:
  550. tmp = self.bus.read_byte_data(self.address, addr)
  551. time.sleep(0.001) # 1ms
  552. # print(addr, tmp) # debug
  553. return tmp
  554. except Exception:
  555. time.sleep(0.01)
  556. continue
  557. return None
  558. def reset(self):
  559. self.write(0, 1)
  560. time.sleep(0.05) # 重启并配置需要时间
  561. def dump(self):
  562. for i in range(0, 32):
  563. print(i, self.read(i))
  564. class singleRgb(stm8s):
  565. def __init__(self):
  566. self.valR=0
  567. self.valG=0
  568. self.valB=0
  569. self.brightness=255
  570. self.show()
  571. def setColor(self,r,g,b):
  572. if(r>=0 and r<=255):
  573. self.valR=int(r*self.brightness/255)
  574. else:
  575. self.valR=0
  576. if(g>=0 and g<=255):
  577. self.valG=int(g*self.brightness/255)
  578. else:
  579. self.valG=0
  580. if(b>=0 and b<=255):
  581. self.valB=int(b*self.brightness/255)
  582. else:
  583. self.valB=0
  584. def setBrightness(self,brightness):
  585. if(brightness>=0 and brightness<=255):
  586. self.brightness=brightness
  587. else:
  588. self.brightness=0
  589. def show(self):
  590. self.write(31, self.valB)
  591. self.write(30, self.valG)
  592. self.write(29, self.valR)
  593. self.write(28, 6)
  594. class dcMotor(stm8s):
  595. def __init__(self,id):
  596. self.id=id
  597. def m1a(self,val=0):
  598. self.write(4,5) #M1A
  599. #self.write(5,0)
  600. #self.write(6,0)
  601. self.write(7,val)
  602. def m1b(self,val=0):
  603. self.write(8,5) #M1B
  604. #self.write(9,0)
  605. #self.write(10,0)
  606. self.write(11,val)
  607. def m2a(self,val=0):
  608. self.write(12,5) #M2A
  609. #self.write(13,0)
  610. #self.write(14,0)
  611. self.write(15,val)
  612. def m2b(self,val=0):
  613. self.write(16,5) #M2B
  614. #self.write(17,0)
  615. #self.write(18,0)
  616. self.write(19,val)
  617. def dcMotorCtrl(self,dir,speed):
  618. dir=1-dir
  619. if(0<speed and speed<255):
  620. if(self.id ==1): #Motor1
  621. if(dir==0):
  622. self.m1a(speed)
  623. self.m1b(255)
  624. else:
  625. self.m1a(255)
  626. self.m1b(speed)
  627. elif(self.id ==2):
  628. if(dir==0):
  629. self.m2a(speed)
  630. self.m2b(255)
  631. else:
  632. self.m2a(255)
  633. self.m2b(speed)
  634. elif(0==speed):
  635. if(self.id ==1): #Motor1
  636. if(dir==0):
  637. self.m1a(255)
  638. self.m1b(255)
  639. else:
  640. self.m1a(255)
  641. self.m1b(255)
  642. elif(self.id ==2):
  643. if(dir==0):
  644. self.m2a(255)
  645. self.m2b(255)
  646. else:
  647. self.m2a(255)
  648. self.m2b(255)
  649. elif(speed==255):
  650. if(self.id ==1): #Motor1
  651. if(dir==0):
  652. self.m1a(0)
  653. self.m1b(255)
  654. else:
  655. self.m1a(255)
  656. self.m1b(0)
  657. elif(self.id ==2):
  658. if(dir==0):
  659. self.m2a(0)
  660. self.m2b(255)
  661. else:
  662. self.m2a(255)
  663. self.m2b(0)
  664. else:
  665. pass
  666. class multiFuncGpio(stm8s):
  667. def __init__(self,id=0,mode=0):
  668. self.id=id
  669. self.rgbId=0
  670. self.brightness=255
  671. self.mode=mode
  672. self.write(20+self.id*4,self.mode)
  673. self.rgbSerial=[0,0,0]*10
  674. time.sleep(0.05)
  675. ##################################################
  676. # mode | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
  677. #-------------------------------------------------
  678. # Func |free |servo|INPUT| OUT | ADC | PWM | BEEP|
  679. ##################################################
  680. # mode=0,为空闲状态,引脚不执行任何功能
  681. # mode=1,为控制舵机模式,值控制范围为0°~180°
  682. # mode=2,为数字输入模式,返回值0或1
  683. # mode=3,为数字输出模式,输出值为0或1
  684. # mode=4,为ADC采样模式,返回值为0~1023
  685. # mode=5,为PWM输出模式,输出值范围为0~255
  686. # mode=6,为控制蜂鸣器模式,控制范围为20hz~12000hz
  687. # mode=7,为控制灯带模式,暂未实现
  688. # id=0,控制多功能引脚1,向20号寄存器写入模式数据
  689. # id=1,控制多功能引脚2,向24号寄存器写入模式数据
  690. def servoCtrl(self,angle):
  691. if ((angle>=0) and (angle<=180)):
  692. self.write(23+self.id*4,angle)
  693. else:
  694. pass
  695. def digitalRead(self):
  696. try:
  697. self.gpioVal= self.read(23+ self.id*4)
  698. if(self.gpioVal != None):
  699. return self.gpioVal
  700. except:
  701. print("ERROR 233")
  702. def digitalWrite(self,val):
  703. if ((val>=0) and (val<=1)):
  704. self.write(23+self.id*4,val)
  705. else:
  706. pass
  707. def analogRead(self):
  708. try:
  709. self.adcValH= self.read(22+ self.id*4)
  710. self.adcValL= self.read(23+ self.id*4)
  711. if (self.adcValH != None and self.adcValL != None):
  712. # adcValH adcValL 大小端合并 16bit
  713. self.adcVal = self.adcValL + (self.adcValH << 8)
  714. return self.adcVal
  715. except:
  716. print("ERROR 2333")
  717. def analogWrite(self,val):
  718. if ((val>=0) and (val<=255)):
  719. self.write(23+self.id*4,val)
  720. else:
  721. pass
  722. def beep(self,frequency):
  723. if ((frequency>=20) and (frequency<=12000)):
  724. self.write(22+self.id*4,frequency>>8)
  725. self.write(23+self.id*4,frequency&0b11111111)
  726. else:
  727. pass
  728. def pixelInit_(self):
  729. for i in range(16):
  730. self.setPixelColor(i,0,0,0)
  731. self.pixelShow()
  732. self.write(23+self.id*4,1)
  733. def setBrightness(self,brightness):
  734. if(brightness>=0 and brightness<=255):
  735. self.brightness=brightness
  736. else:
  737. self.brightness=0
  738. def setPixelColor(self,rgbId,r,g,b):
  739. if(rgbId >=0 and rgbId <=15):
  740. self.rgbId=rgbId #rgbId范围:0~15
  741. else:
  742. self.rgbId=0
  743. if(r>=0 and r<=255):
  744. self.valR=int(r*self.brightness/255)
  745. else:
  746. self.valR=0
  747. if(g>=0 and g<=255):
  748. self.valG=int(g*self.brightness/255)
  749. else:
  750. self.valG=0
  751. if(b>=0 and b<=255):
  752. self.valB=int(b*self.brightness/255)
  753. else:
  754. self.valB=0
  755. #self.id的值为0或1,用于控制灯带缓冲区(S1或者S2引脚)
  756. def pixelShow(self):
  757. self.write(32+ self.id*48+self.rgbId*3, self.valR)
  758. self.write(33+ self.id*48+self.rgbId*3, self.valG)
  759. self.write(34+ self.id*48+self.rgbId*3, self.valB)
  760. def setRgbSerialColor(self,rgbId,r,g,b):
  761. if(rgbId >=0 and rgbId <=15):
  762. self.rgbId=rgbId #rgbId范围:0~15
  763. else:
  764. self.rgbId=0
  765. if(r>=0 and r<=255):
  766. self.valR=int(r*self.brightness/255)
  767. else:
  768. self.valR=0
  769. if(g>=0 and g<=255):
  770. self.valG=int(g*self.brightness/255)
  771. else:
  772. self.valG=0
  773. if(b>=0 and b<=255):
  774. self.valB=int(b*self.brightness/255)
  775. else:
  776. self.valB=0
  777. self.rgbSerial[self.rgbId*3]=self.valR
  778. self.rgbSerial[self.rgbId*3+1]=self.valG
  779. self.rgbSerial[self.rgbId*3+2]=self.valB
  780. def rgbSerialShow(self):
  781. self.fastWrite(32+self.id*48,self.rgbSerial)
  782. self.write(23+self.id*4,1)
  783. ##################################
  784. # 8、UvcVideo #
  785. ##################################
  786. class UvcVideo(camera.MaixVideo):
  787. def __init__(self, source="/dev/videoX"):
  788. self.source = source
  789. super(UvcVideo, self).__init__()
  790. import os, time
  791. usb_path = '/sys/devices/platform/soc/usbc0/otg_role'
  792. # 确认 usb_path 内容为 usb_host 如果不是,自动设置为 usb_host
  793. if os.popen('cat %s' % usb_path).read().strip() != 'usb_host':
  794. os.system('echo "usb_host" > %s' % usb_path)
  795. time.sleep(2) # 要设置 2s 左右才能初始化工作,否则会报 VIDIOC_S_FMT 失败。
  796. def config(self, size=None, video=2, horizontal=0, vertical=0):
  797. if size == None:
  798. size = (320, 240)
  799. super(UvcVideo, self).config(size)
  800. print('[camera] config input size(%d, %d, %d)' %
  801. (self.width(), self.height(), video))
  802. if self.cam:
  803. self.cam = None
  804. try:
  805. import _coco_camera
  806. self.cam = _coco_camera.Camera(self.width(), self.height(), video, horizontal, vertical)
  807. except Exception as e:
  808. print(e)
  809. self.cam = None
  810. def read(self):
  811. if self.cam == None:
  812. self.config()
  813. if self.cam:
  814. ret, frame = self.cam.read()
  815. if ret:
  816. return frame # bytes
  817. else:
  818. try:
  819. self.config()
  820. except Exception as e:
  821. print(e)
  822. return None
  823. def __del__(self):
  824. if self.cam:
  825. self.cam = None
  826. ##################################
  827. # 9、DS3231 #
  828. ##################################
  829. from math import floor
  830. class DS3231(object):
  831. # create RTC instance
  832. def __init__(self):
  833. self.bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  834. self.address = 0x68
  835. def bcd_to_int(self,bcd, n=2):
  836. """Decode n least significant packed binary coded decimal digits to binary.
  837. Return binary result.
  838. n defaults to 2 (BCD digits).
  839. n=0 decodes all digits.
  840. """
  841. return int(('%x' % bcd)[-n:])
  842. def int_to_bcd(self,x, n=2):
  843. """
  844. Encode the n least significant decimal digits of x
  845. to packed binary coded decimal (BCD).
  846. Return packed BCD value.
  847. n defaults to 2 (digits).
  848. n=0 encodes all digits.
  849. """
  850. return int(str(x)[-n:], 0x10)
  851. def read(self, addr):
  852. for i in range(0, 3):
  853. try:
  854. tmp = self.bus.read_byte_data(self.address, addr)
  855. time.sleep(0.001) # 1ms
  856. # print(addr, tmp) # debug
  857. return tmp
  858. except Exception:
  859. time.sleep(0.01)
  860. continue
  861. return None
  862. def write(self, addr, val):
  863. for i in range(0, 3):
  864. try:
  865. self.bus.write_byte_data(self.address, addr, val)
  866. #time.sleep(0.001) # 1ms
  867. # print(addr, val) # debug
  868. return True
  869. except Exception:
  870. time.sleep(0.001)
  871. continue
  872. return False
  873. # set times functions ----------------------------------------
  874. def setYear(self, year):
  875. # only last two digits (last two digits are used if longer)
  876. self.write(0x06, self.int_to_bcd(year%100))
  877. def setMonth(self, month):
  878. if not 1 <= month <= 12:
  879. raise ValueError('Month is out of range [1,12].')
  880. self.write(0x05,self.int_to_bcd(month))
  881. def setDay(self, day):
  882. if not 1 <= day <= 31:
  883. raise ValueError('Day is out of range [1,31].')
  884. self.write(0x04,self.int_to_bcd(day))
  885. def setDayOfWeek(self, dayOfWeek):
  886. if not 1 <= dayOfWeek <= 7:
  887. raise ValueError('Day of week is out of range [1,7].')
  888. self.write(0x03,self.int_to_bcd(dayOfWeek))
  889. def setHour(self, hour):
  890. if not 0 <= hours < 24:
  891. raise ValueError('Hours is out of range [0,23].')
  892. self.write(0x02,self.int_to_bcd(hour)& 0x3F)
  893. def setMinutes(self, minutes):
  894. if not 0 <= minutes < 59:
  895. raise ValueError('Minutes is out of range [0,59].')
  896. self.write(0x01,self.int_to_bcd(minutes))
  897. def setSeconds(self, seconds):
  898. if not 0 <= seconds < 60:
  899. raise ValueError('Seconds is out of range [0,59].')
  900. self.write(0x00,self.int_to_bcd(seconds))
  901. def setDateTime(self, year, month, day, dayOfWeek, hour, minutes, seconds):
  902. # set all the date and times (year is last two digits of year)
  903. self.setYear(year)
  904. self.setMonth(month)
  905. self.setDay(day)
  906. self.setDayOfWeek(dayOfWeek)
  907. self.setHour(hour)
  908. self.setMinutes(minutes)
  909. self.setSeconds(seconds)
  910. # get times functions -------------------------------------------------
  911. def getYear(self):
  912. return self.bcd_to_int(self.read(0x06))
  913. def getMonth(self):
  914. temp = self.read(0x05)
  915. return self.bcd_to_int((temp<<4>>4) &0x7F)
  916. #return temp[0] & 0x7F
  917. def getDay(self):
  918. # 0 - 31
  919. return self.bcd_to_int(self.read(0x04))
  920. def getDayOfWeek(self):
  921. # 1 - 7
  922. return self.bcd_to_int(self.read(0x03))
  923. def getHour(self):
  924. temp = self.read(0x02)
  925. if temp==0x64: #if hour is 24:00,convert it to 00:00
  926. temp=0x40
  927. return self.bcd_to_int((temp<< 4 >>4)& 0x3F)
  928. #return temp[0] & 0x3F
  929. def getMinutes(self):
  930. return self.bcd_to_int(self.read(0x01))
  931. def getSeconds(self):
  932. return self.bcd_to_int(self.read(0x00))
  933. def getDateTime(self):
  934. # returns whole date and time as list
  935. # (last two digits of year, month, day, day of week, hour, minutes, seconds)
  936. dateTime = [0, 0, 0, 0, 0, 0, 0]
  937. dateTime[0] = self.getYear()
  938. dateTime[1] = self.getMonth()
  939. dateTime[2] = self.getDay()
  940. dateTime[3] = self.getDayOfWeek()
  941. dateTime[4] = self.getHour()
  942. dateTime[5] = self.getMinutes()
  943. dateTime[6] = self.getSeconds()
  944. return dateTime
  945. def convertToByteType(self,number):
  946. return bytes([number])
  947. def decodeToDec(self,byte):
  948. return ((byte[0] >> 4) * 10) + (byte[0] & 0x0F)
  949. def encodeToByte(self,dec):
  950. tens = floor(dec / 10)
  951. ones = dec - tens*10
  952. return (tens << 4) + ones
  953. def decodeAlarmType(self,alarmTime):
  954. if(len(alarmTime) > 4):
  955. m1Bit = (alarmTime[3] & 0x80) >> 7
  956. else:
  957. m1Bit = False
  958. m2Bit = (alarmTime[2] & 0x80) >> 7
  959. m3Bit = (alarmTime[1] & 0x80) >> 7
  960. m4Bit = (alarmTime[0] & 0x80) >> 7
  961. dayBit = (alarmTime[0] & 0x40) >> 6
  962. if(m1Bit and m2Bit and m3Bit and m4Bit):
  963. return "everySecond"
  964. elif(not m1Bit and m2Bit and m3Bit and m4Bit):
  965. return "everyMinute"
  966. elif(not m1Bit and not m2Bit and m3Bit and m4Bit):
  967. return "everyHour"
  968. elif(not m1Bit and not m2Bit and not m3Bit and m4Bit):
  969. return "everyDay"
  970. elif(not dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  971. return "everyMonth"
  972. elif(dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  973. return "everyWeek"
  974. else:
  975. return "noValidAlarmType"
  976. def decodeAlarmTime(self,alarmTime):
  977. alarmTime[0] = decodeToDec(convertToByteType(alarmTime[0] & 0x3F))
  978. alarmTime[1] = decodeToDec(convertToByteType(alarmTime[1] & 0x3F))
  979. alarmTime[2] = decodeToDec(convertToByteType(alarmTime[2] & 0x7F))
  980. if(len(alarmTime) > 4):
  981. alarmTime[3] = decodeToDec(convertToByteType(alarmTime[3] & 0x7F))
  982. return alarmTime
  983. def encodeAlarmType(self,alarmType):
  984. if(alarmType == "everySecond"):
  985. return 15 #0b01111
  986. elif(alarmType == "everyMinute"):
  987. return 14 #0b01110
  988. elif(alarmType == "everyHour"):
  989. return 12 #0b01100
  990. elif(alarmType == "everyDay"):
  991. return 8 #0b01000
  992. elif(alarmType == "everyMonth"):
  993. return 0 #0b00000
  994. elif(alarmType == "everyWeek"):
  995. return 16 #0b10000
  996. else:
  997. raise ValueError("""Not a supported alarmType. Options are:
  998. 'everySecond' (only Alarm 1), 'everyMinute', 'everyHour', 'everyDay', 'everyMonth', 'everyWeek'""")
  999. def encodeDateTime(self,day, hour, minutes, seconds, alarmType):
  1000. alarmBits = encodeAlarmType(alarmType)
  1001. alarmTime = [0, 0, 0, 0]
  1002. alarmTime[0] = (encodeToByte(day) & 0x3F) | ((alarmBits & 0x10) << 2) | ((alarmBits & 0x08) << 4)
  1003. alarmTime[1] = (encodeToByte(hour) & 0x3F) | ((alarmBits & 0x04) << 5)
  1004. alarmTime[2] = (encodeToByte(minutes) & 0x7F) | ((alarmBits & 0x02) << 6)
  1005. alarmTime[3] = (encodeToByte(seconds) & 0x7F) | ((alarmBits & 0x01) << 7)
  1006. return alarmTime
  1007. ##################################
  1008. # 10、SPI_WS2812 #
  1009. ##################################
  1010. class SPI_WS2812(object):
  1011. from maix import spi
  1012. spi = spi.SpiDev()
  1013. def __init__(self,num):
  1014. self.num=num
  1015. self.spi.open(0, 0)
  1016. self.spi.mode = 3
  1017. self.spi.bits_per_word = 8
  1018. self.spi.max_speed_hz = 20000000
  1019. self.data=[[0,0,0]]*self.num
  1020. self.brightness=255
  1021. def setRgbColor(self,id,r,g,b):
  1022. if id>(self.num-1):
  1023. raise ValueError("Out of range!")
  1024. else:
  1025. self.data[id]=[int(g*self.brightness/255),int(r*self.brightness/255),int(b*self.brightness/255)]
  1026. #print("set complete!")
  1027. def setBrightness(self,brightness):
  1028. if brightness>255 or brightness<0:
  1029. raise ValueError("Out of range!")
  1030. self.brightness=brightness
  1031. def rgbShow(self):
  1032. tx=[]
  1033. for rgb in self.data:
  1034. for byte in rgb:
  1035. for ibit in range(3,-1,-1):
  1036. tx.append(((byte>>(2*ibit+1))&1)*0x60 +
  1037. ((byte>>(2*ibit+0))&1)*0x06 +
  1038. 0x88)
  1039. print([hex(v) for v in tx])
  1040. tx[0]=0b1000000
  1041. tx.append(0b1000000)
  1042. self.spi.xfer(tx,int(4/1.05e-6))
  1043. def __del__(self):
  1044. self.data=[[0,0,0]]*self.num
  1045. self.rgbShow()
  1046. ##################################
  1047. # 11、HCSR04 #
  1048. ##################################
  1049. class HCSR04:
  1050. def __init__(self,Trig,Echo):
  1051. pinNum={"TXD":"198","RXD":"199","CLK":"224","MOSI":"225","MISO":"226","CS":"227"}
  1052. os.system("insmod /home/drivers/hcsr04.ko")
  1053. pinCmd=pinNum.get(Trig)+","+pinNum.get(Echo)+",23200,0"
  1054. os.system('echo "'+pinCmd+'" > /sys/class/hcsr04/value')
  1055. def getDistance(self):
  1056. startTime=round(time.time(),3)
  1057. #print("startTime:"+str(startTime))
  1058. while True:
  1059. dis=os.popen("cat /sys/class/hcsr04/value").read()
  1060. #print("dis:"+str(dis)+" len:"+str(len(dis)))
  1061. if "-1" in dis:
  1062. pass
  1063. else:
  1064. dis=round(int(dis)/58,2)
  1065. if dis<250:
  1066. return dis
  1067. else:
  1068. pass
  1069. if((round(time.time(),3)-startTime)>=1.200):#超时时间
  1070. return -1
  1071. def __del__(self):
  1072. os.system("rmmod /home/drivers/hcsr04.ko")
  1073. import struct
  1074. import math
  1075. import os
  1076. ##################################
  1077. # 12、MCP23017 #
  1078. ##################################
  1079. class MCP23017(object):
  1080. bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  1081. address = 0x20
  1082. iodira=0x00 #A引脚方向寄存器地址。初始值为0xFF,输入模式
  1083. iodirb=0x01 #B引脚方向寄存器地址。初始值为0xFF,输入模式
  1084. gppua=0x0c #A引脚上拉电阻配置寄存器地址。初始值为0x00,无上拉
  1085. gppub=0x0d #B引脚上拉电阻配置寄存器地址,初始值为0x00,无上拉
  1086. gpioa=0x12 #A端口寄存器,初始值为0x00,低电平
  1087. gpiob=0x13 #B端口寄存器,初始值为0x00,低电平
  1088. DIR_A_V=0xff #A引脚方向初始值
  1089. DIR_B_V=0xff #B引脚方向初始值
  1090. GPPU_A_V=0x00 #A引脚上拉设定初始值
  1091. GPPU_B_V=0x00 #B引脚上拉设定初始值
  1092. GPIO_A_V=0x00 #A引脚电平初始值
  1093. GPIO_B_V=0x00 #B引脚电平初始值
  1094. def __init__(self):
  1095. self.reset()
  1096. def reset(self):
  1097. self.DIR_A=self.DIR_A_V
  1098. self.DIR_B=self.DIR_B_V
  1099. self.GPPU_A=self.GPPU_A_V
  1100. self.GPPU_B=self.GPPU_B_V
  1101. self.GPIO_A=self.GPIO_A_V
  1102. self.GPIO_B=self.GPIO_B_V
  1103. self.byteWrite(self.iodira,self.DIR_A_V)
  1104. self.byteWrite(self.iodirb,self.DIR_B_V)
  1105. self.byteWrite(self.gppua,self.GPPU_A_V)
  1106. self.byteWrite(self.gppub,self.GPPU_B_V)
  1107. self.byteWrite(self.gpioa,self.GPIO_A_V)
  1108. self.byteWrite(self.gpiob,self.GPIO_B_V)
  1109. print("mcp23017 reset completed!")
  1110. def byteWrite(self, addr, val):
  1111. try:
  1112. self.bus.write_byte_data(self.address, addr, val)
  1113. return True
  1114. except Exception:
  1115. pass
  1116. def byteRead(self,addr):
  1117. tmp = self.bus.read_byte_data(self.address, addr)
  1118. return tmp
  1119. def bitWrite(self,reg,num,val): #寄存器值(byte类型),寄存器第...位(0-7),该位的值(0/1)
  1120. return (reg>>(num+1)<<(num+1))|(val << num)|(reg<<(8-num)&0xFF)>>(8-num)
  1121. def bitRead(self,reg,num): #寄存器值(byte类型),寄存器第...位(0-7)
  1122. return ((reg<<(7-num)&0xFF)>>7)
  1123. def setGpioDir(self,channel,pinId,direction): #set gpio direction
  1124. #channel:"A" or "B"
  1125. #pinId:0~7
  1126. #direction:[0:output],[1:input(default)]
  1127. if channel=="A":
  1128. self.DIR_A=self.bitWrite(self.DIR_A,pinId,direction)
  1129. print("Dir_A="+str(self.DIR_A))
  1130. self.byteWrite(self.iodira,self.DIR_A)
  1131. elif channel=="B":
  1132. self.DIR_B=self.bitWrite(self.DIR_B,pinId,direction)
  1133. self.byteWrite(self.iodirb,self.DIR_B)
  1134. else:
  1135. raise ValueError("Error Channel!")
  1136. def setGppuEnable(self,channel,pinId,pullup): #set gpio pullup on or off
  1137. #channel:"A" or "B"
  1138. #pinId:0~7
  1139. #pullup:[0:disable],[1:enable(default)]
  1140. if channel=="A":
  1141. self.GPPU_A=self.bitWrite(self.GPPU_A,pinId,pullup)
  1142. self.byteWrite(self.gppua,self.GPPU_A)
  1143. elif channel=="B":
  1144. self.GPPU_B=self.bitWrite(self.GPPU_B,pinId,pullup)
  1145. self.byteWrite(self.gppub,self.GPPU_B)
  1146. else:
  1147. raise ValueError("Error Channel!")
  1148. def setGpioLevel(self,channel,pinId,level): #set gpio volt level
  1149. #channel:"A" or "B"
  1150. #pinId:0~7
  1151. #level:[0:low(default)],[1:high]
  1152. if channel=="A":
  1153. self.GPIO_A=self.bitWrite(self.GPIO_A,pinId,level)
  1154. self.byteWrite(self.gpioa,self.GPIO_A)
  1155. elif channel=="B":
  1156. self.GPIO_B=self.bitWrite(self.GPIO_B,pinId,level)
  1157. self.byteWrite(self.gpiob,self.GPIO_B)
  1158. else:
  1159. raise ValueError("Error Channel!")
  1160. def getGpioLevel(self,channel,pinId): #get gpio volt level
  1161. #channel:"A" or "B"
  1162. #pinId:0~7
  1163. #level:[0:low(default)],[1:high]
  1164. if channel=="A":
  1165. return self.bitRead(self.byteRead(self.gpioa),pinId)
  1166. elif channel=="B":
  1167. return self.bitRead(self.byteRead(self.gpiob),pinId)
  1168. else:
  1169. raise ValueError("Error Channel!")
  1170. def __del__(self):
  1171. self.reset()
  1172. time.sleep(0.001)
  1173. print("del mcp23017")
  1174. class ADS1115(object):
  1175. bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  1176. # Registers in the ADS1115,设备的4个寄存器
  1177. DEVICE_REG_CONVERSION = 0x00 #转换寄存器
  1178. DEVICE_REG_CONFIG = 0x01 #配置寄存器
  1179. DEVICE_REG_LO_THRESH = 0x02 #最低阈值寄存器
  1180. DEVICE_REG_HI_THRESH = 0x03 #最高阈值寄存器
  1181. # Configuration register fields #配置寄存器展开,共16bit
  1182. # Operational Status #操作状态,在第15位
  1183. CONFIG_OS = 0X8000 #无效
  1184. CONFIG_OS_START = 0X8000 #开始单次转换(处于掉电状态)
  1185. CONFIG_OS_PERFORMING_CONVERSION = 0X0000 #转换进行中
  1186. CONFIG_OS_NOT_PERFORMING_OPERATION = 0X8000 #转换闲置
  1187. # Differential measurements #测量模式设置,在第12-14位
  1188. CONFIG_MUX_AIN0P_AIN1N = 0X0000 # (default) #AIN0差分输入,AIN1作为参考
  1189. CONFIG_MUX_AIN1P_AIN3N = 0X1000 #AIN1差分输入,AIN3作为参考
  1190. CONFIG_MUX_AIN2P_AIN3N = 0X2000 #AIN2差分输入,AIN3作为参考
  1191. CONFIG_MUX_AIN3P_AIN3N = 0X3000 #AIN3差分输入,AIN3作为参考
  1192. # Single ended measurements #单端测量
  1193. CONFIG_MUX_AIN0P_GNDN = 0X4000 #AIN0单端输入
  1194. CONFIG_MUX_AIN1P_GNDN = 0X5000 #AIN1单端输入
  1195. CONFIG_MUX_AIN2P_GNDN = 0X6000 #AIN2单端输入
  1196. CONFIG_MUX_AIN3P_GNDN = 0X7000 #AIN3单端输入
  1197. # Programmable gain amplifier configuration #可编程增益放大器(量程选择)FSR:Feedback Shift Register,反馈移位寄存器,在第9-11位
  1198. CONFIG_FSR_6V144 = 0X0000 #CocoPi 需选择
  1199. CONFIG_FSR_4V096 = 0X0200
  1200. CONFIG_FSR_2V048 = 0X0400 # (default)
  1201. CONFIG_FSR_1V024 = 0X0600
  1202. CONFIG_FSR_0V512 = 0X0800
  1203. CONFIG_FSR_0V256 = 0X0A00
  1204. CONFIG_FSR_0V256 = 0X0C00
  1205. CONFIG_FSR_0V256 = 0X0E00
  1206. # Continuous or single shot mode #设备运行模式:持续转换或者单次转换,在第8位
  1207. CONFIG_MODE_CONTINUOUS = 0X0000 #持续转换
  1208. CONFIG_MODE_SINGLE_SHOT = 0X0100 # (default) #单次转换
  1209. # Data rate #转换速率,第5-7位
  1210. CONFIG_DATA_RATE_8SPS = 0X0000 #SPS:Samples Per Second,每秒8次采样
  1211. CONFIG_DATA_RATE_16SPS = 0X0020
  1212. CONFIG_DATA_RATE_32SPS = 0X0040
  1213. CONFIG_DATA_RATE_64SPS = 0X0060
  1214. CONFIG_DATA_RATE_128SPS = 0X0080 #(default)
  1215. CONFIG_DATA_RATE_2508SPS = 0X00A0
  1216. CONFIG_DATA_RATE_475SPS = 0X00C0
  1217. CONFIG_DATA_RATE_860SPS = 0X00E0
  1218. # Comparitor mode #比较器模式,第4位
  1219. CONFIG_COMP_MODE_TRADITIONAL = 0X0000 #(default) #传统比较器
  1220. CONFIG_COMP_MODE_WINDOW = 0X0010 #窗口模式
  1221. # Comparitor polarity #比较器集型,第3位,控制ALRET/RDY引脚极性
  1222. CONFIG_COMP_POL_ACTIVE_LOW = 0X0000 #(default) #低电平有效(默认)
  1223. CONFIG_COMP_POL_ACTIVE_HIGH = 0X0008 #高电平有效
  1224. # Comparitor latching #锁存比较器,第2位,该位控制ALERT/RDY引脚在被置为有效后锁存,还是在转换后处于上限和下限阈值范围内清零
  1225. CONFIG_COMP_LAT = 0X0004
  1226. CONFIG_COMP_LAT_NON_LATCHING = 0X0000 #(default) #默认不锁存
  1227. CONFIG_COMP_LAT_LATCHING = 0X0004
  1228. # comparitor queue and disable #比较器置位和禁用
  1229. CONFIG_COMP_QUE = 0X0003 #默认禁用比较器并将ALERT/RDY引脚设置为高阻抗
  1230. CONFIG_COMP_QUE_1_CONV = 0X0000 #一次转换后断言
  1231. CONFIG_COMP_QUE_2_CONV = 0X0001 #两次转换后置位
  1232. CONFIG_COMP_QUE_4_CONV = 0X0002 #四次转换后置位
  1233. CONFIG_COMP_QUE_DISABLE = 0X0003 #(default) #默认禁用比较器并将ALERT/RDY引脚设置为高阻抗
  1234. # Address for the device ,设备地址选择
  1235. #addr=0x48 # ADDR tied to GND
  1236. addr=0x49 # ADDR tied to VDD
  1237. #addr=0x4A # ADDR tied to SDA
  1238. #addr=0x4B # ADDR tied to SCL
  1239. def __init__(self):
  1240. self.address=0x49
  1241. self.config=0x0000
  1242. #time.sleep(0.05)
  1243. pass
  1244. def swap(self,val):
  1245. return (((val&0xff00)>>8)|((val&0x00ff)<<8)) #交换高8位与低8位
  1246. ###
  1247. def readAdc(self,channel):
  1248. if (channel>3) or (channel<0):
  1249. return False
  1250. self.config=(self.CONFIG_OS_START + # start conversion
  1251. #self.CONFIG_MUX_AIN0P_GNDN + # single ended conversion
  1252. ((channel+4)<<12) + # select channel
  1253. self.CONFIG_FSR_6V144 + # (5v signal)
  1254. self.CONFIG_MODE_SINGLE_SHOT + # single conversion and shutdown
  1255. self.CONFIG_DATA_RATE_128SPS + # data rate
  1256. self.CONFIG_COMP_MODE_TRADITIONAL + # comp conventional
  1257. self.CONFIG_COMP_POL_ACTIVE_LOW + # comp active low
  1258. self.CONFIG_COMP_LAT_NON_LATCHING + # comp non latching
  1259. self.CONFIG_COMP_QUE_DISABLE ) # comp disabled
  1260. ###
  1261. self.bus.write_word_data(self.address, self.DEVICE_REG_CONFIG, self.swap(self.config))
  1262. while True:
  1263. # read status (note byte swap)
  1264. status=self.swap(self.bus.read_word_data(self.address,self.DEVICE_REG_CONFIG))
  1265. #print("status:"+str(status))
  1266. # when the Operational Status is no longer performing a conversion
  1267. # we can break out of this wait loop
  1268. if (status & self.CONFIG_OS) != self.CONFIG_OS_PERFORMING_CONVERSION:
  1269. break
  1270. # read result (note byte swap)
  1271. result=self.swap(self.bus.read_word_data(self.address,self.DEVICE_REG_CONVERSION))
  1272. # return 16 bit integer A2D result for the specified channel
  1273. volt=round((result*6.144/32768),3)
  1274. return [result,volt]
  1275. class PCA9685(object):
  1276. bus=smbus2.SMBus(2)
  1277. def __init__(self,freq=400,min_us=460,max_us=2400,address=0x40,degrees=180):
  1278. self.address=address
  1279. self.period=1000000/freq
  1280. self.min_duty = self._us2duty(min_us)
  1281. self.max_duty = self._us2duty(max_us)
  1282. self.freq(freq)
  1283. self.reset()
  1284. #for i in range(0,16):
  1285. #self.duty(i,0)
  1286. print("Pca9685 init")
  1287. def write(self, addr, val):
  1288. for i in range(0, 2):
  1289. try:
  1290. self.bus.write_byte_data(self.address, addr, val)
  1291. #time.sleep(0.001) # 1ms
  1292. # print(addr, val) # debug
  1293. return True
  1294. except Exception:
  1295. time.sleep(0.001)
  1296. continue
  1297. return False
  1298. def read(self,addr):
  1299. for i in range(0, 3):
  1300. try:
  1301. tmp = self.bus.read_byte_data(self.address, addr)
  1302. #time.sleep(0.001) # 1ms
  1303. # print(addr, tmp) # debug
  1304. return tmp
  1305. except Exception:
  1306. time.sleep(0.01)
  1307. continue
  1308. return None
  1309. def reset(self):
  1310. self.write(0x00,0x00) #初始化
  1311. def freq(self,freq=None):
  1312. if freq is None:
  1313. return int(25000000.0/4096/(self.read(0xfe)-0.5))
  1314. #设定频率freq,预分频prescale=int(25000000.0 / (4096.0 * freq) + 0.5)
  1315. prescale=int(25000000.0/4096/freq+0.5)
  1316. self.write(0x00,0x10) #设定pca9685为睡眠模式
  1317. self.write(0xfe,prescale) #设定频率
  1318. self.reset()
  1319. time.sleep(0.01)
  1320. self.write(0x00,0xa1) #设定pca9685为活跃模式
  1321. def pwm(self,index,on=None,off=None): #on和off来调节PWM的占空比
  1322. if not 0<= index <=15:
  1323. raise ValueError("Pin ID out of range!")
  1324. if on is None or off is None:
  1325. data = self.bus.read_i2c_block_data(self.address,0x06+index*4,4)
  1326. return data
  1327. data= [0]*4
  1328. data[0]=int(hex(on & 0xff),16)
  1329. data[1]=int(hex((on >> 8) & 0xff),16)
  1330. data[2]=int(hex(off & 0xff),16)
  1331. data[3]=int(hex((off >> 8) & 0xff),16)
  1332. # print(data)
  1333. for i in range(0,4):
  1334. self.write(0x06+i+index*4,data[i])
  1335. def duty(self,index,value=None):
  1336. if value == None:
  1337. return self.pwm(index)
  1338. elif not 0 <= value <=4095:
  1339. raise ValueError("Out of range!")
  1340. elif value==0:
  1341. self.pwm(index,0,4096)
  1342. elif value == 4095:
  1343. self.pwm(index,4096,0)
  1344. else:
  1345. self.pwm(index,0,value)
  1346. def _us2duty(self,value):
  1347. return 4095*value/self.period
  1348. def __del__(self):
  1349. print("del pac9685")
  1350. time.sleep(1)
  1351. for i in range(0,16):
  1352. self.duty(i,0)
  1353. time.sleep(0.001)
  1354. class extDcMotor(PCA9685):
  1355. def __init__(self,motorId):
  1356. PCA9685.__init__(self)
  1357. self.motorPin=[11,12,13,10,9,8,5,6,7,4,3,2]
  1358. self.motorId=motorId
  1359. pass
  1360. def speedControl(self,speed):
  1361. self.speed=abs(speed)
  1362. if not -255<= speed<=255:
  1363. raise ValueError("Out of range!")
  1364. if self.motorId == "C":
  1365. if speed<0:
  1366. self.duty(self.motorPin[0],4095)
  1367. self.duty(self.motorPin[1],0)
  1368. self.duty(self.motorPin[2],int(self.speed*16))
  1369. else:
  1370. self.duty(self.motorPin[0],0)
  1371. self.duty(self.motorPin[1],4095)
  1372. self.duty(self.motorPin[2],int(self.speed*16))
  1373. elif self.motorId == "D":
  1374. if speed<0:
  1375. self.duty(self.motorPin[3],4095)
  1376. self.duty(self.motorPin[4],0)
  1377. self.duty(self.motorPin[5],int(self.speed*16))
  1378. else:
  1379. self.duty(self.motorPin[3],0)
  1380. self.duty(self.motorPin[4],4095)
  1381. self.duty(self.motorPin[5],int(self.speed*16))
  1382. elif self.motorId == "E":
  1383. if speed<0:
  1384. self.duty(self.motorPin[6],4095)
  1385. self.duty(self.motorPin[7],0)
  1386. self.duty(self.motorPin[8],int(self.speed*16))
  1387. else:
  1388. self.duty(self.motorPin[6],0)
  1389. self.duty(self.motorPin[7],4095)
  1390. self.duty(self.motorPin[8],int(self.speed*16))
  1391. elif self.motorId == "F":
  1392. if speed<0:
  1393. self.duty(self.motorPin[9],4095)
  1394. self.duty(self.motorPin[10],0)
  1395. self.duty(self.motorPin[11],int(self.speed*16))
  1396. else:
  1397. self.duty(self.motorPin[9],0)
  1398. self.duty(self.motorPin[10],4095)
  1399. self.duty(self.motorPin[11],int(self.speed*16))
  1400. else:
  1401. pass
  1402. def __del__(self):
  1403. if self.motorId == "C":
  1404. self.duty(self.motorPin[0],0)
  1405. self.duty(self.motorPin[1],0)
  1406. self.duty(self.motorPin[2],0)
  1407. elif self.motorId == "D":
  1408. self.duty(self.motorPin[3],0)
  1409. self.duty(self.motorPin[4],0)
  1410. self.duty(self.motorPin[5],0)
  1411. elif self.motorId == "E":
  1412. self.duty(self.motorPin[6],0)
  1413. self.duty(self.motorPin[7],0)
  1414. self.duty(self.motorPin[8],0)
  1415. elif self.motorId == "F":
  1416. self.duty(self.motorPin[9],0)
  1417. self.duty(self.motorPin[10],0)
  1418. self.duty(self.motorPin[11],0)
  1419. else:
  1420. pass
  1421. time.sleep(0.001)
  1422. class extServo(PCA9685):
  1423. def __init__(self,servoId):
  1424. PCA9685.__init__(self)
  1425. self.servoId=servoId
  1426. self.servoPin=[14,15,1,0]
  1427. self.degrees=180
  1428. pass
  1429. def position(self,degrees=None): #index:0,1,2,3
  1430. span = self.max_duty - self.min_duty
  1431. duty = self.min_duty + span * degrees / self.degrees
  1432. duty = int(min(self.max_duty, max(self.min_duty, int(duty))))
  1433. self.duty(self.servoPin[self.servoId], duty)
  1434. def release(self):
  1435. self.duty(self.servoPin[self.servoId],0)
  1436. def __del__(self):
  1437. self.duty(self.servoPin[self.servoId],0)
  1438. class extOutputPin(PCA9685):
  1439. def __init__(self):
  1440. PCA9685.__init__(self)
  1441. self.pin=[14,15,1,0]
  1442. self.pinId=0
  1443. pass
  1444. def digitalSet(self,pinId,val): #val:0/1
  1445. self.pinId=pinId
  1446. if val==0:
  1447. self.duty(self.pin[self.pinId],0)
  1448. else:
  1449. self.duty(self.pin[self.pinId],4095)
  1450. def pwmWrite(self,pinId,val): #val:0~255
  1451. self.pinId=pinId
  1452. # print("pinid"+str(self.pin[self.pinId]))
  1453. self.duty(self.pin[self.pinId],val*16)
  1454. def __del__(self):
  1455. self.duty(self.pin[self.pinId],0)
  1456. # print("del extPin")
  1457. class extGpio(MCP23017,ADS1115,extOutputPin):
  1458. def __init__(self):
  1459. MCP23017.__init__(self)
  1460. ADS1115.__init__(self)
  1461. extOutputPin.__init__(self)
  1462. self.address=0x20 #初始默认为mcp23017的地址
  1463. def pinMode(self,pinId,mode): #控制mcp23017
  1464. self.address=0x20
  1465. #----------
  1466. #pinId:
  1467. #p0~p3:0~3
  1468. #a0~a3:4~7
  1469. #---------
  1470. #mode:
  1471. #output:1
  1472. #input:0
  1473. if pinId>=0 and pinId<=3:
  1474. if mode==0:
  1475. if pinId==0: #p0
  1476. self.setGpioDir("B",2,0) #output
  1477. self.setGpioLevel("B",2,1) #high
  1478. self.setGpioDir("B",3,1) #input
  1479. elif pinId==1: #p1
  1480. self.setGpioDir("B",1,0)
  1481. self.setGpioLevel("B",1,1)
  1482. self.setGpioDir("B",0,1)
  1483. elif pinId==2: #p2
  1484. self.setGpioDir("B",6,0)
  1485. self.setGpioLevel("B",6,1)
  1486. self.setGpioDir("A",1,1)
  1487. elif pinId==3: #p3
  1488. self.setGpioDir("B",5,0)
  1489. self.setGpioLevel("B",5,1)
  1490. self.setGpioDir("B",4,1)
  1491. else:
  1492. pass
  1493. elif mode==1:
  1494. if pinId==0:
  1495. self.setGpioDir("B",2,0) #output
  1496. self.setGpioLevel("B",2,1) #high
  1497. self.setGpioDir("B",3,0) #output
  1498. elif pinId==1:
  1499. self.setGpioDir("B",1,0)
  1500. self.setGpioLevel("B",1,1)
  1501. self.setGpioDir("B",0,0)
  1502. elif pinId==2:
  1503. self.setGpioDir("B",6,0)
  1504. self.setGpioLevel("B",6,1)
  1505. self.setGpioDir("A",1,0)
  1506. elif pinId==3:
  1507. self.setGpioDir("B",5,0)
  1508. self.setGpioLevel("B",5,1)
  1509. self.setGpioDir("B",4,0)
  1510. # print("a")
  1511. time.sleep(1)
  1512. else:
  1513. pass
  1514. else:
  1515. pass
  1516. elif pinId>=4 and pinId<=7:
  1517. if mode==0:
  1518. if pinId==4: #a0
  1519. self.setGpioDir("A",4,0) #output
  1520. self.setGpioLevel("A",4,1) #high
  1521. self.setGpioDir("A",5,1) #input
  1522. elif pinId==5: #a1
  1523. self.setGpioDir("A",3,0)
  1524. self.setGpioLevel("A",3,1)
  1525. self.setGpioDir("A",7,1)
  1526. elif pinId==6: #a2
  1527. self.setGpioDir("A",2,0)
  1528. self.setGpioLevel("A",2,1)
  1529. self.setGpioDir("A",6,1)
  1530. elif pinId==7: #a3
  1531. self.setGpioDir("B",7,0)
  1532. self.setGpioLevel("B",7,1)
  1533. self.setGpioDir("A",0,1)
  1534. else:
  1535. pass
  1536. elif mode==1:
  1537. if pinId==4: #a0
  1538. self.setGpioDir("A",4,0) #output
  1539. self.setGpioLevel("A",4,1) #high
  1540. self.setGpioDir("A",5,0) #output
  1541. elif pinId==5: #a1
  1542. self.setGpioDir("A",3,0)
  1543. self.setGpioLevel("A",3,1)
  1544. self.setGpioDir("A",7,0)
  1545. elif pinId==6: #a2
  1546. self.setGpioDir("A",2,0)
  1547. self.setGpioLevel("A",2,1)
  1548. self.setGpioDir("A",6,0)
  1549. elif pinId==7: #a3
  1550. self.setGpioDir("B",7,0)
  1551. self.setGpioLevel("B",7,1)
  1552. self.setGpioDir("A",0,0)
  1553. else:
  1554. pass
  1555. else:
  1556. pass
  1557. def digitalWrite(self,pinId,level): #控制mcp23017
  1558. #----------
  1559. #pinId:
  1560. #p0~p3:0~3
  1561. #a0~a3:4~7
  1562. #---------
  1563. #level:
  1564. #5v:1
  1565. #0v:0
  1566. self.address=0x20
  1567. if pinId>=0 and pinId<=3:
  1568. if pinId==0:
  1569. # print("digital write level")
  1570. self.setGpioLevel("B",3,level)
  1571. elif pinId==1:
  1572. self.setGpioLevel("B",0,level)
  1573. elif pinId==2:
  1574. self.setGpioLevel("A",1,level)
  1575. elif pinId==3:
  1576. self.setGpioLevel("B",4,level)
  1577. else:
  1578. pass
  1579. elif pinId>=4 and pinId<=7:
  1580. if pinId==4: #a0
  1581. self.setGpioLevel("A",5,level)
  1582. elif pinId==5: #a1
  1583. self.setGpioLevel("A",7,level)
  1584. elif pinId==6: #a2
  1585. self.setGpioLevel("A",6,level)
  1586. elif pinId==7: #a3
  1587. self.setGpioLevel("A",0,level)
  1588. else:
  1589. pass
  1590. else:
  1591. pass
  1592. def digitalRead(self,pinId): #控制mcp23017
  1593. self.address=0x20
  1594. #----------
  1595. #pinId:
  1596. #p0~p3:0~3
  1597. #a0~a3:4~7
  1598. if pinId>=0 and pinId<=3:
  1599. if pinId==0:
  1600. # print("get digital write level")
  1601. return self.getGpioLevel("B",3)
  1602. elif pinId==1:
  1603. return self.getGpioLevel("B",0)
  1604. elif pinId==2:
  1605. return self.getGpioLevel("A",1)
  1606. elif pinId==3:
  1607. return self.getGpioLevel("B",4)
  1608. else:
  1609. pass
  1610. elif pinId>=4 and pinId<=7:
  1611. if pinId==4: #a0
  1612. return self.getGpioLevel("A",5)
  1613. elif pinId==5: #a1
  1614. return self.getGpioLevel("A",7)
  1615. elif pinId==6: #a2
  1616. return self.getGpioLevel("A",6)
  1617. elif pinId==7: #a3
  1618. return self.getGpioLevel("A",0)
  1619. else:
  1620. pass
  1621. else:
  1622. pass
  1623. def analogWrite(self,pinId,pwm): #控制PCA9685,但是需要Mcp23017进行通道选择
  1624. self.address=0x20 #先用mcp23017进行通道选择
  1625. #select X channel
  1626. if pinId==0: #p0
  1627. self.setGpioDir("B",2,1) #output
  1628. self.setGpioLevel("B",2,0) #low
  1629. elif pinId==1: #p1
  1630. self.setGpioDir("B",1,1)
  1631. self.setGpioLevel("B",1,0)
  1632. elif pinId==2: #p2
  1633. self.setGpioDir("B",6,1)
  1634. self.setGpioLevel("B",6,0)
  1635. elif pinId==3: #p3
  1636. self.setGpioDir("B",5,1)
  1637. self.setGpioLevel("B",5,0)
  1638. else:
  1639. pass
  1640. self.address=0x40 #再用PCA9685进行控制
  1641. self.pwmWrite(pinId,pwm)
  1642. def analogRead(self,pinId): #控制ADS1115,但是需要Mcp23017进行通道选择
  1643. self.adcPin=[3,1,0,2]
  1644. self.address=0x20 #先用mcp23017进行通道选择
  1645. #select X channel
  1646. if pinId==4: #a0
  1647. self.setGpioDir("A",4,1) #input
  1648. self.setGpioLevel("A",4,0) #low
  1649. elif pinId==5: #a1
  1650. self.setGpioDir("A",3,1)
  1651. self.setGpioLevel("A",3,0)
  1652. elif pinId==6: #a2
  1653. self.setGpioDir("A",2,1)
  1654. self.setGpioLevel("A",2,0)
  1655. elif pinId==7: #a3
  1656. self.setGpioDir("B",7,0)
  1657. self.setGpioLevel("B",7,0)
  1658. else:
  1659. pass
  1660. self.address=0x49 #再用Ads1115进行ADC读取
  1661. return self.readAdc(self.adcPin[pinId-4])
  1662. def __del__(self):
  1663. self.address=0x40
  1664. extOutputPin.__del__(self)
  1665. self.address=0x20
  1666. MCP23017.__del__(self) #最先init的配置最后再del
  1667. print("del finished!")