Ejemplo n.º 1
0
        static async Task App()
        {
            var board = await ConnectionService.Instance.GetFirstDeviceAsync();

            await board.ConnectAsync();

            Console.WriteLine("Connected to " + board);

            var driver = new Pca9685(board.I2c);

            // connect the RGB LED as open-drain
            driver.InvertOutput = true;
            driver.OutputDrive  = Pca9685.OutputDriveMode.OpenDrain;

            var ledDriver = new PwmLedDriver <Treehopper.Libraries.IO.PortExpander.Pin>(driver.Pins);

            var rgb = new RgbLed(ledDriver.Leds[0], ledDriver.Leds[1], ledDriver.Leds[2]);

            rgb.BlueGain  = 0.7f;
            rgb.GreenGain = 0.95f;

            while (!Console.KeyAvailable)
            {
                for (int i = 0; i < 360; i++)
                {
                    rgb.SetHsl(i, 100, 50);
                    await Task.Delay(10);
                }
            }

            board.Disconnect();
            Console.WriteLine("Board disconnected");
        }
Ejemplo n.º 2
0
        private static void ServoDemo(Pca9685 pca9685, int channel)
        {
            using (var servo = CreateServo(pca9685, channel))
            {
                PrintServoDemoHelp();

                while (true)
                {
                    var command = Console.ReadLine().ToLower();
                    if (string.IsNullOrEmpty(command) || command[0] == 'q')
                    {
                        return;
                    }

                    if (command[0] == 'c')
                    {
                        CalibrateServo(servo);
                        PrintServoDemoHelp();
                    }
                    else
                    {
                        double value = double.Parse(command);
                        servo.WriteAngle(value);
                        Console.WriteLine($"Angle set to {value}. PWM duty cycle = {pca9685.GetDutyCycle(channel)}");
                    }
                }
            }
        }
Ejemplo n.º 3
0
        private static void TestTubes()
        {
            Console.WriteLine("Connecting to devices");
            Pca9685[] devices = new Pca9685[6];
            for (int i = 0; i < devices.Length; i++)
            {
                devices[i] = new Pca9685(I2cDevice.Create(new I2cConnectionSettings(0, Pca9685.I2cAddressBase + i)), 1000);
            }

            Console.WriteLine("Init...");
            Array.ForEach(devices, d => d.SetDutyCycleAllChannels(0));
            Console.WriteLine("Tests all channels on the devices");
            for (int device = 0; device < devices.Length; device++)
            {
                for (int channel = 0; channel < 16; channel++)
                {
                    Console.WriteLine($"Device: {device}, Channel: {channel}");
                    for (int i = 0; i < 100; i++)
                    {
                        devices[device].SetDutyCycle(channel, i / 100.0);
                        Thread.Sleep(1);
                    }
                    for (int i = 100; i > 0; i--)
                    {
                        devices[device].SetDutyCycle(channel, i / 100.0);
                        Thread.Sleep(1);
                    }
                    devices[device].SetDutyCycle(channel, 0);
                }
            }

            Console.WriteLine("Done");
        }
Ejemplo n.º 4
0
        //private readonly int[] microstepcurve = {0,   25,  50,  74,  98,  120, 141, 162, 180,197, 212, 225, 236, 244, 250, 253, 255}//MICROSTEPS == 16

        /// <summary>
        /// Creates a Stepper motor objet un-initialized
        /// </summary>
        /// <param name="steps">The number of steps per revolution</param>
        /// <param name="num">The Stepper motor port</param>
        /// <param name="pca9685">The PCS968 diver object</param>
        public StepperMotor(int steps, int num, Pca9685 pca9685) : base(pca9685)
        {
            if (num == 0)
            {
                _pwmA = 8;
                _AIN2 = 9;
                _AIN1 = 10;
                _pwmB = 13;
                _BIN2 = 12;
                _BIN1 = 11;
            }
            else if (num == 1)
            {
                _pwmA = 2;
                _AIN2 = 3;
                _AIN1 = 4;
                _pwmB = 7;
                _BIN2 = 6;
                _BIN1 = 5;
            }
            else
            {
                throw new ArgumentException("Stepper num must be 0 or 1");
            }

            _motorSteps = steps;
            SetSpeed(15);
            _currentstep = 0;
        }
Ejemplo n.º 5
0
 public ServoPort(string name, int port, Pca9685 pca9685, bool bInverted) : this()
 {
     InvertDirection = bInverted;
     this.Name       = name;
     this.PortNumber = port;
     _pca9685        = pca9685;
 }
Ejemplo n.º 6
0
        public ServoDriver(Pca9685 pca9685, int channel)
        {
            _pca9685 = pca9685;

            var pwmChannel = _pca9685.CreatePwmChannel(channel);

            _servo = new ServoMotor(pwmChannel, 180, 500, 2500);
        }
Ejemplo n.º 7
0
        void Initialize()
        {
            Console.WriteLine("Initialize hardware...");
            var i2CBus = Device.CreateI2cBus(I2cBusSpeed.FastPlus);

            pca9685 = new Pca9685(i2CBus, 0x40, 50);
            pca9685.Initialize();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MotorHat"/> class with the specified I2C settings and PWM frequency.
        /// </summary>
        /// <param name="settings">The I2C settings of the MotorHat.</param>
        /// <param name="frequency">The frequency in Hz to set the PWM controller.</param>
        /// <remarks>
        /// The default i2c address is 0x60, but the HAT can be configured in hardware to any address from 0x60 to 0x7f.
        /// The PWM hardware used by this HAT is a PCA9685. It has a total possible frequency range of 24 to 1526 Hz.
        /// Setting the frequency above or below this range will cause PWM hardware to be set at its maximum or minimum setting.
        /// </remarks>
        public MotorHat(I2cConnectionSettings settings, double frequency = 1600)
        {
            I2cDevice device = I2cDevice.Create(settings);

            _pca9685 = new Pca9685(device);

            _pca9685.PwmFrequency = frequency;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MotorHat"/> class with the specified I2C settings and PWM frequency.
        /// </summary>
        /// <param name="settings">The I2C settings of the MotorHat.</param>
        /// <param name="frequency">The frequency in Hz to set the PWM controller.</param>
        /// <param name="pinProvider">The <see cref="IMotorPinProvider"/> that provides <see cref="MotorPins"/> for various hats.</param>
        /// <remarks>
        /// The default i2c address is 0x60, but the HAT can be configured in hardware to any address from 0x60 to 0x7f.
        /// The PWM hardware used by this HAT is a PCA9685. It has a total possible frequency range of 24 to 1526 Hz.
        /// Setting the frequency above or below this range will cause PWM hardware to be set at its maximum or minimum setting.
        /// </remarks>
        public MotorHat(I2cConnectionSettings settings, double frequency = 1600, IMotorPinProvider?pinProvider = default)
        {
            I2cDevice device = I2cDevice.Create(settings);

            _pca9685     = new Pca9685(device);
            _pinProvider = pinProvider ?? MotorPinProvider.Default;

            _pca9685.PwmFrequency = frequency;
        }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="i2cBus">i2c bus</param>
        /// <param name="address">The address of the i2c Peripheral</param>
        /// <param name="freq">The PWM frequency for the PCA9685 IC</param>
        public MotorWing(string i2cBus, byte address = 0x60, int frequency = 1600)
        {
            if (i2cBus == null)
            {
                throw new ArgumentNullException("i2cBus");
            }

            pca9685 = new Pca9685(i2cBus, address, frequency);
        }
Ejemplo n.º 11
0
        public ServoWing(string i2cBus, byte address = 0x40, int frequency = 50, short portCount = 8)
        {
            if (portCount != 8 && portCount != 16)
            {
                throw new ArgumentException("Channels need to be 8 or 16", "ports");
            }

            this.portCount = portCount;
            pca9685        = new Pca9685(i2cBus, address, frequency);
        }
Ejemplo n.º 12
0
        public ServoWing(II2cBus i2cBus, byte address = 0x40, int frequency = 50, short ports = 8)
        {
            if (ports != 8 && ports != 16)
            {
                throw new ArgumentException("Channels need to be 8 or 16", "ports");
            }

            _ports   = ports;
            _pca9685 = new Pca9685(i2cBus, address, frequency);
        }
Ejemplo n.º 13
0
        /// <inheritdoc/>
        public void Dispose()
        {
            foreach (var channel in _channelsUsed)
            {
                channel.Stop();
            }

            _pca9685?.Dispose();
            _pca9685 = null !;
        }
Ejemplo n.º 14
0
        public void Init()
        {
            int busId = 1;
            I2cConnectionSettings settings = new I2cConnectionSettings(busId, _i2cAddress);

            _i2cDevice = I2cDevice.Create(settings);
            _pca9685   = new Pca9685(_i2cDevice, pwmFrequency: 50);

            _servoChannel = _pca9685.CreatePwmChannel(_channelNumber);
            _servoMotor   = new ServoMotor(_servoChannel, 180, 500, 2500);
        }
Ejemplo n.º 15
0
        public HardwareAccess()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                // Setup PWM Controller
                var settings = new I2cConnectionSettings(busId, deviceAddress);

                I2cDevice = I2cDevice.Create(settings);
                Pwm       = new Pca9685(I2cDevice);

                // Setup the pins for the buttons
                Gpio = new GpioController(PinNumberingScheme.Logical);

                // Setup the pin for the lights
                Gpio.OpenPin(RELAY_1, PinMode.Output);
            }
        }
Ejemplo n.º 16
0
        public void Init(int channelNumber)
        {
            if (channelNumber < 0 || channelNumber >= MaxNumberOfMotors)
            {
                throw new Exception($"ChannelNumber can be [0...{MaxNumberOfMotors - 1}].");
            }

            if (_motor[channelNumber] != null && _motor[channelNumber].Initialized)
            {
                return;
            }

            Motor motor;

            if (_motor[channelNumber] != null)
            {
                motor = _motor[channelNumber];
            }
            else
            {
                motor = new Motor();
            }

            int busId = 1;

            if (_i2cConnectionSettings == null)
            {
                _i2cConnectionSettings = new I2cConnectionSettings(busId, _i2cAddress);
            }
            if (_i2cDevice == null)
            {
                _i2cDevice = I2cDevice.Create(_i2cConnectionSettings);
            }
            if (_pca9685 == null)
            {
                _pca9685 = new Pca9685(_i2cDevice, pwmFrequency: 50);
            }

            motor.Pwm             = _pca9685.CreatePwmChannel(channelNumber * 3);     //speed
            motor.In1             = _pca9685.CreatePwmChannel(channelNumber * 3 + 1); //in1
            motor.In2             = _pca9685.CreatePwmChannel(channelNumber * 3 + 2); //in2
            motor.Pwm.DutyCycle   = 0.0;                                              //stop motor
            motor.Initialized     = true;
            _motor[channelNumber] = motor;
        }
Ejemplo n.º 17
0
        public static IServiceCollection AddControlLayer(this IServiceCollection services)
        {
            // Configure the Remote Control Controller
            services.AddHostedService <RemoteControlController>(s =>
            {
                var gamepadDriver = new GamepadDriver(s.GetService <ILogger <GamepadDriver> >());

                return(new RemoteControlController(
                           gamepadDriver,
                           s.GetService <IMessageBroker>(),
                           s.GetService <IOptions <RemoteControlOptions> >(),
                           s.GetService <ILogger <RemoteControlController> >()));
            });

            services.AddHostedService <ServoController>((s) =>
            {
                var busId = 1;
                var selectedI2cAddress = 0b000000; // A5 A4 A3 A2 A1 A0
                var deviceAddress      = Pca9685.I2cAddressBase + selectedI2cAddress;
                var settings           = new I2cConnectionSettings(busId, deviceAddress);
                var device             = I2cDevice.Create(settings);
                var pca9685            = new Pca9685(device);
                pca9685.PwmFrequency   = 50;

                return(new ServoController(new List <IServo>
                {
                    new ServoDriver(pca9685, 0),
                    new ServoDriver(pca9685, 1),
                    new ServoDriver(pca9685, 2),
                    new ServoDriver(pca9685, 3),
                    new ServoDriver(pca9685, 4),
                    new ServoDriver(pca9685, 5),
                    new ServoDriver(pca9685, 6),
                    new ServoDriver(pca9685, 7),
                    new ServoDriver(pca9685, 8),
                    new ServoDriver(pca9685, 9),
                    new ServoDriver(pca9685, 10),
                    new ServoDriver(pca9685, 11)
                }, s.GetService <IMessageBroker>(), s.GetService <ILogger <ServoController> >()));
            });

            return(services);
        }
Ejemplo n.º 18
0
        void Initialize()
        {
            Console.WriteLine("Initialize hardware...");

            onboardLed = new RgbPwmLed(device: Device,
                                       redPwmPin: Device.Pins.OnboardLedRed,
                                       greenPwmPin: Device.Pins.OnboardLedGreen,
                                       bluePwmPin: Device.Pins.OnboardLedBlue,
                                       3.3f, 3.3f, 3.3f,
                                       Meadow.Peripherals.Leds.IRgbLed.CommonType.CommonAnode);

            bus = Device.CreateI2cBus(400000);

            pca = new Pca9685(bus, 64, 500);
            pca.Initialize();

            lPwm = pca.CreatePwmPort(14, 0);
            rPwm = pca.CreatePwmPort(15, 0);

            currentPort = rPwm;

            encoder          = new RotaryEncoder(Device, Device.Pins.D15, Device.Pins.D11);
            encoder.Rotated += Encoder_Rotated;
        }
Ejemplo n.º 19
0
        public DCMotor(short num, Pca9685 pca9685) : base(pca9685)
        {
            if (num < 0 || num > 3)
            {
                throw new ArgumentException("Motor must be between 0 and 3");
            }

            switch (num)
            {
            case 0:
                _pwmPin = 8;
                _in2    = 9;
                _in1    = 10;
                break;

            case 1:
                _pwmPin = 13;
                _in2    = 12;
                _in1    = 11;
                break;

            case 2:
                _pwmPin = 2;
                _in2    = 3;
                _in1    = 4;
                break;

            case 3:
                _pwmPin = 7;
                _in2    = 6;
                _in1    = 5;
                break;
            }

            Run(Commmand.RELEASE);
        }
Ejemplo n.º 20
0
 public ServoBoardDriver()
 {
     _pca9685 = new Pca9685();
 }
Ejemplo n.º 21
0
 public void SensorDateProvider()             //contructor method for sensors, current and future go here
 {
     mcp3008 = new MCP3008(ReferenceVoltage); //ADC construction for O2
     mhz16   = new MHZ16();                   // contructor for CO2
     Pca9685 pca9685 = new Pca9685();         //contructor for PWM
 }
Ejemplo n.º 22
0
 public Motor(Pca9685 pca9685)
 {
     _pca9685 = pca9685;
 }
Ejemplo n.º 23
0
 public static void Lunch()
 {
     BasePca = new Pca9685();
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Initializes all hardware and software classes
        /// </summary>
        void Initialize()
        {
            Console.WriteLine("Initialize hardware...");

            onboardLed = new RgbPwmLed(device: Device,
                                       redPwmPin: Device.Pins.OnboardLedRed,
                                       greenPwmPin: Device.Pins.OnboardLedGreen,
                                       bluePwmPin: Device.Pins.OnboardLedBlue,
                                       3.3f, 3.3f, 3.3f,
                                       Meadow.Peripherals.Leds.IRgbLed.CommonType.CommonAnode);

#if DEBUG
            Console.WriteLine("Initializing bus");
#endif
            bus = Device.CreateI2cBus(400000);

#if DEBUG
            Console.WriteLine("Initializing display 1");
#endif
            displaySmall = new DisplayLCD(bus, 0x27, 2, 16);
            displaySmall.Write("I'm alive!");

#if DEBUG
            Console.WriteLine("Initializing display 2");
#endif
            displayBig = new DisplayLCD(bus, 0x23, 4, 20);
            displayBig.Write("I'm alive!");

#if DEBUG
            Console.WriteLine("Initializing hc12");
#endif
            displaySmall.Write("Initializing radio");
            serialCom = new HC12Communication(Device.CreateSerialMessagePort(Device.SerialPortNames.Com4,
                                                                             suffixDelimiter: new byte[] { 10 },
                                                                             preserveDelimiter: true, 115200, 8, Parity.None,
                                                                             StopBits.One));
            com = new CommunicationWrapper(serialCom);

#if DEBUG
            Console.WriteLine("Initializing WiFi");
#endif
            displaySmall.Write("Initializing WiFi");
            ipCom = new WifiUdpCommunication(Device.WiFiAdapter, new Action <string>[] { com.SendMessage, displaySmall.Write });
            //Trying to connect at startup to speed process up, but router might be still booting so in that case will try again when requested
            Task.Run(() =>
            {
                try
                {
                    ConnectToWiFi("");
                }
                catch (Exception e)
                {
                    com.SendMessage(ReturnCommandList.exception + e.Message + ReturnCommandList.exceptionTrace + e.StackTrace);
#if DEBUG
                    Console.WriteLine(e.Message + "/n/n" + e.StackTrace);
#endif
                }
            });

#if DEBUG
            Console.WriteLine("Initializing RTC");
#endif
            displaySmall.Write("Initializing RTC");
            clock = new Rtc(bus, com.SendMessage, SetClock);
            clock.SetClockFromRtc();

#if DEBUG
            Console.WriteLine("Initializing watchdog");
#endif
            displaySmall.Write("Initializing watchdog");
            watchdog = new Watchdog(Watchdog.Type.SerialPort);
            //serialCom.RegisterWatchdog(watchdog.MessageReceived);
            //ipCom.RegisterWatchdog(watchdog.MessageReceived);
            watchdog.RegisterSender(com.SendMessage);
            watchdog.RegisterBlockAction(EmergencyDisable);
            watchdog.RegisterSwitchToSerial(SwitchToSerial);

            dict  = new MethodsDictionary();
            queue = new MethodsQueue(com, dict);
            ipCom.SubscribeToMessages(queue.MessageReceived);
            ipCom.SubscribeToMessages(watchdog.MessageReceived);
            serialCom.SubscribeToMessages(queue.MessageReceived);
            serialCom.SubscribeToMessages(watchdog.MessageReceived);

#if DEBUG
            Console.WriteLine("Initializing pca @1600Hz");
#endif
            displaySmall.Write("Initializing PWM @1600Hz");
            pwm1600 = new Pca9685(bus, 0x61, 1600);
            pwm1600.Initialize();
#if DEBUG
            Console.WriteLine("Initializing pca @50Hz");
#endif
            displaySmall.Write("Initializing PWM @50Hz");
            pwm50 = new Pca9685(bus, 0x60, 50);
            pwm50.Initialize();

#if DEBUG
            Console.WriteLine("Initializing expander 1");
#endif
            displaySmall.Write("Initializing expander 1");
            expander1 = new Mcp23x08(bus, 0x20, Device.CreateDigitalInputPort(Device.Pins.D02, InterruptMode.EdgeBoth));

#if DEBUG
            Console.WriteLine("Initializing expander 2");
#endif
            displaySmall.Write("Initializing expander 2");
            expander2 = new Mcp23x08(bus, 0x21, Device.CreateDigitalInputPort(Device.Pins.D06, InterruptMode.EdgeBoth));

#if DEBUG
            Console.WriteLine("Initializing fans");
#endif
            displaySmall.Write("Initializing fans");
            LEDsFans   = new Fan(expander2.CreateDigitalOutputPort(expander2.Pins.GP4), "LEDs' fans");
            motorsFans = new Fan(expander2.CreateDigitalOutputPort(expander2.Pins.GP5), "Motors' fans");
            inasFan    = new Fan(expander2.CreateDigitalOutputPort(expander2.Pins.GP6), "INAs fan");

#if DEBUG
            Console.WriteLine("Initializing buzzer");
#endif
            displaySmall.Write("Initializing buzzer");
            buzzer = new Buzzer(expander2.CreateDigitalOutputPort(expander2.Pins.GP3, false, OutputType.OpenDrain));
            watchdog.RegisterBuzzer(buzzer.Buzz);
#pragma warning disable CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania
            buzzer.Buzz();
#pragma warning restore CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania

#if DEBUG
            Console.WriteLine("Initializing power sensors");
#endif
            displaySmall.Write("Initializing power sensors");
            INA219.INA219Configuration config = new INA219.INA219Configuration(INA219.BusVoltageRangeSettings.range32v,
                                                                               INA219.PGASettings.Gain320mV,
                                                                               INA219.ADCsettings.Samples128,
                                                                               INA219.ADCsettings.Samples128,
                                                                               INA219.ModeSettings.ShuntBusContinuous);
            ina219s = new INA219Array(new INA219[]
            {
                new INA219(3.2f, 0.1f, 1, bus, 0x41, config, "C"),
                new INA219(10f, 0.01f, 1, bus, 0x44, config, "L"),
                new INA219(10f, 0.01f, 1, bus, 0x45, config, "R")
            }, buzzer, displayBig, EmergencyDisable);
            ina219s.RegisterSender(com.SendMessage);
            ina219s.RegisterFan(inasFan.SetState);
            ina219s.RegisterFan(motorsFans.SetState);
            ina219s.StartMonitoringVoltage();

            //com = new ComCommunication(Device.CreateSerialMessagePort(Device.SerialPortNames.Com4, suffixDelimiter: new byte[] { 10 }, preserveDelimiter: true, 921600, 8, Parity.None, StopBits.One));

#if DEBUG
            Console.WriteLine("Initializing temperature sensor");
#endif
            displaySmall.Write("Initializing temperature sensor");
            tempPresSensor = new TempPressureSensor(bus);
            tempPresSensor.RegisterSender(com.SendMessage);
#if DEBUG
            Console.WriteLine("Initializing position sensor");
#endif
            displaySmall.Write("Initializing position sensor");
            positionSensor = new BNO055(bus, 0x28);
            positionSensor.RegisterSender(com.SendMessage);
            positionSensor.RegisterScreen(displaySmall.Write);

#if DEBUG
            Console.WriteLine("Initializing motor controller");
#endif
            displaySmall.Write("Initializing motor controller");
            motor = new MotorController(pwm1600.CreatePwmPort(3, 0),
                                        pwm1600.CreatePwmPort(2, 0),
                                        pwm1600.CreatePwmPort(1, 0),
                                        pwm1600.CreatePwmPort(0, 0),
                                        pwm50.CreatePwmPort(0),
                                        Device.CreateDigitalInputPort(Device.Pins.D03, InterruptMode.EdgeRising, ResistorMode.InternalPullDown, 20, 20),
                                        Device.CreateDigitalInputPort(Device.Pins.D04, InterruptMode.EdgeRising, ResistorMode.InternalPullDown, 20, 20),
                                        positionSensor, gimbal, queue.ClearQueue);

#if DEBUG
            Console.WriteLine("Initializing gimbal");
#endif
            displaySmall.Write("Initializing camera gimbal");
            gimbal = new CameraGimbal(pwm50.CreatePwmPort(2), pwm50.CreatePwmPort(1), positionSensor);

#if DEBUG
            Console.WriteLine("Initializing proximity sensors");
#endif
            displaySmall.Write("Initializing proximity sensors");
            proxSensors = new ProximitySensorsArray(new ProximitySensor[]
            {
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP0, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Forward, StopBehavior.Stop, "Front, right", queue, motor),
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP1, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Forward, StopBehavior.Stop, "Front, left", queue, motor),
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP2, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Forward, StopBehavior.Stop, "Front, center", queue, motor),
                new ProximitySensor(expander1.CreateDigitalInputPort(expander1.Pins.GP3, InterruptMode.EdgeRising, ResistorMode.InternalPullUp, 500, 500), Direction.Backward, StopBehavior.Stop, "Back, center", queue, motor)
            });
            proxSensors.Register(com.SendMessage);
            //proxSensors.Register(displaySmall.Write);

#if DEBUG
            Console.WriteLine("Initializing lamps");
#endif
            displaySmall.Write("Initializing lamps");
            narrowLed = new LedLamp(pwm1600.CreatePwmPort(4, 0), LEDsFans, "Front, narrow");
            wideLed   = new LedLamp(pwm1600.CreatePwmPort(5, 0), LEDsFans, "Front, wide");

#if DEBUG
            Console.WriteLine("Initializing cameras");
#endif
            displaySmall.Write("Initializing cameras");
            camera = new Camera(expander2.CreateDigitalOutputPort(expander2.Pins.GP7));
            camera.SetCamera(true);

#if DEBUG
            Console.WriteLine("Finishing initialization");
#endif
            displaySmall.Write("Finishing initialization");
            RegisterMethods();
            //watchdog.StartCheckingMessages();
#if DEBUG
            Console.WriteLine("All hardware initialized!");
#endif
            displaySmall.Clear();
            displaySmall.Write("Ready!");
            com.SendMessage("Ready!");
#pragma warning disable CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania
            buzzer.BuzzPulse(100, 100, 3);
#pragma warning restore CS4014 // To wywołanie nie jest oczekiwane, dlatego wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            var busId = 1;  // /dev/i2c-1

            var deviceAddress_fixed      = 0x40;
            var deviceAddress_selectable = 0b000000;    // A5 A4 A3 A2 A1 A0
            var deviceAddress            = deviceAddress_fixed | deviceAddress_selectable;

            var settings = new I2cConnectionSettings(busId, deviceAddress);
            var device   = I2cDevice.Create(settings);

            using (var pca9685 = new Pca9685(device))
            {
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"PCA9685 is ready on I2C bus {device.ConnectionSettings.BusId} with address {device.ConnectionSettings.DeviceAddress}");

                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Command:  F {freq_hz}             set PWM frequency");
                Console.WriteLine("          P {prescale}            set PRE_SCALE register");
                Console.WriteLine("          S {off}                 set off step with on step is 0 to all channels");
                Console.WriteLine("          S {on} {off}            set on step and off step to all channels");
                Console.WriteLine("          S {on} {off} {channel}  set on step and off step to specified channel");

                Console.WriteLine();
                while (true)
                {
                    try
                    {
                        Console.ResetColor();
                        Console.Write("> ");
                        var command = Console.ReadLine().ToLower().Split(' ');

                        switch (command[0][0])
                        {
                        case 'f':       // set PWM frequency
                        {
                            var freq = double.Parse(command[1]);
                            pca9685.PwmFrequency = freq;

                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"PWM Frequency has been set to about {pca9685.PwmFrequency}Hz with prescale is {pca9685.Prescale}");
                            break;
                        }

                        case 'p':       // set PRE_SCALE register
                        {
                            var prescale = (byte)int.Parse(command[1]);
                            pca9685.Prescale = prescale;

                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"PWM Frequency has been set to about {pca9685.PwmFrequency}Hz with prescale is {pca9685.Prescale}");
                            break;
                        }

                        case 's':       // set PWM steps
                        {
                            switch (command.Length)
                            {
                            case 2:             // 1 parameter : set off step with on step is 0 to all channels
                            {
                                var off = int.Parse(command[1]);
                                pca9685.SetPwm(0, off);

                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"PWM pulse width has been set to {off}/4096");
                                break;
                            }

                            case 3:             // 2 parametes : set on step and off step to all channels
                            {
                                var on  = int.Parse(command[1]);
                                var off = int.Parse(command[2]);
                                pca9685.SetPwm(on, off);

                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"PWM pulse pull up at step {on} and pull down at step {off} on all channels");
                                break;
                            }

                            case 4:             // 3 parametes : set on step and off step to specified channel
                            {
                                var on      = int.Parse(command[1]);
                                var off     = int.Parse(command[2]);
                                var channel = int.Parse(command[3]);
                                pca9685.SetPwm(on, off, channel);

                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"PWM pulse pull up at step {on} and pull down at step {off} on channel {channel}");
                                break;
                            }
                            }
                            break;
                        }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(ex.GetBaseException().Message);
                        Console.ResetColor();
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public void Pca9685Test()
        {
            Pca9685 pca9685 = new Pca9685();

            pca9685.SetAngle(0, 10);
        }
Ejemplo n.º 27
0
 private static ServoMotor.ServoMotor CreateServo(Pca9685 pca9685, int channel)
 {
     return(new ServoMotor.ServoMotor(
                pca9685.CreatePwmChannel(channel),
                AngleRange, MinPulseWidthMicroseconds, MaxPulseWidthMicroseconds));
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Example program main entry point
        /// </summary>
        /// <param name="args">Command line arguments, see <see cref="PrintHelp"/></param>
        public static void Main(string[] args)
        {
            var busId = 1;
            var selectedI2cAddress = 0b000000; // A5 A4 A3 A2 A1 A0
            var deviceAddress      = Pca9685.I2cAddressBase + selectedI2cAddress;

            var settings = new I2cConnectionSettings(busId, deviceAddress);
            var device   = I2cDevice.Create(settings);

            using (var pca9685 = new Pca9685(device))
            {
                Console.WriteLine(
                    $"PCA9685 is ready on I2C bus {device.ConnectionSettings.BusId} with address {device.ConnectionSettings.DeviceAddress}");
                Console.WriteLine($"PWM Frequency: {pca9685.PwmFrequency}Hz");
                Console.WriteLine();
                PrintHelp();

                while (true)
                {
                    var command = Console.ReadLine().ToLower().Split(' ');
                    if (string.IsNullOrEmpty(command[0]))
                    {
                        return;
                    }

                    switch (command[0][0])
                    {
                    case 'q':
                        pca9685.SetDutyCycleAllChannels(0.0);
                        return;

                    case 'f':
                    {
                        var freq = double.Parse(command[1]);
                        pca9685.PwmFrequency = freq;
                        Console.WriteLine($"PWM Frequency has been set to {pca9685.PwmFrequency}Hz");
                        break;
                    }

                    case 'd':
                    {
                        switch (command.Length)
                        {
                        case 2:
                        {
                            double value = double.Parse(command[1]);
                            pca9685.SetDutyCycleAllChannels(value);
                            Console.WriteLine($"PWM duty cycle has been set to {value}");
                            break;
                        }

                        case 3:
                        {
                            int    channel = int.Parse(command[1]);
                            double value   = double.Parse(command[2]);
                            pca9685.SetDutyCycle(channel, value);
                            Console.WriteLine($"PWM duty cycle has been set to {value}");
                            break;
                        }
                        }

                        break;
                    }

                    case 'h':
                    {
                        PrintHelp();
                        break;
                    }

                    case 't':
                    {
                        int channel = int.Parse(command[1]);
                        ServoDemo(pca9685, channel);
                        PrintHelp();
                        break;
                    }
                    }
                }
            }
        }