CocoPi.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  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. def out(self,value):
  393. if value==0 or value==1:
  394. self.value=1-value
  395. else:
  396. self.value=0
  397. SUNXI_GPIO.output(self.gpioId,self.value)
  398. ##################################
  399. # 6、QMI8658 #
  400. ##################################
  401. class QMI8658(object):
  402. def __init__(self, smbus=2, address=0X6B):
  403. self._address = address
  404. import smbus2
  405. self._bus = smbus2.SMBus(smbus)
  406. bRet = self.WhoAmI()
  407. if bRet:
  408. self.Read_Revision()
  409. else:
  410. return None
  411. self.Config_apply()
  412. def _read_byte(self, cmd):
  413. rec = self._bus.read_i2c_block_data(int(self._address), int(cmd), 1)
  414. return rec[0]
  415. def _read_block(self, reg, length=1):
  416. rec = self._bus.read_i2c_block_data(int(self._address), int(reg), length)
  417. return rec
  418. def _read_u16(self, cmd):
  419. LSB = self._bus.read_i2c_block_data(int(self._address), int(cmd), 1)
  420. MSB = self._bus.read_i2c_block_data(int(self._address), int(cmd)+1, 1)
  421. return (MSB[0] << 8) + LSB[0]
  422. def _write_byte(self, cmd, val):
  423. self._bus.write_i2c_block_data(int(self._address), int(cmd), bytes([int(val)]))
  424. def WhoAmI(self):
  425. bRet = False
  426. if (0x05) == self._read_byte(0x00):
  427. bRet = True
  428. return bRet
  429. def Read_Revision(self):
  430. return self._read_byte(0x01)
  431. def Config_apply(self):
  432. self._write_byte(0x02, 0x40)
  433. self._write_byte(0x08, 0x03)
  434. self._write_byte(0x03, 0x04)
  435. self._write_byte(0x04, 0x64)
  436. self._write_byte(0x06, 0x11)
  437. def Read_Raw_XYZ(self):
  438. xyz = [0, 0, 0, 0, 0, 0]
  439. vals={}
  440. raw_timestamp = self._read_block(0x30, 3)
  441. raw_acc_xyz = self._read_block(0x35, 6)
  442. raw_gyro_xyz = self._read_block(0x3b, 6)
  443. raw_xyz = self._read_block(0x35, 12)
  444. timestamp = (raw_timestamp[2] << 16) | (
  445. raw_timestamp[1] << 8) | (raw_timestamp[0])
  446. for i in range(6):
  447. xyz[i] = (raw_xyz[(i*2)+1] << 8) | (raw_xyz[i*2])
  448. if xyz[i] >= 32767:
  449. xyz[i] = xyz[i]-65535
  450. vals["AcX"]=xyz[0]
  451. vals["AcY"]=xyz[1]
  452. vals["AcZ"]=xyz[2]
  453. vals["GyX"]=xyz[3]
  454. vals["GyY"]=xyz[4]
  455. vals["GyZ"]=xyz[5]
  456. return vals
  457. def Read_XYZ(self):
  458. xyz = [0, 0, 0, 0, 0, 0]
  459. raw_xyz = self.Read_Raw_XYZ()
  460. #QMI8658AccRange_8g
  461. acc_lsb_div = (1 << 12)
  462. #QMI8658GyrRange_512dps
  463. gyro_lsb_div = 64
  464. for i in range(3):
  465. xyz[i] = raw_xyz[i]/acc_lsb_div # (acc_lsb_div/1000.0)
  466. xyz[i+3] = raw_xyz[i+3]*1.0/gyro_lsb_div
  467. return xyz
  468. def get_accel(self, samples=10, calibration=None):
  469. result = {}
  470. for _ in range(samples):
  471. v = self.Read_Raw_XYZ()
  472. for m in v.keys():
  473. result[m] = result.get(m, 0) + v[m] / samples
  474. if calibration:
  475. for m in calibration.keys():
  476. if m == "AcZ":
  477. pass
  478. else:
  479. result[m] -= calibration[m]
  480. return result
  481. def calibrate(self, threshold=50):
  482. print('Calibrating QMI8658... ', end='')
  483. while True:
  484. v1 = self.get_accel(100)
  485. v2 = self.get_accel(100)
  486. if all(abs(v1[m] - v2[m]) < threshold for m in v1.keys()):
  487. print('Done.')
  488. return v1
  489. def getPitchYawRollGxGyGz(self,calibration):
  490. caliData=self.get_accel(10, calibration)
  491. pitch=caliData["AcX"]/182.04
  492. yaw=caliData["AcY"]/182.04
  493. roll=caliData["AcZ"]/182.04
  494. groX=caliData["GyX"]
  495. groY=caliData["GyY"]
  496. groZ=caliData["GyZ"]
  497. if roll<0:
  498. if pitch >=0:
  499. pitch=180-pitch
  500. elif pitch <0:
  501. pitch=(180+pitch)*(-1)
  502. if yaw >=0:
  503. yaw=180-yaw
  504. elif pitch <0:
  505. yaw=(180+yaw)*(-1)
  506. return [pitch,yaw,roll,groX,groY,groZ]
  507. ##################################
  508. # 7、STM8S #
  509. ##################################
  510. import smbus2
  511. import time
  512. class stm8s(object):
  513. bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  514. address = 0x50
  515. # 0x00 # 触发配置
  516. # 0x01 # 重置配置
  517. # 0x02 # pwm0 历史配置
  518. # 0x03 # pwm1 历史配置
  519. # 引脚配置模式有 1. pwm 2. gpio ouput gpio input 3. adc 4.ws2812_singe 5 ws2812_multi
  520. def __init__(self):
  521. self.reset()
  522. time.sleep(0.05)
  523. pass
  524. def clear(self):
  525. self.write(1, 1)
  526. self.reset()
  527. time.sleep(0.05)
  528. def write(self, addr, val):
  529. for i in range(0, 3):
  530. try:
  531. self.bus.write_byte_data(self.address, addr, val)
  532. time.sleep(0.001) # 1ms
  533. # print(addr, val) # debug
  534. return True
  535. except Exception:
  536. time.sleep(0.01)
  537. continue
  538. return False
  539. def fastWrite(self,addr,valBlock):
  540. try:
  541. self.bus.write_i2c_block_data(self.address,addr,valBlock)
  542. return True
  543. except Exception:
  544. return False
  545. def read(self, addr):
  546. for i in range(0, 3):
  547. try:
  548. tmp = self.bus.read_byte_data(self.address, addr)
  549. time.sleep(0.001) # 1ms
  550. # print(addr, tmp) # debug
  551. return tmp
  552. except Exception:
  553. time.sleep(0.01)
  554. continue
  555. return None
  556. def reset(self):
  557. self.write(0, 1)
  558. time.sleep(0.05) # 重启并配置需要时间
  559. def dump(self):
  560. for i in range(0, 32):
  561. print(i, self.read(i))
  562. class singleRgb(stm8s):
  563. def __init__(self):
  564. self.valR=0
  565. self.valG=0
  566. self.valB=0
  567. self.brightness=255
  568. self.show()
  569. def setColor(self,r,g,b):
  570. if(r>=0 and r<=255):
  571. self.valR=int(r*self.brightness/255)
  572. else:
  573. self.valR=0
  574. if(g>=0 and g<=255):
  575. self.valG=int(g*self.brightness/255)
  576. else:
  577. self.valG=0
  578. if(b>=0 and b<=255):
  579. self.valB=int(b*self.brightness/255)
  580. else:
  581. self.valB=0
  582. def setBrightness(self,brightness):
  583. if(brightness>=0 and brightness<=255):
  584. self.brightness=brightness
  585. else:
  586. self.brightness=0
  587. def show(self):
  588. self.write(31, self.valB)
  589. self.write(30, self.valG)
  590. self.write(29, self.valR)
  591. self.write(28, 6)
  592. class dcMotor(stm8s):
  593. def __init__(self,id):
  594. self.id=id
  595. def m1a(self,val=0):
  596. self.write(4,5) #M1A
  597. #self.write(5,0)
  598. #self.write(6,0)
  599. self.write(7,val)
  600. def m1b(self,val=0):
  601. self.write(8,5) #M1B
  602. #self.write(9,0)
  603. #self.write(10,0)
  604. self.write(11,val)
  605. def m2a(self,val=0):
  606. self.write(12,5) #M2A
  607. #self.write(13,0)
  608. #self.write(14,0)
  609. self.write(15,val)
  610. def m2b(self,val=0):
  611. self.write(16,5) #M2B
  612. #self.write(17,0)
  613. #self.write(18,0)
  614. self.write(19,val)
  615. def dcMotorCtrl(self,dir,speed):
  616. dir=1-dir
  617. if(0<speed and speed<255):
  618. if(self.id ==1): #Motor1
  619. if(dir==0):
  620. self.m1a(speed)
  621. self.m1b(255)
  622. else:
  623. self.m1a(255)
  624. self.m1b(speed)
  625. elif(self.id ==2):
  626. if(dir==0):
  627. self.m2a(speed)
  628. self.m2b(255)
  629. else:
  630. self.m2a(255)
  631. self.m2b(speed)
  632. elif(0==speed):
  633. if(self.id ==1): #Motor1
  634. if(dir==0):
  635. self.m1a(255)
  636. self.m1b(255)
  637. else:
  638. self.m1a(255)
  639. self.m1b(255)
  640. elif(self.id ==2):
  641. if(dir==0):
  642. self.m2a(255)
  643. self.m2b(255)
  644. else:
  645. self.m2a(255)
  646. self.m2b(255)
  647. elif(speed==255):
  648. if(self.id ==1): #Motor1
  649. if(dir==0):
  650. self.m1a(0)
  651. self.m1b(255)
  652. else:
  653. self.m1a(255)
  654. self.m1b(0)
  655. elif(self.id ==2):
  656. if(dir==0):
  657. self.m2a(0)
  658. self.m2b(255)
  659. else:
  660. self.m2a(255)
  661. self.m2b(0)
  662. else:
  663. pass
  664. class multiFuncGpio(stm8s):
  665. def __init__(self,id=0,mode=0):
  666. self.id=id
  667. self.rgbId=0
  668. self.brightness=255
  669. self.mode=mode
  670. self.write(20+self.id*4,self.mode)
  671. self.rgbSerial=[0,0,0]*10
  672. time.sleep(0.05)
  673. ##################################################
  674. # mode | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
  675. #-------------------------------------------------
  676. # Func |free |servo|INPUT| OUT | ADC | PWM | BEEP|
  677. ##################################################
  678. # mode=0,为空闲状态,引脚不执行任何功能
  679. # mode=1,为控制舵机模式,值控制范围为0°~180°
  680. # mode=2,为数字输入模式,返回值0或1
  681. # mode=3,为数字输出模式,输出值为0或1
  682. # mode=4,为ADC采样模式,返回值为0~1023
  683. # mode=5,为PWM输出模式,输出值范围为0~255
  684. # mode=6,为控制蜂鸣器模式,控制范围为20hz~12000hz
  685. # mode=7,为控制灯带模式,暂未实现
  686. # id=0,控制多功能引脚1,向20号寄存器写入模式数据
  687. # id=1,控制多功能引脚2,向24号寄存器写入模式数据
  688. def servoCtrl(self,angle):
  689. if ((angle>=0) and (angle<=180)):
  690. self.write(23+self.id*4,angle)
  691. else:
  692. pass
  693. def digitalRead(self):
  694. try:
  695. self.gpioVal= self.read(23+ self.id*4)
  696. if(self.gpioVal != None):
  697. return self.gpioVal
  698. except:
  699. print("ERROR 233")
  700. def digitalWrite(self,val):
  701. if ((val>=0) and (val<=1)):
  702. self.write(23+self.id*4,val)
  703. else:
  704. pass
  705. def analogRead(self):
  706. try:
  707. self.adcValH= self.read(22+ self.id*4)
  708. self.adcValL= self.read(23+ self.id*4)
  709. if (self.adcValH != None and self.adcValL != None):
  710. # adcValH adcValL 大小端合并 16bit
  711. self.adcVal = self.adcValL + (self.adcValH << 8)
  712. return self.adcVal
  713. except:
  714. print("ERROR 2333")
  715. def analogWrite(self,val):
  716. if ((val>=0) and (val<=255)):
  717. self.write(23+self.id*4,val)
  718. else:
  719. pass
  720. def beep(self,frequency):
  721. if ((frequency>=20) and (frequency<=12000)):
  722. self.write(22+self.id*4,frequency>>8)
  723. self.write(23+self.id*4,frequency&0b11111111)
  724. else:
  725. pass
  726. def pixelInit_(self):
  727. for i in range(16):
  728. self.setPixelColor(i,0,0,0)
  729. self.pixelShow()
  730. self.write(23+self.id*4,1)
  731. def setBrightness(self,brightness):
  732. if(brightness>=0 and brightness<=255):
  733. self.brightness=brightness
  734. else:
  735. self.brightness=0
  736. def setPixelColor(self,rgbId,r,g,b):
  737. if(rgbId >=0 and rgbId <=15):
  738. self.rgbId=rgbId #rgbId范围:0~15
  739. else:
  740. self.rgbId=0
  741. if(r>=0 and r<=255):
  742. self.valR=int(r*self.brightness/255)
  743. else:
  744. self.valR=0
  745. if(g>=0 and g<=255):
  746. self.valG=int(g*self.brightness/255)
  747. else:
  748. self.valG=0
  749. if(b>=0 and b<=255):
  750. self.valB=int(b*self.brightness/255)
  751. else:
  752. self.valB=0
  753. #self.id的值为0或1,用于控制灯带缓冲区(S1或者S2引脚)
  754. def pixelShow(self):
  755. self.write(32+ self.id*48+self.rgbId*3, self.valR)
  756. self.write(33+ self.id*48+self.rgbId*3, self.valG)
  757. self.write(34+ self.id*48+self.rgbId*3, self.valB)
  758. def setRgbSerialColor(self,rgbId,r,g,b):
  759. if(rgbId >=0 and rgbId <=15):
  760. self.rgbId=rgbId #rgbId范围:0~15
  761. else:
  762. self.rgbId=0
  763. if(r>=0 and r<=255):
  764. self.valR=int(r*self.brightness/255)
  765. else:
  766. self.valR=0
  767. if(g>=0 and g<=255):
  768. self.valG=int(g*self.brightness/255)
  769. else:
  770. self.valG=0
  771. if(b>=0 and b<=255):
  772. self.valB=int(b*self.brightness/255)
  773. else:
  774. self.valB=0
  775. self.rgbSerial[self.rgbId*3]=self.valR
  776. self.rgbSerial[self.rgbId*3+1]=self.valG
  777. self.rgbSerial[self.rgbId*3+2]=self.valB
  778. def rgbSerialShow(self):
  779. self.fastWrite(32+self.id*48,self.rgbSerial)
  780. self.write(23+self.id*4,1)
  781. ##################################
  782. # 8、UvcVideo #
  783. ##################################
  784. class UvcVideo(camera.MaixVideo):
  785. def __init__(self, source="/dev/videoX"):
  786. self.source = source
  787. super(UvcVideo, self).__init__()
  788. import os, time
  789. usb_path = '/sys/devices/platform/soc/usbc0/otg_role'
  790. # 确认 usb_path 内容为 usb_host 如果不是,自动设置为 usb_host
  791. if os.popen('cat %s' % usb_path).read().strip() != 'usb_host':
  792. os.system('echo "usb_host" > %s' % usb_path)
  793. time.sleep(2) # 要设置 2s 左右才能初始化工作,否则会报 VIDIOC_S_FMT 失败。
  794. def config(self, size=None, video=2, horizontal=0, vertical=0):
  795. if size == None:
  796. size = (320, 240)
  797. super(UvcVideo, self).config(size)
  798. print('[camera] config input size(%d, %d, %d)' %
  799. (self.width(), self.height(), video))
  800. if self.cam:
  801. self.cam = None
  802. try:
  803. import _coco_camera
  804. self.cam = _coco_camera.Camera(self.width(), self.height(), video, horizontal, vertical)
  805. except Exception as e:
  806. print(e)
  807. self.cam = None
  808. def read(self):
  809. if self.cam == None:
  810. self.config()
  811. if self.cam:
  812. ret, frame = self.cam.read()
  813. if ret:
  814. return frame # bytes
  815. else:
  816. try:
  817. self.config()
  818. except Exception as e:
  819. print(e)
  820. return None
  821. def __del__(self):
  822. if self.cam:
  823. self.cam = None
  824. ##################################
  825. # 9、DS3231 #
  826. ##################################
  827. from math import floor
  828. class DS3231(object):
  829. # create RTC instance
  830. def __init__(self):
  831. self.bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  832. self.address = 0x68
  833. def bcd_to_int(self,bcd, n=2):
  834. """Decode n least significant packed binary coded decimal digits to binary.
  835. Return binary result.
  836. n defaults to 2 (BCD digits).
  837. n=0 decodes all digits.
  838. """
  839. return int(('%x' % bcd)[-n:])
  840. def int_to_bcd(self,x, n=2):
  841. """
  842. Encode the n least significant decimal digits of x
  843. to packed binary coded decimal (BCD).
  844. Return packed BCD value.
  845. n defaults to 2 (digits).
  846. n=0 encodes all digits.
  847. """
  848. return int(str(x)[-n:], 0x10)
  849. def read(self, addr):
  850. for i in range(0, 3):
  851. try:
  852. tmp = self.bus.read_byte_data(self.address, addr)
  853. time.sleep(0.001) # 1ms
  854. # print(addr, tmp) # debug
  855. return tmp
  856. except Exception:
  857. time.sleep(0.01)
  858. continue
  859. return None
  860. def write(self, addr, val):
  861. for i in range(0, 3):
  862. try:
  863. self.bus.write_byte_data(self.address, addr, val)
  864. #time.sleep(0.001) # 1ms
  865. # print(addr, val) # debug
  866. return True
  867. except Exception:
  868. time.sleep(0.001)
  869. continue
  870. return False
  871. # set times functions ----------------------------------------
  872. def setYear(self, year):
  873. # only last two digits (last two digits are used if longer)
  874. self.write(0x06, self.int_to_bcd(year%100))
  875. def setMonth(self, month):
  876. if not 1 <= month <= 12:
  877. raise ValueError('Month is out of range [1,12].')
  878. self.write(0x05,self.int_to_bcd(month))
  879. def setDay(self, day):
  880. if not 1 <= day <= 31:
  881. raise ValueError('Day is out of range [1,31].')
  882. self.write(0x04,self.int_to_bcd(day))
  883. def setDayOfWeek(self, dayOfWeek):
  884. if not 1 <= dayOfWeek <= 7:
  885. raise ValueError('Day of week is out of range [1,7].')
  886. self.write(0x03,self.int_to_bcd(dayOfWeek))
  887. def setHour(self, hour):
  888. if not 0 <= hours < 24:
  889. raise ValueError('Hours is out of range [0,23].')
  890. self.write(0x02,self.int_to_bcd(hour)& 0x3F)
  891. def setMinutes(self, minutes):
  892. if not 0 <= minutes < 59:
  893. raise ValueError('Minutes is out of range [0,59].')
  894. self.write(0x01,self.int_to_bcd(minutes))
  895. def setSeconds(self, seconds):
  896. if not 0 <= seconds < 60:
  897. raise ValueError('Seconds is out of range [0,59].')
  898. self.write(0x00,self.int_to_bcd(seconds))
  899. def setDateTime(self, year, month, day, dayOfWeek, hour, minutes, seconds):
  900. # set all the date and times (year is last two digits of year)
  901. self.setYear(year)
  902. self.setMonth(month)
  903. self.setDay(day)
  904. self.setDayOfWeek(dayOfWeek)
  905. self.setHour(hour)
  906. self.setMinutes(minutes)
  907. self.setSeconds(seconds)
  908. # get times functions -------------------------------------------------
  909. def getYear(self):
  910. return self.bcd_to_int(self.read(0x06))
  911. def getMonth(self):
  912. temp = self.read(0x05)
  913. return self.bcd_to_int((temp<<4>>4) &0x7F)
  914. #return temp[0] & 0x7F
  915. def getDay(self):
  916. # 0 - 31
  917. return self.bcd_to_int(self.read(0x04))
  918. def getDayOfWeek(self):
  919. # 1 - 7
  920. return self.bcd_to_int(self.read(0x03))
  921. def getHour(self):
  922. temp = self.read(0x02)
  923. if temp==0x64: #if hour is 24:00,convert it to 00:00
  924. temp=0x40
  925. return self.bcd_to_int((temp<< 4 >>4)& 0x3F)
  926. #return temp[0] & 0x3F
  927. def getMinutes(self):
  928. return self.bcd_to_int(self.read(0x01))
  929. def getSeconds(self):
  930. return self.bcd_to_int(self.read(0x00))
  931. def getDateTime(self):
  932. # returns whole date and time as list
  933. # (last two digits of year, month, day, day of week, hour, minutes, seconds)
  934. dateTime = [0, 0, 0, 0, 0, 0, 0]
  935. dateTime[0] = self.getYear()
  936. dateTime[1] = self.getMonth()
  937. dateTime[2] = self.getDay()
  938. dateTime[3] = self.getDayOfWeek()
  939. dateTime[4] = self.getHour()
  940. dateTime[5] = self.getMinutes()
  941. dateTime[6] = self.getSeconds()
  942. return dateTime
  943. def convertToByteType(self,number):
  944. return bytes([number])
  945. def decodeToDec(self,byte):
  946. return ((byte[0] >> 4) * 10) + (byte[0] & 0x0F)
  947. def encodeToByte(self,dec):
  948. tens = floor(dec / 10)
  949. ones = dec - tens*10
  950. return (tens << 4) + ones
  951. def decodeAlarmType(self,alarmTime):
  952. if(len(alarmTime) > 4):
  953. m1Bit = (alarmTime[3] & 0x80) >> 7
  954. else:
  955. m1Bit = False
  956. m2Bit = (alarmTime[2] & 0x80) >> 7
  957. m3Bit = (alarmTime[1] & 0x80) >> 7
  958. m4Bit = (alarmTime[0] & 0x80) >> 7
  959. dayBit = (alarmTime[0] & 0x40) >> 6
  960. if(m1Bit and m2Bit and m3Bit and m4Bit):
  961. return "everySecond"
  962. elif(not m1Bit and m2Bit and m3Bit and m4Bit):
  963. return "everyMinute"
  964. elif(not m1Bit and not m2Bit and m3Bit and m4Bit):
  965. return "everyHour"
  966. elif(not m1Bit and not m2Bit and not m3Bit and m4Bit):
  967. return "everyDay"
  968. elif(not dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  969. return "everyMonth"
  970. elif(dayBit and not m1Bit and not m2Bit and not m3Bit and not m4Bit):
  971. return "everyWeek"
  972. else:
  973. return "noValidAlarmType"
  974. def decodeAlarmTime(self,alarmTime):
  975. alarmTime[0] = decodeToDec(convertToByteType(alarmTime[0] & 0x3F))
  976. alarmTime[1] = decodeToDec(convertToByteType(alarmTime[1] & 0x3F))
  977. alarmTime[2] = decodeToDec(convertToByteType(alarmTime[2] & 0x7F))
  978. if(len(alarmTime) > 4):
  979. alarmTime[3] = decodeToDec(convertToByteType(alarmTime[3] & 0x7F))
  980. return alarmTime
  981. def encodeAlarmType(self,alarmType):
  982. if(alarmType == "everySecond"):
  983. return 15 #0b01111
  984. elif(alarmType == "everyMinute"):
  985. return 14 #0b01110
  986. elif(alarmType == "everyHour"):
  987. return 12 #0b01100
  988. elif(alarmType == "everyDay"):
  989. return 8 #0b01000
  990. elif(alarmType == "everyMonth"):
  991. return 0 #0b00000
  992. elif(alarmType == "everyWeek"):
  993. return 16 #0b10000
  994. else:
  995. raise ValueError("""Not a supported alarmType. Options are:
  996. 'everySecond' (only Alarm 1), 'everyMinute', 'everyHour', 'everyDay', 'everyMonth', 'everyWeek'""")
  997. def encodeDateTime(self,day, hour, minutes, seconds, alarmType):
  998. alarmBits = encodeAlarmType(alarmType)
  999. alarmTime = [0, 0, 0, 0]
  1000. alarmTime[0] = (encodeToByte(day) & 0x3F) | ((alarmBits & 0x10) << 2) | ((alarmBits & 0x08) << 4)
  1001. alarmTime[1] = (encodeToByte(hour) & 0x3F) | ((alarmBits & 0x04) << 5)
  1002. alarmTime[2] = (encodeToByte(minutes) & 0x7F) | ((alarmBits & 0x02) << 6)
  1003. alarmTime[3] = (encodeToByte(seconds) & 0x7F) | ((alarmBits & 0x01) << 7)
  1004. return alarmTime
  1005. ##################################
  1006. # 10、SPI_WS2812 #
  1007. ##################################
  1008. class SPI_WS2812(object):
  1009. from maix import spi
  1010. spi = spi.SpiDev()
  1011. def __init__(self,num):
  1012. self.num=num
  1013. self.spi.open(0, 0)
  1014. self.spi.mode = 3
  1015. self.spi.bits_per_word = 8
  1016. self.spi.max_speed_hz = 20000000
  1017. self.data=[[0,0,0]]*self.num
  1018. self.brightness=255
  1019. def setRgbColor(self,id,r,g,b):
  1020. if id>(self.num-1):
  1021. raise ValueError("Out of range!")
  1022. else:
  1023. self.data[id]=[int(g*self.brightness/255),int(r*self.brightness/255),int(b*self.brightness/255)]
  1024. #print("set complete!")
  1025. def setBrightness(self,brightness):
  1026. if brightness>255 or brightness<0:
  1027. raise ValueError("Out of range!")
  1028. self.brightness=brightness
  1029. def rgbShow(self):
  1030. tx=[]
  1031. for rgb in self.data:
  1032. for byte in rgb:
  1033. for ibit in range(3,-1,-1):
  1034. tx.append(((byte>>(2*ibit+1))&1)*0x60 +
  1035. ((byte>>(2*ibit+0))&1)*0x06 +
  1036. 0x88)
  1037. print([hex(v) for v in tx])
  1038. tx[0]=0b1000000
  1039. tx.append(0b1000000)
  1040. self.spi.xfer(tx,int(4/1.05e-6))
  1041. def __del__(self):
  1042. self.data=[[0,0,0]]*self.num
  1043. self.rgbShow()
  1044. ##################################
  1045. # 11、HCSR04 #
  1046. ##################################
  1047. class HCSR04:
  1048. def __init__(self,Trig,Echo):
  1049. pinNum={"TXD":"198","RXD":"199","CLK":"224","MOSI":"225","MISO":"226","CS":"227"}
  1050. os.system("insmod /home/drivers/hcsr04.ko")
  1051. pinCmd=pinNum.get(Trig)+","+pinNum.get(Echo)+",23200,0"
  1052. os.system('echo "'+pinCmd+'" > /sys/class/hcsr04/value')
  1053. def getDistance(self):
  1054. startTime=round(time.time(),3)
  1055. #print("startTime:"+str(startTime))
  1056. while True:
  1057. dis=os.popen("cat /sys/class/hcsr04/value").read()
  1058. #print("dis:"+str(dis)+" len:"+str(len(dis)))
  1059. if "-1" in dis:
  1060. pass
  1061. else:
  1062. dis=round(int(dis)/58,2)
  1063. if dis<250:
  1064. return dis
  1065. else:
  1066. pass
  1067. if((round(time.time(),3)-startTime)>=1.200):#超时时间
  1068. return -1
  1069. def __del__(self):
  1070. os.system("rmmod /home/drivers/hcsr04.ko")
  1071. import struct
  1072. import math
  1073. import os
  1074. ##################################
  1075. # 12、MCP23017 #
  1076. ##################################
  1077. class MCP23017(object):
  1078. bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  1079. address = 0x20
  1080. iodira=0x00 #A引脚方向寄存器地址。初始值为0xFF,输入模式
  1081. iodirb=0x01 #B引脚方向寄存器地址。初始值为0xFF,输入模式
  1082. gppua=0x0c #A引脚上拉电阻配置寄存器地址。初始值为0x00,无上拉
  1083. gppub=0x0d #B引脚上拉电阻配置寄存器地址,初始值为0x00,无上拉
  1084. gpioa=0x12 #A端口寄存器,初始值为0x00,低电平
  1085. gpiob=0x13 #B端口寄存器,初始值为0x00,低电平
  1086. DIR_A_V=0xff #A引脚方向初始值
  1087. DIR_B_V=0xff #B引脚方向初始值
  1088. GPPU_A_V=0x00 #A引脚上拉设定初始值
  1089. GPPU_B_V=0x00 #B引脚上拉设定初始值
  1090. GPIO_A_V=0x00 #A引脚电平初始值
  1091. GPIO_B_V=0x00 #B引脚电平初始值
  1092. def __init__(self):
  1093. self.reset()
  1094. def reset(self):
  1095. self.DIR_A=self.DIR_A_V
  1096. self.DIR_B=self.DIR_B_V
  1097. self.GPPU_A=self.GPPU_A_V
  1098. self.GPPU_B=self.GPPU_B_V
  1099. self.GPIO_A=self.GPIO_A_V
  1100. self.GPIO_B=self.GPIO_B_V
  1101. self.byteWrite(self.iodira,self.DIR_A_V)
  1102. self.byteWrite(self.iodirb,self.DIR_B_V)
  1103. self.byteWrite(self.gppua,self.GPPU_A_V)
  1104. self.byteWrite(self.gppub,self.GPPU_B_V)
  1105. self.byteWrite(self.gpioa,self.GPIO_A_V)
  1106. self.byteWrite(self.gpiob,self.GPIO_B_V)
  1107. print("mcp23017 reset completed!")
  1108. def byteWrite(self, addr, val):
  1109. try:
  1110. self.bus.write_byte_data(self.address, addr, val)
  1111. return True
  1112. except Exception:
  1113. pass
  1114. def byteRead(self,addr):
  1115. tmp = self.bus.read_byte_data(self.address, addr)
  1116. return tmp
  1117. def bitWrite(self,reg,num,val): #寄存器值(byte类型),寄存器第...位(0-7),该位的值(0/1)
  1118. return (reg>>(num+1)<<(num+1))|(val << num)|(reg<<(8-num)&0xFF)>>(8-num)
  1119. def bitRead(self,reg,num): #寄存器值(byte类型),寄存器第...位(0-7)
  1120. return ((reg<<(7-num)&0xFF)>>7)
  1121. def setGpioDir(self,channel,pinId,direction): #set gpio direction
  1122. #channel:"A" or "B"
  1123. #pinId:0~7
  1124. #direction:[0:output],[1:input(default)]
  1125. if channel=="A":
  1126. self.DIR_A=self.bitWrite(self.DIR_A,pinId,direction)
  1127. print("Dir_A="+str(self.DIR_A))
  1128. self.byteWrite(self.iodira,self.DIR_A)
  1129. elif channel=="B":
  1130. self.DIR_B=self.bitWrite(self.DIR_B,pinId,direction)
  1131. self.byteWrite(self.iodirb,self.DIR_B)
  1132. else:
  1133. raise ValueError("Error Channel!")
  1134. def setGppuEnable(self,channel,pinId,pullup): #set gpio pullup on or off
  1135. #channel:"A" or "B"
  1136. #pinId:0~7
  1137. #pullup:[0:disable],[1:enable(default)]
  1138. if channel=="A":
  1139. self.GPPU_A=self.bitWrite(self.GPPU_A,pinId,pullup)
  1140. self.byteWrite(self.gppua,self.GPPU_A)
  1141. elif channel=="B":
  1142. self.GPPU_B=self.bitWrite(self.GPPU_B,pinId,pullup)
  1143. self.byteWrite(self.gppub,self.GPPU_B)
  1144. else:
  1145. raise ValueError("Error Channel!")
  1146. def setGpioLevel(self,channel,pinId,level): #set gpio volt level
  1147. #channel:"A" or "B"
  1148. #pinId:0~7
  1149. #level:[0:low(default)],[1:high]
  1150. if channel=="A":
  1151. self.GPIO_A=self.bitWrite(self.GPIO_A,pinId,level)
  1152. self.byteWrite(self.gpioa,self.GPIO_A)
  1153. elif channel=="B":
  1154. self.GPIO_B=self.bitWrite(self.GPIO_B,pinId,level)
  1155. self.byteWrite(self.gpiob,self.GPIO_B)
  1156. else:
  1157. raise ValueError("Error Channel!")
  1158. def getGpioLevel(self,channel,pinId): #get gpio volt level
  1159. #channel:"A" or "B"
  1160. #pinId:0~7
  1161. #level:[0:low(default)],[1:high]
  1162. if channel=="A":
  1163. return self.bitRead(self.byteRead(self.gpioa),pinId)
  1164. elif channel=="B":
  1165. return self.bitRead(self.byteRead(self.gpiob),pinId)
  1166. else:
  1167. raise ValueError("Error Channel!")
  1168. def __del__(self):
  1169. self.reset()
  1170. time.sleep(0.001)
  1171. print("del mcp23017")
  1172. class ADS1115(object):
  1173. bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
  1174. # Registers in the ADS1115,设备的4个寄存器
  1175. DEVICE_REG_CONVERSION = 0x00 #转换寄存器
  1176. DEVICE_REG_CONFIG = 0x01 #配置寄存器
  1177. DEVICE_REG_LO_THRESH = 0x02 #最低阈值寄存器
  1178. DEVICE_REG_HI_THRESH = 0x03 #最高阈值寄存器
  1179. # Configuration register fields #配置寄存器展开,共16bit
  1180. # Operational Status #操作状态,在第15位
  1181. CONFIG_OS = 0X8000 #无效
  1182. CONFIG_OS_START = 0X8000 #开始单次转换(处于掉电状态)
  1183. CONFIG_OS_PERFORMING_CONVERSION = 0X0000 #转换进行中
  1184. CONFIG_OS_NOT_PERFORMING_OPERATION = 0X8000 #转换闲置
  1185. # Differential measurements #测量模式设置,在第12-14位
  1186. CONFIG_MUX_AIN0P_AIN1N = 0X0000 # (default) #AIN0差分输入,AIN1作为参考
  1187. CONFIG_MUX_AIN1P_AIN3N = 0X1000 #AIN1差分输入,AIN3作为参考
  1188. CONFIG_MUX_AIN2P_AIN3N = 0X2000 #AIN2差分输入,AIN3作为参考
  1189. CONFIG_MUX_AIN3P_AIN3N = 0X3000 #AIN3差分输入,AIN3作为参考
  1190. # Single ended measurements #单端测量
  1191. CONFIG_MUX_AIN0P_GNDN = 0X4000 #AIN0单端输入
  1192. CONFIG_MUX_AIN1P_GNDN = 0X5000 #AIN1单端输入
  1193. CONFIG_MUX_AIN2P_GNDN = 0X6000 #AIN2单端输入
  1194. CONFIG_MUX_AIN3P_GNDN = 0X7000 #AIN3单端输入
  1195. # Programmable gain amplifier configuration #可编程增益放大器(量程选择)FSR:Feedback Shift Register,反馈移位寄存器,在第9-11位
  1196. CONFIG_FSR_6V144 = 0X0000 #CocoPi 需选择
  1197. CONFIG_FSR_4V096 = 0X0200
  1198. CONFIG_FSR_2V048 = 0X0400 # (default)
  1199. CONFIG_FSR_1V024 = 0X0600
  1200. CONFIG_FSR_0V512 = 0X0800
  1201. CONFIG_FSR_0V256 = 0X0A00
  1202. CONFIG_FSR_0V256 = 0X0C00
  1203. CONFIG_FSR_0V256 = 0X0E00
  1204. # Continuous or single shot mode #设备运行模式:持续转换或者单次转换,在第8位
  1205. CONFIG_MODE_CONTINUOUS = 0X0000 #持续转换
  1206. CONFIG_MODE_SINGLE_SHOT = 0X0100 # (default) #单次转换
  1207. # Data rate #转换速率,第5-7位
  1208. CONFIG_DATA_RATE_8SPS = 0X0000 #SPS:Samples Per Second,每秒8次采样
  1209. CONFIG_DATA_RATE_16SPS = 0X0020
  1210. CONFIG_DATA_RATE_32SPS = 0X0040
  1211. CONFIG_DATA_RATE_64SPS = 0X0060
  1212. CONFIG_DATA_RATE_128SPS = 0X0080 #(default)
  1213. CONFIG_DATA_RATE_2508SPS = 0X00A0
  1214. CONFIG_DATA_RATE_475SPS = 0X00C0
  1215. CONFIG_DATA_RATE_860SPS = 0X00E0
  1216. # Comparitor mode #比较器模式,第4位
  1217. CONFIG_COMP_MODE_TRADITIONAL = 0X0000 #(default) #传统比较器
  1218. CONFIG_COMP_MODE_WINDOW = 0X0010 #窗口模式
  1219. # Comparitor polarity #比较器集型,第3位,控制ALRET/RDY引脚极性
  1220. CONFIG_COMP_POL_ACTIVE_LOW = 0X0000 #(default) #低电平有效(默认)
  1221. CONFIG_COMP_POL_ACTIVE_HIGH = 0X0008 #高电平有效
  1222. # Comparitor latching #锁存比较器,第2位,该位控制ALERT/RDY引脚在被置为有效后锁存,还是在转换后处于上限和下限阈值范围内清零
  1223. CONFIG_COMP_LAT = 0X0004
  1224. CONFIG_COMP_LAT_NON_LATCHING = 0X0000 #(default) #默认不锁存
  1225. CONFIG_COMP_LAT_LATCHING = 0X0004
  1226. # comparitor queue and disable #比较器置位和禁用
  1227. CONFIG_COMP_QUE = 0X0003 #默认禁用比较器并将ALERT/RDY引脚设置为高阻抗
  1228. CONFIG_COMP_QUE_1_CONV = 0X0000 #一次转换后断言
  1229. CONFIG_COMP_QUE_2_CONV = 0X0001 #两次转换后置位
  1230. CONFIG_COMP_QUE_4_CONV = 0X0002 #四次转换后置位
  1231. CONFIG_COMP_QUE_DISABLE = 0X0003 #(default) #默认禁用比较器并将ALERT/RDY引脚设置为高阻抗
  1232. # Address for the device ,设备地址选择
  1233. #addr=0x48 # ADDR tied to GND
  1234. addr=0x49 # ADDR tied to VDD
  1235. #addr=0x4A # ADDR tied to SDA
  1236. #addr=0x4B # ADDR tied to SCL
  1237. def __init__(self):
  1238. self.address=0x49
  1239. self.config=0x0000
  1240. #time.sleep(0.05)
  1241. pass
  1242. def swap(self,val):
  1243. return (((val&0xff00)>>8)|((val&0x00ff)<<8)) #交换高8位与低8位
  1244. ###
  1245. def readAdc(self,channel):
  1246. if (channel>3) or (channel<0):
  1247. return False
  1248. self.config=(self.CONFIG_OS_START + # start conversion
  1249. #self.CONFIG_MUX_AIN0P_GNDN + # single ended conversion
  1250. ((channel+4)<<12) + # select channel
  1251. self.CONFIG_FSR_6V144 + # (5v signal)
  1252. self.CONFIG_MODE_SINGLE_SHOT + # single conversion and shutdown
  1253. self.CONFIG_DATA_RATE_128SPS + # data rate
  1254. self.CONFIG_COMP_MODE_TRADITIONAL + # comp conventional
  1255. self.CONFIG_COMP_POL_ACTIVE_LOW + # comp active low
  1256. self.CONFIG_COMP_LAT_NON_LATCHING + # comp non latching
  1257. self.CONFIG_COMP_QUE_DISABLE ) # comp disabled
  1258. ###
  1259. self.bus.write_word_data(self.address, self.DEVICE_REG_CONFIG, self.swap(self.config))
  1260. while True:
  1261. # read status (note byte swap)
  1262. status=self.swap(self.bus.read_word_data(self.address,self.DEVICE_REG_CONFIG))
  1263. #print("status:"+str(status))
  1264. # when the Operational Status is no longer performing a conversion
  1265. # we can break out of this wait loop
  1266. if (status & self.CONFIG_OS) != self.CONFIG_OS_PERFORMING_CONVERSION:
  1267. break
  1268. # read result (note byte swap)
  1269. result=self.swap(self.bus.read_word_data(self.address,self.DEVICE_REG_CONVERSION))
  1270. # return 16 bit integer A2D result for the specified channel
  1271. volt=round((result*6.144/32768),3)
  1272. return [result,volt]
  1273. class PCA9685(object):
  1274. bus=smbus2.SMBus(2)
  1275. def __init__(self,freq=400,min_us=460,max_us=2400,address=0x40,degrees=180):
  1276. self.address=address
  1277. self.period=1000000/freq
  1278. self.min_duty = self._us2duty(min_us)
  1279. self.max_duty = self._us2duty(max_us)
  1280. self.freq(freq)
  1281. self.reset()
  1282. #for i in range(0,16):
  1283. #self.duty(i,0)
  1284. print("Pca9685 init")
  1285. def write(self, addr, val):
  1286. for i in range(0, 2):
  1287. try:
  1288. self.bus.write_byte_data(self.address, addr, val)
  1289. #time.sleep(0.001) # 1ms
  1290. # print(addr, val) # debug
  1291. return True
  1292. except Exception:
  1293. time.sleep(0.001)
  1294. continue
  1295. return False
  1296. def read(self,addr):
  1297. for i in range(0, 3):
  1298. try:
  1299. tmp = self.bus.read_byte_data(self.address, addr)
  1300. #time.sleep(0.001) # 1ms
  1301. # print(addr, tmp) # debug
  1302. return tmp
  1303. except Exception:
  1304. time.sleep(0.01)
  1305. continue
  1306. return None
  1307. def reset(self):
  1308. self.write(0x00,0x00) #初始化
  1309. def freq(self,freq=None):
  1310. if freq is None:
  1311. return int(25000000.0/4096/(self.read(0xfe)-0.5))
  1312. #设定频率freq,预分频prescale=int(25000000.0 / (4096.0 * freq) + 0.5)
  1313. prescale=int(25000000.0/4096/freq+0.5)
  1314. self.write(0x00,0x10) #设定pca9685为睡眠模式
  1315. self.write(0xfe,prescale) #设定频率
  1316. self.reset()
  1317. time.sleep(0.01)
  1318. self.write(0x00,0xa1) #设定pca9685为活跃模式
  1319. def pwm(self,index,on=None,off=None): #on和off来调节PWM的占空比
  1320. if not 0<= index <=15:
  1321. raise ValueError("Pin ID out of range!")
  1322. if on is None or off is None:
  1323. data = self.bus.read_i2c_block_data(self.address,0x06+index*4,4)
  1324. return data
  1325. data= [0]*4
  1326. data[0]=int(hex(on & 0xff),16)
  1327. data[1]=int(hex((on >> 8) & 0xff),16)
  1328. data[2]=int(hex(off & 0xff),16)
  1329. data[3]=int(hex((off >> 8) & 0xff),16)
  1330. print(data)
  1331. for i in range(0,4):
  1332. self.write(0x06+i+index*4,data[i])
  1333. def duty(self,index,value=None):
  1334. if value == None:
  1335. return self.pwm(index)
  1336. elif not 0 <= value <=4095:
  1337. raise ValueError("Out of range!")
  1338. elif value==0:
  1339. self.pwm(index,0,4096)
  1340. elif value == 4095:
  1341. self.pwm(index,4096,0)
  1342. else:
  1343. self.pwm(index,0,value)
  1344. def _us2duty(self,value):
  1345. return 4095*value/self.period
  1346. def __del__():
  1347. print("del pac9685")
  1348. time.sleep(1)
  1349. for i in range(0,16):
  1350. self.duty(i,0)
  1351. time.sleep(0.001)
  1352. class extDcMotor(PCA9685):
  1353. def __init__(self,motorId):
  1354. PCA9685.__init__(self)
  1355. self.motorPin=[11,12,13,10,9,8,5,6,7,4,3,2]
  1356. self.motorId=motorId
  1357. pass
  1358. def speedControl(self,speed):
  1359. self.speed=abs(speed)
  1360. if not -255<= speed<=255:
  1361. raise ValueError("Out of range!")
  1362. if self.motorId == "C":
  1363. if speed<0:
  1364. self.duty(self.motorPin[0],4095)
  1365. self.duty(self.motorPin[1],0)
  1366. self.duty(self.motorPin[2],int(self.speed*16))
  1367. else:
  1368. self.duty(self.motorPin[0],0)
  1369. self.duty(self.motorPin[1],4095)
  1370. self.duty(self.motorPin[2],int(self.speed*16))
  1371. elif self.motorId == "D":
  1372. if speed<0:
  1373. self.duty(self.motorPin[3],4095)
  1374. self.duty(self.motorPin[4],0)
  1375. self.duty(self.motorPin[5],int(self.speed*16))
  1376. else:
  1377. self.duty(self.motorPin[3],0)
  1378. self.duty(self.motorPin[4],4095)
  1379. self.duty(self.motorPin[5],int(self.speed*16))
  1380. elif self.motorId == "E":
  1381. if speed<0:
  1382. self.duty(self.motorPin[6],4095)
  1383. self.duty(self.motorPin[7],0)
  1384. self.duty(self.motorPin[8],int(self.speed*16))
  1385. else:
  1386. self.duty(self.motorPin[6],0)
  1387. self.duty(self.motorPin[7],4095)
  1388. self.duty(self.motorPin[8],int(self.speed*16))
  1389. elif self.motorId == "F":
  1390. if speed<0:
  1391. self.duty(self.motorPin[9],4095)
  1392. self.duty(self.motorPin[10],0)
  1393. self.duty(self.motorPin[11],int(self.speed*16))
  1394. else:
  1395. self.duty(self.motorPin[9],0)
  1396. self.duty(self.motorPin[10],4095)
  1397. self.duty(self.motorPin[11],int(self.speed*16))
  1398. else:
  1399. pass
  1400. def __del__(self):
  1401. if self.motorId == "C":
  1402. self.duty(self.motorPin[0],0)
  1403. self.duty(self.motorPin[1],0)
  1404. self.duty(self.motorPin[2],0)
  1405. elif self.motorId == "D":
  1406. self.duty(self.motorPin[3],0)
  1407. self.duty(self.motorPin[4],0)
  1408. self.duty(self.motorPin[5],0)
  1409. elif self.motorId == "E":
  1410. self.duty(self.motorPin[6],0)
  1411. self.duty(self.motorPin[7],0)
  1412. self.duty(self.motorPin[8],0)
  1413. elif self.motorId == "F":
  1414. self.duty(self.motorPin[9],0)
  1415. self.duty(self.motorPin[10],0)
  1416. self.duty(self.motorPin[11],0)
  1417. else:
  1418. pass
  1419. time.sleep(0.001)
  1420. class extServo(PCA9685):
  1421. def __init__(self,servoId):
  1422. PCA9685.__init__(self)
  1423. self.servoId=servoId
  1424. self.servoPin=[14,15,1,0]
  1425. self.degrees=180
  1426. pass
  1427. def position(self,degrees=None): #index:0,1,2,3
  1428. span = self.max_duty - self.min_duty
  1429. duty = self.min_duty + span * degrees / self.degrees
  1430. duty = int(min(self.max_duty, max(self.min_duty, int(duty))))
  1431. self.duty(self.servoPin[self.servoId], duty)
  1432. def release(self):
  1433. self.duty(self.servoPin[self.servoId],0)
  1434. def __del__(self):
  1435. self.duty(self.servoPin[self.servoId],0)
  1436. class extOutputPin(PCA9685):
  1437. def __init__(self):
  1438. PCA9685.__init__(self)
  1439. self.pin=[14,15,1,0]
  1440. self.pinId=0
  1441. pass
  1442. def digitalSet(self,pinId,val): #val:0/1
  1443. self.pinId=pinId
  1444. if val==0:
  1445. self.duty(self.pin[self.pinId],0)
  1446. else:
  1447. self.duty(self.pin[self.pinId],4095)
  1448. def pwmWrite(self,pinId,val): #val:0~255
  1449. self.pinId=pinId
  1450. print("pinid"+str(self.pin[self.pinId]))
  1451. self.duty(self.pin[self.pinId],val*16)
  1452. def __del__(self):
  1453. self.duty(self.pin[self.pinId],0)
  1454. print("del extPin")
  1455. class extGpio(MCP23017,ADS1115,extOutputPin):
  1456. def __init__(self):
  1457. MCP23017.__init__(self)
  1458. ADS1115.__init__(self)
  1459. extOutputPin.__init__(self)
  1460. self.address=0x20 #初始默认为mcp23017的地址
  1461. def pinMode(self,pinId,mode): #控制mcp23017
  1462. self.address=0x20
  1463. #----------
  1464. #pinId:
  1465. #p0~p3:0~3
  1466. #a0~a3:4~7
  1467. #---------
  1468. #mode:
  1469. #output:1
  1470. #input:0
  1471. if pinId>=0 and pinId<=3:
  1472. if mode==0:
  1473. if pinId==0: #p0
  1474. self.setGpioDir("B",2,0) #output
  1475. self.setGpioLevel("B",2,1) #high
  1476. self.setGpioDir("B",3,1) #input
  1477. elif pinId==1: #p1
  1478. self.setGpioDir("B",1,0)
  1479. self.setGpioLevel("B",1,1)
  1480. self.setGpioDir("B",0,1)
  1481. elif pinId==2: #p2
  1482. self.setGpioDir("B",6,0)
  1483. self.setGpioLevel("B",6,1)
  1484. self.setGpioDir("A",1,1)
  1485. elif pinId==3: #p3
  1486. self.setGpioDir("B",5,0)
  1487. self.setGpioLevel("B",5,1)
  1488. self.setGpioDir("B",4,1)
  1489. else:
  1490. pass
  1491. elif mode==1:
  1492. if pinId==0:
  1493. self.setGpioDir("B",2,0) #output
  1494. self.setGpioLevel("B",2,1) #high
  1495. self.setGpioDir("B",3,0) #output
  1496. elif pinId==1:
  1497. self.setGpioDir("B",1,0)
  1498. self.setGpioLevel("B",1,1)
  1499. self.setGpioDir("B",0,0)
  1500. elif pinId==2:
  1501. self.setGpioDir("B",6,0)
  1502. self.setGpioLevel("B",6,1)
  1503. self.setGpioDir("A",1,0)
  1504. elif pinId==3:
  1505. self.setGpioDir("B",5,0)
  1506. self.setGpioLevel("B",5,1)
  1507. self.setGpioDir("B",4,0)
  1508. print("a")
  1509. time.sleep(1)
  1510. else:
  1511. pass
  1512. else:
  1513. pass
  1514. elif pinId>=4 and pinId<=7:
  1515. if mode==0:
  1516. if pinId==4: #a0
  1517. self.setGpioDir("A",4,0) #output
  1518. self.setGpioLevel("A",4,1) #high
  1519. self.setGpioDir("A",5,1) #input
  1520. elif pinId==5: #a1
  1521. self.setGpioDir("A",3,0)
  1522. self.setGpioLevel("A",3,1)
  1523. self.setGpioDir("A",7,1)
  1524. elif pinId==6: #a2
  1525. self.setGpioDir("A",2,0)
  1526. self.setGpioLevel("A",2,1)
  1527. self.setGpioDir("A",6,1)
  1528. elif pinId==7: #a3
  1529. self.setGpioDir("B",7,0)
  1530. self.setGpioLevel("B",7,1)
  1531. self.setGpioDir("A",0,1)
  1532. else:
  1533. pass
  1534. elif mode==1:
  1535. if pinId==4: #a0
  1536. self.setGpioDir("A",4,0) #output
  1537. self.setGpioLevel("A",4,1) #high
  1538. self.setGpioDir("A",5,0) #output
  1539. elif pinId==5: #a1
  1540. self.setGpioDir("A",3,0)
  1541. self.setGpioLevel("A",3,1)
  1542. self.setGpioDir("A",7,0)
  1543. elif pinId==6: #a2
  1544. self.setGpioDir("A",2,0)
  1545. self.setGpioLevel("A",2,1)
  1546. self.setGpioDir("A",6,0)
  1547. elif pinId==7: #a3
  1548. self.setGpioDir("B",7,0)
  1549. self.setGpioLevel("B",7,1)
  1550. self.setGpioDir("A",0,0)
  1551. else:
  1552. pass
  1553. else:
  1554. pass
  1555. def digitalWrite(self,pinId,level): #控制mcp23017
  1556. #----------
  1557. #pinId:
  1558. #p0~p3:0~3
  1559. #a0~a3:4~7
  1560. #---------
  1561. #level:
  1562. #5v:1
  1563. #0v:0
  1564. self.address=0x20
  1565. if pinId>=0 and pinId<=3:
  1566. if pinId==0:
  1567. print("digital write level")
  1568. self.setGpioLevel("B",3,level)
  1569. elif pinId==1:
  1570. self.setGpioLevel("B",0,level)
  1571. elif pinId==2:
  1572. self.setGpioLevel("A",1,level)
  1573. elif pinId==3:
  1574. self.setGpioLevel("B",4,level)
  1575. else:
  1576. pass
  1577. elif pinId>=4 and pinId<=7:
  1578. if pinId==4: #a0
  1579. self.setGpioLevel("A",5,level)
  1580. elif pinId==5: #a1
  1581. self.setGpioLevel("A",7,level)
  1582. elif pinId==6: #a2
  1583. self.setGpioLevel("A",6,level)
  1584. elif pinId==7: #a3
  1585. self.setGpioLevel("A",0,level)
  1586. else:
  1587. pass
  1588. else:
  1589. pass
  1590. def digitalRead(self,pinId): #控制mcp23017
  1591. self.address=0x20
  1592. #----------
  1593. #pinId:
  1594. #p0~p3:0~3
  1595. #a0~a3:4~7
  1596. if pinId>=0 and pinId<=3:
  1597. if pinId==0:
  1598. print("get digital write level")
  1599. return self.getGpioLevel("B",3)
  1600. elif pinId==1:
  1601. return self.getGpioLevel("B",0)
  1602. elif pinId==2:
  1603. return self.getGpioLevel("A",1)
  1604. elif pinId==3:
  1605. return self.getGpioLevel("B",4)
  1606. else:
  1607. pass
  1608. elif pinId>=4 and pinId<=7:
  1609. if pinId==4: #a0
  1610. return self.getGpioLevel("A",5)
  1611. elif pinId==5: #a1
  1612. return self.getGpioLevel("A",7)
  1613. elif pinId==6: #a2
  1614. return self.getGpioLevel("A",6)
  1615. elif pinId==7: #a3
  1616. return self.getGpioLevel("A",0)
  1617. else:
  1618. pass
  1619. else:
  1620. pass
  1621. def analogWrite(self,pinId,pwm): #控制PCA9685,但是需要Mcp23017进行通道选择
  1622. self.address=0x20 #先用mcp23017进行通道选择
  1623. #select X channel
  1624. if pinId==0: #p0
  1625. self.setGpioDir("B",2,1) #output
  1626. self.setGpioLevel("B",2,0) #low
  1627. elif pinId==1: #p1
  1628. self.setGpioDir("B",1,1)
  1629. self.setGpioLevel("B",1,0)
  1630. elif pinId==2: #p2
  1631. self.setGpioDir("B",6,1)
  1632. self.setGpioLevel("B",6,0)
  1633. elif pinId==3: #p3
  1634. self.setGpioDir("B",5,1)
  1635. self.setGpioLevel("B",5,0)
  1636. else:
  1637. pass
  1638. self.address=0x40 #再用PCA9685进行控制
  1639. self.pwmWrite(pinId,pwm)
  1640. def analogRead(self,pinId): #控制ADS1115,但是需要Mcp23017进行通道选择
  1641. self.adcPin=[3,1,0,2]
  1642. self.address=0x20 #先用mcp23017进行通道选择
  1643. #select X channel
  1644. if pinId==4: #a0
  1645. self.setGpioDir("A",4,1) #input
  1646. self.setGpioLevel("A",4,0) #low
  1647. elif pinId==5: #a1
  1648. self.setGpioDir("A",3,1)
  1649. self.setGpioLevel("A",3,0)
  1650. elif pinId==6: #a2
  1651. self.setGpioDir("A",2,1)
  1652. self.setGpioLevel("A",2,0)
  1653. elif pinId==7: #a3
  1654. self.setGpioDir("B",7,0)
  1655. self.setGpioLevel("B",7,0)
  1656. else:
  1657. pass
  1658. self.address=0x49 #再用Ads1115进行ADC读取
  1659. return self.readAdc(self.adcPin[pinId-4])
  1660. def __del__(self):
  1661. self.address=0x40
  1662. extOutputPin.__del__(self)
  1663. self.address=0x20
  1664. MCP23017.__del__(self) #最先init的配置最后再del
  1665. print("del finished!")