def motor_control(): # define various I/O pins for ADC adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) # set up motor with PWM and timer control A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) pwm_out = Pin('X1') tim = Timer(2, freq = 1000) motor = tim.channel(1, Timer.PWM, pin = pwm_out) A1.high() # motor in brake position A2.high() # Calibrate the neutral position for joysticks MID = adc_1.read() # read the ADC 1 value now to calibrate DEADZONE = 10 # middle position when not moving # Use joystick to control forward/backward and speed while True: # loop forever until CTRL-C speed = int(100*(adc_1.read()-MID)/MID) if (speed >= DEADZONE): # forward A1.high() A2.low() motor.pulse_width_percent(speed) elif (speed <= -DEADZONE): A1.low() # backward A2.high() motor.pulse_width_percent(-speed) else: A1.low() # stop A2.low()
def tempe(): adc=ADC(Pin('X1')) level=float(adc.read()) volt=(level/4095)*3.3 resitor=(1500*volt)/(3.3-volt) tem=(0.0587*resitor-99.1176) print(tem)
def __init__(self, rtc): self.rtc = rtc # Try to access the SD card and make the new path try: self.sensor_file = "/sd/{0}".format(filename) f = open(self.sensor_file, 'r') f.close() print("INFO: Using SD card for data.") except: print("ERROR: cannot mount SD card, reverting to flash!") self.sensor_file = SENSOR_DATA print("Data filename = {0}".format(self.sensor_file)) # Setup the dictionary for each soil moisture sensor soil_moisture1 = { 'sensor': ADC(Pin('X19')), 'power': Pin('X20', Pin.OUT_PP), 'location': 'Green ceramic pot on top shelf', 'num': 1, } soil_moisture2 = { 'sensor': ADC(Pin('X20')), 'power': Pin('X21', Pin.OUT_PP), 'location': 'Fern on bottom shelf', 'num': 2, } # Setup a list for each sensor dictionary self.sensors = [soil_moisture1, soil_moisture2] # Setup the alarm to read the sensors self.alarm = pyb.millis() print("Plant Monitor class is ready...")
def __init__(self): #Defines the pins which the infrared sensors are connected to self.IR1 = Pin('X9', Pin.IN) self.IR2 = Pin('X10', Pin.IN) #sets up the timer self.tim = Timer(2, freq = 1000) #Defines the pins that motor A is connected to self.A1 = 'Y9' self.A2 = 'Y10' self.PWMA = 'X1' self.chanA = 1 self.motorA = Motor(self.A1, self.A2, self.PWMA, self.chanA, self.tim) #Defines the pins which motor B is connected to self.B1 = 'Y11' self.B2 = 'Y12' self.PWMB = 'X2' self.chanB = 2 self.motorB = Motor(self.B1, self.B2, self.PWMB, self.chanB, self.tim) #Initial speed of the robot self.speed = 50 #Initial state of the path self.pathBlocked = False #Defines the speed at which the robot rotate self.ROTATION_SPEED = 50 #The pin which is connected to the potentiometer self.pot = ADC(Pin('X8'))
def print_resistance(): adc = ADC(Pin('A2')) # Identify the pin to measure V2 V1 = 3.3 # Set V1 to 3.3 Volts since we're using the '3.3V' pin to power the circuit V2 = adc.read() / 1024.0 # Set V2 to the voltage measured by the A2 pin R1 = 220000 # Set R1 as the 220 KOhm resistor at the beginning of our circuit R2 = (V2 / (V1 - V2) ) * R1 # solve for the resistance of R2 (thermistor) using Ohm's Law print(V2, ' Volts, ', R2, ' Ohms')
class JoyStick: # expo formula # ouput =((EXPO*POW(input,3))+((1-EXPO)*input))*RATE # where input & output are on [-1,1] def __init__(self,xp,yp, pbp, pbFunc): # last arg is a pointer to the interrupt handler self.XPin = ADC(Pin(xp)) self.YPin = ADC(Pin(yp)) self.PBPin = Pin(pbp, Pin.IN, Pin.PULL_UP) self.maxAnalog = 4095 self.minAnalog = 0 self.maxOutput = 100 self.minOutput = -100 self.pinExpo = 25 self.onPB = pbFunc self.changeDelta = 400 # ms self.lastChangeTime = 0 # ms self._calibrateXY() def _calibrateXY(self): xSum = 0 ySum = 0 for i in range(100): xSum += self.XPin.read() ySum += self.YPin.read() self.X0 = round(xSum/100.0) self.Y0 = round(ySum/100.0) def checkPB(self): now = time.ticks_ms() if now-self.lastChangeTime > self.changeDelta: if not self.PBPin.value(): self.onPB() self.lastChangeTime = now def _read(self, x): pin = self.XPin V0 = self.X0 if not x: pin = self.YPin V0 = self.Y0 val = pin.read() if abs(val - V0) < self.pinExpo: return(0) return arduino_map(val,V0,self.maxAnalog,0,self.maxOutput) \ if val > self.X0 else \ arduino_map(val,self.minAnalog,V0,self.minOutput,0) def readX(self): return self._read(True) def readY(self): return self._read(False)
def check_joystick(): adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) J_sw = Pin('Y11', Pin.IN) while True: print('Vertical: ',adc_1.read(), 'Horizontal: ', adc_2.read(), 'Switch: ',J_sw.value()) pyb.delay(2000)
def find_initpoint(): adc = ADC("P6") # Must always be "P6". 获取灰度传感器的ADC引脚 location = (adc.read()) #获取灰度传感器传来的模拟量 OPENMV的模拟量最大值为4095 while location > 800: p_out_0.low() #低电平逆时针旋转 location = (adc.read()) print("location=%f" % location) p_out_0.high() #步进电机停止旋转
def __init__(self, pin): """pin may be name or pin object. It must be able to handle ADC input.""" if type(pin) == str: p = Pin(pin) elif type(pin) == Pin: p = pin else: raise Exception( "pin must be pin name or pyb.Pin able to support ADC") self._adc = ADC(p)
def main(): print("Started ..") slider = ADC(Pin('Y4')) # setup slider lcd = LCD() # setup LCD logo = Logo() # init Logo pos = slider.read() # get slider position lcd.clear() # Draw on LCD lcd.blit(logo.buf, logo.x, logo.y) lcd.text(pos, 0, 0) lcd.draw() print(pos) # write slider position
class Adc(): def __init__(self): self.adv = ADC(Pin('X11')) self.adc = ADC(Pin('X12')) self.adt = pyb.ADCAll(12) def read_ad(self): v = self.adv.read() c = self.adc.read() t = self.adt.read_core_temp() v = 100/4096*v c = 600/4096*c return ('%.2f' % v, '%.2f' % c, '%.2f' % t)
def start_continuous_measurement(measure_time=0, measure_interval=500, pin='X1', file_name=''): ''' start_continuous_measurement(measure_time = 0, measure_interval = 500, pin = 'X1', file_name = '') Start a continuous measurement of the connected peripheral, and saves the result as to a CSV file on the PyBoards drive, under the 'Results' folder. Press Ctrl+C to stop the measuring at any time. Parameters ---------- measure_time : int Upper limit for measurement's length, in miliseconds. Defaults to 0, which means an infinite measurement. measure_interval : int Time interval between two consecutive measurements, miliseconds. Defaults to 500. pin : str Name of the pin connected to your connected peripheral. Defaults to X1. file_name : str Name for the saved file. Will be concatenated to the current CPU clock as file name to avoid possible duplicates and data loss. Returns ------- None ''' link = open( './Results/' + pin + file_name + '_' + str(time.ticks_ms()) + '.csv', 'w') adc = ADC(Pin(pin)) if measure_time == 0: while True: try: cur = adc.read() link.write(str(measure_time) + ',' + str(cur) + '\n') cls() print(cur) delay(measure_interval) measure_time += measure_interval except KeyboardInterrupt: print('Measurment stopped') link.close() break else: for i in range(0, measure_time, measure_interval): cur = adc.read() link.write(str(i) + ',' + str(cur) + '\n') cls() print(cur) delay(measure_interval) link.close() print('Measurment finished')
def Init(): # Power Power.bat24v = Pin('Y11', Pin.OUT) Power.dc24_bat24 = Pin('Y12', Pin.OUT) Power.dc_v = ADC('X3') Power.battery_v = ADC('X4') Power.dc_c = ADC('X5') Power.main_pump_c = ADC('X7') Power.skim_pump_c = ADC('X6') # ADC all object Power.adc = ADCAll(12, 0x70000) Power.check_ticks_ms = 0
class SlopeLeader(object): def __init__(self): self.adc = ADC(Pin('rINC')) self._timer = Timer(7, freq=100) self._buffer = bytearray(10) def read(self): self.adc.read_timed(self._buffer, self._timer) # resolution 256 value = sum(self._buffer) // len(self._buffer) slope = value / 256 # ratio to cover return slope def off(self): #value = self.read() #print('slope=', value) return True if self.read() <= 0.1 else False
class EC(object): def __init__(self, temperature=25, logger=None): # SET UP adc and set temp compensation self._adc = ADC(Pin.board.X5) self._temp = temperature self._tempCoeff = self.tempCoeff() def get(self): volts = ((self._adc.read() / adc_range) * in_voltage) coef_volt = volts / self._tempCoeff if coef_volt < 150: # No solution return 0 elif coef_volt > 3300: return 0 if coef_volt <= 448: ec_cur = 6.84 * coef_volt - 64.32 elif coef_volt <= 1457: ec_cur = 6.98 * coef_volt - 127 else: ec_cur = 5.3 * coef_volt + 2278 ec_cur = ec_cur / 1000 # convert us/cm to ms/cm return ec_cur def tempCoeff(self): return 1.0 + 0.0185 * (self._temp - 25.0)
class Sonar: """Sonar library""" MIN_DISTANCE = 50 MAX_DISTANCE = 600 def __init__(self, debug=False, out_pin='X11'): self.out_pin = ADC(Pin(out_pin)) self.debug = debug def get_distance(self): value = self.out_pin.read() result = round(1024 * value / 5000) - self.MIN_DISTANCE if (0 > result): result = 0 if True == self.debug: print('value', value) print('distance', result) return result def get_distance_cm(self): return round(self.get_distance() / 10, 2) def is_see_board(self): return (self.MAX_DISTANCE > self.get_distance())
class SplitPot: def __init__(self,pinName,mapRange,nbSplits=2,cutOff=5): self.adc = ADC(pinName) self.nbRanges = nbSplits self.ranges = getRanges(nbSplits,cutOff) self.mappers = [RMap(r,mapRange,True) for r in self.ranges] def update(self,avgNum=5): """ returns a tuple(range,value) if reading is ok, or None if not uses a rolling average to smooth the results """ res = None vADC = 0 for i in range(avgNum): vADC += self.adc.read() delay(1) vADC /=avgNum for i in range(self.nbRanges): if vADC in range(self.ranges[i][0],self.ranges[i][1]): res = (i,self.mappers[i].v(vADC)) return res def test(self): """ a little test routine that will conitnually read the pot and print the values """ try: while True: v = self.update() if v!=None: print (v) except KeyboardInterrupt: print('Done')
def __init__(self,xp,yp, pbp, pbFunc): # last arg is a pointer to the interrupt handler self.XPin = ADC(Pin(xp)) self.YPin = ADC(Pin(yp)) self.PBPin = Pin(pbp, Pin.IN, Pin.PULL_UP) self.maxAnalog = 4095 self.minAnalog = 0 self.maxOutput = 100 self.minOutput = -100 self.pinExpo = 25 self.onPB = pbFunc self.changeDelta = 400 # ms self.lastChangeTime = 0 # ms self._calibrateXY()
class IRDistance(object): """ Driver for Sharp Gp2y0a IR distance sensor. The distance range is around 3 to 40 inches. """ maxinches = 31.5 #Maximun range of IR board in inches. _v2i = -1.02 #Voltage to inches power. def __init__( self, pin ) : """pin may be name or pin object. It must be able to handle ADC input.""" if type(pin) == str: p = Pin(pin) elif type(pin) == Pin: p = pin else: raise Exception("pin must be pin name or pyb.Pin able to support ADC") self._adc = ADC(p) @property def distance( self ) : return self._adc.read() @property def inches( self ) : volts = self.distance * 0.0048828125 return 65.0 * pow(volts, IRDistance._v2i) @property def centimeters( self ) : return self.inches * 2.54
class GroveAirQuality(object): def __init__(self, pin): self.adc = ADC(pin) @property def value(self): return self.adc.read() / 4096 * 1024
def __init__(self, directionPinA, directionPinB, pwmPin, encoderNumber=None, cs=None, max_speed=127): """ Parameters ---------- directionPinA : Pin name, pyb.Pin, e.g. pyb.Pin.board.Y7 directionPinB : pyb.Pin, e.g. pyb.Pin.board.Y7 pwmPin : pyb.Pin, e.g. pyb.Pin.board.Y7 encoderNumber : cs : pyb.Pin, e.g. pyb.Pin.board.Y7 max_speed : int """ self.directionPinA = Pin(directionPinA, Pin.OUT) self.directionPinB = Pin(directionPinB, Pin.OUT) self.pwm = PWM(pwmPin) self.directionFactor = 1 #self.directSetSpeed(0) #self.set_speed(0) #self.encoder = pyb.Encoder(encoderNumber) self.encoderLastCount = 0 self.desiredSpeed = 0 self.cs = cs self.cs_adc = ADC(self.cs) self.max_speed = max_speed self.direct_set_speed(0)
class LaserBeam: def __init__(self, laser_pinname, photodiode_pinname): self.laser = Pin(laser_pinname, Pin.OUT_OD) self.photodiode = ADC(photodiode_pinname) self.threshold = 100 def ping(self): dark = self.photodiode.read() self.laser.value(0) # pull down to on light = self.photodiode.read() self.laser.value(1) # float to off return light-dark def interrupted(self): return self.ping() < self.threshold \ and sum(self.ping() for i in range(10)) < 10 * self.threshold
class LaserBeam: def __init__(self, laser_pinname, photodiode_pinname): self.laser = Pin(laser_pinname, Pin.OUT_OD) self.photodiode = ADC(photodiode_pinname) self.threshold = 100 def ping(self): dark = self.photodiode.read() self.laser.value(0) # pull down to on light = self.photodiode.read() self.laser.value(1) # float to off return light - dark def interrupted(self): return self.ping() < self.threshold \ and sum(self.ping() for i in range(10)) < 10 * self.threshold
class IRDistance(object): """ Driver for Sharp Gp2y0a IR distance sensor. The distance range is around 3 to 40 inches. """ maxinches = 31.5 #Maximun range of IR board in inches. _v2i = -1.02 #Voltage to inches power. def __init__(self, pin): """pin may be name or pin object. It must be able to handle ADC input.""" if type(pin) == str: p = Pin(pin) elif type(pin) == Pin: p = pin else: raise Exception( "pin must be pin name or pyb.Pin able to support ADC") self._adc = ADC(p) @property def distance(self): return self._adc.read() @property def inches(self): volts = self.distance * 0.0048828125 return 65.0 * pow(volts, IRDistance._v2i) @property def centimeters(self): return self.inches * 2.54
class irdistance(object): """ Driver for Sharp Gp2y0a IR distance sensor. The distance range is around 3 to 40 inches. """ def __init__(self, pin): """pin may be name or pin object. It must be able to handle ADC input.""" if type(pin) == str: p = Pin(pin) elif type(pin) == Pin: p = pin else: raise Exception( "pin must be pin name or pyb.Pin able to support ADC") self._adc = ADC(p) @property def distance(self): return self._adc.read() @property def inches(self): #distance / 204.8? Why? volts = self.distance * 0.0048828125 #inches = v^-1.02. return 65.0 * pow(volts, -1.02) @property def centimeters(self): return self.inches * 2.54
def main(): """ The method that controls everything. Initialization procedure: 1: Wait for bytes from PC are specifically 'start' 1a: Dim the indicator light 2: Write the array of pins, `pin_strings`, so that the PC knows what it's working with """ # Objects usb = VCP() # Initial while True: read = usb.read_timeout(inf) if read == 'start': usb.write_encode('start') break # Object manipulation indicator_light.intensity(32) # dim the indicator light # Writes usb.write_encode(pin_strings) # Reads timer_frequency = int(usb.verify_read(inf)) # Post init variables pins = tuple(Pin(i) for i in pin_strings) adc_pins = tuple(ADC(p) for p in pins) adc_arrays = tuple(array('H', [0]) for j in adc_pins) timer = Timer(8, freq=timer_frequency) # Loop while True: start_time = millis() ADC.read_timed_multi(adc_pins, adc_arrays, timer) if usb.read_timeout(1) == 'kill': hard_reset() write_table = {} usb.write_encode('newset\n') for i, v in enumerate(adc_arrays): usb.write_encode('\'{pin}\': {value}\n'.format(pin=pin_strings[i], value=v[0])) #write_table[pin_strings[i]] = v[0] usb.write_encode('endset\n') write_table['duration'] = elapsed_millis(start_time)
def remote(): #initialise UART communication uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2) # define various I/O pins for ADC adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) # set up motor with PWM and timer control A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) pwm_out = Pin('X1') tim = Timer(2, freq = 1000) motor = tim.channel(1, Timer.PWM, pin = pwm_out) # Motor in idle state A1.high() A2.high() speed = 0 DEADZONE = 5 # Use keypad U and D keys to control speed while True: # loop forever until CTRL-C while (uart.any()!=10): #wait we get 10 chars n = uart.any() command = uart.read(10) if command[2]==ord('5'): if speed < 96: speed = speed + 5 print(speed) elif command[2]==ord('6'): if speed > - 96: speed = speed - 5 print(speed) if (speed >= DEADZONE): # forward A1.high() A2.low() motor.pulse_width_percent(speed) elif (speed <= -DEADZONE): A1.low() # backward A2.high() motor.pulse_width_percent(-speed) else: A1.low() # idle A2.low()
def __init__(self): self.ultrasonic_sensor = ADC(Pin("X4")) self.hall_sensor = Pin("X6", Pin.IN) self.pot = ADC(Pin("X8")) self.ring = WS2812(spi_bus=2, led_count=15) self.red = Colour(1, 0, 0) self.green = Colour(0.4, 1, 0) self.purple = Colour(0.4, 0, 1) self.off = Colour(0, 0, 0) self.magnet_detected = self.green self.ultrasound_detected = self.purple self.colour = self.red self.HISTORY_DEPTH = 15 self.history = [0 for i in range(self.HISTORY_DEPTH)] self.i = 0
class Mic: def __init__(self, mic_pinname, timer_id=6): self.mic = ADC(mic_pinname) self.tim = Timer(timer_id, freq=48000) self.samples = array.array('h', range(4800)) self.normalized_spl = 0.0 def level(self): samples = self.samples self.mic.read_timed(samples, self.tim) ave = sum(samples) / len(samples) self.normalized_spl = \ min(1.0, sum((v-ave)**2 for v in samples) / len(samples) / 2278619.0) return self.normalized_spl def excited(self): return self.level() > 0.01
class ZZSGTHC: def __init__(self, adcPin): self.adc = ADC(Pin(adcPin)) def getSoilMoisture(self): voltage = self.adc.read() moisture = voltage * 2 / 100 return round(moisture, 2)
def adc_setstate(state): #assert(state == 'SingleDMA' or state == "TripleDMA" or state == "Single" or state =="NONE") global ADC_STATE if state != ADC_STATE: ADC_STATE = state global adc adc.deinit_setup() adc = ADC(adcpin, state) else: print("ADC STATE UNCHANGED")
def calibrate(): global calibint global count global calibadc count = 0 # reset counter adc_setstate("Single") # set state of adc obj to mode Single calibadc = ADC(calibpin, "Single") # init the second ADC in mode Single calibint.enable() utime.sleep(10) # 10s of calibration calibint.disable()
class GroveTemp(object): def __init__(self, pin): self.adc = ADC(pin) def value(self): val = self.adc.read() R = 4095/val-1.0 R = R0*R temperature = 1.0/(math.log10(R/R0)/B+1/298.15)-273.15 return temperature
def init(cls): cls._gps = Pin('X5', mode=Pin.OUT_PP, pull=Pin.PULL_DOWN) cls._gsm = Pin('X6', mode=Pin.OUT_PP, pull=Pin.PULL_DOWN) cls._gps.value(True) cls._gsm.value(True) cls._red = LED(1) cls._blue = LED(4) cls._batt = ADC('X7') # create an analog object from a pin
class GroveSPL(object): def __init__(self, pin): self.adc = ADC(pin) def value(self): val = 0 for i in range (100): val = val + self.adc.read() val = val / 100 return val
class Mode: def __init__(self): self.ultrasonic_sensor = ADC(Pin("X4")) self.hall_sensor = Pin("X6", Pin.IN) self.pot = ADC(Pin("X8")) self.ring = WS2812(spi_bus=2, led_count=15) self.red = Colour(1, 0, 0) self.green = Colour(0.4, 1, 0) self.purple = Colour(0.4, 0, 1) self.off = Colour(0, 0, 0) self.magnet_detected = self.green self.ultrasound_detected = self.purple self.colour = self.red self.HISTORY_DEPTH = 15 self.history = [0 for i in range(self.HISTORY_DEPTH) ] #stores the last few values recorded self.i = 0 def loop(self): self.i += 1 #increase the pointer by one self.i = self.i % self.HISTORY_DEPTH #ensure that the pointer loops back to 0 when it reaches the end of the list if self.ultrasonic_sensor.read( ) > 2800: #2700 is the threshold voltage, we found the value generally only exceeds 2600 if the ultrasonic sensor is nearby self.history[ self. i] = 1 #adds a 1 / True value to the history as the sensor has detected ultrasound else: self.history[ self. i] = 0 #adds a 0 / False value as the sensor hasn't detected ultrasound #calculates the number of times the ultrasound has been triggered within the alloted time self.total = 0 for x in self.history: self.total += x #if it's greater than one assume that an ultrasound has been detected #however the brightness of the LEDs can reflect the certainty (the more time's it has been triggered within the time, the more certain we are) if self.total > 0: self.colour = self.ultrasound_detected self.colour.brightness = self.total / self.HISTORY_DEPTH * 125 #the certainty is reflected in the brightness of the LEDs #checks to see if the hall sensor value elif not self.hall_sensor.value(): self.colour = self.magnet_detected self.colour.brightness = 100 else: self.colour = self.off self.data = [(self.colour.R, self.colour.G, self.colour.B) for i in range(15)] self.ring.show(self.data) def __repr__(self): return 'task_two'
def __init__(self,pin,rm=None): """ instance creation, args: * pin is a pyb.Pin object as per: pyb.Pin('X1', pyb.Pin.ANALOG) * an optional RMap instance to provide a reading in the proper range """ self.a = ADC(pin) if rm: self.v = lambda x: rm.v(x) else: self.v = lambda x:x
def __init__(self): self.tim = Timer(2, freq=1000) self.A1 = 'X7' self.A2 = 'X8' self.PWMA = 'X2' self.chanA = 2 self.motorA = Motor(self.A1, self.A2, self.PWMA, self.chanA, self.tim) self.B1 = 'X4' self.B2 = 'X3' self.PWMB = 'X1' self.chanB = 1 self.motorB = Motor(self.B1, self.B2, self.PWMB, self.chanB, self.tim) self.speed = 50 self.ROTATION_SPEED = 50 self.pot = ADC(Pin('X11'))
def __init__( self, pin ) : """pin may be name or pin object. It must be able to handle ADC input.""" if type(pin) == str: p = Pin(pin) elif type(pin) == Pin: p = pin else: raise Exception("pin must be pin name or pyb.Pin able to support ADC") self._adc = ADC(p)
def lightLevel(): adc=ADC(Pin('X1')) level=float(adc.read()) volt=(level/4095)*3.3 resitor=(1500*volt)/(3.3-volt) tem=(0.0587*resitor-99.1176) i2c = I2C(1) i2c.init(I2C.MASTER, baudrate=10000) i2c.send(0x43, addr=0x39) channel0_data = i2c.recv(1, addr=0x39)[0] i2c.send(0x83, addr=0x39) channel1_data = i2c.recv(1, addr=0x39)[0] if (channel0_data&0x80>0) and (channel1_data&0x80>0): chord0=cho(channel0_data) step0=ste(channel0_data) chord1=cho(channel1_data) step1=ste(channel1_data) #print(chord0,chord1,step0,step1) cho0_count=adc_value(chord0,step0) cho1_count=adc_value(chord1,step1) level=light(cho0_count,cho1_count) print(level,tem)
class VoltageDividerPot: def __init__(self,pin,rm=None): """ instance creation, args: * pin is a pyb.Pin object as per: pyb.Pin('X1', pyb.Pin.ANALOG) * an optional RMap instance to provide a reading in the proper range """ self.a = ADC(pin) if rm: self.v = lambda x: rm.v(x) else: self.v = lambda x:x def update(self): """ returns the current reading as per config """ return self.v(self.a.read())
def __init__(self,pinName,id,q,isToneRange=False,outputRangeTuple=(0,5),cutOff=30,spacing=30): #bMgr, """ Create an instance: * pinName is used for the creation of the ADC, be sure to use a pin with an ADC! * outputRangeTuple is the range for output values after conversion & mapping * cutOff is the analog reading below wich a reading is considered NOISE, and is thus ignored * spacing is the number of readings between the 2 pots * if isToneRange, then the first range is reduced to length of 0 """ self.q = q self.adc = ADC(pinName) self.id = id self.cutOff = cutOff self.ranges = [(cutOff,cutOff+1 if isToneRange else 2048-round(spacing/2.0)), (2048+round(spacing/2.0),4095-cutOff)] self.rMaps = [RMap(r,outputRangeTuple,True) for r in self.ranges] self.isToneRange = isToneRange self.tracking = False self.update = self.noTrackingUpdate self.track(False)
def __init__(self, mic_pinname, timer_id=6): self.mic = ADC(mic_pinname) self.tim = Timer(timer_id, freq=48000) self.samples = array.array('h', range(4800)) self.normalized_spl = 0.0
from pyb import Pin, ADC, UART, I2C, DAC import char_lcd import time import math import binascii import pyb from light import lightvalue print ("kek") #Define sensors tempsensor = ADC(Pin('X1')) motionsensor = Pin('Y12', Pin.IN, Pin.PULL_UP) beeper = DAC(1) waterportion = Pin('X11', Pin.OUT_PP) doortrigger = Pin('Y7', Pin.IN, Pin.PULL_UP) doortrigger2 = Pin('Y8', Pin.IN, Pin.PULL_UP) #Define UART bus and I2C bus uart = UART(6, 115200) i2c = I2C(1, I2C.MASTER, baudrate = 9600) i2c2 = I2C(2, I2C.MASTER, baudrate = 9600) #Define LCD d = char_lcd.HD44780(i2c2) def changetemp(temp): #Convert the value the temperature sensor gives into celsius: URX = (temp / 4095) * 3.3
import pyb from pyb import Pin, Timer, ExtInt from pyb import LED from pyb import Pin, Timer, ADC, DAC, LED import time from oled_938 import OLED_938 from mpu6050 import MPU6050 from motor import DRIVE import micropython micropython.alloc_emergency_exception_buf(100) pot = ADC(Pin('X11')) oled = OLED_938(pinout={'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8'}, height=64, external_vcc=False, i2c_devid=61) oled.poweron() oled.init_display() oled.draw_text(0,0, 'Group 8') oled.draw_text(0, 10, 'Milestone 3: Balencing') oled.draw_text(0, 20, 'Press USR button') oled.display() print('Performing Milestone 3') print('Waiting for button press') trigger = pyb.Switch() # Create trigger switch object while not trigger(): # Wait for trigger press time.sleep(0.001) while trigger(): pass # Wait for release print('Button pressed - Running')
from pyb import ADC, Timer adct = ADC(16) # Temperature 930 -> 20C print(adct) adcv = ADC(17) # Voltage 1500 -> 3.3V print(adcv) # read single sample; 2.5V-5V is pass range val = adcv.read() assert val > 1000 and val < 2000 # timer for read_timed tim = Timer(5, freq=500) # read into bytearray buf = bytearray(b'\xff' * 50) adcv.read_timed(buf, tim) print(len(buf)) for i in buf: assert i > 50 and i < 150 # read into arrays with different element sizes import array arv = array.array('h', 25 * [0x7fff]) adcv.read_timed(arv, tim) print(len(arv)) for i in arv: assert i > 1000 and i < 2000 arv = array.array('i', 30 * [-1]) adcv.read_timed(arv, tim)
from pyb import ADC from pyb import Pin adc = ADC('X22') print(adc) adc.read() buf = bytearray(100) adc.read_timed(buf, 500)
# Read ADC Example # # This example shows how to read the ADC on your OpenMV Cam. import time from pyb import ADC adc = ADC("P6") # Must always be "P6". while(True): # The ADC has 12-bits of resolution for 4096 values. print("ADC = %fv" % ((adc.read() * 3.3) / 4095)) time.sleep(100)
# Task 4: Joystick Controlling the Motor # Author: BSG # Version 1.0 # 26 May 2016 print ('This is Test 4: Joystick Controlling the Motor') from pyb import Pin, Timer, ADC while True: pyb.delay(1) A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) A1.high() A2.low() motor = Pin('X1') tim = Timer(2, freq = 1000) ch = tim.channel(1, Timer.PWM, pin = motor) adc_1 = ADC(Pin('X19')) #vertical adc_2 = ADC(Pin('X20')) #horizontal J_sw = Pin('Y11', Pin.IN) #switch vertical = (int(adc_2.read()) / 1700)*100 ch.pulse_width_percent(vertical)
from pyb import ADC from pyb import Pin pin = Pin('X22', mode=Pin.IN, pull=Pin.PULL_DOWN) adc = ADC('X22') print(adc) # read single sample val = adc.read() assert val < 500 # read into bytearray buf = bytearray(50) adc.read_timed(buf, 500) print(len(buf)) for i in buf: assert i < 500 # read into arrays with different element sizes import array ar = array.array('h', 25 * [0]) adc.read_timed(ar, 500) print(len(ar)) for i in buf: assert i < 500 ar = array.array('i', 30 * [0]) adc.read_timed(ar, 500) print(len(ar)) for i in buf: assert i < 500
class SplitPot: """" This version only works for 2 pot split, reads the ADC 10 times over 10ms, and aborts if any of the values is out of scope! """ def __init__(self,pinName,id,q,isToneRange=False,outputRangeTuple=(0,5),cutOff=30,spacing=30): #bMgr, """ Create an instance: * pinName is used for the creation of the ADC, be sure to use a pin with an ADC! * outputRangeTuple is the range for output values after conversion & mapping * cutOff is the analog reading below wich a reading is considered NOISE, and is thus ignored * spacing is the number of readings between the 2 pots * if isToneRange, then the first range is reduced to length of 0 """ self.q = q self.adc = ADC(pinName) self.id = id self.cutOff = cutOff self.ranges = [(cutOff,cutOff+1 if isToneRange else 2048-round(spacing/2.0)), (2048+round(spacing/2.0),4095-cutOff)] self.rMaps = [RMap(r,outputRangeTuple,True) for r in self.ranges] self.isToneRange = isToneRange self.tracking = False self.update = self.noTrackingUpdate self.track(False) def isMaster(self): return (self.id == 0) def track(self,onOff): self.tracking = onOff if onOff: self.update = self.trackingUpdate self.enQV= [EnQueueable((EnQueueable.INC,EnQueueable.VOL),self.q), EnQueueable((EnQueueable.INC,EnQueueable.TONE),self.q)] else: self.update = self.noTrackingUpdate self.enQV= [EnQueueable((EnQueueable.VOL,),self.q), EnQueueable((EnQueueable.TONE,),self.q)] def poll(self): #if not self.bounceMgr.ready(): # return res = self.update() if res: #self.bounceMgr.trigger() irq_state = disable_irq() self.enQV[res[0]].push(self.id,res[1]) enable_irq(irq_state) def getTrackingRange(self,vADC): curRange = None # 2 splits if not ToneRange, only second split if ToneRange for i in range((1 if self.isToneRange else 0),2): if vADC >= self.ranges[i][0] and vADC<=self.ranges[i][1]: curRange=i break return curRange def inBounds(self,vADC): #print ('inBounds returning: ', (vADC >= self.cutOff and vADC <= self.ranges[1][1])) return (vADC >= self.cutOff and vADC <= self.ranges[1][1]) def trackingUpdate(self): """ This means we touch and hold, slide, then let go. The slide distance corresponds to the magnitude and sign of the desired dec/increment. To simplify, we dec/inc by +/- 0,1,2. The initial touch determines the choice of vol or tone. The slide can go beyond the mid line dead zone without being invalidated! Sadly, calling INC means that the microvaluator will interpret the value to be inced, so we have to multiply the inc by 10 !! vRead <- adc.read() rangeId <- computeRange(Vread) if rangeId != None: that means vRead is a value in a valid range vInit <- vRead vLast <- vInit else: return None while vRead >lowCutOff && vRead < highCutoff and the delta(vLast,vRead) is with 30% of vLast vLast <- vRead vRead <- adc.read() delta <- abs(vLast - vInit) sign <- 1 if vLast >= vInit else -1 # NO it's upside down! if delta < epsilon: # we have no tracked values return None else if delta > bigStep: return (rangeId,20*sign) else: return (rangeId, 10*sign) convert to +1 or -1 (or maybe even +/-2 if big difference bewteen vLast and vInit and add to present value?? return new value else: return None """ vInit = self.adc.read() rangeID = self.getTrackingRange(vInit) if rangeID == None: return vLast = vInit vRead = self.adc.read() #print('vInit: ', vInit) #print('rangeID: ', rangeID) #print('new vRead: ',vRead) while (self.inBounds(vRead) and abs(vRead-vLast) < State.splitPotTrackingPercentCutoff*vLast): vLast = vRead vRead = self.adc.read() delay(1) #print('final vRead: ', vRead) #print('final vLast: ', vLast) delta = abs(vLast-vInit) sign = -1 if vInit >= vLast else 1 #print('vInit: ', vInit, 'vLast: ',vLast) #print('delta: ', delta, 'sign: ', sign) #print('parametered Corrected! SplitPot ID: ',self.id) if self.isMaster(): sign *= State.splitPotMasterFactor # correct for microvaluation on master vol/tone! if delta < State.splitPotTrackingError: #print('return None') return None elif delta < State.splitPotTrackingBigStep: #print('return (',rangeID,sign*State.splitPotTrackingSmallMultiplier,')') return (rangeID,sign*State.splitPotTrackingSmallMultiplier) elif delta < 2*State.splitPotTrackingBigStep: #print('return (',rangeID,sign*State.splitPotTrackingBigMultiplier,')') return (rangeID,sign*State.splitPotTrackingBigMultiplier) else: # this is full vol/tone in one go! #print('return (',rangeID,sign*5,')') # State.splitPotTrackingBigMultiplier return (rangeID,sign*5) #State.splitPotTrackingBigMultiplier) def noTrackingUpdate(self): """ takes nbReadings reads, then avgs them and maps the result to the appropriate range and returns it. returns None if no valid value read """ nbReadings = State.splitPotNoTrackingNbReadings vADC = 0 for i in range(nbReadings): v=self.adc.read() if v<self.cutOff or (v>self.ranges[0][1] and v<self.ranges[1][0]) or v>self.ranges[1][1]: #print(v) return None vADC += v delay(1) vADC = round(vADC/nbReadings) #print(vADC) for i in range((1 if self.isToneRange else 0),2): # 2 splits if not ToneRange, only second split if ToneRange if vADC >= self.ranges[i][0] and vADC<=self.ranges[i][1]: #State.printT('VADC= ' +str(vADC) + " tuple: " +str((i,self.rMaps[i].v(vADC)))) return (i,self.rMaps[i].v(vADC))
from pyb import ADC from pyb import Pin pin = Pin('X22', mode=Pin.IN, pull=Pin.PULL_DOWN) adc = ADC('X22') print(adc) # read single sample val = adc.read() assert val < 500 # timer for read_timed tim = pyb.Timer(5, freq=500) # read into bytearray buf = bytearray(50) adc.read_timed(buf, tim) print(len(buf)) for i in buf: assert i < 500 # read into arrays with different element sizes import array ar = array.array('h', 25 * [0]) adc.read_timed(ar, tim) print(len(ar)) for i in buf: assert i < 500 ar = array.array('i', 30 * [0]) adc.read_timed(ar, tim) print(len(ar))
""" from pyb import ADC import os machine = os.uname().machine if "LaunchPad" in machine: adc_pin = "GP5" adc_channel = 3 elif "WiPy" in machine: adc_pin = "GP3" adc_channel = 1 else: raise Exception("Board not supported!") adc = ADC(0) print(adc) adc = ADC() print(adc) adc = ADC(0, bits=12) print(adc) apin = adc.channel(adc_channel) print(apin) apin = adc.channel(id=adc_channel) print(apin) apin = adc.channel(adc_channel, pin=adc_pin) print(apin) apin = adc.channel(id=adc_channel, pin=adc_pin) print(apin)
def __init__(self,pinName,mapRange,nbSplits=2,cutOff=5): self.adc = ADC(pinName) self.nbRanges = nbSplits self.ranges = getRanges(nbSplits,cutOff) self.mappers = [RMap(r,mapRange,True) for r in self.ranges]
def __init__(self, laser_pinname, photodiode_pinname): self.laser = Pin(laser_pinname, Pin.OUT_OD) self.photodiode = ADC(photodiode_pinname) self.threshold = 100