CocoPi.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  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. def numberMap(self,value, leftMin, leftMax, rightMin, rightMax):
  1247. leftSpan = leftMax - leftMin
  1248. rightSpan = rightMax - rightMin
  1249. valueScaled = float(value - leftMin) / float(leftSpan)
  1250. return rightMin + (valueScaled * rightSpan)
  1251. ###
  1252. def readAdc(self,channel):
  1253. # print("111111111111111",(channel>3) or (channel<0))
  1254. # if (channel>3) or (channel<0):
  1255. # return False
  1256. self.config=(self.CONFIG_OS_START + # start conversion
  1257. #self.CONFIG_MUX_AIN0P_GNDN + # single ended conversion
  1258. ((channel+4)<<12) + # select channel
  1259. self.CONFIG_FSR_6V144 + # (5v signal)
  1260. self.CONFIG_MODE_SINGLE_SHOT + # single conversion and shutdown
  1261. self.CONFIG_DATA_RATE_128SPS + # data rate
  1262. self.CONFIG_COMP_MODE_TRADITIONAL + # comp conventional
  1263. self.CONFIG_COMP_POL_ACTIVE_LOW + # comp active low
  1264. self.CONFIG_COMP_LAT_NON_LATCHING + # comp non latching
  1265. self.CONFIG_COMP_QUE_DISABLE ) # comp disabled
  1266. ###
  1267. self.bus.write_word_data(self.address, self.DEVICE_REG_CONFIG, self.swap(self.config))
  1268. while True:
  1269. # read status (note byte swap)
  1270. status=self.swap(self.bus.read_word_data(self.address,self.DEVICE_REG_CONFIG))
  1271. #print("status:"+str(status))
  1272. # when the Operational Status is no longer performing a conversion
  1273. # we can break out of this wait loop
  1274. if (status & self.CONFIG_OS) != self.CONFIG_OS_PERFORMING_CONVERSION:
  1275. break
  1276. # read result (note byte swap)
  1277. result=self.swap(self.bus.read_word_data(self.address,self.DEVICE_REG_CONVERSION))
  1278. # return 16 bit integer A2D result for the specified channel
  1279. # volt=round((result*6.144/32768),3)
  1280. result = int(self.numberMap(result,0,32768,0,1023))
  1281. return result
  1282. class PCA9685(object):
  1283. bus=smbus2.SMBus(2)
  1284. def __init__(self,freq=400,min_us=460,max_us=2400,address=0x40,degrees=180):
  1285. self.address=address
  1286. self.period=1000000/freq
  1287. self.min_duty = self._us2duty(min_us)
  1288. self.max_duty = self._us2duty(max_us)
  1289. self.freq(freq)
  1290. self.reset()
  1291. #for i in range(0,16):
  1292. #self.duty(i,0)
  1293. # print("Pca9685 init")
  1294. def write(self, addr, val):
  1295. for i in range(0, 2):
  1296. try:
  1297. self.bus.write_byte_data(self.address, addr, val)
  1298. #time.sleep(0.001) # 1ms
  1299. # print(addr, val) # debug
  1300. return True
  1301. except Exception:
  1302. time.sleep(0.001)
  1303. continue
  1304. return False
  1305. def read(self,addr):
  1306. for i in range(0, 3):
  1307. try:
  1308. tmp = self.bus.read_byte_data(self.address, addr)
  1309. #time.sleep(0.001) # 1ms
  1310. # print(addr, tmp) # debug
  1311. return tmp
  1312. except Exception:
  1313. time.sleep(0.01)
  1314. continue
  1315. return None
  1316. def reset(self):
  1317. self.write(0x00,0x00) #初始化
  1318. def freq(self,freq=None):
  1319. if freq is None:
  1320. return int(25000000.0/4096/(self.read(0xfe)-0.5))
  1321. #设定频率freq,预分频prescale=int(25000000.0 / (4096.0 * freq) + 0.5)
  1322. prescale=int(25000000.0/4096/freq+0.5)
  1323. self.write(0x00,0x10) #设定pca9685为睡眠模式
  1324. self.write(0xfe,prescale) #设定频率
  1325. self.reset()
  1326. time.sleep(0.01)
  1327. self.write(0x00,0xa1) #设定pca9685为活跃模式
  1328. def pwm(self,index,on=None,off=None): #on和off来调节PWM的占空比
  1329. if not 0<= index <=15:
  1330. raise ValueError("Pin ID out of range!")
  1331. if on is None or off is None:
  1332. data = self.bus.read_i2c_block_data(self.address,0x06+index*4,4)
  1333. return data
  1334. data= [0]*4
  1335. data[0]=int(hex(on & 0xff),16)
  1336. data[1]=int(hex((on >> 8) & 0xff),16)
  1337. data[2]=int(hex(off & 0xff),16)
  1338. data[3]=int(hex((off >> 8) & 0xff),16)
  1339. # print(data)
  1340. for i in range(0,4):
  1341. self.write(0x06+i+index*4,data[i])
  1342. def duty(self,index,value=None):
  1343. if value == None:
  1344. return self.pwm(index)
  1345. elif not 0 <= value <=4095:
  1346. raise ValueError("Out of range!")
  1347. elif value==0:
  1348. self.pwm(index,0,4096)
  1349. elif value == 4095:
  1350. self.pwm(index,4096,0)
  1351. else:
  1352. self.pwm(index,0,value)
  1353. def _us2duty(self,value):
  1354. return 4095*value/self.period
  1355. def __del__(self):
  1356. print("del pac9685")
  1357. time.sleep(1)
  1358. for i in range(0,16):
  1359. self.duty(i,0)
  1360. time.sleep(0.001)
  1361. class extDcMotor(PCA9685):
  1362. def __init__(self,motorId):
  1363. PCA9685.__init__(self)
  1364. self.motorPin=[11,12,13,10,9,8,5,6,7,4,3,2]
  1365. self.motorId=motorId
  1366. pass
  1367. def speedControl(self,speed):
  1368. self.speed=abs(speed)
  1369. if not -255<= speed<=255:
  1370. raise ValueError("Out of range!")
  1371. if self.motorId == "C":
  1372. if speed<0:
  1373. self.duty(self.motorPin[0],4095)
  1374. self.duty(self.motorPin[1],0)
  1375. self.duty(self.motorPin[2],int(self.speed*16))
  1376. else:
  1377. self.duty(self.motorPin[0],0)
  1378. self.duty(self.motorPin[1],4095)
  1379. self.duty(self.motorPin[2],int(self.speed*16))
  1380. elif self.motorId == "D":
  1381. if speed<0:
  1382. self.duty(self.motorPin[3],4095)
  1383. self.duty(self.motorPin[4],0)
  1384. self.duty(self.motorPin[5],int(self.speed*16))
  1385. else:
  1386. self.duty(self.motorPin[3],0)
  1387. self.duty(self.motorPin[4],4095)
  1388. self.duty(self.motorPin[5],int(self.speed*16))
  1389. elif self.motorId == "E":
  1390. if speed<0:
  1391. self.duty(self.motorPin[6],4095)
  1392. self.duty(self.motorPin[7],0)
  1393. self.duty(self.motorPin[8],int(self.speed*16))
  1394. else:
  1395. self.duty(self.motorPin[6],0)
  1396. self.duty(self.motorPin[7],4095)
  1397. self.duty(self.motorPin[8],int(self.speed*16))
  1398. elif self.motorId == "F":
  1399. if speed<0:
  1400. self.duty(self.motorPin[9],4095)
  1401. self.duty(self.motorPin[10],0)
  1402. self.duty(self.motorPin[11],int(self.speed*16))
  1403. else:
  1404. self.duty(self.motorPin[9],0)
  1405. self.duty(self.motorPin[10],4095)
  1406. self.duty(self.motorPin[11],int(self.speed*16))
  1407. else:
  1408. pass
  1409. def __del__(self):
  1410. if self.motorId == "C":
  1411. self.duty(self.motorPin[0],0)
  1412. self.duty(self.motorPin[1],0)
  1413. self.duty(self.motorPin[2],0)
  1414. elif self.motorId == "D":
  1415. self.duty(self.motorPin[3],0)
  1416. self.duty(self.motorPin[4],0)
  1417. self.duty(self.motorPin[5],0)
  1418. elif self.motorId == "E":
  1419. self.duty(self.motorPin[6],0)
  1420. self.duty(self.motorPin[7],0)
  1421. self.duty(self.motorPin[8],0)
  1422. elif self.motorId == "F":
  1423. self.duty(self.motorPin[9],0)
  1424. self.duty(self.motorPin[10],0)
  1425. self.duty(self.motorPin[11],0)
  1426. else:
  1427. pass
  1428. time.sleep(0.001)
  1429. class extServo(PCA9685):
  1430. def __init__(self,servoId):
  1431. PCA9685.__init__(self)
  1432. self.servoId=servoId
  1433. self.servoPin=[14,15,1,0]
  1434. self.degrees=180
  1435. pass
  1436. def position(self,degrees=None): #index:0,1,2,3
  1437. span = self.max_duty - self.min_duty
  1438. duty = self.min_duty + span * degrees / self.degrees
  1439. duty = int(min(self.max_duty, max(self.min_duty, int(duty))))
  1440. self.duty(self.servoPin[self.servoId], duty)
  1441. def release(self):
  1442. self.duty(self.servoPin[self.servoId],0)
  1443. def __del__(self):
  1444. self.duty(self.servoPin[self.servoId],0)
  1445. class extOutputPin(PCA9685):
  1446. def __init__(self):
  1447. PCA9685.__init__(self)
  1448. self.pin=[14,15,1,0]
  1449. self.pinId=0
  1450. pass
  1451. def digitalSet(self,pinId,val): #val:0/1
  1452. self.pinId=pinId
  1453. if val==0:
  1454. self.duty(self.pin[self.pinId],0)
  1455. else:
  1456. self.duty(self.pin[self.pinId],4095)
  1457. def pwmWrite(self,pinId,val): #val:0~255
  1458. self.pinId=pinId
  1459. # print("pinid"+str(self.pin[self.pinId]))
  1460. self.duty(self.pin[self.pinId],val*16)
  1461. def __del__(self):
  1462. self.duty(self.pin[self.pinId],0)
  1463. print("del extPin")
  1464. class extGpio(MCP23017,ADS1115,extOutputPin):
  1465. def __init__(self):
  1466. MCP23017.__init__(self)
  1467. ADS1115.__init__(self)
  1468. extOutputPin.__init__(self)
  1469. self.address=0x20 #初始默认为mcp23017的地址
  1470. def pinMode(self,pinId,mode): #控制mcp23017
  1471. self.address=0x20
  1472. #----------
  1473. #pinId:
  1474. #p0~p3:0~3
  1475. #a0~a3:4~7
  1476. #---------
  1477. #mode:
  1478. #output:1
  1479. #input:0
  1480. if pinId>=0 and pinId<=3:
  1481. if mode==0:
  1482. if pinId==0: #p0
  1483. self.setGpioDir("B",2,0) #output
  1484. self.setGpioLevel("B",2,1) #high
  1485. self.setGpioDir("B",3,1) #input
  1486. elif pinId==1: #p1
  1487. self.setGpioDir("B",1,0)
  1488. self.setGpioLevel("B",1,1)
  1489. self.setGpioDir("B",0,1)
  1490. elif pinId==2: #p2
  1491. self.setGpioDir("B",6,0)
  1492. self.setGpioLevel("B",6,1)
  1493. self.setGpioDir("A",1,1)
  1494. elif pinId==3: #p3
  1495. self.setGpioDir("B",5,0)
  1496. self.setGpioLevel("B",5,1)
  1497. self.setGpioDir("B",4,1)
  1498. else:
  1499. pass
  1500. elif mode==1:
  1501. if pinId==0:
  1502. self.setGpioDir("B",2,0) #output
  1503. self.setGpioLevel("B",2,1) #high
  1504. self.setGpioDir("B",3,0) #output
  1505. elif pinId==1:
  1506. self.setGpioDir("B",1,0)
  1507. self.setGpioLevel("B",1,1)
  1508. self.setGpioDir("B",0,0)
  1509. elif pinId==2:
  1510. self.setGpioDir("B",6,0)
  1511. self.setGpioLevel("B",6,1)
  1512. self.setGpioDir("A",1,0)
  1513. elif pinId==3:
  1514. self.setGpioDir("B",5,0)
  1515. self.setGpioLevel("B",5,1)
  1516. self.setGpioDir("B",4,0)
  1517. # print("a")
  1518. time.sleep(1)
  1519. else:
  1520. pass
  1521. else:
  1522. pass
  1523. elif pinId>=4 and pinId<=7:
  1524. if mode==0:
  1525. if pinId==4: #a0
  1526. self.setGpioDir("A",4,0) #output
  1527. self.setGpioLevel("A",4,1) #high
  1528. self.setGpioDir("A",5,1) #input
  1529. elif pinId==5: #a1
  1530. self.setGpioDir("A",3,0)
  1531. self.setGpioLevel("A",3,1)
  1532. self.setGpioDir("A",7,1)
  1533. elif pinId==6: #a2
  1534. self.setGpioDir("A",2,0)
  1535. self.setGpioLevel("A",2,1)
  1536. self.setGpioDir("A",6,1)
  1537. elif pinId==7: #a3
  1538. self.setGpioDir("B",7,0)
  1539. self.setGpioLevel("B",7,1)
  1540. self.setGpioDir("A",0,1)
  1541. else:
  1542. pass
  1543. elif mode==1:
  1544. if pinId==4: #a0
  1545. self.setGpioDir("A",4,0) #output
  1546. self.setGpioLevel("A",4,1) #high
  1547. self.setGpioDir("A",5,0) #output
  1548. elif pinId==5: #a1
  1549. self.setGpioDir("A",3,0)
  1550. self.setGpioLevel("A",3,1)
  1551. self.setGpioDir("A",7,0)
  1552. elif pinId==6: #a2
  1553. self.setGpioDir("A",2,0)
  1554. self.setGpioLevel("A",2,1)
  1555. self.setGpioDir("A",6,0)
  1556. elif pinId==7: #a3
  1557. self.setGpioDir("B",7,0)
  1558. self.setGpioLevel("B",7,1)
  1559. self.setGpioDir("A",0,0)
  1560. else:
  1561. pass
  1562. else:
  1563. pass
  1564. def digitalWrite(self,pinId,level): #控制mcp23017
  1565. #----------
  1566. #pinId:
  1567. #p0~p3:0~3
  1568. #a0~a3:4~7
  1569. #---------
  1570. #level:
  1571. #5v:1
  1572. #0v:0
  1573. self.address=0x20
  1574. if pinId>=0 and pinId<=3:
  1575. if pinId==0:
  1576. # print("digital write level")
  1577. self.setGpioLevel("B",3,level)
  1578. elif pinId==1:
  1579. self.setGpioLevel("B",0,level)
  1580. elif pinId==2:
  1581. self.setGpioLevel("A",1,level)
  1582. elif pinId==3:
  1583. self.setGpioLevel("B",4,level)
  1584. else:
  1585. pass
  1586. elif pinId>=4 and pinId<=7:
  1587. if pinId==4: #a0
  1588. self.setGpioLevel("A",5,level)
  1589. elif pinId==5: #a1
  1590. self.setGpioLevel("A",7,level)
  1591. elif pinId==6: #a2
  1592. self.setGpioLevel("A",6,level)
  1593. elif pinId==7: #a3
  1594. self.setGpioLevel("A",0,level)
  1595. else:
  1596. pass
  1597. else:
  1598. pass
  1599. def digitalRead(self,pinId): #控制mcp23017
  1600. self.address=0x20
  1601. #----------
  1602. #pinId:
  1603. #p0~p3:0~3
  1604. #a0~a3:4~7
  1605. if pinId>=0 and pinId<=3:
  1606. if pinId==0:
  1607. # print("get digital write level")
  1608. return self.getGpioLevel("B",3)
  1609. elif pinId==1:
  1610. return self.getGpioLevel("B",0)
  1611. elif pinId==2:
  1612. return self.getGpioLevel("A",1)
  1613. elif pinId==3:
  1614. return self.getGpioLevel("B",4)
  1615. else:
  1616. pass
  1617. elif pinId>=4 and pinId<=7:
  1618. if pinId==4: #a0
  1619. return self.getGpioLevel("A",5)
  1620. elif pinId==5: #a1
  1621. return self.getGpioLevel("A",7)
  1622. elif pinId==6: #a2
  1623. return self.getGpioLevel("A",6)
  1624. elif pinId==7: #a3
  1625. return self.getGpioLevel("A",0)
  1626. else:
  1627. pass
  1628. else:
  1629. pass
  1630. def analogWrite(self,pinId,pwm): #控制PCA9685,但是需要Mcp23017进行通道选择
  1631. self.address=0x20 #先用mcp23017进行通道选择
  1632. #select X channel
  1633. if pinId==0: #p0
  1634. self.setGpioDir("B",2,1) #output
  1635. self.setGpioLevel("B",2,1) #low
  1636. elif pinId==1: #p1
  1637. self.setGpioDir("B",1,1)
  1638. self.setGpioLevel("B",1,1)
  1639. elif pinId==2: #p2
  1640. self.setGpioDir("B",6,1)
  1641. self.setGpioLevel("B",6,1)
  1642. elif pinId==3: #p3
  1643. self.setGpioDir("B",5,1)
  1644. self.setGpioLevel("B",5,1)
  1645. else:
  1646. pass
  1647. self.address=0x40 #再用PCA9685进行控制
  1648. self.pwmWrite(pinId,pwm)
  1649. def analogRead(self,pinId): #控制ADS1115,但是需要Mcp23017进行通道选择
  1650. self.adcPin=[3,1,0,2]
  1651. self.address=0x20 #先用mcp23017进行通道选择
  1652. #select X channel
  1653. if pinId==4: #a0
  1654. self.setGpioDir("A",4,0) #input
  1655. self.setGpioLevel("A",4,0) #low
  1656. elif pinId==5: #a1
  1657. self.setGpioDir("A",3,0)
  1658. self.setGpioLevel("A",3,0)
  1659. elif pinId==6: #a2
  1660. self.setGpioDir("A",2,0)
  1661. self.setGpioLevel("A",2,0)
  1662. elif pinId==7: #a3
  1663. self.setGpioDir("B",7,0)
  1664. self.setGpioLevel("B",7,0)
  1665. else:
  1666. pass
  1667. self.address=0x49 #再用Ads1115进行ADC读取
  1668. return self.readAdc(self.adcPin[pinId-4])
  1669. def __del__(self):
  1670. self.address=0x40
  1671. extOutputPin.__del__(self)
  1672. self.address=0x20
  1673. MCP23017.__del__(self) #最先init的配置最后再del
  1674. # print("del fini