def environment(request): B=4275 R0=100000 lightSensor = mraa.Aio(0) a = float(lightSensor.read()) tempSensor = mraa.Aio(1) b = float(tempSensor.read()) R = 1023/b-1 R = R0*R b = 1/(math.log(R/R0)/B+1/298.15)-273.15 soundSensor = mraa.Aio(2) c = float(soundSensor.read()) result="" if a>300: result+="Turn down the light." if b>26: result+="Turn down the temperature." if b<22: result+="Turn up the temperature." print c if c<200: result+="Turn down the sound." if result=="": result="Good environment." return HttpResponse(result)
def initGlobals(): #File writer global writer #Hardware related globals global main_aio global jib_aio global collect_aio #Sailing related globals global heading global apWndDir global apWndSpd global amrRoll global cog global sog global vmg global vmgUp global truWndDir jib_aio = mraa.Aio(2) main_aio = mraa.Aio(3) #TODO confirm these!!! collect_aio = mraa.Aio(0) #Aux 2 for data collection amrRoll = 0.0 heading = 0.0 apWndDir = 0.0 apWndSpd = 0.0 cog = 0.0 sog = 0.0 vmg = 0.0 vmgUp = 0.0 truWndDir = 0.0
def __init__(self): # Important variables. self.threads = {} self.running = False self.last_temperatures = [] self.last_avg_temp = 0 self.messages_to_send = [] self.moment_last_email = datetime.datetime(1970, 1, 1) # Configure the digital outputs for cold and warm led. self.cold_led = mraa.Gpio(COLD_LED) self.warm_led = mraa.Gpio(WARM_LED) self.hot_led = mraa.Gpio(HOT_LED) self.buzzer = mraa.Gpio(BUZZER_PIN) self.cold_led.dir(mraa.DIR_OUT) self.warm_led.dir(mraa.DIR_OUT) self.hot_led.dir(mraa.DIR_OUT) self.buzzer.dir(mraa.DIR_OUT) self.cold_led.write(0) self.warm_led.write(0) self.hot_led.write(0) self.buzzer.write(1) # Configures the Hi-Z button. self.button = mraa.Gpio(BUTTON_PULLUP_PIN) self.button.dir(mraa.DIR_IN) self.button.mode(mraa.MODE_PULLUP) self.button.isr(mraa.EDGE_FALLING, button_pressed, self.button) # Configures the ADC. self.adc = mraa.Aio(SENSOR_ADC_PIN)
def publish_message(): ''' Description: This function publish light sensor data to the google cloud Pub/Sub. Args: None Returns: None Raise: Throw an exception on failure ''' try: mraa.addSubplatform(mraa.GROVEPI, "0") x = mraa.Aio(512) while True: args.message = "Light Sensor: (%d)" % (x.read()) cloudApisObj.publish_message_to_subpub( args.project_id, args.registry_id, args.device_id, args.message_type, args.base_url, args.cloud_region, args.algorithm, args.private_key_file, args.message_data_type, args.message) time.sleep(2) except Exception, e: print e
def main(): #TODO: not sure 100 samples is any more consistent than 16 n_samples = 100 #The number of analog reads we average to get servo position avg_start = 25 #The internal range of data to use in the mean (get rid of outliers) avg_end = 75 # " " " upper bound analog = mraa.Aio( 4 ) #Read from the rudder ADC, fine as long as as all ADC's created equal servo.initPWMs() servo.hijack() #Turn the relays to autonomous mode for deg in range(0, 90, 5): print("Deg: " + str(deg)) servo.rotate(hackMsg(deg, 0)) #Output the servo time.sleep(1) for test in range(5): print("Test #: " + str(test)) samps = [] #Average across middle 50% of multiple reads to reduce noise from ADC for samp in range(n_samples): samps.append(analog.read()) #Take the middle 50% of samples and average them samps.sort() val = np.mean(samps[avg_start:avg_end]) print("Avg ADC value: " + str(val)) time.sleep( 0.1) #TODO this might be an important sleep, not quite sure print("")
def __init__(self): # Important variables. self.threads = {} self.running = False self.sensor_value = 0 self.seconds = 0 self.mode = 1 self.pwm_dryer = 0 # Configure the digital output for the LED 3. self.led_system = mraa.Gpio(LED_SYSTEM_PIN) self.led_system.dir(mraa.DIR_OUT) # Configures the PWM generators (LEDs and dryer). self.led_sensor = mraa.Pwm(LED_SENSOR_PWM_PIN) self.led_sensor.period_ms(5) self.led_dryer = mraa.Pwm(LED_DRYER_PWM_PIN) self.led_dryer.period_ms(5) # Configures the Hi-Z button, with pull-up and falling edge. self.button = mraa.Gpio(BUTTON_PULLUP_PIN) self.button.dir(mraa.DIR_IN) self.button.mode(mraa.MODE_PULLUP) self.button.isr(mraa.EDGE_FALLING, button_pressed, self.button) # Configures the ADC. self.adc = mraa.Aio(SENSOR_ADC_PIN) # Configures the socket. self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Starts the Network. self.network_start()
def configureArduinoAdc(self): ckboxtree = CheckboxTree(height=6, scroll=0) ckboxtree.append(text='ADC 0', item=0, selected=self.checkPinmuxConfig('ADC_0')) ckboxtree.append(text='ADC 1', item=1, selected=self.checkPinmuxConfig('ADC_1')) ckboxtree.append(text='ADC 2', item=2, selected=self.checkPinmuxConfig('ADC_2')) ckboxtree.append(text='ADC 3', item=3, selected=self.checkPinmuxConfig('ADC_3')) ckboxtree.append(text='ADC 4', item=4, selected=self.checkPinmuxConfig('ADC_4')) ckboxtree.append(text='ADC 5', item=5, selected=self.checkPinmuxConfig('ADC_5')) buttonbar = ButtonBar(screen=self.topmenu.gscreen, buttonlist=[('Ok', 'ok'), ('Cancel', 'cancel', 'ESC')]) g = GridForm(self.topmenu.gscreen, # screen 'Enable ADC on IO14-IO19', # title 1, 2) # 1x1 grid g.add(ckboxtree, 0, 0) g.add(buttonbar, 0, 1) result = g.runOnce() if buttonbar.buttonPressed(result) == 'cancel': return selected = ckboxtree.getSelection() for n in range(0, 6): if n in selected: aio = mraa.Aio(n) self.setPinmuxOfUserConfig('ADC_' + str(n)) else: self.resetPinmuxOfUserConfig('ADC_' + str(n)) self.saveConfig(self.config)
def readHumidity(pin): sensor = mraa.Aio(pin) humidity = sensor.read() humidity = (2.4 / 767) * humidity humidity = (1 / humidity) * 100 return humidity
def getTemp(): B=3975 ain = mraa.Aio(3) a = ain.read() resistance = (1023-a)*10000.0/a temp = 1/(math.log(resistance/10000.0)/B+1/298.15)-273.15 return "{0:.2f}".format(temp)+" graus Celsius"
def analog_read(self, pin_number): if not pin_number in self.pins["analog"]: pin = mraa.Aio(pin_number) self.pins["analog"][pin_number] = pin else: pin = self.pins["analog"][pin_number] return pin.read()
def getSensorData(): tmp = mraa.Aio(2) total = 0.0 for i in range(0, 5): total = total + calculateCelcius(float(tmp.read())) celciusVal = total / 5 sound = mraa.Aio(0) soundVal = int(sound.read()) light = mraa.Aio(3) lightVal = int(light.read()) dic = {'Temperature': celciusVal, 'Sound': soundVal, 'Light': lightVal} return json.dumps(dic)
def first(): pin = mraa.Aio(0) pin.setBit(12) rawReading = pin.read() volts = float(rawReading / 819.0) tempC = (volts * 100) - 50 tempF = (tempC * 9.0 / 5.0) + 32.0 return render_template("display_temp.html", name=tempF)
def tmp(): try: #Initialize the MRAA pin pin = mraa.Aio(1) #Set it to a 12 bit value pin.setBit(12) except Exception, e: print("Error: {:s}".format(e)) sys.exit()
def AIO_init(): global a_pin try: a_pin = m.Aio(a_p) print("Initializing pin " + str(a_p) + " as AIO") return 0 except ValueError: print(sys.exc_info()[1][0]) return 1
def readTemperature(pin): B = 3975 sensor = mraa.Aio(pin) aValue = sensor.read() resistance = (1023 - aValue) * 10000 / aValue celsiusTmp = 1 / (math.log(resistance / 10000) / B + 1 / 298.15) - 273.15 return celsiusTmp
def AquisicaoDados(fila_tempo, fila_aquisicao): # Define os pinos 0 (14), ligado ao sensor de temperatura, e o pino 1 (15), ligado ao sensor de luminosidade, como entradas ADC adc_temp = mraa.Aio(0) adc_lum = mraa.Aio(1) while(True): #Recebe dados da Thread timer (tempo atual, tempo de envio dos dados) tempo_atual = fila_tempo.get() #Se -1 for enviado pela fila indicando o fim do programa, a thread é desativada if(tempo_atual[0] == -1): #Envia comando de extinção para proxima thread (ProcessamentoDados) fila_aquisicao.put_nowait((-1, 0, 0, tempo_atual[1])) break # Envia (tempo atual, valor do sensor de temperatura, valor do sendor de luminosidade, tempo de envio de dados) para a thread ProcessamentoDados fila_aquisicao.put_nowait((tempo_atual[0], adc_temp.read(), adc_lum.read(), tempo_atual[1]))
def main(): #Setup duty = 0 val = 0 #Servo Constants, duty of 1 outputs abou 3.3 volts #Rudder period = 3030.0 duty_min = 1000.0 / period duty_max = 2000.0 / period #Winches # period = 20000.0 # duty_min = 1100.0/period # duty_max=1900.0 /period #main is 90 degrees out at duty cycle 0.3 (1 is all the way in) #jib is 90 degrees out at duty cycle 0.7 (0 is all the way in) #MRAA setup #switch to autonomous mode. AUTONOMOUS_SELECT_PIN = 2 #2 is for rudder, 4 is main/jib auto_select_pin = mraa.Gpio(AUTONOMOUS_SELECT_PIN) auto_select_pin.dir( mraa.DIR_OUT ) #Really important that you set the input/output of the pin... auto_select_pin.write(1) #PWM_PIN = 6; #pwm pins are the same as listed on the breakout board. (3 jib, 5 main, 6 rudder) #pwm = mraa.Pwm(PWM_PIN); #pwm.period_us(int(period)); #Period in microseconds, corresponds to 50Hz like the winch motors. #pwm.enable(True); #Analog config #ANALOG_PIN = 1 #Reading from aux 1 #ANALOG_PIN=0 #Reading from aux 2 ANALOG_PIN = 5 #Reading from Rudder aio = mraa.Aio(ANALOG_PIN) while True: val = input("Enter a duty cycle in [0,1]: ") print(val) if val < 0 or val > 1: print("Duty is out of range") continue duty = val writeval = (duty_min + (duty_max - duty_min) * duty) print writeval val = aio.read() #pwm.write(writeval); #Scale it according to our ranges print('value from analaog ' + str(ANALOG_PIN) + ": " + str(aval)) print('equivalent to ' + str(aio.read() / 1024.0 * 5.0 * 2.0) + ' volts')
def __init__(self): self.position = (0.0, 0.0) self.theta = 0.0 self.velocity = 0.0 self.gyro = mraa.Aio(2) self.left = mraa.Gpio(2) #self.left.isr(mraa.EDGE_RISING, leftbump, leftbump) self.right = mraa.Gpio(4) #self.right.isr(mraa.EDGE_RISING, rightbump, rightbump) self.time = 0
def get_temp(request): temp_pin_number = 1 temp = mraa.Aio(temp_pin_number) temperature = float(temp.read()) R = 1023.0 / (temperature) - 1.0 R = 100000.0 * R temperature = 1.0 / (math.log(R / 100000.0) / 4275 + 1 / 298.15) - 273.15 d = {'temperature': temperature} print(d) return JsonResponse(d)
def __init__(self, dht_type, pin): if dht_type != self.DHT_TYPE['DHT11'] and dht_type != self.DHT_TYPE['DHT22']: print('ERROR: Please use 11|22 as dht type.') exit(1) self.dht_type = dht_type #self.pin = GPIO(pin, GPIO.OUT) self.pin = mraa.Aio(pin) #self.pin.dir(mraa.DIR_OUT) self._last_temp = 0.0 self._last_humi = 0.0
def set_pin(self, pin): """ initalises the pin for use :param pin: GPIO AD pin used for measuring :return: initalised mraa class for later reuse """ if pin not in range (0, 6): raise Exception("Incorrect pin selection. Pins available (0, 1, 2, 3, 4, 5)") else: self.aio = mraa.Aio(pin) return self.aio
def __init__(self, pin): # The sensor length in mm. By default we use 200mm sensor # 1 mm self.length = 200 self.low = 0 self.high = self.length self.step = 0.1 self.sensor = mraa.Aio(pin) self.state = self.sensor.readFloat(), print("Water level sensor was initialised!") return
def pin_mode(pin, pin_type=PIN_TYPE_DIGITAL, pin_mode=PIN_MODE_INPUT, **kwargs): if device_type == DEVICE_TYPE_MRAA: if pin_type == PIN_TYPE_DIGITAL: if pin_mode == PIN_MODE_INPUT: obj = mraa.Gpio(pin) obj.dir(mraa.DIR_IN) return obj elif pin_mode == PIN_MODE_OUTPUT: obj = mraa.Gpio(pin) obj.dir(mraa.DIR_OUT) return obj elif pin_type == PIN_TYPE_ANALOG: obj = mraa.Aio(pin) return obj elif pin_type == PIN_TYPE_I2C: pass elif device_type == DEVICE_TYPE_RPI: if pin_type == PIN_TYPE_DIGITAL: if pin_mode == PIN_MODE_INPUT: GPIO.setup(pin, GPIO.IN, **kwargs) return pin elif pin_mode == PIN_MODE_OUTPUT: GPIO.setup(pin, GPIO.OUT, **kwargs) return pin else: pass elif device_type == DEVICE_TYPE_GPI: if pin_type == PIN_TYPE_DIGITAL: if pin_mode == PIN_MODE_INPUT: grovepi.pinMode(pin, "INPUT") return pin elif pin_mode == PIN_MODE_OUTPUT: grovepi.pinMode(pin, "OUTPUT") return pin elif pin_type == PIN_TYPE_ANALOG: grovepi.pinMode(pin, "INPUT") return pin else: pass raise NotImplementedError
def check_voltage(): ain0 = mraa.Aio(0) ain1 = mraa.Aio(1) ain2 = mraa.Aio(2) ain3 = mraa.Aio(3) ain4 = mraa.Aio(4) ain5 = mraa.Aio(5) ain6 = mraa.Aio(6) times = 100 sum = 0 values = [] os.system("echo 59 > /sys/class/gpio/export") os.system("echo out > /sys/class/gpio/gpio59/direction") os.system("echo 1 > /sys/class/gpio/gpio59/value") os.system("echo 117 > /sys/class/gpio/export") os.system("echo in > /sys/class/gpio/gpio117/direction") # Read GPIO3_21 for 100 times, values HIGH should not less than 30 while times: times = times - 1 values.append(os.popen("cat /sys/class/gpio/gpio117/value").read()) for i in values: sum += int(i) print "sum: ", sum if sum < 30: print "GPIO3_21 check fail!" else: print "GPIO3_21 check ok!" VOLTAGES = [ ["AIN0", 1.50, 1.80, ain0], ["AIN2", 0.85, 0.95, ain2], ["AIN4", 0.90, 1.30, ain4], ["AIN6", 1.42, 1.58, ain6], ["AIN1", 1.04, 1.16, ain1], # VDD_3V3B / 3 ["AIN3", 1.40, 1.75, ain3], # VDD_5V / 3 ["AIN5", 1.40, 1.80, ain5] ] # SYS_5V / 3 # ADC.setup() result = [] status = 'ok' for v in VOLTAGES: ain = v[3].read() / 1024.0 * 1.8 #ain = ADC.read(v[0])*1.8 #print ain if ain < v[1] or ain > v[2]: result.append('%f (%s) is out of range: %f ~ %f.' % (ain, v[0], v[1], v[2])) status = 'error' else: result.append('%f (%s) is in of range: %f ~ %f.' % (ain, v[0], v[1], v[2])) return status, result
def parse_data(): #sensor number i = 0 data1 = [] data2 = [] data3 = [] data4 = [] avg_data1 = 0 avg_data2 = 0 avg_data3 = 0 avg_data4 = 0 avg_data = [] while (i < 10): d1 = mraa.Aio(0) #reading value from sensor d2 = mraa.Aio(1) d3 = mraa.Aio(2) d4 = mraa.Aio(3) data1.append(d1.read()) #reading value from data variable data2.append(d2.read()) data3.append(d3.read()) data4.append(d4.read()) i += 1 time.sleep(.001) for x in data1: #adding data together x = int(x) avg_data1 = avg_data1 + x for x in data2: x = int(x) avg_data2 = avg_data2 + x for x in data3: x = int(x) avg_data3 = avg_data3 + x for x in data4: x = int(x) avg_data4 = avg_data4 + x avg_data.append(avg_data1 / len(data1)) #averaging data avg_data.append(avg_data2 / len(data2)) avg_data.append(avg_data3 / len(data3)) avg_data.append(avg_data4 / len(data4)) return avg_data
def get_uv(): try: uv_sensor = mraa.Aio(3) Vsig = uv_sensor.readFloat() intensity = 307 * Vsig # 307 taken from documentation. msg = '' uv_idx = intensity // 200 # print uv_idx return uv_idx except IOError: print 'IO Error!' return
def readingSensorValue(queueSensor, cont, pin): # Hook the SIGINT signal.signal(signal.SIGINT, signal.SIG_IGN) light = mraa.Aio(pin) while cont.value: # Read interger value sensorIntegerLight = light.read() queueSensor.put({ "type": "LIGHT_SENSOR", "payload": sensorIntegerLight }) time.sleep(1)
def temp(): B = 4275 R0 = 100000 try: tempSensor = mraa.Aio(1) a = tempSensor.read() R = 1023.0 / a - 1.0 R = R0 * R v = 1.0 / (log(R / R0) / B + 1 / 298.15) - 273.15 print(v), "is the current temperature" return v except KeyboardInterrupt: return None
def setup(): global Light Light = mraa.Gpio(8) Light.dir(mraa.DIR_OUT) global sensorPin sensorPin = mraa.Aio(5) global BaseStepper BaseStepper = Stepper(10,11,9,'eighth_step') global ReceiverStepper ReceiverStepper = Stepper(7,6,2,'eighth_step') ReceiverStepper.rotateMotor(45)
def dataVolt(): # Get Voltage and current data xpt=0.0 try: xpi= mraa.Aio(0) for i in range (25): xp = xpi.readFloat() #(xp + xpi.readFloat()) xpt=xp+xpt print xp print xpt xv=xpt / 25 print ('The current value is= ', xv) except: print ("Error capturing the Voltage(V) value data...") return xv