Ejemplo n.º 1
0
    def __init__(self):
        self.servoLeft = 8
        self.servoRight = 9

        self.board = pymata4.Pymata4()
        self.board.set_pin_mode_servo(self.servoLeft)
        self.board.set_pin_mode_servo(self.servoRight)
Ejemplo n.º 2
0
def keep_alive_test(pin_number):
    """
    This program will set a digital output pin to high.
    It is assumed that an LED is connected to this pin.
    After 2 seconds the program exits, and in approximately
    one second the LED should extinguish.

    If keep_alive is working, the LED should extinguish.

    :param pin_number: A pin with an LED connected to it
    """

    board = pymata4.Pymata4()

    # set the as a digital output
    board.set_pin_mode_digital_output(pin_number)

    # set the pin high
    board.digital_write(pin_number, 1)

    # turn on keep_alives
    board.keep_alive()

    print('Sleeping for 2 seconds...')
    time.sleep(2)
    print('Exiting. In about 1 second, the LED should extinguish.')
    sys.exit(0)
    def __init__(self, analog_pin=2, poll_time=5, differential=5):
        """

        :param analog_pin: arduino analog input pin number

        :param poll_time: polling interval in seconds

        :param differential: difference between current value and
                             previous value to consider the change
                             in value a change event
        """
        self.analog_pin = analog_pin
        self.poll_time = poll_time
        self.differential = differential

        # Callback data indices
        self.CB_PIN_MODE = 0  # pin mode (see pin modes in private_constants.py)
        self.CB_PIN = 1  # pin number
        self.CB_VALUE = 2  # reported value
        self.CB_TIME = 3  # raw time stamp

        # instantiate pymata4
        self.board = pymata4.Pymata4()

        # set the pin mode for analog input
        self.board.set_pin_mode_analog_input(self.analog_pin,
                                             self.the_callback,
                                             self.differential)

        # start polling
        self.keep_polling()
Ejemplo n.º 4
0
def connectToBoard():
    #TODO: Add timeout if board does not connect in time.
    global BOARD
    ProgramLogger.info("Connecting to board.")
    try:
        #TODO: Document connecting to an Arduino Due.
        BOARD = pymata4.Pymata4()
        ProgramLogger.info(
            f"Total Digital Pins: {str(len(BOARD.digital_pins))} Total Analog Pins: {str(len(BOARD.analog_pins))}"
        )
    except AttributeError:
        #TODO: Check if borad is an Arduino Due.
        loading.destroy()
        info = "Could not connect to arduino board. Is it pluged in? Reconnect the arduino USB cable, then try again. Or check that the arduino board is assigned a COM port in Device Manager."
        ProgramLogger.critical(info, exc_info=True)
        messagebox.showerror(
            PROGRAM_NAME, f"{info}\n\nCheck program log file for more info.")
        return
    except RuntimeError as err:
        loading.destroy()
        info = f"An error occurred during board communication. If this error has somthing to do with a timeout, close the program and reconnect the arduino USB cable.\n\n{err}"
        ProgramLogger.critical(info, exc_info=True)
        messagebox.showerror(
            PROGRAM_NAME, f"{info}\n\nCheck program log file for more info.")
        return
    attatchSteppers()
Ejemplo n.º 5
0
def main():

    board = pymata4.Pymata4()
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    ex = pwmUI(board=board)
    sys.exit(app.exec_())
Ejemplo n.º 6
0
 def __init__(self):
     self.values = {
         'leftX': 0,
         'leftY': 0,
         'rightX': 0,
         'rightY': 0,
         'sonar': 0,
         'distance': 0,
         'light': 0,
         'temp': 0,
         'rot': 0,
     }
     self.pins = {
         'pwmOut': {
             'leftEnA': 3,
             'leftEnB': 2,
             'rightEnA': 4,
             'rightEnB': 5,
         },
         'digitalOut': {
             'leftIn1': 24,
             'leftIn2': 25,
             'leftIn3': 22,
             'leftIn4': 23,
             'rightIn1': 26,
             'rightIn2': 27,
             'rightIn3': 28,
             'rightIn4': 29,
             'relay': 53,
         },
         'analogOut': {
             'distance': 0,
             'light': 1,
             'temp': 2,
             'rot': 3
         },
         'sonar': {
             'trigger': 12,
             'echo': 13
         }
     }
     self.board = pymata4.Pymata4()
     [
         self.board.set_pin_mode_pwm_output(self.pins['pwmOut'][x])
         for x in self.pins['pwmOut']
     ]
     [
         self.board.set_pin_mode_pwm_output(self.pins['digitalOut'][x])
         for x in self.pins['digitalOut']
     ]
     [
         self.board.set_pin_mode_pwm_output(self.pins['analogOut'][x])
         for x in self.pins['analogOut']
     ]
     self.board.set_pin_mode_sonar(self.pins['sonar']['trigger'],
                                   self.pins['sonar']['echo'])
Ejemplo n.º 7
0
    def __init__(self):
        self.servoPin = 9
        self.enaPin = 5
        self.in1Pin = 6
        self.in2Pin = 7

        self.board = pymata4.Pymata4()
        self.board.set_pin_mode_servo(self.servoPin)
        self.board.set_pin_mode_pwm_output(self.enaPin)
        self.board.set_pin_mode_digital_output(self.in1Pin)
        self.board.set_pin_mode_digital_output(self.in2Pin)
Ejemplo n.º 8
0
def setup(tempSensors, sensorGroups, hvacControlPins):
    LOGGER = logging.getLogger("__main__.hvac.setup")
    LOGGER.debug("tempSensors {}\nsensorGroups {}\nhvacControlPins {}".format(
        tempSensors, sensorGroups, hvacControlPins))
    hvac = HVAC()
    # Setup the thermostat
    hvac.thermostat = Thermostat()
    # Add the sensors to the thermostat
    for sensorName, sensorData in tempSensors.items():
        hvac.thermostat.addSensor(
            sensors.TempSensor(sensorName, sensorData[0], sensorData[1]))
    # Create the groups of sensors
    for groupName, sensorNames in sensorGroups.items():
        hvac.thermostat.createSensorGroup(groupName)
        # Add the sensors to the group
        for sName in sensorNames:
            for sensor in hvac.thermostat.tempSensors:
                if sName == sensor.name:
                    hvac.thermostat.addSensorToGroup(sensor, groupName)
    # Setup the heater
    hvac.heater = Heater()
    hvac.heater.controlPins = hvacControlPins["HEAT_PINS"]

    # Setup the vent
    hvac.vent = Vent()
    hvac.vent.controlPins = hvacControlPins["VENT_PINS"]

    # Setup the AC
    hvac.ac = AirConditioner()
    hvac.ac.controlPins = hvacControlPins["AC_PINS"]

    # Setup the pymata board
    hvac.board = pymata4.Pymata4()

    # Add all of the control and sensor pins to the board
    # Sensor pins
    for tSensor in hvac.thermostat.tempSensors:
        hvac.board.set_pin_mode_analog_input(tSensor.controlPin)
        # LOGGER.debug("{}  {}".format(tSensor, tSensor.controlPin))
    # Control pins
    # Heater
    for pin in hvac.heater.controlPins:
        hvac.board.set_pin_mode_digital_output(pin)
        LOGGER.debug("heater controlPin  {}".format(pin))
    # Vent
    for pin in hvac.vent.controlPins:
        hvac.board.set_pin_mode_digital_output(pin)
        LOGGER.debug("vent controlPin  {}".format(pin))
    # AC
    for pin in hvac.ac.controlPins:
        hvac.board.set_pin_mode_digital_output(pin)
        LOGGER.debug("ac controlPin  {}".format(pin))

    return hvac
Ejemplo n.º 9
0
 def __init__(self):
     self.board = pymata4.Pymata4()
     self.LED_PIN = 9
     self.Q1_PIN = 3
     self.Q2_PIN = 5
     self.T1_PIN = 0
     self.T2_PIN = 2
     self.board.set_pin_mode_pwm_output(self.LED_PIN)
     self.board.set_pin_mode_pwm_output(self.Q1_PIN)
     self.board.set_pin_mode_pwm_output(self.Q2_PIN)
     self.board.set_pin_mode_analog_input(self.T1_PIN)
     self.board.set_pin_mode_analog_input(self.T2_PIN)
     self._Q1 = 0
     self._Q2 = 0
     time.sleep(0.1)
Ejemplo n.º 10
0
def sensor_manager():
    global status, light
    # Intialize node and topic
    pub_light = rospy.Publisher('light_data', Int16MultiArray, queue_size=10)
    pub_force = rospy.Publisher('force_data', Int16MultiArray, queue_size=10)
    pub_mic = rospy.Publisher('mic_data', Int16MultiArray, queue_size=10)

    rospy.init_node('senor_manager', anonymous=False)
    rate = rospy.Rate(10)  # 10hz
    # msg = vect_msg()

    # Initialize Arduino Leoardo with pymata4
    board = pymata4.Pymata4()

    # Initialize i2c
    board.set_pin_mode_i2c()
    board.i2c_write(bh1750_address, [bh1750_power_on])
    board.i2c_write(bh1750_address, [bh1750_resolution])

    # Initialize input analog pins
    for pin in analog_pins:
        board.set_pin_mode_analog_input(pin_number=pin)

    # Initialize output digital pins
    for pin in digital_pins:
        board.set_pin_mode_digital_output(pin_number=pin)

    mic_msg = Int16MultiArray()
    fsr_msg = Int16MultiArray()
    light_msg = Int16MultiArray()

    # Get raw data from board
    while True:
        # mic data
        mic_val = []
        for pin in mic:
            mic_val.append(list(board.analog_read(pin)))
            time.sleep(0.01)
        mic_msg.data = [mic_val[0][0], mic_val[1][0]]
        pub_mic.publish(mic_msg)

        # fsr data
        fsr_val = []
        for pin in fsr:
            fsr_val.append(list(board.analog_read(pin)))
            time.sleep(0.01)
        fsr_msg.data = [fsr_val[0][0], fsr_val[1][0]]
        pub_force.publish(fsr_msg)

        # light
        board.i2c_read(address=bh1750_address,
                       register=None,
                       number_of_bytes=nbytes,
                       callback=ckb)
        light_msg.data = light
        pub_light.publish(light_msg)
        time.sleep(0.2)

        # status led
        status = not status
        board.digital_write(led_status, status)

        rospy.loginfo('Sent data')
        rate.sleep()
Ejemplo n.º 11
0
"""
This example demonstrates running a stepper motor
"""
NUM_STEPS = 512
ARDUINO_PINS = [8, 9, 10, 11]


def stepper(my_board, steps_per_rev, pins):
    """
    Set the motor control control pins to stepper mode.
    Rotate the motor.

    :param my_board: pymata_express instance
    :param steps_per_rev: Number of steps per motor revolution
    :param pins: A list of the motor control pins
    """

    my_board.set_pin_mode_stepper(steps_per_rev, pins)
    time.sleep(1)
    my_board.stepper_write(20, 500)


board = pymata4.Pymata4()
try:
    stepper(board, NUM_STEPS, ARDUINO_PINS)
    board.shutdown()
except KeyboardInterrupt:
    board.shutdown()
    sys.exit(0)
        high_nibble: int = value & 0xf0
        low_nibble: int = (value << 4) & 0xf0
        self.write_4_bits(high_nibble | mode)
        self.write_4_bits(low_nibble | mode)

    def write_4_bits(self, value: int) -> None:
        self.expander_write(value)
        self.pulse_enable(value)

    def expander_write(self, data: int) -> None:
        self.board.i2c_write(self.address, [data, self._backlight_value])

    def pulse_enable(self, data: int) -> None:
        self.expander_write(data | self.ENABLE_BIT)
        sleep(0.000001)

        self.expander_write(data & ~self.ENABLE_BIT)
        sleep(0.00005)

    def print(self, string: AnyStr) -> None:
        for character in string:
            self.write(ord(character))
            sleep(0.000001)
        else:
            sleep(0.00005)


Board = pymata4.Pymata4("/dev/ttyACM0")
LCD = LiquidCrystal_I2C(0x27, 0, 1, Board)
LCD.enable_backlight()
LCD.print("Hello, Worlds!")
Ejemplo n.º 13
0
def arduino_init(delay=2):
    if pymata_ex:
        return pymata_express.PymataExpress(arduino_wait=delay)
    else:
        return pymata4.Pymata4(arduino_wait=delay)
Ejemplo n.º 14
0
    # set the servo to 90 degrees
    my_board.servo_write(pin, 90)


def servo_rev(my_board, pin):
    my_board.set_pin_mode_servo(pin)

    my_board.servo_write(pin, 40)


def stepper(my_board, steps_per_rev, pins):
    """
    Set the motor control control pins to stepper mode.
    Rotate the motor.
    :param my_board: pymata4
    :param steps_per_rev: Number of steps per motor revolution
    :param pins: A list of the motor control pins
    """

    my_board.stepper_write(10, 100)
    my_board.stepper_write(10, -100)


board = pymata4.Pymata4("COM4")
try:
    sonar(board, TRIGGER_PIN, ECHO_PIN, the_callback)
    board.shutdown()
except (KeyboardInterrupt, RuntimeError):
    board.shutdown()
    sys.exit(0)
Ejemplo n.º 15
0
    def __init__(self, root):

        root.title("TJ-Collaborative Robotics Platform")
        root.geometry("500x500")
        mainframe = ttk.Frame(root)
        mainframe.grid(column=0, row=0, sticky=(N, W, E, S))

        self.ultrasonicVar = StringVar()
        self.distanceVar = StringVar()
        self.lightVar = StringVar()
        self.tempVar = StringVar()
        self.rotVar = StringVar()
        self.relayVar = StringVar()

        self.ultrasonicAverage = streamingMovingAverage(50)
        self.distanceAverage = streamingMovingAverage(50)
        self.lightAverage = streamingMovingAverage(50)
        self.tempAverage = streamingMovingAverage(50)
        self.rotAverage = streamingMovingAverage(15)
        self.relayAverage = streamingMovingAverage(50)

        ttk.Label(mainframe, text='Data').grid(column=0, row=0, sticky=(W, E))
        ttk.Label(mainframe, text='Ultrasonic').grid(column=0,
                                                     row=1,
                                                     sticky=(W, E))
        ttk.Label(mainframe, textvariable=self.ultrasonicVar).grid(column=1,
                                                                   row=1)
        ttk.Label(mainframe, text='Distance').grid(column=0,
                                                   row=2,
                                                   sticky=(W, E))
        ttk.Label(mainframe, textvariable=self.distanceVar).grid(column=1,
                                                                 row=2)
        ttk.Label(mainframe, text='Light').grid(column=0, row=3, sticky=(W, E))
        ttk.Label(mainframe, textvariable=self.lightVar).grid(column=1, row=3)
        ttk.Label(mainframe, text='Temperature').grid(column=0,
                                                      row=4,
                                                      sticky=(W, E))
        ttk.Label(mainframe, textvariable=self.tempVar).grid(column=1, row=4)
        ttk.Label(mainframe, text='Rotations').grid(column=0,
                                                    row=5,
                                                    sticky=(W, E))
        ttk.Label(mainframe, textvariable=self.rotVar).grid(column=1, row=5)
        ttk.Label(mainframe, text='Relay').grid(column=0, row=6, sticky=(W, E))
        ttk.Label(mainframe, textvariable=self.relayVar).grid(column=1, row=6)

        self.board = pymata4.Pymata4()
        self.board.set_pin_mode_sonar(
            sensorDict["ultrasonicSensor"]["triggerPin"],
            sensorDict["ultrasonicSensor"]["triggerPin"],
            self.ultrasonicCallback)
        self.board.set_pin_mode_analog_input(
            sensorDict["distanceSensor"]["pin"],
            callback=self.distanceCallback,
            differential=10)
        self.board.set_pin_mode_analog_input(sensorDict["lightSensor"]["pin"],
                                             callback=self.lightCallback,
                                             differential=10)
        self.board.set_pin_mode_analog_input(sensorDict["tempSensor"]["pin"],
                                             callback=self.tempCallback)
        self.board.set_pin_mode_analog_input(sensorDict["rotSensor"]["pin"],
                                             callback=self.rotCallback)
Ejemplo n.º 16
0
#!/usr/bin/python3

import rospy
from std_msgs.msg import String
import sys
import time

from pymata4 import pymata4

BOARD_PORT = "/dev/ttyACM0"
SERVO_PIN = 5


def servo_callback(angle):
    angle_data = float(angle.data) / 1.5
    board.servo_write(SERVO_PIN, int(angle_data))


if __name__ == '__main__':
    try:
        #ros node init\
        board = pymata4.Pymata4(BOARD_PORT)
        rospy.init_node("pymata")
        rospy.Subscriber("angle", String, servo_callback)
        board.set_pin_mode_servo(SERVO_PIN)
        rospy.spin()
    except KeyboardInterrupt:
        board.shutdown()
        sys.exit(0)
Ejemplo n.º 17
0
def blink(my_board, pin):
    """
    This function will to toggle a digital pin.

    :param my_board: an PymataExpress instance
    :param pin: pin to be controlled
    """

    # set the pin mode
    my_board.set_pin_mode_digital_output(pin)
    my_board.digital_write(pin, 1)

    # toggle the pin 4 times and exit
    for x in range(4):
        print('ON')
        my_board.digital_write(pin, 1)
        time.sleep(1)
        print('OFF')
        my_board.digital_write(pin, 0)
        time.sleep(1)

    my_board.shutdown()


board = pymata4.Pymata4(ip_address=IP_ADDRESS, ip_port=IP_PORT)
try:
    blink(board, DIGITAL_PIN)
except KeyboardInterrupt:
    board.shutdown()
    sys.exit(0)
Ejemplo n.º 18
0
    #    print('OFF')
    #    my_board.digital_write(pin, 0)
    #    time.sleep(1)

    #my_board.shutdown()
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("Hellos/+")

def on_message(client, userdata, msg):
    incoming_gesture = msg.payload.decode('ascii')
    print("Topic: {} message {}".format(msg.topic, incoming_gesture))
    blink(board, incoming_gesture)

### Initialize the board
board = pymata4.Pymata4(com_port='/dev/ttyS5')
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("127.0.0.1", 1883, 60)

try:
    client.loop_forever()
except:
    board.shutdown()
    sys.exit(0)

#from pymata4.private_constants import PrivateConstants

"""