Exemple #1
0
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()		
Exemple #2
0
    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...")
Exemple #3
0
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)	
Exemple #4
0
    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
Exemple #5
0
    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)
Exemple #6
0
    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)

        #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)

        #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'))
Exemple #7
0
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
Exemple #9
0
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')
Exemple #10
0
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()  #步进电机停止旋转
Exemple #11
0
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()
Exemple #12
0
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 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
def main():
    pwm_timer = Timer(MOTOR_TIMER, freq=PWM_FREQ)

    ch1 = motorController(PIN_CH1, pwm_timer, 1)
    ch2 = motorController(PIN_CH2, pwm_timer, 2)

    adc = ADC(PIN_ADC)
    main_loop = loop(adc, ch1, ch2)

    event_timer = Timer(EVENT_TIMER, freq=1000)
    event_timer.freq(10)
    event_timer.callback(lambda t: next(main_loop))
Exemple #15
0
    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)
Exemple #16
0
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
Exemple #17
0
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')
Exemple #18
0
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)
Exemple #19
0
    def generate(self):
        '''
		generating entropy and initializing private key
		entropy both from RNG chip and analog-to-digital converters on board
		'''

        #creating entropy for private key
        entropy = urandom(32) + b'lsoeitgmmcnxgwt364495p5,5m5b4g3y344k3jhuri99'
        ADC_entropy = bytes(
            [ADC(choice(ADC_ops)).read() % 256 for i in range(2048)])
        self.key = ec.PrivateKey.parse(sha256(entropy + ADC_entropy).digest())

        #garbage collection to ensure the secrets are not in memory
        #FIXME: transition the private key to a bytearray for direct memory access
        del entropy
        del ADC_entropy
        collect()
def main():
    pwm_timer = Timer(MOTOR_TIMER, freq=PWM_FREQ)

    ch1 = motorController(PIN_CH1, pwm_timer, 1)
    ch2 = motorController(PIN_CH2, pwm_timer, 2)
    ch3 = motorController(PIN_CH3, pwm_timer, 3)
    ch4 = motorController(PIN_CH4, pwm_timer, 4)

    adc = ADC(PIN_ADC)

    pb_in = Pin(PIN_PB_H, Pin.IN, Pin.PULL_UP)
    pb_out = Pin(PIN_PB_L, Pin.OUT_PP)
    pb_out.low()

    main_loop = loop(adc, ch1, ch2, ch3, ch4, pb_in)

    event_timer = Timer(EVENT_TIMER, freq=1000)
    event_timer.freq(10)
    event_timer.callback(lambda t: next(main_loop))
Exemple #21
0
def boolean_measurment(pin='X1', threshold=2730):
    '''
boolean_measurment(pin = 'X1', threshold = 2730)

Parameters
----------
pin : str
	Name of the pin connected to your connected peripheral. Defaults to X1.
threshold : int
	Sets the voltage threshold for returning 1 (==True). Defaults to 2730, which is 2/3 of the max voltage (4095).
Returns
-------
int : Current value of selected pin.
'''
    device = ADC(Pin(pin)).read()
    if device > threshold:
        return 1
    else:
        return 0
Exemple #22
0
 def __init__(self):
     self.vd = ADC(Pin(Pin.cpu.A2))
     self.servo = Servo(4)
     self.curr_angle = self.center_angle = 48
     self.f2b = 0
     self.r1 = Pin(Pin.cpu.C4, Pin.OUT)
     self.r2 = Pin(Pin.cpu.A4, Pin.OUT)
     self.t2 = Timer(2, freq=1000)
     self.l = self.t2.channel(2, Timer.PWM, pin=Pin(Pin.cpu.B3))
     self.l1 = Pin(Pin.cpu.B9, Pin.OUT)
     self.l2 = Pin(Pin.cpu.B0, Pin.OUT)
     self.t8 = Timer(8, freq=1000)
     self.r = self.t8.channel(3, Timer.PWM_INVERTED, pin=Pin(Pin.cpu.B15))
     self.lv = 0
     self.rv = 0
     self.v = 25
     self.countR = self.countL = 0
     self.turn(self.center_angle)
     self.dinit_encoder()
     self.init_encoder()
Exemple #23
0
    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'))
Exemple #24
0
def pins_test():
    i2c = I2C(1, I2C.MASTER)
    spi = SPI(2, SPI.MASTER)
    uart = UART(3, 9600)
    servo = Servo(1)
    adc = ADC(Pin.board.X3)
    dac = DAC(1)
    pin = Pin('X4', mode=Pin.AF_PP, af=Pin.AF3_TIM9)
    pin = Pin('Y1', mode=Pin.AF_OD, af=3)
    pin = Pin('Y2', mode=Pin.OUT_PP)
    pin = Pin('Y3', mode=Pin.OUT_OD, pull=Pin.PULL_UP)
    pin.high()
    pin = Pin('Y4', mode=Pin.OUT_OD, pull=Pin.PULL_DOWN)
    pin.high()
    pin = Pin('X18', mode=Pin.IN, pull=Pin.PULL_NONE)
    pin = Pin('X19', mode=Pin.IN, pull=Pin.PULL_UP)
    pin = Pin('X20', mode=Pin.IN, pull=Pin.PULL_DOWN)
    print('===== output of pins() =====')
    pins()
    print('===== output of af() =====')
    af()
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
Exemple #26
0
    def __init__(self):
        self.btn = Pin("Y8",Pin.IN,Pin.PULL_UP)
        self.water_adc = ADC(Pin.cpu.C4)
        self.accel = pyb.Accel()
        self.nbiot = NBIOT(3,9600,1,1)

        self.btn_state = 1
        self.accel_state = 0
        self.accel_thres = -11
        self.sonic_thres = 0

        self.real_time_delay = 0
        self.time_regular = 1
        self.reconnect_duration = 20
        self.reconnect_count = 3

        self.alter_ip1 = 0
        self.alter_ip2 = 0
        self.alter_ip3 = 0
        self.alter_ip4 = 0
        self.id_number = '00000058'

        self.export_id()
Exemple #27
0
    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'))
Exemple #28
0
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()
Exemple #29
0
'''
-----------------------------------------------------------
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()
Exemple #30
0
time.callback(lambda t: pyb.LED(1).toggle())
'''
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')