import time OUTPUT = 1 INPUT = 0 HIGH = 1 LOW = 0 TIMEOUT = 60000 uS = 1e-6 def reg(pin): try: exp = open('/sys/class/gpio/export','wb',0) exp.write(str(pin)) print('Registion Successful: pin%d' %pin) #exp.close() except IOError as e: #print('Registion Error: pin%d' %pin) print('Error: %d - %s' %(e.errno,e.strerror)) def unreg(pin): try: uexp = open('/sys/class/gpio/unexport','wb',0) uexp.write(str(pin)) print('Unregistion Successful: pin%d' %pin) uexp.close() except IOError as e: #print('Unregistion Error: pin%d' %pin) print('Error: %d - %s' %(e.errno,e.strerror)) def pinMode(pin, mode): try: direction = open('/sys/class/gpio/gpio%d/direction' %pin,'wb',0) direction.write('out' if mode == OUTPUT else 'in') #print('pin%d setted at %s' %(pin,'out' if mode == OUTPUT else 'in')) direction.close() except IOError as e: #print('CANNOT SET PIN MODE: pin%d' %pin) print('Error: %d - %s' %(e.errno,e.strerror)) def digitalWrite(pin,value): try: val = open('/sys/class/gpio/gpio%d/value' %pin,'wb',0) val.write(str(value)) val.close() except IOError as e: #print('WRITE ERROR: pin%d' %pin) print('Error: %d - %s' %(e.errno,e.strerror)) def digitalRead(pin): try: file = open('/sys/class/gpio/gpio%d/value' %pin,'rb',0) value = file.read() file.close() return int(value) except IOError as e: #print('READ ERROR') print('Error: %d - %s' %(e.errno,e.strerror)) return 0 def analogRead(pin): filePath = '/sys/devices/platform/c0000000.soc/c0053000.adc/iio:device0/in_voltage%d_raw' %pin print(filePath) try: file = open(filePath,"rb",0) value = file.read() file.close() return int(value) except IOError as e: print('Error: %d - %s' %(e.errno, e.strerror)) return 0 def pulseIn(pin,state,timeout=1000000L): #Wait for any previous pulse to stop while (digitalRead(pin) == state): print(timeout) if (timeout == 0): print('PULSE TIMEOUT') return 0 #time.sleep(uS) timeout -= 1 #Wait for next pulse to start while (digitalRead(pin) != state): if (timeout==0): print('PULSE TIMEOUT') return 0 #time.sleep(uS) timeout -= 1 #Initialize TIMER Timer = time.time() #Measuring current pulse while (digitalRead(pin) == state): if (timeout==0): print('PULSE TIMEOUT') return 0 #time.sleep(uS) timeout -= 1 return (time.time() - Timer) * 1000000 #ULTRASONIC SENSOR trig = 128 # ARTIK 710의 GPIO 0번 echo = 129 # ARTIK 710의 GPIO 1번 reg(trig) reg(echo) pinMode(trig,OUTPUT) pinMode(echo,INPUT) try: while True: digitalWrite(trig,LOW) time.sleep(20 * uS) digitalWrite(trig,HIGH) time.sleep(1 * uS) digitalWrite(trig,LOW) duration = pulseIn(echo,HIGH) distance = duration/2/29.412 print('Duration: %d - Distance: %0.2f' %(duration,distance)) time.sleep(0.5) except KeyboardInterrupt: unreg(trig) unreg(echo)
|