Пример #1
0
        public void Backward(double frequency, double dutyCycle)
        {
            if (pwmController == null || servoGpioPinEn == null || gpioPinIn1 == null || gpioPinIn2 == null)
            {
                return;
            }

            var max = pwmController.MaxFrequency;
            var min = pwmController.MinFrequency;

            frequency = Math.Min(frequency, max);
            frequency = Math.Max(frequency, min);

            var maxDuty = 1.0;
            var minDuty = 0.0;

            dutyCycle = Math.Min(dutyCycle, maxDuty);
            dutyCycle = Math.Max(dutyCycle, minDuty);

            pwmController.SetDesiredFrequency(frequency);
            servoGpioPinEn.SetActiveDutyCyclePercentage(dutyCycle);

            gpioPinIn1.Write(GpioPinValue.High);
            gpioPinIn2.Write(GpioPinValue.Low);

            servoGpioPinEn.Start();
        }
Пример #2
0
 public void TiltUp()
 {
     mTopTiltServo.SetActiveDutyCyclePercentage(Math.Max(mBottomPanServo.GetActiveDutyCyclePercentage() - 0.01, 0));
     mTopTiltServo.Start();
     Task.Run(() =>
     {
         System.Threading.Tasks.Task.Delay(100).Wait();
         mTopTiltServo.Stop();
     });
 }
Пример #3
0
        // Initialize the PwmController class instance
        public async void Initialize()
        {
            try
            {
                var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());

                var pwmController = pwmControllers[1];    // the device controller
                pwmController.SetDesiredFrequency(50);

                Pwm = pwmController.OpenPin(LED_pin);
                Pwm.SetActiveDutyCyclePercentage(0);  // start at 0%
                Pwm.Start();
                if (Pwm == null)
                {
                    Debug.WriteLine("ERROR! Pwm device {0} may be in use.");
                    return;
                }
                Debug.WriteLine("GPIO pin setup for Pwm.");
            }
            catch (Exception e)
            {
                Debug.WriteLine("EXEPTION CAUGHT: " + e.Message + "\n" + e.StackTrace);
                throw;
            }
        }
        private async void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            if (LightningProvider.IsLightningEnabled)
            {
                LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();

                var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());

                var pwmController = pwmControllers[1]; // the on-device controller
                pwmController.SetDesiredFrequency(50); // try to match 50Hz

                _pin27 = pwmController.OpenPin(27);
                _pin27.SetActiveDutyCyclePercentage(0);
                _pin27.Start();
            }

            var gpioController = await GpioController.GetDefaultAsync();

            if (gpioController == null)
            {
                StatusMessage.Text = "There is no GPIO controller on this device.";
                return;
            }
            _pin22 = gpioController.OpenPin(22);
            _pin22.SetDriveMode(GpioPinDriveMode.Output);
            _pin22.Write(GpioPinValue.Low);
        }
Пример #5
0
        private void DoWork()
        {
            while (true)
            {
                MusicNote note;
                lock (_syncRoot)
                {
                    if (_playlist.Count == 0)
                    {
                        break;
                    }

                    note = (MusicNote)_playlist.Dequeue();
                }

                if (Math.Abs(note.Tone.Frequency) > 0.01)
                {
                    _pwmPin.Controller.SetDesiredFrequency((int)note.Tone.Frequency);
                    _pwmPin.SetActiveDutyCyclePercentage(0.5);
                    _pwmPin.Start();
                }
                else
                {
                    _pwmPin.Stop();
                }

                Thread.Sleep(note.Duration);
            }

            _pwmPin.Controller.SetDesiredFrequency(100);
            _pwmPin.SetActiveDutyCyclePercentage(0.0001);
        }
        private async void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            if (LightningProvider.IsLightningEnabled)
            {
                LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();

                var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());

                var pwmController = pwmControllers[1]; // the on-device controller
                pwmController.SetDesiredFrequency(50); // try to match 50Hz


                internetLed = new InternetLed();

                _pin18 = pwmController.OpenPin(18);

                while (true)
                {
                    await internetLed.GetThrottleFromWeb();

                    double test = internetLed.getThrottle() / 100.0;

                    _pin18.SetActiveDutyCyclePercentage(internetLed.getThrottle() / 100.0);
                    _pin18.Start();


                    await Task.Delay(200);
                }
            }
        }
Пример #7
0
 public PwmMotor(PwmController pwmController, int pwmPin, int direction1Pin, int direction2Pin) : base(pwmController, pwmPin)
 {
     _directionPin1 = PwmController.OpenPin(direction1Pin);
     _directionPin2 = PwmController.OpenPin(direction2Pin);
     _directionPin1.Start();
     _directionPin2.Start();
 }
Пример #8
0
        public async void StepperMotorExample()
        {
            MotorHat2348    mh      = null;
            PwmStepperMotor stepper = null;
            PwmPin          pwm     = null;

            if (mh == null)
            {
                // Create a driver object for the HAT at address 0x60
                mh = new MotorHat2348(0x60);
                // Create a stepper motor object at the specified ports and steps per rev
                stepper = mh.CreateStepperMotor(1, 2, 200);
                // Create a PwmPin object at one of the auxiliary PWMs on the HAT
                pwm = mh.CreatePwm(1);
            }

            // step 200 full steps in the forward direction using half stepping (so 400 steps total) at 30 rpm
            stepper.SetSpeed(30);
            await stepper.StepAsync(200, Direction.Forward, SteppingStyle.Half);

            // Activate the pin and set it to 50% duty cycle
            pwm.Start();
            pwm.SetActiveDutyCyclePercentage(0.5);

            // for demonstration purposes we will wait 10 seconds to observe the PWM and motor operation.
            await Task.Delay(10000);

            // Stop the auxiliary PWM pin
            pwm.Stop();

            // Dispose of the MotorHat and free all its resources
            mh.Dispose();
        }
Пример #9
0
        private async void OnPageLoad(object sender, RoutedEventArgs e)
        {
            if (LightningProvider.IsLightningEnabled)
            {
                LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
            }

            var gpioController = await GpioController.GetDefaultAsync();

            if (gpioController == null)
            {
                return;
            }

            var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());


            pwmController = pwmControllers[1];       //hard code from examples to use index 1
            pwmController.SetDesiredFrequency(1000); //do *not* debug over this line, it will crash
            rightDrive = pwmController.OpenPin(13);
            rightDrive.SetActiveDutyCyclePercentage(0.5);
            rightDrive.Start();
            leftDrive = pwmController.OpenPin(12);
            leftDrive.SetActiveDutyCyclePercentage(0.5);
            leftDrive.Start();
        }
Пример #10
0
 public static void SetMotorDuty(Servo servo, double speedPercentage, Direction direction)
 {
     if (speedPercentage < 0 || speedPercentage > 100)
     {
         throw new ArgumentOutOfRangeException("speedPercentage", "Must be between 0 and 100 %");
     }
     if (servo == Servo.A)
     {
         if (direction == Direction.Back)
         {
             DIRA.Write(GpioPinValue.Low);
         }
         else
         {
             DIRA.Write(GpioPinValue.High);
         }
         PWM1.SetDesiredFrequency(5000);
         PWMA.Start();
         PWMA.SetActiveDutyCyclePercentage(speedPercentage / 100);
     }
     else
     {
         if (direction == Direction.Forvard)
         {
             DIRB.Write(GpioPinValue.High);
         }
         else
         {
             DIRB.Write(GpioPinValue.Low);
         }
         PWM3.SetDesiredFrequency(5000);
         PWMB.Start();
         PWMB.SetActiveDutyCyclePercentage(speedPercentage / 100);
     }
 }
Пример #11
0
        public static void Main()
        {
            Debug.WriteLine("devMobile.Longboard.PwmTest starting");
            Debug.WriteLine(PwmController.GetDeviceSelector());

            try
            {
                PwmController pwm        = PwmController.FromId("TIM5");
                AdcController adc        = AdcController.GetDefault();
                AdcChannel    adcChannel = adc.OpenChannel(0);

                PwmPin pwmPin = pwm.OpenPin(PinNumber('A', 0));
                pwmPin.Controller.SetDesiredFrequency(1000);
                pwmPin.Start();

                while (true)
                {
                    double value = adcChannel.ReadRatio();

                    Debug.WriteLine(value.ToString("F2"));

                    pwmPin.SetActiveDutyCyclePercentage(value);

                    Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Пример #12
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            _controller     = new PinsController();
            _gpioController = GpioController.GetDefault();

            bool initialized = await _controller.InitAsync(PWM_FREQUENCY);

            if (initialized)
            {
                _pin1 = _controller.OpenPin(6);
                _pin1.Start();

                _pin2 = _controller.OpenPin(13);
                _pin2.Start();

                _pin3 = _controller.OpenPin(19);
                _pin3.Start();

                _pin4 = _controller.OpenPin(26);
                _pin4.Start();

                _pin5 = _gpioController.OpenPin(4);
                _pin5.SetDriveMode(GpioPinDriveMode.Output);
                _pin5.Write(GpioPinValue.Low);
            }

            _httpServer = new HttpServer(6000, 250);
            _httpServer.StartServer();

            _httpServer.MessageReceived       += new EventHandler <byte[]>((s, m) => HandleMessage(m));
            _httpServer.CommunicationTimedOut += new EventHandler <long>((s, l) => HandleTimeOut(l));
        }
Пример #13
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // Check presence of GPIO Controller
            // Since this is UWP, this application runs on desktop, mobile, as well as embedded devices
            // best to confirm we are running on an embedded device like R Pi
            GpioController gpio = GpioController.GetDefault();

            if (gpio == null)
            {
                Debug.WriteLine("This device does not have GPIO Controller.");
                return;
            }

            var pwmManager = new PwmProviderManager();

            pwmManager.Providers.Add(new SoftPwm());

            var pwmContollers = await pwmManager.GetControllersAsync();

            pwmController = pwmContollers[0];
            pwmController.SetDesiredFrequency(50);

            pwmPin = pwmController.OpenPin(servoPin);
            pwmPin.Start();

            timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(15)
            };
            timer.Tick += Timer_Tick;
            timer.Start();

            IsClockwise = false;
        }
Пример #14
0
        public async Task <bool> Rotate(LuisResult result, object context, object speak)
        {
            var speech = (App.SpeechFunc)speak;

            var c = (Context)context;

            if (c.IsIoTCore)
            {
                speech("Feel the burn baby!");

                pwmController = (await PwmController.GetControllersAsync(PwmSoftware.PwmProviderSoftware.GetPwmProvider()))[0];
                pwmController.SetDesiredFrequency(50);

                try
                {
                    motorPin = pwmController.OpenPin(26);
                }

                catch
                { }

                motorPin.SetActiveDutyCyclePercentage(RestingPulseLegnth);
                motorPin.Start();
                iteration = 0;
                timer     = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromSeconds(1));
            }
            else
            {
                speech("I am a fully functioning PC, not a robot.");
            }
            return(true);
        }
Пример #15
0
 internal Servo(PwmController pwmController, int pwmPin)
 {
     _position  = 0.0;
     _limitsSet = false;
     _pwmPin    = pwmController.OpenPin(pwmPin);
     _pwmPin.Start();
 }
Пример #16
0
 protected PwmMotorBase(PwmController pwmController, int pwmPin)
 {
     if (pwmController == null)
     {
         throw new ArgumentNullException(nameof(pwmController));
     }
     PwmController = pwmController;
     PwmPin        = PwmController.OpenPin(pwmPin);
     PwmPin.Start();
 }
Пример #17
0
 /// <summary>
 /// Creates an instance.
 /// </summary>
 /// <param name="pin">The PWM-enabled pin to use.</param>
 public AnalogPwmOutput(DigitalPwmOutputPin pin)
 {
     if (_controller == null)
     {
         CreateController(PwmFrequency);
     }
     _pin = _controller.OpenPin((int)pin);
     _pin.SetActiveDutyCyclePercentage(0.0);
     _pin.Start();
 }
Пример #18
0
        public virtual Task InitializeAsync()
        {
            if (!LightningProvider.IsLightningEnabled)
            {
                throw new NotSupportedException("PwmPinBase is not supported outside Lightning Provider");
            }

            _pin.Start();
            return(Task.CompletedTask);
        }
Пример #19
0
        /// <summary>
        /// If you dont move the servo outter forces can disorient it so we have to refresh it periodically.
        /// </summary>
        /// <param name="state"></param>
        private void TimerTick(object state)
        {
            // do some work not connected with UI
            pin.SetActiveDutyCyclePercentage(percentage);

            lock (lockObject)
            {
                pin.Start();
                Task.Delay(SIGNAL_DURATION).Wait();
                pin.Stop();
            }

            /*
             * await Window.Current.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
             *  () =>
             *  {
             *
             *      // do some work on UI here;
             *  });
             */
        }
Пример #20
0
        public void RotateServo()
        {
            // Start the servo with pwm
            pin.SetActiveDutyCyclePercentage(currPercent);
            pin.Start();

            // Update the previous duty cycle
            prevPercent = currPercent;
            // Wait 1s for servo to turn
            Task.Delay(1000).Wait();
            // Stop the servo
            pin.Stop();
        }
Пример #21
0
        private async void InitGPIO()
        {
            if (LightningProvider.IsLightningEnabled)
            {
                LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
                var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());

                _pwmController = pwmControllers[1];

                _outputPin = _pwmController.OpenPin(18);
                _outputPin.SetActiveDutyCyclePercentage(0.012);
                _outputPin.Start();
            }
        }
Пример #22
0
        public MainPage()
        {
            InitializeComponent();

            LED.Fill = new SolidColorBrush(Windows.UI.Colors.Blue);

            timer          = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(500);
            timer.Tick    += Timer_Tick;

            if (LightningProvider.IsLightningEnabled)
            {
                LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();

                var pwmControllers = PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider()).AsTask().Result;

                var pwm = pwmControllers[1]; // use the on-device controller

                if (pwm == null)
                {
                    pinR            = pinG = null;
                    GpioStatus.Text = "There is no PWM controller on this device.";
                }
                else
                {
                    pwm.SetDesiredFrequency(50);

                    pinR          = pwm.OpenPin(17);
                    pinR.Polarity = PwmPulsePolarity.ActiveLow;
                    pinR.SetActiveDutyCyclePercentage(0);
                    pinR.Stop();

                    pinG          = pwm.OpenPin(18);
                    pinG.Polarity = PwmPulsePolarity.ActiveLow;
                    pinG.SetActiveDutyCyclePercentage(0);
                    pinG.Stop();

                    GpioStatus.Text = "PWM pins initialized correctly.";

                    pinR.Start();
                    pinG.Start();

                    if (pinR != null && pinG != null)
                    {
                        timer.Start();
                    }
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Sets the position of the Servo Motor.
        /// </summary>
        /// <param name="position">The position of the servo between 0 and 180 degrees.</param>
        public void SetPosition(double position)
        {
            if (position < 0 || position > 180)
            {
                throw new ArgumentOutOfRangeException("degrees", "degrees must be between 0 and 180.");
            }

            // Typically, with 50 hz, 0 degree is 0.05 and 180 degrees is 0.10
            //double duty = ((position / 180.0) * (0.10 - 0.05)) + 0.05;
            double duty = ((position / 180.0) * (_MaxPulseCalibration / 20 - _MinPulseCalibration / 20)) + _MinPulseCalibration / 20;


            servo.SetActiveDutyCyclePercentage(duty);
            servo.Start();
        }
Пример #24
0
        /// <inheritdoc />
        public void SetActiveDutyCyclePercent(int newDutyCycle)
        {
            double newDutyCyclePercent = Math.Round(newDutyCycle / 100D, 2);

            _wrappedPin.SetActiveDutyCyclePercentage(newDutyCyclePercent);

            if (!_wrappedPin.IsStarted)
            {
                _wrappedPin.Start();
            }
            if (_wrappedPin.IsStarted && newDutyCyclePercent < 0.01)
            {
                _wrappedPin.Stop();
            }
        }
Пример #25
0
        public async void Setup(int _pinNumber, double _frequency)
        {
            var gpioController = GpioController.GetDefault();
            var pwmManager     = new PwmProviderManager();

            pwmManager.Providers.Add(new SoftPwm());

            var pwmControllers = await pwmManager.GetControllersAsync();

            _pwmController = pwmControllers[0];
            frequency      = _frequency; //TODO: get; set;
            _pwmController.SetDesiredFrequency(frequency);

            _pwmPin = _pwmController.OpenPin(_pinNumber);
            _pwmPin.Start();
        }
Пример #26
0
        private async void Init(int pin, int frequency, int activeDutyCyclePercentage)
        {
            this.pin         = pin;
            currentFrequency = frequency;
            this.activeDutyCyclePercentage = activeDutyCyclePercentage;

            var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());

            pwmController = pwmControllers[1]; // use the on-device controller

            motorPin = pwmController.OpenPin(pin);
            pwmController.SetDesiredFrequency(currentFrequency); // try to match 50Hz
            motorPin.SetActiveDutyCyclePercentage(activeDutyCyclePercentage);
            motorPin.Start();
            ready = true;
            BuzzerReady?.Invoke(this);
        }
        public void Initialize()
        {
            _redController.SetDesiredFrequency(10000);
            _greenController.SetDesiredFrequency(10000);
            _blueController.SetDesiredFrequency(10000);

            _redPin   = _redController.OpenPin(0);
            _greenPin = _greenController.OpenPin(2);
            _bluePin  = _blueController.OpenPin(4);

            _redPin.SetActiveDutyCyclePercentage(0.000f);
            _greenPin.SetActiveDutyCyclePercentage(0.000f);
            _bluePin.SetActiveDutyCyclePercentage(0.000f);

            _redPin.Start();
            _greenPin.Start();
            _bluePin.Start();
        }
Пример #28
0
        public static void Main()
        {
            Debug.WriteLine("devMobile.Longboard starting");
            Debug.WriteLine($"I2C:{I2cDevice.GetDeviceSelector()}");
            Debug.WriteLine($"PWM:{PwmController.GetDeviceSelector()}");

            try
            {
                Debug.WriteLine("LED Starting");
                GpioPin led = GpioController.GetDefault().OpenPin(PinNumber('A', 10));
                led.SetDriveMode(GpioPinDriveMode.Output);
                led.Write(GpioPinValue.Low);

                Debug.WriteLine("LED Starting");
                WiiNunchuk nunchuk = new WiiNunchuk("I2C1");

                Debug.WriteLine("ESC Starting");
                PwmController pwm    = PwmController.FromId("TIM5");
                PwmPin        pwmPin = pwm.OpenPin(PinNumber('A', 1));
                pwmPin.Controller.SetDesiredFrequency(PulseFrequency);
                pwmPin.Start();

                Debug.WriteLine("Thread.Sleep Starting");
                Thread.Sleep(2000);

                Debug.WriteLine("Mainloop Starting");
                while (true)
                {
                    nunchuk.Read();

                    double duration = Map(nunchuk.AnalogStickY, WiiNunchukYMinimum, WiiNunchukYMaximum, PulseDurationMinimum, PulseDurationMaximum);
                    Debug.WriteLine($"Value:{nunchuk.AnalogStickY} Duration:{duration:F3}");

                    pwmPin.SetActiveDutyCyclePercentage(duration);

                    led.Toggle();
                    Thread.Sleep(ThrottleUpdatePeriod);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Пример #29
0
        /// <summary>
        /// Initialize the servo.
        /// </summary>
        /// <returns></returns>
        public async Task InitializeAsync()
        {
            if (!LightningProvider.IsLightningEnabled)
            {
                throw new Exception("Servo can only be used with Lihtning provider");
            }


            controller = (await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider()))[1];

            pin = controller.OpenPin(PIN_NUMBER);
            controller.SetDesiredFrequency(FREQUENCY);

            pin.Start();

            DesiredPulseWidth = MIDDLE_PULSE_WIDTH;

            MoveServo();
        }
Пример #30
0
        private void SetMotorDirection(App.DIRECTION d)
        {
            //first stop the motors, change direction and then start the motors
            pwmMotorLeft.Stop();
            pwmMotorRight.Stop();

            switch (d)
            {
            case App.DIRECTION.FORWARD:
                //Both Motors in the same direction - Forward
                MotorLeftNegative.Write(GpioPinValue.Low);
                MotorLeftPositive.Write(GpioPinValue.High);
                MotorRightNegative.Write(GpioPinValue.Low);
                MotorRightPositive.Write(GpioPinValue.High);
                break;

            case App.DIRECTION.REVERSE:
                //Both Motors in the same direction but Reverse
                MotorLeftNegative.Write(GpioPinValue.High);
                MotorLeftPositive.Write(GpioPinValue.Low);
                MotorRightNegative.Write(GpioPinValue.High);
                MotorRightPositive.Write(GpioPinValue.Low);
                break;

            case App.DIRECTION.LEFT:
                //One of the Motor is in the reverse, while the other forward - Friction turn
                MotorLeftNegative.Write(GpioPinValue.Low);
                MotorLeftPositive.Write(GpioPinValue.High);     //Left Motor Forward
                MotorRightNegative.Write(GpioPinValue.High);
                MotorRightPositive.Write(GpioPinValue.Low);     //Right Motor Reverse
                break;

            case App.DIRECTION.RIGHT:
                //One of the Motor is in the reverse, while the other forward - Friction turn
                MotorLeftNegative.Write(GpioPinValue.High);
                MotorLeftPositive.Write(GpioPinValue.Low);
                MotorRightNegative.Write(GpioPinValue.Low);
                MotorRightPositive.Write(GpioPinValue.High);
                break;
            }
            pwmMotorLeft.Start();
            pwmMotorRight.Start();
        }