def read(self): voltageHI = ADC.read("AIN0") * 1800 #1.8V voltageLO = ADC.read("AIN1") * 1800 #1.8V # print voltage self.add('/tempLO',voltageLO) self.add('/tempHI',voltageHI)
def getVolumeAndStationValue(): prevStation = 0 while True: sample = 0 volReading = 0 statReading = 0 while sample < 10: volReading += adc.read(self.volumePot) time.sleep(0.01) statReading += adc.read(self.stationPot) sample += 1 time.sleep(0.05) volReading = volReading / 10.0 statReading = int(statReading * 100) station = statReading if station != prevStation: # print prevStation, station if self.have_stations: print 'True' prevStation = station volume = volReading volString = "%.2f" % round(volume, 2) previousVolume = self.player.get_property('volume') prevVolString = "%.2f" % round(previousVolume, 2) if volString != prevVolString: # print previousVolume, volume self.player.set_property('volume', volume)
def get_voltage(self): Vo = ADC.read("P9_39")* 1.8 Vo = ADC.read("P9_39") * 1.8 R1 = 10 * 1000 R2 = 2.2 * 1000 Vi = Vo * (R1 + R2) / R2 return Vi
def read_IR(self): self.mid = ADC.read("P9_35") self.lef = ADC.read("P9_33") self.rig = ADC.read("P9_36") self.mrig = ADC.read("P9_37") self.mlef = ADC.read("P9_39") self.value = [self.lef, self.mid, self.rig, self.mlef, self.mrig]
def read(self): voltageLO = ADC.read("AIN2") * 1.8 #1.8V voltageHI = ADC.read("AIN3") * 1.8 #1.8V # print voltage self.add('/soil_moistureLO',voltageLO) self.add('/soil_moistureHI',voltageHI)
def read(self): voltageLO = ADC.read("AIN2") * 1.8 #1.8V voltageHI = ADC.read("AIN3") * 1.8 #1.8V # print voltage self.add('/humidityLO',voltageLO) self.add('/humidityHI',voltageHI)
def getAngularVelocity(self, m): if m in self.pin_map: pin = self.pin_map[m] else: return None #TODO: Handle Gracefully # There's currently a bug in the Adafruit library where the ADC pin must # be read twice to get the latest value. ADC.read(pin) raw_value = ADC.read(pin) value = self.RAW2REV * raw_value
def read_color(self): while True: color = [0,0,0] color[0] = ADC.read(self.a_pin) time.sleep(0.001); color[1] = ADC.read(self.b_pin) time.sleep(0.001); color[2] = ADC.read(self.c_pin) time.sleep(0.001); if all(map(lambda x: x>0.00001, color)): return color print "[color_sensor.read_color] Invalid color:", color
def readADCs(): while True: a0 = open("ADC0data.txt","a+") a1 = open("ADC1data.txt","a+") a2 = open("ADC2data.txt","a+") a3 = open("ADC3data.txt","a+") a4 = open("ADC4data.txt","a+") a5 = open("ADC5data.txt","a+") adc0 = ADC.read('AIN0') a0.write(str(adc0)) a0.write("\n") adc1 = ADC.read('AIN1') a1.write(str(adc1)) a1.write("\n") adc2 = ADC.read('AIN2') a2.write(str(adc2)) a2.write("\n") adc3 = ADC.read('AIN3') a3.write(str(adc3)) a3.write("\n") adc4 = ADC.read('AIN4') a4.write(str(adc4)) a4.write("\n") adc5 = ADC.read('AIN5') a5.write(str(adc5)) a5.write("\n") time.sleep(0.1) a0.close() a1.close() a2.write("\n") adc3 = ADC.read('AIN3') a3.write(str(adc3)) a3.write("\n") adc4 = ADC.read('AIN4') a4.write(str(adc4)) a4.write("\n") adc5 = ADC.read('AIN5') a5.write(str(adc5)) a5.write("\n") time.sleep(0.1) a0.close() a1.close() a2.close() a3.close() a4.close() a5.close()
def do_sensor_read(): print 'sensor read' global readings readings = {} # value = ADC.read("AIN1") # adc returns value from 0 to 1. # use read_raw(pin) to get V values # tank = adc.read(tankPin) tank = adc.read(tankPin) # have to read twice due to bbio bug print 'tank is %s' % tank time.sleep(1) # photo = adc.read(photoPin) # have to read twice due to bbio bug photo = 1.0-adc.read(photoPin) # reverse range so that 0 is darkest print 'photo is %s' % photo time.sleep(1) # temp1 = adc.read_raw(thermistor1) temp1 = adc.read_raw(thermistor1) time.sleep(1) print 'temp1 raw %s' % temp1 temp1 = convert_thermistor_special(temp1) readings['bedTemp'] = temp1 print 'converted bed_temp is %s' % temp1 # # do conversion per # # http://learn.adafruit.com/thermistor/using-a-thermistor # temp2 = adc.read_raw(thermistor2) temp2 = adc.read_raw(thermistor2) time.sleep(1) print 'temp2 raw %s' % temp2 print temp2 temp2 = convert_thermistor(temp2) readings['tankTemp'] = temp2 print 'converted reservoir_temp is %s' % temp2 # do conversion per # http://learn.adafruit.com/thermistor/using-a-thermistor # tmp36reading = adc.read_raw(tmp36Pin) # tmp36reading = adc.read_raw(tmp36Pin) # have to read twice due to bbio bug # millivolts = tmp36reading * 1800 # 1.8V reference = 1800 mV # temp_c = (millivolts - 500) / 10 # print temp_c # ph_val = get_ph() # print 'ph_val was thoght to be %s' % ph_val readings['tankLevel'] = tank # tank level readings['photocell'] = photo # photocell
def control(): logger.debug("getTemperature called") try: x1 = ADC.read("AIN6") x0 = ADC.read("AIN6") logger.debug("%s %s", "AIN6 Raw reading ", x0) b0 = x0 * 1800 logger.debug("%s %s", "Raw reading converted to mV ", b0) pretemp = (b0 - 500) / 10 logger.debug("%s %s", "mv converted to C ((b0 - 500) / 10) ", pretemp) # We always want to return the following format +/-00.0 if re.match("^\d$", str(pretemp)): # matched 0 - 9 temp = '+' + str(pretemp).zfill(2) + '.' + '0' elif re.match("^\d\.\d*$", str(pretemp)): a = str(pretemp).split('.') b = a[0].zfill(2) temp = '+' + b + '.' + a[1][:1] elif re.match("^\d{2}$", str(pretemp)): temp = '+' + str(pretemp) + '.0' elif re.match("^\d{2}\.\d*$", str(pretemp)): temp = '+' + str(pretemp)[:4] elif re.match("^-\d$", str(pretemp)): a = str(pretemp).replace('-', '') temp = '-' + str(a).zfill(2) + '.0' elif re.match("^-\d{1,2}\.\d*$", str(pretemp)): # matched -1.8888 a = str(pretemp).replace('-', '') b = str(a).split('.') c = b[0].zfill(2) temp = '-' + c + '.' + b[1][:1] elif re.match("-\d{2}\.\d*$", str(pretemp)): temp = str(pretemp)[:5] else: temp = '+00.0' value = temp logger.debug("%s %s", "getTemperature returned value ", value) except IOError as e: logger.critical("%s %s", "premature termination", e) status = 4 value = e logger.critical("%s %s", "getTemperature premature termination", e) else: status = 0 status = status return status, value
def batteryMeasure(): for i in range(1, 10): bat1 = ADC.read(adc01) bat2 = ADC.read(adc02) bat3 = ADC.read(adc03) battery01 = battery01 + bat1 battery02 = battery02 + bat2 battery03 = battery03 + bat3 data.data[0] = (battery01)/10 data.data[1] = (battery02)/10 data.data[2] = (battery03)/10 return data
def read_adc_v(adc_pin, adc_max_v=1.8): ''' Read a BBB ADC pin and return the voltage. Keyword arguments: adc_pin -- BBB AIN pin to read (required) adc_max_v -- Maximum voltage for BBB ADC (default 1.8) Return: ADC reading as a voltage Note: Read the ADC twice to overcome a bug reported in the Adafruit_BBIO library documentation. ''' ADC.read(adc_pin) return ADC.read(adc_pin) * adc_max_v
def IRread(): # Useful Lists: IR1list = [] IR2list = [] IR3list = [] IR4list = [] IR5list = [] # General purpose variables: count = 0 samples = 20 voltMulti = 5 ADC.setup() # Reading analog inputs: IR1 = ADC.read("P9_33") * voltMulti #added a voltage multiplier IR2 = ADC.read("P9_35") * voltMulti IR3 = ADC.read("P9_36") * voltMulti IR4 = ADC.read("P9_39") * voltMulti IR5 = ADC.read("P9_37") * voltMulti for i in range(samples): count = count + 1 IR1list.append(IR1) IR2list.append(IR2) IR3list.append(IR3) IR4list.append(IR4) IR5list.append(IR5) if (count == samples): # Calculating the average of 20 readings: avgIR1 = round(sum(IR1list) / len(IR1list),3) avgIR2 = round(sum(IR2list) / len(IR2list),3) avgIR3 = round(sum(IR3list) / len(IR3list),3) avgIR4 = round(sum(IR4list) / len(IR4list),3) avgIR5 = round(sum(IR5list) / len(IR5list),3) # Clearing each list: IR1list = [] IR2list = [] IR3list = [] IR4list = [] IR5list = [] count = 0 return (avgIR1, avgIR2, avgIR3, avgIR4, avgIR5)
def senseLdr(addr, tags, msg, source): if bbbExists == True: ldrVal = ADC.read("P9_40") else: ldrVal = random.uniform(0, 1) print "sending msg: '{0}' '{1}'".format(pythonSenseReturnOscPath, ldrVal) client.send( OSCMessage( pythonSenseReturnOscPath, ldrVal ) )
def GPIOlightRead(): ADC.setup() value = ADC.read("P9_33") if value >= 0.3: # state of turn on the romm's light return 1 else: return 0
def batt(): #enable is P9_41 #adc input is P9_36 GPIO.output("P9_41",GPIO.HIGH); #there is a bug currently that the first read is not the latest value value = ADC.read("P9_36") value=0; for x in range(0,5): value += ADC.read("P9_36") GPIO.output("P9_41",GPIO.LOW); value/=5 #values are returned in 0-1.0 range, multiplying by 1.8 gives the actual result value*=1.8 #1.12k and 8.22k resistor divider return value*8.339
def callDist(data): #reads voltage value voltage = ADC.read("P9_40") #converts voltage values into distance(meters) distance = (voltage**-.8271732796) distance = distance*.1679936709 #checks and discards data outside of accurate range if distance>2: distance = 2 elif distance<.15: distance = .15 #Writes data to Range message msg = Range() header = Header() #creates header msg.header.stamp.secs = rospy.get_time() msg.header.frame_id = "/base_link" msg.radiation_type = 1 msg.field_of_view = .15 #about 8.5 degrees msg.min_range = .15 msg.max_range = 2 msg.range = distance pub.publish(msg)
def get_wind_direction(self): value = ADC.read(ADS80422.pin_dir) voltage_value = value * 1.8000 direction = self.voltage_to_degrees(voltage_value, ADS80422._currentWindDirection) self._logger.debug('Current wind direction {0:.2f})'.format(direction)) return direction
def getVoltage(): ADC.setup() adc = 0.0 for i in range(MEASURE_POINTS) : adc = adc + ADC.read(voltagePin) adc /= MEASURE_POINTS if adc<0.405: return "low" if adc>0.565: return "high" adc = "{0:.2f}".format(adc) try: voltage = adcToVoltage[adc] except: return "error" return str(voltage)
def read(self): unsuccesfull = 0 value = None with ADC_LOCK: while not value: # adafruit says it is a bug http://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/adc try: ADC.read(self._input) value = ADC.read(self._input) # read 0 to 1 except IOError as e: if unsuccesfull>10: _logger.warn("Error reading value: %s", e) unsuccesfull += 1 if unsuccesfull > 100: raise e return thermistors.get_thermistor_reading(self._thermistor_type, value)
def getAccel(axis): global line zeroOffset = 0.4584 conversionFactor = 0.0917 rawRead = ADC.read(axis) value = (rawRead - zeroOffset) / conversionFactor line += str(value)+"; "
def run(self): """ Continuously monitor the A/D :return: """ value = None while True: try: for entry in self.pin_states: if entry['enabled']: if entry['mode'] == 'analog': value = ADC.read(entry['pin']) value = round(value, 4) elif entry['mode'] == 'sonar': value = ADC.read_raw(entry['pin']) value = self.convert_to_distance(value) digital_reply_msg = umsgpack.packb({u"command": "analog_read", u"pin": entry['pin'], u"value": str(value)}) envelope = ("B" + self.board_num).encode() self.publisher.send_multipart([envelope, digital_reply_msg]) time.sleep(0.05) except KeyboardInterrupt: sys.exit(0)
def check_voltage(): 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") VOLTAGES = [['AIN0', 0.30, 1.7], ['AIN2', 0.85, 0.95], ['AIN4', 1.14, 1.26], ['AIN6', 1.42, 1.58], ['AIN1', 1.04, 1.16], # VDD_3V3B / 3 ['AIN3', 1.58, 1.75], # VDD_5V / 3 ['AIN5', 1.60, 1.70]] # SYS_5V / 3 ADC.setup() result = [] status = 'ok' for v in VOLTAGES: ain = ADC.read(v[0])*1.8 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 read_temp(): """Reads temperature locally. Returns a float""" reading = ADC.read(sensor_pin) millivolts = reading * 1800 # 1.8V reference = 1800 mV temp_f = ((millivolts - 500) / 10 * 9/5) + 32 + calibration logger.debug("Read a temperature of %.2f", temp_f) return temp_f
def getIluminacion(self): while 1: valor = AD.read("P9_" + str(self.pin)) if (valor>.001): valor = 100 - valor*100 break; return valor
def poll(self, controlsetup, ctrldef, ctrltype, ctrlstate, ctrlvalue): value = ctrlvalue state = ctrlstate pot = ADC.read(self.pins['POT']) #Only check the new value if it is far enough away from the last value if abs(pot - self.lastValue) > 0.001: self.lastValue = pot #Interpretation varies by control type if ctrltype == 'toggle': if ctrlvalue == None: #We'll take the mid line to decide if pot < 0.5: state = 0 else: state = 1 elif pot < 0.4: #Dead zone in the middle state = 0 elif pot > 0.6: state = 1 else: state = ctrlstate #if not decisively left or right, stay the same if state != ctrlstate: value = state elif ctrltype == 'selector': state = SHControlBargraphPot.__translateCalibratedValue(self, pot, controlsetup['calibration'][ctrltype]) value = int(state) return value, state
def monitor_sensor(): """Read the sensor value and detect an alarm condition.""" logger.info("Starting to monitor sensor") post_to_twitter("Door Entry Alarm: started") ADC.setup() # start with door in closed state is_open = False logger.info("Door closed") post_to_twitter("Door closed") samples_counter = 0 while True: reading = ADC.read(SENSOR_PIN) if is_open == False: if reading > SENSOR_THRESHOLD: samples_counter += 1 if samples_counter >= SAMPLES_REQUIRED: is_open = True logger.info("Door opened") post_to_twitter("Door opened") samples_counter = 0 else: samples_counter = 0 elif is_open == True: if reading <= SENSOR_THRESHOLD: is_open = False logger.info("Door closed") post_to_twitter("Door closed") samples_counter = 0 time.sleep(SAMPLE_FREQUENCY)
def main(): script, bitfile = argv ADC.setup() file_counter=0 counter=0 start_time = calendar.timegm(time.gmtime()) # First collect enough data to get a reasonable estimate of the average history = [] average_count = 10000 average = 0.0 print "Pulling data for average: " for i in xrange(0, average_count): val = (ADC.read(in_channel)*1.8) average+=val sys.stdout.write("Collected %d/%d samples.\r" % (i, average_count)) history.append(val) sys.stdout.flush() average /= average_count speed = 0.0 print "Starting collection:\n" disparity_count = 0 while(True): counter+=1 val = ADC.read(in_channel)*1.8 # history[(counter-1) % (len(history))] = val average = ((average*average_count)+val)/(average_count+1) # average = sum(history)/len(history) # average = (max(history)+min(history))/2 average_count+=1 with open(bitfile, "a") as file: if val > average: file.write("1") disparity_count+=1 elif val < average: file.write("0") disparity_count-=1 file.close() if(calendar.timegm(time.gmtime()) != start_time): speed = average_count/(calendar.timegm(time.gmtime())-start_time) sys.stdout.write("\t Counter: %d. Disparity: %d. Current Average: %f. Current Bit: %d. Current Voltage: %f. Speed : %f.\t\r" % (counter, disparity_count, average, 1 if val > average else (0 if val < average else -1), val, speed)) sys.stdout.flush()
def PID_Algorithm(kp, ki, kd, n, u, ideal_value): print "----------------inside----------------" # variables that must be remembered outside the scope of this # function but don't need to be passed are global global error2 global error1 global error global u1 # calculate k1, k2, k3 k1 = kp + ki + kd k2 = -1*kp -2*kd k3 = kd # limits of control signal, u u_min = 0 u_max = 1 # read value from pin and display it measured_value = ADC.read(ADC_INPUT) print "measured value: ", measured_value # if first call if (n == 1): error2 = 0 error1 = 0 u1 = 0 # if second call elif (n == 2): error2 = 0 error1 = error u1 = u # if after second call else: error2 = error1 error1 = error u1 = u # calculate error and control signal, u error = ideal_value - measured_value u = u1 + 1*error + 2*error1 + 3*error2 # bound control signal, u if (u > u_max): u = u_max if (u < u_min): u = u_min # display values print "IF error2: ", error2 print "IF error1: ", error1 print "IF error: ", error print "u1: ", u1 print "IF u: ", u # return control, u return u
def set_motor_speed(self): motor_duty_span = self.motor_duty_max - self.motor_duty_min #Max value minus min value angle = float( ADC.read(self.adcPin) ) #Value between 0 and 1 from the potentiometer, instead of 0-4095 duty = ((angle * motor_duty_span) + self.motor_duty_min) print(angle) PWM.set_duty_cycle(self.motorPin, duty) #Outputs stuff to the motor
def readUS(pin): usonicVal = ADC.read(pin) usonicVolt = usonicVal * 1.8 # Convert to voltage # Convert to meters via manual tuning # This equation works for .3 - 7.5 meters distanceMetersUS = (usonicVolt - US_B) / US_M return distanceMetersUS
def set_servo_angle(adc_pin, servo_pin): servo_duty_span = servo_duty_max - servo_duty_min angle = float(ADC.read(adc_pin)) duty = ((angle * servo_duty_span) + servo_duty_min) if (debug): print("angle = {0}; duty = {1}".format(angle, duty)) PWM.set_duty_cycle(servo_pin, duty)
def readIR(pin): irVal = ADC.read(pin) irVolt = irVal * 1.8 # Convert to voltage # Prevent divide by zero error add small delta # This equation only works for 1-5.5 meters distance distanceMetersIR = (1 / (irVolt + IR_DELTA) - IR_B) / IR_M return distanceMetersIR
def read_sensor(self): ain_value = ADC.read("P9_39") ain_voltage = 1.8 * ain_value sensor_output_voltage = ain_voltage * 2 f = sensor_output_voltage * 100 c = (f - 32) * 5 / 9 c_str = "{:.2f}".format(c) return c_str
def index(): while (1): potVal = ADC.read("P9_33") potVolt = potVal * 1.8 olt = repr(potVolt) #return olt #api.add_resource(olt) #print "The Potentiometer Voltage is: ",potVolt return render_template('index.html', username=olt)
def checkMoisture(): for relay in myconfig['relays']: moist = int(ADC.read(relay['senspin']) * 1000) if (moist < int(relay['moisture'])): mqtt_log("Zone {} moisture is below the threshold.".format( relay['name'])) pulse(relay) else: mqtt_log("Zone {} moisture: {}".format(relay['name'], moist))
def proc_stats(): global stats currTime = time.ctime() rps = counter / 10 ws = rps * 1.492 #stats['currentspeed'] = float( str("%.1f" % ws) ) stats['currenttime'] = currTime direction = ADC.read(dirPin) * 3.3 stats['direction'] = direction_text(direction)
def get_analog(self, port): """ Reads an analog signal from the beagle board :param port: string identifying the port, for example "P9_40" :return: value of the signal """ ADC.setup() value = ADC.read(port) return value
def run(self): """Class run method""" # While running, repeatedly beep while constantly checking tempo while (1): PWM.start(self.speaker, 50, 2000) time.sleep(0.1) PWM.start(self.speaker, 0, 2000) time.sleep(1 - float(ADC.read(tempo_pot))) return
def read_adc_voltage(pin): adc_reading = 0 for i in range(NUM_SAMPLES_AVG): adc_reading += ADC.read(pin) #returns float in 0.0-1.0 range timer.sleep(ADC_DELAY) adc_reading /= NUM_SAMPLES_AVG adc_reading *= 1.8 #adc ref is 1.8V logger.debug("read ADC %d volts" %adc_reading) return (adc_reading)
def read_distance(): ADC.setup() #set up ADC value = ADC.read("P9_39") #setup pin p9_39 as an ADC pin voltage = value * 3.2 #1.8V distance = ( 25.36 / (voltage + .42)) / 100 #convert from voltage to distance in meters #distance = 0.01 DEBUG return distance
def test_port(self): print(ADC.read("P9_33")) #0.663736283779 print(ADC.read("P9_35")) #0.408791214228 print(ADC.read("P9_36")) #0.626129448414 print(ADC.read("P9_37")) #0.927960932255 print(ADC.read("P9_38")) #0.577777802944 print(ADC.read("P9_39")) #0.913308918476 print(ADC.read("P9_40")) #0.827106237411
def position(state, Status3, minTherm): blinkCount = 0 startCount = 0 servoCount = 0 thermistor = "P9_39" #spin the mallow! potVal = ADC.read(pot) GPIO.output(motorA, GPIO.HIGH) GPIO.output(motorB, GPIO.LOW) PWM.set_duty_cycle(motorPWM, (100 * .56)) time.sleep(.2) servoCom = "Y" #set servo to start position ser.write(servoCom) while state == 6: if (GPIO.input(SButton) == 1): state = 7 #return a state of 7 so manual state control can occur if (blinkCount <= 1): GPIO.output(Status3, GPIO.HIGH) blinkCount = blinkCount + 1 elif (1 < blinkCount <= 3): GPIO.output(Status3, GPIO.LOW) blinkCount = blinkCount + 1 else: blinkCount = 0 servoCom = "W" #move servo down (6) degrees ser.write(servoCom) #reads thermistor to check quality of position time.sleep(.35) thermistor = ADC.read_raw("P9_39") servoCount = servoCount + 1 #if thermistor angle is where we want it if (thermistor > (80 + minTherm) and startCount > 3): servoCom = "W" #move servo down (6) degrees ser.write(servoCom) state = 8 #allows for immediate state change to roasting elif (servoCount >= 29): servoCount = 0 startCount = startCount + 1 #try again? if startCount == 1: #go back to search #GPIO.output(Status3, GPIO.LOW) #state=4 state = 8 else: servoCom = "Y" #set servo to start position ser.write(servoCom) return state
def gsr_alcohol(): while (True): val = ADC.read(analog_Pin_1) val2 = ADC.read(analog_Pin_2) val = int(val * 1000) val2 = int(val2 * 1000) if (val > threshold_gsr or val2 > threshold_alchahol): GPIO.output( ignition_control_pin, HIGH) #Disables ignition by turning the ignition lock on. mydata = {} mydata['api_key'] = key1 r = requests.delete(URL_delete, data=json.dumps(mydata)) send_warning( ) #Warns serverside of anomaly with particular customer. continue elif (val > threshold_gsr and val2 > threshold_alchahol): GPIO.output(ignition_control_pin, LOW) break
def readCtrlLoop(): PWM.start(PWM_VENTILO, 0) try: while True: val = ADC.read(AIN) # read_raw() PWM.set_duty_cycle(PWM_VENTILO, val * 100) time.sleep(.001) except KeyboardInterrupt: print('Ok, end') PWM.cleanup()
def read_ai_all(): # case_list = case_list_test_analogue # !!! FOR TESTING !!! case_list = {} min_range_array = {} max_range_array = {} for key, value in analogInTypes.items(): case = {"val": ui_scale(key, ADC.read(value))} case_list[key] = case min_range_array[key] = ui_calibration_table(key)[0] max_range_array[key] = ui_calibration_table(key)[1]
def distance(self): """ Returns the distance in cm using the calibration data """ distance = self.coeff * (ADC.read(self.AIN) * 1.8 * self.scale) ** self.power if distance < self.min: distance = -1 # invalid distance elif distance > self.max: distance = self.max return distance
def read_ai(io_num=None): gpio = analog_in(io_num) if gpio == -1: return jsonify({'1_state': "unknownType", '2_ioNum': io_num, '3_gpio': gpio, '4_val': 'null', "5_msg": analogInTypes}), http_error else: val = ADC.read(gpio) # !!! GPIO CALL !!! # val = fake_analogue_data() # !!! FOR TESTING !!! return jsonify({'1_state': "readOk", '2_ioNum': io_num, '3_gpio': gpio, '4_val': val, '5_msg': 'read value ok'}), http_success
def getVolt(NO): while True: ADC.setup() analogPin = "P9_40" potVal = ADC.read(analogPin) t = time.time() potVolt = potVal * 1.8 msg = {"device_no": NO, "time": t, "voltage": potVal} trsq.put(msg) time.sleep(0.01)
def test_many_read_adc(self): import time ADC.setup() for x in range(0, 1000): start = time.time() value = -1 value = ADC.read("AIN1") assert value != -1
def Move(): while 1: value = ADC.read("P9_40") rawv = ADC.read_raw("P9_40") voltage = value * 1.8 #1.8V D = voltage/0.00699 #.00699 if D <= 50: speak('Move bitch get out the way') print('Move')
def run(self): """ Class run method Called automatically when a new thread is started. """ while (True): V_out = ADC.read(self.pin) play_note(self.pin, V_out) time.sleep(0.5)
def get_location(): # only testing one location loc1 = ADC.read(pin1) loc1 = loc1 * 1.8 if loc1 > 1: location = "house" elif loc1 < 1: location = "office" return location
def lig(): import Adafruit_BBIO.ADC as ADC import time sensor_pin = 'P9_40' ADC.setup() print('Reading\t\tVolts') while True: reading = ADC.read(sensor_pin) volts = reading * 1.800 print('%f\t%f' % (reading, volts)) time.sleep(1)
def run(self): # main loop print("Starting bubble loop...") while not self._kill: try: self.in_bubble = self.q_in.get(timeout=1.0) # print("In bubble? {}".format(self.in_bubble)) except Queue.Empty: continue # handle new bubble - am I in a bubble now, and I wasn't before? if self.in_bubble == True and len(self.starts) == len(self.finishes): # put the current time in the starts list self.starts.append(time.time()) # increment bubble count self.bubble_count += 1 # handle bubble that is now gone - am I not in a bubble and was I before? if self.in_bubble == False and len(self.starts) != len(self.finishes): # put the current time in the finishes list self.finishes.append(time.time()) # get the length of the bubble length = self.bubble_length( self.speed, self.starts[self.bubble_count - 1], self.finishes[self.bubble_count - 1] ) # get the volume of the bubble volume = self.bubble_volume(length, self.internal_d) # add volume to total volume counter self.bubble_volume_total += self.cubic_in_to_liters(volume) # print(volume) # get avg bubble rate over the entire session # could be improved by looking at a rolling average rate = self.bubble_rate(30) # get abv of the beer self.abv = self.vol_co2_to_abv(self.bubble_volume_total, self.fermentation_volume) if WORKING_ON_BEAGLEBONE: beer_temp = ADC.read('P9_37') else: beer_temp = hat.analog.one.read() blob = { "beer_temperature": (beer_temp*18+5)/10 + 32, "co2_volume": self.bubble_volume_total, "abv": self.abv, "bubble_rate": rate, "bubble_total": self.bubble_count, "start_time": self.system_start, "brew_volume": self.fermentation_volume } print(json.dumps(blob, indent=2)) self.murano_thread_q.put(json.dumps(blob))
def __init__(self): raw = 0 ADC.setup() while True: for x in range(0, 20): raw += ADC.read(configSub.depth_pin) raw = raw/20 pressure = psi(raw) value = convert(pressure) depth = value.split(",") depth = "f:" + depth[0] + ";m:"+ depth[1] return depth
def check_photo_resistor(): global PHOTO_RESISTOR_CHANGE photo_resistor = ADC.read("P9_33") diff = abs(photo_resistor - PHOTO_RESISTOR_CHANGE) print("Photoresistor: {}".format(photo_resistor)) if diff > 0.02: if photo_resistor < 0.05: print(PHOTO_RESISTOR_INSTRUCTION) send_instruction(PHOTO_RESISTOR_INSTRUCTION) PHOTO_RESISTOR_CHANGE = photo_resistor else: pass
def adc_read(self): if self.mock_hardware: with open(self.path, 'r') as fh: value = fh.read() else: value = adc.read(self.pin) try: ret_val = float(value) except ValueError: # print('Could not convert %s to float' % value) ret_val = 0.0 return ret_val