def __init__(self, **kwargs):
        """Initialize Valve.

        If there is an error connecting to the external DAC,
        And if user agrees, sets self.dac to use SimDac class.
        Otherwise raises Exception.

        Sets all initial volts values to calibrated off of 45.

        Requires no external arguments.
        Contains **kwargs to pass kywd=arg pairs down MRO chain.
        """
        super().__init__(**kwargs)

        if BOARD:
            self.__i2c = busio.I2C(board.SCL, board.SDA)
            self.dac = adafruit_mcp4725.MCP4725(self.__i2c)
        elif input('Use simulated DAC?\n(Y/N) = ').upper() == 'Y':
            print()
            self.dac = SimDac()
        else:
            raise Exception("No DAC or unsupported DAC connected.")

        self.volts = self.clog_volts = self.__optimal_volts = 45

        self.__latency = time.time()
        self.__time_open = 0
        self.clogged = False

        print(":: VALVE INITIALIZED ::\n")
예제 #2
0
    def setup_output(self):
        import adafruit_mcp4725
        from adafruit_extended_bus import ExtendedI2C

        self.setup_output_variables(OUTPUT_INFORMATION)

        try:
            self.dac = adafruit_mcp4725.MCP4725(
                ExtendedI2C(self.output.i2c_bus),
                address=int(str(self.output.i2c_location), 16))

            self.channel = {0: self.dac.channel_a}

            # Channel A
            if self.options_channels['vref'][0] == "internal":
                self.channel[0].vref = adafruit_mcp4728.Vref.INTERNAL
            else:
                self.channel[0].vref = adafruit_mcp4728.Vref.VDD
            self.channel[0].gain = self.options_channels['gain'][0]
            if (self.options_channels['state_start'][0] == "value"
                    and self.options_channels['state_start_value'][0]):
                self.channel[0].value = int(
                    65535 * (self.options_channels['state_start_value'][0] /
                             self.vref))

            self.dac.save_settings()

            self.output_setup = True
        except:
            self.output_setup = False
예제 #3
0
파일: hardware.py 프로젝트: sonoptic/lab
    def __init__(self):
        self.IMU_ADDRESS = 0x29
        self.DRV_ADDRESS = 0x5A
        self.METER_ADDRESS = '0x40'
        self.DACL_ADDRESS = 0x62
        self.DACR_ADDRESS = 0x63

        self.i2c = busio.I2C(board.SCL, board.SDA)
        devices = self.scan_bus()
        print(devices)
        if len(devices) == 0: print('* No I/O device found')

        if str(self.IMU_ADDRESS) in devices:
            print('* Motion sensor detected')
            self.motion = adafruit_bno055.BNO055_I2C(self.i2c,
                                                     self.IMU_ADDRESS)
        else:
            self.motion = None

        if str(self.DRV_ADDRESS) in devices:
            haptic = adafruit_drv2605.DRV2605(self.i2c, self.DRV_ADDRESS)
            haptic.mode(0x03)  # Analog/PWM Mode
            haptic.use_LRM()
            print('* Haptic driver detected (and set to analog mode)')
        else:
            self.haptic = None

        if str(self.METER_ADDRESS) in devices:
            self.meter = INA219(0.1, 3)
            self.meter.configure(self.meter.RANGE_16V)
            print('* Current sensor detected')
        else:
            self.meter = None

        if str(self.DACL_ADDRESS) in devices:
            self.leftDAC = adafruit_mcp4725.MCP4725(self.i2c,
                                                    self.DACL_ADDRESS)
            print('* Left DAC detected')
        else:
            self.leftDAC = None

        if str(self.DACL_ADDRESS) in devices:
            self.rightDAC = adafruit_mcp4725.MCP4725(self.i2c,
                                                     self.DACR_ADDRESS)
            print('* Left DAC detected')
        else:
            self.rightDAC = None
예제 #4
0
 def __init__(self):
     """Sonicator init."""
     self.i2c = busio.I2C(board.SCL, board.SDA)
     self.dac = adafruit_mcp4725.MCP4725(self.i2c, address=0x60)
     self.sonicator_enable = digitalio.DigitalInOut(board.D4)
     self.sonicator_enable.direction = digitalio.Direction.OUTPUT
     self.sonicator_enable.value = False
     self.dac.normalized_value = 0.0
예제 #5
0
def init_mcp4725():
    global i2c, dac
    import board
    import busio
    import adafruit_mcp4725

    i2c = busio.I2C(board.SCL, board.SDA)
    dac = adafruit_mcp4725.MCP4725(i2c)
    set_voltage(0)
예제 #6
0
def setup_rpi(registry):
    from controller.device import SwimPumpDevice, TempSensorDevice, TankSensorDevice
    from controller.device import ArduinoDevice, EZOSensorDevice, LcdDevice

    # Relay
    import RPi.GPIO as GPIO
    setup_gpio(registry, GPIO)

    # Initialize I2C bus.
    import board
    import busio
    i2c = busio.I2C(board.SCL, board.SDA)

    # ADC
    import adafruit_ads1x15.ads1015 as ADS
    # Create the ADC object using the I2C bus
    adc = ADS.ADS1015(i2c)
    # With a gain of 2/3 and a sensor output of 0.25V-5V, the values should be around 83 and 1665
    params = ((int, "channel"), (float, "gain"), (int, "low"), (int, "high"))
    registry.add_sensor(
        TankSensorDevice("tank", adc,
                         *[t(config["adc", n]) for t, n in params]))

    # DAC
    import adafruit_mcp4725
    dac = adafruit_mcp4725.MCP4725(i2c)
    registry.add_pump(
        SwimPumpDevice("swim", GPIO, int(config["pins", "swim"]), dac))

    # pH, ORP
    registry.add_sensor(EZOSensorDevice("ph", config["serial", "ph"]))
    registry.add_sensor(EZOSensorDevice("orp", config["serial", "orp"]))

    # Arduino (cover, water)
    registry.add_device(ArduinoDevice("arduino", config["serial", "arduino"]))

    # LCD
    registry.add_device(LcdDevice("lcd", config["serial", "lcd"]))

    # 1-wire
    # 28-031634d04aff
    # 28-0416350909ff
    # 28-031634d54bff
    # 28-041635088bff
    registry.add_sensor(
        TempSensorDevice("temperature_pool", config["1-wire", "pool"]))
    registry.add_sensor(
        TempSensorDevice("temperature_air", config["1-wire", "air"]))
    registry.add_sensor(
        TempSensorDevice("temperature_local", config["1-wire", "local"]))
    registry.add_sensor(
        TempSensorDevice("temperature_ncc", config["1-wire", "ncc"]))
예제 #7
0
	def __init__(self,GUI_hvac_Ref):
		#init de sensores y dac
		self.GUI_hvac_Ref = GUI_hvac_Ref
		self.TaskControlTemp = threading.Thread(target = self.ControlTemp_Routine)
		
		self.spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
		self.cs = digitalio.DigitalInOut(board.D10)
		self.max31855 = adafruit_max31855.MAX31855(self.spi, self.cs)
		
		self.Relay = digitalio.DigitalInOut(board.D13)
		self.Relay.direction = digitalio.Direction.OUTPUT
		
		self.i2c = busio.I2C(board.SCL, board.SDA)
		self.dac = adafruit_mcp4725.MCP4725(self.i2c, address = 0x60)
		
		self.TaskControlTemp.start()
		pass
예제 #8
0
    def __init__(self, i2c, gps: UBX):

        # Drive Controller (Millipak) Digital Pins
        self.forward = DIO.DigitalInOut(board.D16)  # D3
        self.reverse = DIO.DigitalInOut(board.D26)  # D4
        self.fs1 = DIO.DigitalInOut(board.D19)  # D5
        self.seat = DIO.DigitalInOut(board.D13)  # D6
        self.power = DIO.DigitalInOut(board.D6)  # D7

        # Set as outputs
        self.forward.direction = DIO.Direction.OUTPUT
        self.reverse.direction = DIO.Direction.OUTPUT
        self.fs1.direction = DIO.Direction.OUTPUT
        self.seat.direction = DIO.Direction.OUTPUT
        self.power.direction = DIO.Direction.OUTPUT

        # I2C and ADC Setup

        self._i2c_interface = i2c

        # Setup Drive Speed DAC
        self.dac_output = DAC.MCP4725(self._i2c_interface, address=96)

        # Speed
        self._measured_speed = 0.
        self._speed_set_point = 0.

        # Speed PID Controller
        self._prev_error = 0.
        self.p_gain = 0.5
        self.d_gain = 1
        self._output_voltage = 0.
        self._max_output_voltage = 1.

        # GPS
        self._gps = gps

        # Threading
        self._speed_thread = None
        self._stop_threads = False

        # Set DAC Output to 0V
        self.dac_output.value = 0
예제 #9
0
import mido
import adafruit_mcp4725
import board
import busio

i2c_1 = busio.I2C(board.SCL, board.SDA)
#i2c_2 = busio.I2C(24, 23)

dac_PITCH = adafruit_mcp4725.MCP4725(i2c_1, address=0x60)
dac_HOLD = adafruit_mcp4725.MCP4725(i2c_1, address=0x61)
#dac_MOD = adafruit_mcp4725.MCP4725(i2c_2, address= 0x60)
#dac_TRIG = adafruit_mcp4725.MCP4725(i2c_2, address= 0x61)

from midi_handler import *
from port_manager import *

p = PortManager()
m = MidiHandler()

try:
    while True:
        if not p.is_scanning:
            with mido.open_input(p.input_name) as port:
                while not port.closed:
                    for msg in port.iter_pending():
                        m.input_signal(msg)
                    if p.is_scanning:
                        port.close()
                    dac_PITCH.normalized_value = m.PITCH_V
except KeyboardInterrupt:
    GPIO.cleanup()
    def __init__(self, gps: UBX):
        # self.steer = SteeringController(i2c=i2c)
        # self.speed = SpeedController(i2c=i2c, gps=gps)

        self.sampling_time = 0.001
        self.time_stamp = 0.

        # Steering Digital Pins
        self.left_pin = DIO.DigitalInOut(board.D21)  # D1
        self.right_pin = DIO.DigitalInOut(board.D20)  # D2
        # Set as outputs
        self.left_pin.direction = DIO.Direction.OUTPUT
        self.right_pin.direction = DIO.Direction.OUTPUT

        # Drive Controller (Millipak) Digital Pins
        self.forward = DIO.DigitalInOut(board.D16)  # D3
        self.reverse = DIO.DigitalInOut(board.D26)  # D4
        self.fs1 = DIO.DigitalInOut(board.D19)  # D5
        self.seat = DIO.DigitalInOut(board.D13)  # D6
        self.power = DIO.DigitalInOut(board.D6)  # D7

        # Set as outputs
        self.forward.direction = DIO.Direction.OUTPUT
        self.reverse.direction = DIO.Direction.OUTPUT
        self.fs1.direction = DIO.Direction.OUTPUT
        self.seat.direction = DIO.Direction.OUTPUT
        self.power.direction = DIO.Direction.OUTPUT

        # GPS
        self._gps = gps
        # self._gps.start_reading()

        # I2C and ADC Setup
        self._i2c_interface = busio.I2C(board.SCL, board.SDA)

        # Setup Steering Angle ADC
        adc = ADC.ADS1115(self._i2c_interface, address=72)
        self.steer_adc = AnalogIn(adc, ADC.P0)

        # Setup Steering Angle DAC
        self.steer_dac = DAC.MCP4725(self._i2c_interface, address=97)

        # Setup Drive Speed DAC
        self.speed_dac = DAC.MCP4725(self._i2c_interface, address=96)

        # Speed
        self._measured_speed = 0.
        self._speed_set_point = 0.
        self._stop = False

        # Speed PID Controller
        self._prev_error_speed = 0.
        self._cumulative_error_speed = 0.
        # Original non-time related
        # self.p_gain_speed = 0.01
        # self.d_gain_speed = 1.
        # self.i_gain_speed = 0.
        # Sample time related
        self.p_gain_speed = 0.01
        self.d_gain_speed = 1. / 1000
        self.i_gain_speed = 0. * 1000
        self._speed_output_voltage = 0
        self._max_speed_voltage = 1.6
        self.driving_forward = True

        # Steering
        # 0 Degree Steer = 2.582V
        self._steer_output_voltage = 0.
        self._max_steer_voltage = 4.5
        self._min_steer_voltage = 0.05
        self._steering_angle_set_point = 0.
        self._current_steering_angle = 0.
        self._steer_adc_measurements = deque(maxlen=1)
        self._steering_changed = False
        self._steer_adc_average = 0.
        self._steer_adc_set_point = 0.
        self.left_max = 20
        self.right_max = -20

        # Steering PID Controller
        # Original non-time related
        # self.p_gain_steer = 15.
        # self.d_gain_steer = 0.
        # self.i_gain_steer = .2
        # Sampling time related
        self.p_gain_steer = 15.
        self.d_gain_steer = 0. / 1000
        self.i_gain_steer = .2 * 1000

        self._prev_error_steer = 0.
        self._cumulative_error_steer = 0.

        # Set DAC Output
        self.steer_dac.value = 0
        self.speed_dac.value = 0

        # Threading
        self._stop_threads = False
        self._control_thread = None
import busio
import time
from simpleio import map_range
import adafruit_trellism4
import adafruit_adxl34x  # accelerometer

import adafruit_mcp4725  # external DACs

trellis = adafruit_trellism4.TrellisM4Express()
acc_i2c = busio.I2C(board.ACCELEROMETER_SCL,
                    board.ACCELEROMETER_SDA)  # for accelerometer
dac_i2c = busio.I2C(board.SCL, board.SDA)  # for DACs

# Initialize accelerometer and DACs
accelerometer = adafruit_adxl34x.ADXL345(acc_i2c)
pitch_dac = adafruit_mcp4725.MCP4725(dac_i2c, address=0x62)
gate_dac = adafruit_mcp4725.MCP4725(dac_i2c, address=0x63)

# There are a three ways to set the DAC output, you can use any of these:
# dac2.value = 65535
# dac2.raw_value = 4095
# dac2.normalized_value = 1.0

step_delay = 0.0

print("2018-12-18 dual DAC CV test v02.py")

while True:
    x, y, z = accelerometer.acceleration
    # print((x,y,z))
예제 #12
0
  'AutoStart': 4,
  'ErrorFlag': 5,
  'Bottle': 6,
  'DataMemory': 7,
  'CalMemory': 8
}


# MFC
i2c = busio.I2C(board.SCL, board.SDA)
ads = ADS.ADS1015(i2c)

# MFC_1 sample flow
MFC_SAMPLE = {
  'NAME': 'sample',
  'DAC': adafruit_mcp4725.MCP4725(i2c),
  'ADC': AnalogIn(ads, ADS.P1),
  'RANGE': 3.0,
  'FLOW': 1.0,
  'LOWER_LIMIT': 0.75,
  'UPPER_LIMIT': 1.25,
}

# MFC_2 zero air flow
MFC_CAL = {
  'NAME': 'cal',
  'DAC': adafruit_mcp4725.MCP4725(i2c, address=0x63),
  'ADC': AnalogIn(ads, ADS.P2),
  'RANGE': 5.0,
  'FLOW': 2.0,
  'LOWER_LIMIT': 1.5,
예제 #13
0
class Heater:

    desired_temp = None  # Fully populated once constructed
    current_step = 0  # Track which iteration we are on
    temperature_readings = [0]  # Add to list as we step
    errors = [0]  # Add to this as we step
    current_temperature = 0  # Updated in step()

    if on_pi_hardware:
        # Raspberry Pi software SPI configuration. (For thermocouple)
        CLK = 25
        CS = 24
        DO = 18
        sensor = MAX31855.MAX31855(CLK, CS, DO)

        # Raspberry Pi hardware SPI configuration. (For thermocouple)
        # SPI_PORT = 0
        # SPI_DEVICE = 0
        # sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=5000000))

        i2c = busio.I2C(board.SCL, board.SDA)
        dac = adafruit_mcp4725.MCP4725(i2c)

    # Calculates the temperature based on dni_arr and secs_per_cycle
    def __init__(self, dni_arr, secs_per_cycle):
        self.mutex = Lock()

        # sample every secs_per_cycle since this probably won't run every second
        desired_temp = dni_arr[::secs_per_cycle]

        # multiply by 2 for some reason
        desired_temp = np.multiply(desired_temp, 2)

        # v = (5 / 208) * (DNI) / sqrt(DNI / R)(on each element in the list)
        R = 15
        voltage_ratio = 5 / 208  # The ratio of the analog control voltage to max voltage into the heater

        for i in range(0, len(desired_temp)):
            desired_temp[i] = voltage_ratio * desired_temp[i] / math.sqrt(
                desired_temp[i] / R)

        # desired_temp = 8.6*v^2 + 115v (on each element in the list)
        # Estimated calibration equation, analog voltage to Celsius
        for i in range(0, len(desired_temp)):
            desired_temp[i] = 8.6 * math.pow(desired_temp[i],
                                             2) + 115 * desired_temp[i]

        self.desired_temp = desired_temp
        print("DEBUG: [Heater] Constructed")

    # public facing step method
    # spawns a thread and calls the synchronous step_sync helper method
    def step(self):
        print("DEBUG: [Heater] Stepping")
        t1 = Thread(target=self.__step_sync)
        t1.start()

    # private synchronous helper method that runs each time we need to check heater temp
    def __step_sync(self):

        # Stop stepping once we have reached the end of the desired_temp array
        # (for the case where the desired_temp arr is not evenly divisible by secs_per_cycle
        if self.current_step >= len(self.desired_temp) - 1:
            return
        else:
            self.current_step += 1
        if not on_pi_hardware:
            return
        self.mutex.acquire()
        print("DEBUG: [Heater] Stepping for", self.current_step)

        # Read the current temperature
        current_temp = self.sensor.readTempC()
        self.current_temperature = current_temp

        # Calculate the control temperature
        kP = 1000
        ki = 10
        kd = 25

        # control_temperature = desired_temp_c[currentsecond] + kP * error[current reading and current desired
        # temperature] + ki * [sum of all errors] + kd * (this error - previous error)
        ref_temp = self.desired_temp[self.current_step]
        error = ref_temp - current_temp
        control_temperature = ref_temp + kP * error + ki * np.sum(
            self.errors) + kd * self.errors[len(self.errors) - 1]
        self.errors.append(error)

        # convert control temperature to voltage
        control_voltage = 500 * control_temperature

        # actual dac output (0-4096)
        actual_dac_output = control_voltage / 5 * 4096

        if actual_dac_output > 4096:
            actual_dac_output = 4096
        elif actual_dac_output < 0:
            actual_dac_output = 0

        self.dac.set_voltage(actual_dac_output)

        print("DEBUG: [Heater] Done stepping for", self.current_step)

        self.mutex.release()

    # returns the state of this stepper motor
    def get_state(self):
        return {
            "current_temperature": str(self.current_temperature),
            "reference_temperature": str(self.desired_temp[self.current_step])
        }

    def get_desired_temp_arr(self):
        return self.desired_temp.tolist()
예제 #14
0
I2C1_SDA_PIN = 2
I2C1_SCL_PIN = 3

# For Channel 0
# GPIO 0, Board Pin Numbers 27
# GPIO 1, Board Pin Numbers 28

# Initialize I2C bus.
i2c = busio.I2C(I2C1_SCL_PIN, I2C1_SDA_PIN)
# default TCA address=0x70
tca = adafruit_tca9548a.TCA9548A(i2c)

print("attempting to connect to DAC")
# Initialize all 5 MCP4725 at default address=0x60
time.sleep(1)
dac1 = adafruit_mcp4725.MCP4725(tca[0], address=0x60)
print("connected to MCP on tca[0]")
input("Press enter...")
time.sleep(1)
dac2 = adafruit_mcp4725.MCP4725(tca[1], address=0x60)
print("connected to MCP on tca[1]")
input("Press enter...")
dac3 = adafruit_mcp4725.MCP4725(tca[2], address=0x60)
print("connected to MCP on tca[2]")
input("Press enter...")
dac4 = adafruit_mcp4725.MCP4725(tca[3], address=0x60)
print("connected to MCP on tca[3]")
input("Press enter...")
dac5 = adafruit_mcp4725.MCP4725(tca[4], address=0x60)
print("connected to MCP on tca[4]")
# Optionally you can specify a different addres if you override the A0 pin.
예제 #15
0
def controller_thread():
    global state
    global dac_value
    global on_button_pressed
    global off_button_pressed
    global shutoff_timer_start
    # Open the DAC device.
    i2c = busio.I2C(board.SCL, board.SDA)
    dac = adafruit_mcp4725.MCP4725(i2c)
    # Get the current value of the DAC. We read the value 10 times from I2C to avoid reading an erroneously high value that would cause the RAMP_DOWN state to write that erroneously high value back to the DAC and break the crystal.
    dac_readings = []
    print("Starting controller...", end='', flush=True)
    for _ in range(10):
        dac_readings.append(dac.raw_value)
        print('.', end='', flush=True)
        time.sleep(0.05)
    print("\nController started.")
    dac_value = int(sum(dac_readings) / float(len(dac_readings)))
    # If the DAC isn't off right now, ramp down.
    if dac_value > 0:
        log_action("AUTO", "FILAMENT_OFF", "")
        state = RAMP_DOWN
        if computer_control:
            status_led_flash_red()
    else:
        state = OFF
        if computer_control:
            status_led_solid_red()
    # Main state machine loop.
    while True:
        if state == OFF:
            if on_button_pressed:
                shutoff_timer_start = time.time()
                status_led_flash_green()
                state = RAMP_UP
            off_button_pressed = False
            on_button_pressed = False
            time.sleep(0.1)
        elif state == RAMP_UP:
            off_button_pressed = False
            on_button_pressed = False
            time.sleep(float(RAMP_TIME_SECONDS) / (max_dac_value + 1))
            dac_value += 1
            dac.raw_value = dac_value
            if dac_value >= max_dac_value:
                state = ON
                status_led_solid_green()
        elif state == ON:
            if off_button_pressed:
                state = RAMP_DOWN
                status_led_flash_red()
            if time.time(
            ) - shutoff_timer_start >= SHUTOFF_TIMER_DURATION_SECONDS:
                state = RAMP_DOWN
                status_led_flash_red()
                log_action("SHUTOFF", "FILAMENT_OFF", "")
            off_button_pressed = False
            on_button_pressed = False
            time.sleep(0.1)
        elif state == RAMP_DOWN:
            off_button_pressed = False
            on_button_pressed = False
            time.sleep(float(RAMP_TIME_SECONDS) / (max_dac_value + 1))
            dac_value -= 1
            dac.raw_value = dac_value
            if dac_value <= 0:
                state = OFF
                status_led_solid_red()
예제 #16
0
    def main(self, config, log, local):
        from inputs import get_gamepad, UnpluggedError, devices
        from time import sleep

        import adafruit_mcp4725
        i2c = busio.I2C(board.SCL, board.SDA)
        motor = adafruit_mcp4725.MCP4725(i2c)

        # PulseIO is not yet supported on Raspberry Pi
        # (f11384e0 is the last commit with Adafruit Servo code
        # should Pi's be supported in the future.)
        import pigpio
        steering = pigpio.pi()

        reverse = digitalio.DigitalInOut(board.D24)
        reverse.direction = digitalio.Direction.OUTPUT
        reverse.value = True

        boost = False

        currentSteeringSensetivity = 0
        log["driveUnit.reverse"] = False

        while True:
            try:
                leftStickCenter = None
                leftStickPosition = None
                while leftStickCenter == None:
                    events = get_gamepad()
                    for event in events:
                        if event.code == "ABS_X":
                            leftStickPosition = event.state
                        if event.code == "BTN_SELECT":
                            if leftStickPosition != None:
                                leftStickCenter = leftStickPosition
                                gamepad = devices.gamepads[0]

                while True:
                    events = get_gamepad()
                    log['driveUnit.controllerConnected'] = True
                    for event in events:
                        if event.code == "BTN_SELECT":
                            leftStickCenter = leftStickPosition

                        if event.code == "BTN_WEST":
                            reverse.value = not event.state
                            log["driveUnit.reverse"] = not reverse.value  # The reverse pin/transistor is pulled the wrong way, so this double invert is needed.

                        if event.code == "BTN_EAST":
                            boost = event.state
                            log["driveUnit.boost"] = boost

                        if event.code == "ABS_X":
                            leftStickPosition = event.state
                            steeringInput = event.state - leftStickCenter
                            log["driveUnit.steeringInput"] = steeringInput
                            steeringNormalized = steeringInput / 16384
                            speed = speedUnit.getSpeed(config, speedUnitLocal)
                            if speed > 10 and config[
                                    'speedSteeringSensitivity']:  # Ajust steering sensetivity/range based on speed.
                                if speed < currentSteeringSensetivity:
                                    if -config[
                                            'steeringDeadzone'] < steeringNormalized < config[
                                                'steeringDeadzone']:
                                        steeringNormalized = steeringNormalized / (
                                            speed / 10
                                        )  # Adjust steering sensitivity based on speed.
                                        currentSteeringSensetivity = speed
                                else:
                                    steeringNormalized = steeringNormalized / (
                                        speed / 10
                                    )  # Adjust steering sensitivity based on speed.
                                    currentSteeringSensetivity = speed
                            steeringNormalized = steeringNormalized * config[
                                'steeringSensitivity']

                            if -config[
                                    'steeringDeadzone'] < steeringNormalized < config[
                                        'steeringDeadzone']:
                                steeringNormalized = 0
                            elif steeringNormalized < 0:
                                steeringNormalized += config[
                                    'steeringDeadzone']
                            elif steeringNormalized > 0:
                                steeringNormalized -= config[
                                    'steeringDeadzone']

                            self.setSteering(log, steering, steeringNormalized)

                        elif event.code == "ABS_RZ":
                            throttleInput = event.state
                            log["driveUnit.throttleInput"] = throttleInput
                            throttleNormalized = (
                                (throttleInput * (0.76 - 0.18)) /
                                1024) + 0.18  # Motor activates at ~0.24
                            if throttleNormalized > 0.2 and boost:
                                throttleNormalized = 1
                            self.setMotor(config, log, motor,
                                          throttleNormalized)
            except Exception as exception:
                log["exceptions"].append(str(exception))
                if type(exception) == UnpluggedError:
                    log['driveUnit.controllerConnected'] = False
                motor.normalized_value = 0
                reverse.value = 0
예제 #17
0
# from Cedar Grove's CircuitPython StringCar Racer project
# adapted for John Park's workshop 3/29/2018 pan/tilt project
# modified for dual DAC output to drive oscilloscope

# ### Setup ###
import board

import time
import neopixel as neo
from analogio import AnalogIn, AnalogOut

import busio
import adafruit_mcp4725

ext_i2c = busio.I2C(board.SCL, board.SDA)  # for DACs
x_out = adafruit_mcp4725.MCP4725(ext_i2c, address=0x62)
y_out = adafruit_mcp4725.MCP4725(ext_i2c, address=0x63)

# set up x-y scope output pins
# x_out = AnalogOut(board.A0)
# y_out = AnalogOut(board.A1)

# dim the on-board neopixel and show yellow start-up indicator
pixel = neo.NeoPixel(board.NEOPIXEL,1, brightness=0.01, auto_write=False)
pixel[0] = (128, 128, 0)
pixel.write()

trellis_outline = [  # raw, absolute 12-bit data points
    (0, 0),
    (0, 41520),
    (21760, 41520),
예제 #18
0
Created on Fri Apr 30 02:05:15 2021 
 
@author: Nat 
""" 
 
#python can be used to control a microcontoller's ouput voltage to a component using DAC.
#This code is for an Arduino or Raspberry Pi microcontroller using CircuitPython and 
# the MCP4725 component, which has the circuit python library bundle for the MCP4725
 
import board 
import busio 
import adafruit_mcp4725 


i2c = busio.I2C(board.SCL, board.SDA) # Initialize I2C bus. 
dac = adafruit_mcp4725.MCP4725(i2c) # Initialize MCP4725. # Create a DAC instance.  #Using i2c 

#set the DAC output using: 
dac.raw_value = 4095  # The raw_value property to directly reads and writes 
# to the 12-bit DAC value.   

#takes an incoming peltier temperature value and converts it to the 12 bit DAC 
#value between # 0 (minimum/ground) to 4095 (maximum/Vout), which 
#corresponds to a Vout pin voltage between 0-3.3V. A heating range of 35 deg
#is used here https://www.cuidevices.com/product/resource/cp18-m.pdf 

class microcontroller():
    def __init__ (self):
        EffectorBase.__init__(self, "microcontroller")
        self.temp = 0
        self.maxtemp = 35
import board
import busio

import adafruit_mcp4725

from time import sleep

# Initialize I2C bus.
i2c = busio.I2C(board.SCL, board.SDA)

# Initialize MCP4725.
dac = adafruit_mcp4725.MCP4725(i2c, address=0x60)

# There are a three ways to set the DAC output, you can use any of these:
dac.value = 65535  # Use the value property with a 16-bit number just like
# the AnalogOut class.  Note the MCP4725 is only a 12-bit
# DAC so quantization errors will occur.  The range of
# values is 0 (minimum/ground) to 65535 (maximum/Vout).

dac.raw_value = 4095  # Use the raw_value property to directly read and write
# the 12-bit DAC value.  The range of values is
# 0 (minimum/ground) to 4095 (maximum/Vout).

dac.normalized_value = 1.0  # Use the normalized_value property to set the
# output with a floating point value in the range
# 0 to 1.0 where 0 is minimum/ground and 1.0 is
# maximum/Vout.

# Main loop will go up and down through the range of DAC values forever.
while True:
    dac.raw_value = 0
예제 #20
0
# Alternatively, there is a quick start command by using "~/gitFolder/startUpScript.sh"

# Written by Valentine Lin and Eric Trollsaas, 2020
# Contact: [email protected], [email protected]

import rospy
from std_msgs.msg import String
from sensor_msgs.msg import LaserScan
import time
import adafruit_mcp4725
import math
import board
import busio

i2c = busio.I2C(board.SCL, board.SDA)
dac1 = adafruit_mcp4725.MCP4725(i2c, address=0x60)
dac2 = adafruit_mcp4725.MCP4725(i2c, address=0x61)

brakeDistance = 0.5
stairDistance = 10  #Currently effectively unused, but may be useful for stair avoidance
breakVoltage = 0.4  #This can be given as any value between 0 and 1, where 1 is full braking power and 0 is no power.


def turn(direction):
    print("Turning " + direction)
    if direction == "left":
        dac1.normalized_value = breakVoltage
        dac2.normalized_value = 0
    elif direction == "right":
        dac1.normalized_value = 0
        dac2.normalized_value = breakVoltage
예제 #21
0
centerY = 2.3458
#

#EXPANDED
#centerY = 2.956;
#centerX = 2.53;

voltageToPositionX = 4.12
# mm/V
voltageToPositionY = 3.52
# mm/V
laserSpotRadius = 0.949
#mm unexpanded

i2c = busio.I2C(board.SCL, board.SDA)
dac = adafruit_mcp4725.MCP4725(i2c, address=0x62)
dacY = adafruit_mcp4725.MCP4725(i2c, address=0x63)
x = 0

try:
    if mode == 1:
        # Goes from 0,0 to a point (x,y) in one move, then waits, then moves back

        #1) generate list of points (this will change depending on what we want to do)
        #xlist
        #xlist=[lev(centerX-0.50),lev(centerX-0.25),lev(centerX),lev(centerX+0.25),lev(centerX+0.50)]
        xlist = []
        for b in range(-4, 5):
            xlist.append(lev(centerX + b / 2.0))
            print((centerX + b / 2.0))
        #ylist
예제 #22
0
if __name__ == "__main__":
    # I2C and ADC Setup
    i2c_interface = busio.I2C(board.SCL, board.SDA)
    # First I2C bus is normal RasPi I2C pins
    # i2c_adc = busio.I2C(board.SCL, board.SDA)

    # Second I2C bus is set to: SCL GPIO17, SDA GPIO27
    # i2c_dac_steering = busio.I2C(board.D17, board.D27)

    # Setup Steering Angle ADC
    # adc = ADC.ADS1115(i2c_interface, address=72)
    # adc_input = AnalogIn(adc, ADC.P0)

    # Setup Steering Angle DAC
    dac_output = DAC.MCP4725(i2c_interface, address=97)
    output_voltage = 0.
    direction = True
    add = 0.1
    try:
        while True:
            dac_output.raw_value = round(output_voltage / 5 * 4095)
            if output_voltage >= 4.9 and direction:
                direction = not direction
                print(f"Voltage going down")
                add *= -1
            if output_voltage <= 0.1 and not direction:
                direction = not direction
                print(f"Voltage going up")
                add *= -1
            output_voltage += add
예제 #23
0
    return np.minimum(10,(v1*10/3.3)) , np.minimum(10,(v2*10/3.3)) 

def dac_converter(u):
    #Definimos que 0 a 25 sera 0 a 1
    #Pero la salida es de 0-3.3 es 0-4095
    u_scalebin = np.divide((u*4095),(25*3.3))
    u_scalevolt = np.divide(u,25)
    u_bin = np.int(np.maximum(0,np.minimum(4095,u_scalebin)))
    u_volt = np.maximum(0,np.minimum(1,u_scalevolt))
    return u_volt, u_bin
    

if __name__=="__main__":
    i2c = busio.I2C(board.SCL, board.SDA)
    ads = ADS.ADS1115(i2c, address = 0x48)
    dac = adafruit_mcp4725.MCP4725(i2c)
   
   #Create single-ended input on channel 0
    chan1 = AnalogIn(ads, ADS.P0)
    chan2 = AnalogIn(ads, ADS.P1)
    chan3 = AnalogIn(ads, ADS.P2)
    dac.raw_value = 0
    print('Inicializando, wait 10 seconds')
    time.sleep(10)
    start = time.time()
    

    while True:
        u = (chan1.voltage/3.3)
        u_volt, u_bin = dac_converter(25*u)
        dac.raw_value = u_bin
예제 #24
0
 def __init__(self):
     self.i2c = busio.I2C(board.SCL, board.SDA)
     self.dac = adafruit_mcp4725.MCP4725(self.i2c)
     self.dac.value = 0