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()
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() #步进电机停止旋转
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')
class GroveAirQuality(object): def __init__(self, pin): self.adc = ADC(pin) @property def value(self): return self.adc.read() / 4096 * 1024
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)
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')
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. """ 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 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 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 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. """ 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
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 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 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
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'
class Robot(): def __init__(self): self.IR1 = Pin('X9', Pin.IN) self.IR2 = Pin('X10', Pin.IN) self.tim = Timer(2, freq=1000) 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) 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) self.speed = 50 self.ROTATION_SPEED = 50 self.pot = ADC(Pin('X8')) def moveForwards(self): self.motorA.forward() self.motorB.forward() def moveBackwards(self): self.motorA.backward() self.motorB.backward() def stop(self): self.motorA.stop() self.motorB.stop() def changeSpeed(self, s): self.motorA.speed = s self.motorB.speed = s def updateSpeed(self): self.s = (self.pot.read() / 4095) * 100 self.changeSpeed(self.s) def rotateLeft(self): self.changeSpeed(self.ROTATION_SPEED) self.motorA.backward() self.motorB.forward() def rotateRight(self): self.changeSpeed(self.ROTATION_SPEED) self.motorA.forward() self.motorB.backward()
class GP2Y0A02YK0F(): mapping = {'off': 4014} pin = None # Lower-level ADC-connection to the sensor height = None # Last checked height (ADC'ed) def __init__(self, config): self.pin = ADC(Pin(config['connected_pin'])) def read(self): self.height = self.pin.read() print(self.height)
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 LineDetector: """detect black line""" def __init__(self, pin, debug = False): self.out = ADC(Pin(pin)) self.debug = debug def raw(self): out = self.out.read() if self.debug: print(out) return out def is_path(self): out = self.raw() return out > 100
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)] self.i = 0 def loop(self): self.i += 1 self.i = self.i % self.HISTORY_DEPTH if self.ultrasonic_sensor.read() > 2800: self.history[self.i] = 1 else: self.history[self.i] = 0 self.total = 0 for x in self.history: self.total += x if self.total > 0: self.colour = self.ultrasound_detected self.colour.brightness = self.total / self.HISTORY_DEPTH * 125 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'
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())
class DCMotor: def __init__(self, tim_num, channel, frequency, pin): self.tim = Timer(tim_num, freq=frequency) self.pin = Pin(pin) self.channel = channel def set_control(self, in_a, in_b, en_a, en_b): self.INA = Pin(in_a, Pin.OUT_PP) self.INB = Pin(in_b, Pin.OUT_PP) self.ENA = Pin(en_a, Pin.OUT_PP) self.ENB = Pin(en_b, Pin.OUT_PP) self.ENA.high() self.ENB.high() def set_current_sense(self, cs, cs_dis): self.CS_DIS = Pin(cs_dis, Pin.OUT_PP) self.CS = Pin(cs, Pin.IN) self.current = ADC(self.CS) def get_current(self): return self.current.read() def set_duty_cycle(self, duty_cycle): self.tim.channel(self.channel, Timer.PWM, pin=self.pin, pulse_width_percent=duty_cycle) def forward(self): self.INA.low() self.INB.high() def reverse(self): self.INA.high() self.INB.low() def brake_gnd(self): self.INA.low() self.INB.low() def brake_vcc(self): self.INA.high() self.INB.high()
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)
def ltilaMittaus(): adc = ADC(Pin('X1')) tulos = adc.read() resistanssi = ((((tulos / 4095) * 3.3) * 1.78) / (3.3 - ((tulos / 4095) * 3.3)) * 1000) if (resistanssi < 1603): ltila = 0 elif (resistanssi >= 1603) and (resistanssi <= 1797): ltila = interpolointi(1797, 1603, 10, 0, resistanssi) elif (resistanssi > 1797) and (resistanssi <= 1944): ltila = interpolointi(1944, 1797, 20, 10, resistanssi) elif (resistanssi > 1944) and (resistanssi <= 2020): ltila = interpolointi(2020, 1944, 25, 20, resistanssi) elif (resistanssi > 2020) and (resistanssi <= 2102): ltila = interpolointi(2102, 2020, 30, 25, resistanssi) return ltila
class Turbidity(object): """ Turbidity meter """ def __init__(self): """ initialize the turbidity meter """ self._adc = ADC(Pin.board.X6) def get(self): """ returns the raw values of the turbidity meter :return: """ volts = ((self._adc.read() / adc_range) * in_voltage) return volts def NTU(self): volts = self.get() if volts <= 2.5: return 3000 return (-1120.4 * (volts**2)) + (5742.3 * volts) - 4352.9
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, Pin, ADCALL adc0 = ADC(Pin.board.A4) val = adc0.read() adc_all = ADCALL( 12, 0x60000 ) #0x60000: enable channal 17 (core tempture) and channel 18 (battery voltage) adc_all.read_core_temp() adc_all.read_core_vbat()
Name: Lab 4 Exercise 4 ----------------------------------------------------------- Learning to use rhe OLED deisplay driver ----------------------------------------------------------- ''' import pyb from pyb import LED, ADC, Pin # Pyboard basic library from oled_938 import OLED_938 # Use various class libraries in pyb # Create peripheral objects b_LED = LED(4) pot = ADC(Pin('X11')) # I2C connected to Y9, Y10 (I2C bus 2) and Y11 is reset low active oled = OLED_938(pinout = {'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8'}, height = 64, external_vcc = False, i2c_devid = 61) oled.poweron() oled.init_display() # Simple Hello world message oled.draw_text(0, 0, 'Hello, world!') # each character is 6x8 pixels tic = pyb.millis() # store starting time while True: b_LED.toggle() toc = pyb.millis() # read elapsed time oled.draw_text(0, 20, 'Delayed time:{:6.3f}sec'.format((toc-tic)*0.001)) oled.draw_text(0, 40, 'POT5K reading:{:5d}'.format(pot.read())) tic = pyb.millis() # start time oled.display() delay = pyb.rng()%1000 # Generate a random number btw 0 and 999 pyb.delay(delay) # Delay in milliseconds
''' 1.8 PWM ''' from pyb import Pin, Timer p = Pin('X1') tim = Timer(2, freq=1000) ch = Timer.channel(1, Timer.PWM, pin=p) ch.pulse_width_percent(50) ''' 1.9 ADC ''' from pyb import Pin, ADC adc = ADC(Pin('X19')) adc.read() # read value, 0 - 4095 ''' 1.10 DAC ''' from pyb import Pin, DAC dac = DAC(Pin('X5')) dac.write(120) # output between 0 and 255 ''' 1.11 UART ''' from pyb import UART uart1 = UART(1, 9600) uart1.write('hello') uart1.read(5) # read up to 5 bytes
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') # PID tuning pot = pyb.ADC(Pin('X11')) scale1 = 4 scale2 = 0.6 while not trigger(): # Wait to tune Kp time.sleep(0.001) K_p = pot.read() * scale1 / 4095 # Use potentiometer to set Kp oled.draw_text(0, 30, 'Kp = {:5.5f}'.format(K_p)) # Display live value on oled oled.display() while trigger(): pass while not trigger(): # Wait to tune Ki time.sleep(0.001) K_i = pot.read() * scale2 / 4095 # Use pot to set Ki oled.draw_text(0, 40, 'Ki = {:5.5f}'.format(K_i)) # Display live value on oled oled.display() while trigger(): pass while not trigger(): # Wait to tune Kd time.sleep(0.001) K_d = pot.read() * scale2 / 4095 # Use pot to set Ki oled.draw_text(0, 50, 'Kd = {:5.5f}'.format(K_d)) # Display live value on oled oled.display() while trigger(): pass
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)
p1 = Pin('X1') # X1 is rightMotor p3 = Pin('X3') # X3 is leftMotor tim = Timer(2, freq=1000) rightMotor = tim.channel(1, Timer.PWM, pin=p1) leftMotor = tim.channel(3, Timer.PWM, pin=p3) rightLineSensor = ADC(Pin('X5')) leftLineSensor = ADC(Pin('X6')) rightMotor.pulse_width_percent(0) leftMotor.pulse_width_percent(0) while (True): rightDetect = rightLineSensor.read() leftDetect = leftLineSensor.read() if (leftDetect > 1000 and rightDetect > 1000): rightMotor.pulse_width_percent(50) leftMotor.pulse_width_percent(50) if (leftDetect > 1000 and rightDetect < 1000): rightMotor.pulse_width_percent(10) if (leftDetect < 1000 and rightDetect > 1000): leftMotor.pulse_width_percent(10) if (leftDetect < 1000 and rightDetect < 1000): rightMotor.pulse_width_percent(0) leftMotor.pulse_width_percent(0)
if sensor == 0: #create a buffer containing a sine-wave buf = bytearray(100) for i in range(len(buf)): buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf))) #output the sine-wave at 400hz beeper.write_timed(buf, 400 * len(buf), mode = DAC.NORMAL) #Loop starts while True: #Read motionsensor value sensor = (motionsensor.value()) * 10 #Read temperature value temp = tempsensor.read() #Reaad light level value lightLevel = lightvalue(i2c) / 10 #Define doortrigger value trigger1 = doortrigger.value() trigger2 = doortrigger2.value() doortriggervalue = 10 * (trigger1 + trigger2) keypad() changetemp(temp) beep(beeper)
# 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 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)
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))