Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.45 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. ########################################################################
  3. # Filename : UltrasonicRanging.py
  4. # Description : Get distance from UltrasonicRanging.
  5. # Author : freenove
  6. # modification: 2018/08/03
  7. ########################################################################
  8. import RPi.GPIO as GPIO
  9. from threading import Thread
  10. import time
  11. #Initialisation clavier
  12. #class Key:Define some of the properties of Key
  13. class Key(object):
  14. NO_KEY = '\0'
  15. #Defines the four states of Key
  16. IDLE = 0
  17. PRESSED = 1
  18. HOLD = 2
  19. RELEASED = 3
  20. #define OPEN and CLOSED
  21. OPEN = 0
  22. CLOSED =1
  23. #constructor
  24. def __init__(self):
  25. self.kchar = self.NO_KEY
  26. self.kstate = self.IDLE
  27. self.kcode = -1
  28. self.stateChanged = False
  29.  
  30. class Keypad(object):
  31. NULL = '\0'
  32. LIST_MAX = 10 #Max number of keys on the active list.
  33. MAPSIZE = 10 #MAPSIZE is the number of rows (times 16 columns)
  34. bitMap = [0]*MAPSIZE
  35. key = [Key()]*LIST_MAX
  36. holdTime = 500 #key hold time
  37. holdTimer = 0
  38. startTime = 0
  39. #Allows custom keymap, pin configuration, and keypad sizes.
  40. def __init__(self,usrKeyMap,row_Pins,col_Pins,num_Rows,num_Cols):
  41. GPIO.setmode(GPIO.BOARD)
  42. self.rowPins = row_Pins
  43. self.colPins = col_Pins
  44. self.numRows = num_Rows
  45. self.numCols = num_Cols
  46.  
  47. self.keymap = usrKeyMap
  48. self.setDebounceTime(10)
  49. #Returns a single key only. Retained for backwards compatibility.
  50. def getKey(self):
  51. single_key = True
  52. if(self.getKeys() and self.key[0].stateChanged and (self.key[0].kstate == self.key[0].PRESSED)):
  53. return self.key[0].kchar
  54. single_key = False
  55. return self.key[0].NO_KEY
  56. #Populate the key list.
  57. def getKeys(self):
  58. keyActivity = False
  59. #Limit how often the keypad is scanned.
  60. if((time.time() - self.startTime) > self.debounceTime*0.001):
  61. self.scanKeys()
  62. keyActivity = self.updateList()
  63. self.startTime = time.time()
  64. return keyActivity
  65. #Hardware scan ,the result store in bitMap
  66. def scanKeys(self):
  67. #Re-intialize the row pins. Allows sharing these pins with other hardware.
  68. for pin_r in self.rowPins:
  69. GPIO.setup(pin_r,GPIO.IN,pull_up_down = GPIO.PUD_UP)
  70. #bitMap stores ALL the keys that are being pressed.
  71. for pin_c in self.colPins:
  72. GPIO.setup(pin_c,GPIO.OUT)
  73. GPIO.output(pin_c,GPIO.LOW)
  74. for r in self.rowPins: #keypress is active low so invert to high.
  75. self.bitMap[self.rowPins.index(r)] = self.bitWrite(self.bitMap[self.rowPins.index(r)],self.colPins.index(pin_c),not GPIO.input(r))
  76. #Set pin to high impedance input. Effectively ends column pulse.
  77. GPIO.output(pin_c,GPIO.HIGH)
  78. GPIO.setup(pin_c,GPIO.IN)
  79. #Manage the list without rearranging the keys. Returns true if any keys on the list changed state.
  80. def updateList(self):
  81. anyActivity = False
  82. kk = Key()
  83. #Delete any IDLE keys
  84. for i in range(self.LIST_MAX):
  85. if(self.key[i].kstate == kk.IDLE):
  86. self.key[i].kchar = kk.NO_KEY
  87. self.key[i].kcode = -1
  88. self.key[i].stateChanged = False
  89. # Add new keys to empty slots in the key list.
  90. for r in range(self.numRows):
  91. for c in range(self.numCols):
  92. button = self.bitRead(self.bitMap[r],c)
  93. keyChar = self.keymap[r * self.numCols +c]
  94. keyCode = r * self.numCols +c
  95. idx = self.findInList(keyCode)
  96. #Key is already on the list so set its next state.
  97. if(idx > -1):
  98. self.nextKeyState(idx,button)
  99. #Key is NOT on the list so add it.
  100. if((idx == -1) and button):
  101. for i in range(self.LIST_MAX):
  102. if(self.key[i].kchar == kk.NO_KEY): #Find an empty slot or don't add key to list.
  103. self.key[i].kchar = keyChar
  104. self.key[i].kcode = keyCode
  105. self.key[i].kstate = kk.IDLE #Keys NOT on the list have an initial state of IDLE.
  106. self.nextKeyState(i,button)
  107. break #Don't fill all the empty slots with the same key.
  108. #Report if the user changed the state of any key.
  109. for i in range(self.LIST_MAX):
  110. if(self.key[i].stateChanged):
  111. anyActivity = True
  112. return anyActivity
  113. #This function is a state machine but is also used for debouncing the keys.
  114. def nextKeyState(self,idx, button):
  115. self.key[idx].stateChanged = False
  116. kk = Key()
  117. if(self.key[idx].kstate == kk.IDLE):
  118. if(button == kk.CLOSED):
  119. self.transitionTo(idx,kk.PRESSED)
  120. self.holdTimer = time.time() #Get ready for next HOLD state.
  121. elif(self.key[idx].kstate == kk.PRESSED):
  122. if((time.time() - self.holdTimer) > self.holdTime*0.001): #Waiting for a key HOLD...
  123. self.transitionTo(idx,kk.HOLD)
  124. elif(button == kk.OPEN): # or for a key to be RELEASED.
  125. self.transitionTo(idx,kk.RELEASED)
  126. elif(self.key[idx].kstate == kk.HOLD):
  127. if(button == kk.OPEN):
  128. self.transitionTo(idx,kk.RELEASED)
  129. elif(self.key[idx].kstate == kk.RELEASED):
  130. self.transitionTo(idx,kk.IDLE)
  131.  
  132. def transitionTo(self,idx,nextState):
  133. self.key[idx].kstate = nextState
  134. self.key[idx].stateChanged = True
  135. #Search by code for a key in the list of active keys.
  136. #Returns -1 if not found or the index into the list of active keys.
  137. def findInList(self,keyCode):
  138. for i in range(self.LIST_MAX):
  139. if(self.key[i].kcode == keyCode):
  140. return i
  141. return -1
  142. #set Debounce Time, The default is 50ms
  143. def setDebounceTime(self,ms):
  144. self.debounceTime = ms
  145. #set HoldTime,The default is 500ms
  146. def setHoldTime(self,ms):
  147. self.holdTime = ms
  148. #
  149. def isPressed(keyChar):
  150. for i in range(self.LIST_MAX):
  151. if(self.key[i].kchar == keyChar):
  152. if(self.key[i].kstate == self.self.key[i].PRESSED and self.key[i].stateChanged):
  153. return True
  154. return False
  155. #
  156. def waitForKey():
  157. kk = Key()
  158. waitKey = kk.NO_KEY
  159. while(waitKey == kk.NO_KEY):
  160. waitKey = getKey()
  161. return waitKey
  162.  
  163. def getState():
  164. return self.key[0].kstate
  165. #
  166. def keyStateChanged():
  167. return self.key[0].stateChanged
  168.  
  169. def bitWrite(self,x,n,b):
  170. if(b):
  171. x |= (1<<n)
  172. else:
  173. x &=(~(1<<n))
  174. return x
  175. def bitRead(self,x,n):
  176. if((x>>n)&1 == 1):
  177. return True
  178. else:
  179. return False
  180. #Fin initialisation du clavier
  181. #
  182. ROWS = 4
  183. COLS = 4
  184. keys = [ '1','2','3','A',
  185. '4','5','6','B',
  186. '7','8','9','C',
  187. '*','0','#','D' ]
  188. rowsPins = [12,29,37,22]
  189. colsPins = [19,40,13,11]
  190.  
  191. alarm = False
  192. trigPin = 16
  193. echoPin = 18
  194. ledPin = 15
  195. MAX_DISTANCE = 220 #define the maximum measured distance
  196. timeOut = MAX_DISTANCE*60 #calculate timeout according to the maximum measured distance
  197.  
  198. def loop1():
  199. while(True):
  200. global alarm
  201. keypad = Keypad(keys,rowsPins,colsPins,ROWS,COLS)
  202. keypad.setDebounceTime(50)
  203. pwd = "1239"
  204. password = ""
  205. resetPass = False
  206. while(alarm == True):
  207. key = keypad.getKey()
  208. if(key != keypad.NULL):
  209. print ("You Pressed Key : %c "%(key) )
  210. if (key == "D"):
  211. if (password == pwd):
  212. print ("Alarme arreter")
  213. resetPass = True
  214. alarm = False
  215. else:
  216. print ("Mauvais mots de passe")
  217. resetPass = True
  218. password = password + str(key)
  219. if(resetPass == True):
  220. password = ""
  221. resetPass = False
  222. print ("Password : %s "%(password) )
  223.  
  224. #
  225.  
  226.  
  227. def pulseIn(pin,level,timeOut): # function pulseIn: obtain pulse time of a pin
  228. t0 = time.time()
  229. while(GPIO.input(pin) != level):
  230. if((time.time() - t0) > timeOut*0.000001):
  231. return 0;
  232. t0 = time.time()
  233. while(GPIO.input(pin) == level):
  234. if((time.time() - t0) > timeOut*0.000001):
  235. return 0;
  236. pulseTime = (time.time() - t0)*1000000
  237. return pulseTime
  238.  
  239. def getSonar(): #get the measurement results of ultrasonic module,with unit: cm
  240. GPIO.output(trigPin,GPIO.HIGH) #make trigPin send 10us high level
  241. time.sleep(0.00001) #10us
  242. GPIO.output(trigPin,GPIO.LOW)
  243. pingTime = pulseIn(echoPin,GPIO.HIGH,timeOut) #read plus time of echoPin
  244. distance = pingTime * 340.0 / 2.0 / 10000.0 # the sound speed is 340m/s, and calculate distance
  245. return distance
  246.  
  247. def setup():
  248. print ('Program is starting...')
  249. GPIO.setmode(GPIO.BOARD) #numbers GPIOs by physical location
  250. GPIO.setup(trigPin, GPIO.OUT) #
  251. GPIO.setup(echoPin, GPIO.IN)
  252. GPIO.setup(ledPin, GPIO.OUT)
  253. GPIO.output(ledPin, GPIO.LOW)
  254.  
  255.  
  256. def blink():
  257. global alarm
  258. while(alarm == True):
  259. GPIO.output(ledPin, GPIO.HIGH) # led on
  260. print ('...led on')
  261. time.sleep(1)
  262. GPIO.output(ledPin, GPIO.LOW) # led off
  263. print ('led off...')
  264. time.sleep(1)
  265.  
  266.  
  267. def loop():
  268. global alarm
  269. distance1 = getSonar()
  270. while(alarm == False):
  271. distance = getSonar()
  272. if (distance + 1) < distance1:
  273. alarm = True
  274. blink() # led on
  275. print ("La taille mesurer est de : %.2f cm"%(distance))
  276. time.sleep(1)
  277.  
  278.  
  279. if __name__ == '__main__': #program start from here
  280. setup()
  281. try:
  282. Thread(target = loop).start()
  283. Thread(target = loop1).start()
  284. except KeyboardInterrupt: #when 'Ctrl+C' is pressed, the program will exit
  285. GPIO.output(ledPin, GPIO.LOW)
  286. GPIO.cleanup() #release resource
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement