Exemplo n.º 1
0
    def test_calc_frequency(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act & Assert
        self.assertEqual(dev.calc_frequency(30), 197)
        self.assertEqual(dev.calc_frequency(5), 1017)
Exemplo n.º 2
0
    def test_calc_pre_scale(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act & Assert
        self.assertEqual(dev.calc_pre_scale(200), 30)
        self.assertEqual(dev.calc_pre_scale(1000), 5)
Exemplo n.º 3
0
 def plugin_init(self, enableplugin=None):
     plugin.PluginProto.plugin_init(self, enableplugin)
     self.initialized = False
     self.pca = None
     if self.enabled:
         i2cport = -1
         try:
             for i in range(0, 2):
                 if gpios.HWPorts.is_i2c_usable(
                         i) and gpios.HWPorts.is_i2c_enabled(i):
                     i2cport = i
                     break
         except:
             i2cport = -1
         if i2cport > -1 and int(self.taskdevicepluginconfig[0]) > 0:
             try:
                 freq = int(self.taskdevicepluginconfig[1])
                 if freq < self.MIN_FREQUENCY or freq > self.MAX_FREQUENCY:
                     freq = self.MAX_FREQUENCY
             except:
                 freq = self.MAX_FREQUENCY
             try:
                 self.pca = Device(address=int(
                     self.taskdevicepluginconfig[0]),
                                   bus_number=int(i2cport))
                 if self.pca is not None:
                     self.initialized = True
                     self.pca.set_pwm_frequency(freq)
             except Exception as e:
                 misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                             "PCA9685 device init failed: " + str(e))
                 self.pca = None
         if self.pca is not None:
             pass
Exemplo n.º 4
0
 def get_dev(self):
     self.speed = cbpi.get_config_parameter("PCA_" + self.a_busad + "_Hz",
                                            None)
     if self.speed is None:
         self.speed = "50"
         cbpi.add_config_parameter("PCA_" + self.a_busad + "_Hz", "50",
                                   "text", "PCA Frequency")
     print self.speed
     self.dev = Device(self.busad)
Exemplo n.º 5
0
    def test_led_number_wrong_getter(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act & Assert
        with self.assertRaises(AttributeError):
            self.assertEqual(dev.led_42, 2047)
        with self.assertRaises(AttributeError):
            self.assertEqual(dev.teve, 2047)
Exemplo n.º 6
0
    def test_set_pwm_frequency_wrong_input(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act & Assert
        with self.assertRaises(DeviceException):
            dev.set_pwm_frequency(2000)
        with self.assertRaises(DeviceException):
            dev.set_pwm_frequency(10)
Exemplo n.º 7
0
    def test_get_pwm_frequency(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act
        dev.set_pwm_frequency(197)

        # Assert
        self.assertEqual(dev.get_pwm_frequency(), 197)
Exemplo n.º 8
0
    def test_search_for_i2c_devices(self):
        # Arrange
        def glob(pattern):
            return ['/dev/i2c-8']

        # Act
        dev = Device(0, None, FakeSMBus, glob)

        # Assert
        self.assertEqual(dev.bus.bus_number, 8)
Exemplo n.º 9
0
    def test_set_pwm_value(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act
        dev.set_pwm(4, 1042)

        # Assert
        self.assertEqual(dev.bus.values[24], 18)
        self.assertEqual(dev.bus.values[25], 4)
Exemplo n.º 10
0
 def __init__(self, *args, **kwargs):
     super(Robot, self).__init__(*args, **kwargs)
     self.motor_driver = Device(0x40, self.i2c_bus)
     self.left_motor = Motor(self.motor_driver,
                             channel=self.left_motor_channel,
                             alpha=self.left_motor_alpha)
     self.right_motor = Motor(self.motor_driver,
                              channel=self.right_motor_channel,
                              alpha=self.right_motor_alpha)
     self.motor_driver.set_pwm_frequency(50)
    def initPCA9685(self):
        """
        @description configure Jetson Nano GPIO for communication with PCA9685
        @return a PCA9685 Device object to communicate with PCA9685 chip
        """
        GPIO.setmode(GPIO.BOARD)
        mode = GPIO.getmode()
        print("Jetson Nano GPIO Mode: {}".format(mode))

        # discover I2C devices
        i2c_devs = Device.get_i2c_bus_numbers()
        print("The following /dev/i2c-* devices were found:\n{}".format(
            i2c_devs))

        # Create I2C device
        """
        working_devs = list()
        print("Looking out which /dev/i2c-* devices is connected to PCA9685")
        for dev in i2c_devs:
            try:
                pca9685 = Device(0x40,dev)
                # Set duty cycle
                pca9685.set_pwm(5, 2047)

                # set pwm freq
                pca9685.set_pwm_frequency(1000)
                print("Device {} works!".format(dev))
                working_devs.append(dev)
            except:
                print("Device {} does not work.".format(dev))

        # Select any working device, for example, the first one
        print("Configuring PCA9685 connected to /dev/i2c-{} device.".format(working_devs[0]))
        pca9685 = Device(0x40, working_devs[0]) 
        """
        pca9685 = Device(
            0x40, 1
        )  # Immediately set a working device, this assumes PCA9685 is connected to I2C channel 1

        # ESC work at 50Hz
        pca9685.set_pwm_frequency(50)

        # Set slow speed duty cycles
        self.set_channel_duty_cycle(pca9685, 0, 5.0)
        self.set_channel_duty_cycle(pca9685, 1, 5.0)
        self.set_channel_duty_cycle(pca9685, 2, 5.0)
        self.set_channel_duty_cycle(pca9685, 3, 5.0)

        # configure rest of channels to 0 duty cycle
        rest = np.arange(4, 16, 1)
        for channel in rest:
            self.set_channel_duty_cycle(pca9685, channel, 0.0)

        return pca9685
Exemplo n.º 12
0
    def test_set_pwm_frequency(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act
        dev.set_pwm_frequency(200)

        # Assert
        self.assertEqual(dev.bus.wrote_values[0], (0, 17))
        self.assertEqual(dev.bus.wrote_values[1], (254, 30))
        self.assertEqual(dev.bus.wrote_values[2], (0, 1))
Exemplo n.º 13
0
    def __init__(self, thread_id, thread_name):
        """Initialize PCA9685 servo driver and set angles for servo motors

        Args:
            thread_id (int): id of thread
            thread_name (str): name of thread
        """
        self.thread_id = thread_id
        self.thread_name = thread_name
        self.pwm = Device(0x40)  # setup PCA9685 servo driver device
        self.pwm.set_pwm_frequency(60)  # setup PCA9685 servo driver frequency
        self.steering_angle = 90  # set initial angle of servo for steering
        self.motor_angle = 133  # set initial angle of servo for motor
        self.set_angle(14, self.steering_angle)  # set angle for motors
        self.set_angle(15, self.motor_angle)  # set angle for motors
    def __init__(self, thread_id, name):
        self.thread_id = thread_id
        self.name = name

        self.pwm = Device(0x40)  # setup PCA9685 servo driver device
        self.pwm.set_pwm_frequency(60)  # setup PCA9685 servo driver frequency

        self.steering_angle = 90  # set initial angle of servo for steering
        self.motor_angle = 133  # set initial angle of servo for motor

        # numpy data setup
        self.npy_file = 'datasets/dataset.npy'  # numpy file for storing training data
        self.left_val = 0  # [0,*,*]
        self.forward_val = 0  # [*,0,*]
        self.right_val = 0  # [*,*,0]
        self.training_data = [
        ]  # array for controller input data [left_val, motor_val, right_val]
        self.printed_length = False  # used to print length of training data

        self.stream = frame.Frame(1, 'SaveFrame')  # setup camera stream
        self.stream.start()  # start camera stream
        self.start()  # start data collection
Exemplo n.º 15
0
class Lightdrv(object):
    val = [0.0, 0.0, 0.0, 0.0]
    dev = Device(0x40)

    def set(self, vec):
        for i in range(0, len(vec)):
            if (vec[i] < 0) | (vec[i] > 4095):
                continue
	    self.val = vec
            try:
                self.dev.set_pwm(i, int(vec[i]))
            except Exception:
                pass

    def get(self):
        return self.val

    def getReal(self):
        res = [0, 0, 0, 0]
        for i in range(0, 4):
            res[i] = self.dev.get_pwm(i)
        return res
Exemplo n.º 16
0
 def plugin_init(self, enableplugin=None):
     plugin.PluginProto.plugin_init(self, enableplugin)
     self.initialized = False
     self.pca = None
     if self.enabled:
         try:
             i2cl = self.i2c
         except:
             i2cl = -1
         try:
             i2cport = gpios.HWPorts.geti2clist()
             if i2cl == -1:
                 i2cl = int(i2cport[0])
         except:
             i2cport = []
         if len(i2cport) > 0 and i2cl > -1 and int(
                 self.taskdevicepluginconfig[0]) > 0:
             try:
                 freq = int(self.taskdevicepluginconfig[1])
                 if freq < self.MIN_FREQUENCY or freq > self.MAX_FREQUENCY:
                     freq = self.MAX_FREQUENCY
             except:
                 freq = self.MAX_FREQUENCY
             try:
                 self.pca = Device(address=int(
                     self.taskdevicepluginconfig[0]),
                                   bus_number=int(i2cl))
                 if self.pca is not None:
                     self.initialized = True
                     self.pca.set_pwm_frequency(freq)
             except Exception as e:
                 misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                             "PCA9685 device init failed: " + str(e))
                 self.pca = None
         if self.pca is not None:
             pass
Exemplo n.º 17
0
sys.path.append('/usr/local/lib/python3.6/dist-packages'
                )  # caminho da biblioteca pca9685_driver
# sudo pip install PCA9685-driver(Example code for using the GPIO in Jetson Nano)
sys.path.append(
    '/opt/nvidia/jetson-gpio/lib/python')  # caminho generico sugerido
sys.path.append('/opt/nvidia/jetson-gpio/lib/python/Jetson/GPIO'
                )  # caminho generico sugerido
sys.path.append(
    '/home/nvidia/repositories/nano_gpio/gpio_env/lib/python2.7/site-packages/periphery/'
)  # caminho generico sugerido

import Jetson.GPIO as GPIO
from pca9685_driver import Device

dev = Device(0x40, 1)  #endereco 0x40 , device(bus) 0,1,2,3,4,5,6

import time

time.sleep(1)
t0 = 0.01
t1 = 0.1
#inicio

#frequencia
dev.set_pwm_frequency(50)

#seguranca
for i in range(15):
    dev.set_pwm(i, 330)
Exemplo n.º 18
0
from pca9685_driver import Device
from time import sleep

# 0x40 from i2cdetect -y 1 (1 if Raspberry pi 2)
dev = Device(0x40)

# set the duty cycle for LED05 to 50%
dev.set_pwm(0, 204)

# set the pwm frequency (Hz)
dev.set_pwm_frequency(50)

lb = int(0.01 * 4097)
ub = int(0.12 * 4097)
for i in range(lb, ub):
    dev.set_pwm(0, i)
    print(i)
    sleep(0.01)
Exemplo n.º 19
0
# SET GPIO mode to BOARD
GPIO.setmode(GPIO.BOARD)
mode = GPIO.getmode()
print(mode)

# discover I2C devices
i2c_devs = Device.get_i2c_bus_numbers()
print("The following /dev/i2c-* devices were found:\n{}".format(i2c_devs))

# Create I2C device
working_devs = list()
print("Looking out which /dev/i2c-* devices is connected to PCA9685")
for dev in i2c_devs:
    try:
        pca9685 = Device(0x40, dev)
        # Set duty cycle
        pca9685.set_pwm(5, 2047)

        # set pwm freq
        pca9685.set_pwm_frequency(1000)
        print("Device {} works!".format(dev))
        working_devs.append(dev)
    except:
        print("Device {} does not work.".format(dev))

# Select any working device, for example, the first one
print("Configuring PCA9685 connected to /dev/i2c-{} device.".format(
    working_devs[0]))
pca9685 = Device(0x40, working_devs[0])
Exemplo n.º 20
0
    def test_led_number_getter(self):
        # Arrange
        dev = Device(0, 0, FakeSMBus)

        # Act & Assert
        self.assertEqual(dev.led_0, 2047)  # default value in FakeSMBus
Exemplo n.º 21
0
def immediateShutDownServos():
    pwm = Device(0x41)
Exemplo n.º 22
0
def safeShuntdownServos():
    pwm.set_pwm(0, servo_max)
    time.sleep(state.LaunchTimeQuit)
    pwm = Device(0x41)
Exemplo n.º 23
0
    def __init__(self):

        #importing needed data
        self.CWL = clawWidthList.clawWidthList()
        self.UsSensor = UsSensor.UsSensor()

        # setting channel names
        self.StepY = 22
        self.DirectionY = 19
        self.ResetY = 21
        self.clockZ = 5
        self.dataZ = 3
        self.clawChannel = 0  #unchanged
        self.emChannel = 1  #unchanged
        self.StepX = 38
        self.DirectionX = 40
        self.ResetX = 36
        self.PWMZ = 14  #,dutycycle is speed
        self.DirectionZ = 15
        self.ResetZ = 11

        self.dutycyclevalue = 0
        self.deltaerror = 1
        self.error0 = 1
        self.error1 = 1
        self.kp = .34
        self.kd = .01
        self.ki = 20
        self.readings = 50

        # Assuming X is direction in which trays open/close

        # These are the ports for the motors which move things in the x,y,or z axis.
        self.PORTX = "X"
        self.PORTY = "Y"
        self.PORTZ = "Z"

        # These are locations for the robot when they trays are closed
        self.CLOSETRAYY = 0

        # these are locations for when the part is being dropped from serializer
        self.DEFAULTX = 100
        self.DEFAULTY = 1000

        # Variable becomes false if it is reset

        # Code to set up GPIO stuff
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.DirectionX, GPIO.OUT, initial=GPIO.LOW)  # directionX
        GPIO.setup(self.StepX, GPIO.OUT, initial=GPIO.LOW)  # stepX
        GPIO.setup(self.ResetX, GPIO.IN)

        GPIO.setup(self.DirectionY, GPIO.OUT, initial=GPIO.LOW)  # directionX
        GPIO.setup(self.StepY, GPIO.OUT, initial=GPIO.LOW)  # stepX
        GPIO.setup(self.ResetY, GPIO.IN)

        GPIO.setup(self.ResetZ, GPIO.IN)

        self.xpos = 0.0
        self.ypos = 0.0
        self.zpos = 0.0

        # Set state: GPIO.output(channel,state)
        # set state: GPIO.output(channel,state, intital = GPIO.HIGH  OR GPIO.LOW)
        # Read value (high or low): GPIO.input(channel)

        self.move = True

        # working_devs = [1,2,3,4,5]
        self.pca9685 = Device(0x40, 1)
        # Set duty cycle
        self.pca9685.set_pwm(0, 2047)

        # set pwm freq
        self.pca9685.set_pwm_frequency(50)

        self.stepFrac = 1

        self.set_duty_cycle(self.pca9685, self.PWMZ, 0)

        self.zerror = 1
from pca9685_driver import Device


def set_duty_cycle(pwmdev, channel, dt):
    """    
    @channel Channel or PIN number in PCA9685 to configure 0-15
    @dt desired duty cycle
    """
    val = (dt * 4095) // 100
    pwmdev.set_pwm(channel, val)


pca9685 = Device(0x40, 1)

# Set duty cycle
#pca9685.set_pwm(0, 2047)

# set pwm freq
pca9685.set_pwm_frequency(60)

set_duty_cycle(pca9685, 0, 7)
Exemplo n.º 25
0
# drive rc car with xbox one controller, only used for testing

from picamera.array import PiRGBArray  # for pi camera
from picamera import PiCamera  # for pi camera
from approxeng.input.selectbinder import ControllerResource  # for xbox controller
from pca9685_driver import Device  # for PCA9685 servo driver
from time import sleep

pwm = Device(0x40)  # setup PCA9685 servo driver
pwm.set_pwm_frequency(60)  # setup PCA9685 servo driver

steering_angle = 90  # initial angle of servo for steering
motor_angle = 133  # initial angle of servo for motor


def set_angle(channel, angle):
    pulse = (int(angle) * 2.5) + 150
    pwm.set_pwm(channel, int(pulse))


print('Ready, drive only')
while 1:
    try:
        with ControllerResource(print_events=False, controller_class=None, hot_zone=0.1,
                                dead_zone=0.1) as controller:
            print('Found a controller')
            while controller.connected:
                set_angle(14, steering_angle)
                set_angle(15, motor_angle)
            
                # right trigger moved (motor forward)
import time
from GPS_VK2828U7G5LF import init_gps_GPRMC, read_gps
from mpu6050 import mpu6050
import ADS1115
import board
import busio
import Jetson.GPIO as GPIO
import sys
import cv2

sys.path.append('/opt/nvidia/jetson-gpio/lib/python')
sys.path.append('/opt/nvidia/jetson-gpio/lib/python/Jetson/GPIO')

from pca9685_driver import Device

servo = Device(0x40, 1)

init_gps_GPRMC()
imu = mpu6050(0x68)

aceleracao_max = 0
desaceleracao_max = 0

ads = ADS1115.ADS1115()

gstreamer = 'nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3280, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method=0 ! video/x-raw, width=640, height=480, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'

cam = cv2.VideoCapture(gstreamer)

while True:
    start = time.time()
Exemplo n.º 27
0
from flask import Flask
import logging
import logging.config
from pca9685_driver import Device

from .config import config, config_loader

APPNAME = 'pca9685_driver_http'

app = Flask(APPNAME)

logging.config.dictConfig(config['logger'])

logger = logging.getLogger(__name__)

logger.info("Config loaded from %s" % config_loader.filename)

devices = {}

for name, conf in config['devices'].items():
    devices[name] = Device(conf['address'], conf['bus'])
    devices[name].wake()
    logger.info("PCA9685 device created on address %s in bus #%s" % (conf['address'], conf['bus']))

from .controllers import *
from .error_handlers import *
Exemplo n.º 28
0
            board_addr))
        pwm_dict = servo_center_dict[board_addr]
        print('pwm_dict:')
        [print('{}  :  {}'.format(k, v)) for k, v in pwm_dict.items()]
    else:
        print('\nBoard addr {} NOT in center file, using default.'.format(
            board_addr))
else:
    print('\nFile {} does not exist, using default pwm list.'.format(
        center_pwm_file))
    servo_center_dict = {}

# 0x40 from i2cdetect -y 1 (1 if Raspberry pi 2)
print('i2c hex board_addr:', args.board_addr, type(args.board_addr))
if args.board_addr == 40:
    dev = Device(0x40)
if args.board_addr == 41:
    dev = Device(0x41)

dev.set_pwm_frequency(50)

min_pwm = 110
max_pwm = 515
mid_pwm = int((min_pwm + max_pwm) / 2)
delta_pwm = 10

cur_servo = 0
#[dev.set_pwm(k, v) for k,v in pwm_dict.items()]


def moveCursorRefresh(stdscr):
Exemplo n.º 29
0
# imports
from __future__ import division

import sys
import time
import datetime
import random

import state

sys.path.append('./PCA9685Driver')
# Import the PCA9685 module.
from pca9685_driver import Device

# launch servo
pwm = Device(0x41)
# Set frequency to 60hz, good for pwm.
pwm.set_pwm_frequency(60)

#PC9685 - TB6612FNG
# PWM8  - PWMA
# PWM9  - AIN1
# PWM10 - AIN2
#
# PWM11 - BIN1
# PWM12 - BIN2
# PWM13 - PWMB

pwmA = 8
ain1 = 9
ain2 = 10