Пример #1
0
        private void RotateExample()
        {
            try
            {

                using (var hat = new PwmController())
                {
                    hat.SetDesiredFrequency(364); // spec'd to 658?

                    while (true)
                    {

                        int s = 0;
                        int m = 8;

                        int max = (int) ((float) 4096*(0.75));
                        int min = (int) ((float) 4096*(0.28));

                        while (true)
                        {
                            s += m;
                            if (s >= max)
                            {
                                s = max;
                                m = -4;
                            }
                            if (s <= min)
                            {
                                s = min;
                                m = 4;
                            }
                            hat.SetPulseParameters(15, s);

                            Task.Delay(TimeSpan.FromMilliseconds(10)).Wait();
                        }

                        hat.SetPulseParameters(15, 0);

                        hat.SetPulseParameters(4, 40); //aux
                        hat.SetPulseParameters(3, 40); //rud
                        hat.SetPulseParameters(2, 40); //ele
                        hat.SetPulseParameters(1, 40); //ail
                        hat.SetPulseParameters(0, 40); //thr

                        Task.Delay(TimeSpan.FromSeconds(5)).Wait();

                        hat.SetPulseParameters(15, 4096);

                        hat.SetPulseParameters(4, 4055); //aux
                        hat.SetPulseParameters(3, 4055); //rud
                        hat.SetPulseParameters(2, 4055); //ele
                        hat.SetPulseParameters(1, 4055); //ail
                        hat.SetPulseParameters(0, 4055); //thr

                        Task.Delay(TimeSpan.FromSeconds(5)).Wait();
                    }
                }
            }

            /* If the write fails display the error and stop running */
            catch (Exception ex)
            {
                Text_Status.Text = "Failed to communicate with device: " + ex.Message;
                return;
            }

        }
Пример #2
0
        /// <summary>
        /// Initializes the Remote Arduino Provider and stores the handles to the 4 controllers. Only runs once.
        /// </summary>
        private static async Task InitAsync()
        {
            await semaphoreSlim.WaitAsync();

            try
            {
                if (!initialized)
                {
                    // Change this to true for Bluetooth and false for USB
                    bool UseBluetooth       = false;
                    bool configurationFound = false;
                    DeviceInformation connectedDeviceInformation = null;

                    if (UseBluetooth)
                    {
                        // This assumes that there is only one BT SPP device on the computer. If there are multiple devices
                        // the you will need to identify the device from the list returned from FindAllAsync() and use
                        // that one as the device to pass to the arduino provider
                        string spp_aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
                        DeviceInformationCollection deviceList = await DeviceInformation.FindAllAsync(spp_aqs);

                        if (deviceList.Count > 0)
                        {
                            DeviceInformation device = deviceList[0];

                            // Remember to ensure that the Firmata Sketch has the baud rate set to the same default as the BT device
                            ArduinoProviders.ArduinoProvider.Configuration = new ArduinoProviders.ArduinoConnectionConfiguration(device, 57600);
                            configurationFound = true;
                        }
                        else
                        {
                            Debug.WriteLine("No bluetooth connected Arduino found");
                        }
                    }
                    else
                    {
                        Selector selector = new Selector();
                        IEnumerable <ArduinoDeviceListEntry> list = await selector.GetDeviceList();

                        if (list.Count() > 0)
                        {
                            var listArray = list.ToArray();

                            connectedDeviceInformation = listArray[0].DeviceInformation;
                            ArduinoProviders.ArduinoProvider.Configuration = new ArduinoProviders.ArduinoConnectionConfiguration(connectedDeviceInformation, 57600);
                            configurationFound = true;
                        }
                        else
                        {
                            Debug.WriteLine("No USB Connected Ardino found");
                        }
                    }

                    // we can't use a null check on Configuration as it will auto allocate and be in an invalid state
                    if (configurationFound)
                    {
                        // Check our firmata and make sure we are good, if not we will flash the device with our required MakeCode specific firmata
                        int  retry = 2;
                        bool FirmwareUploadRequired = false;

                        while (retry-- > 0)
                        {
                            FirmwareUploadRequired = false;
                            try
                            {
                                if (firmataProvider == null)
                                {
                                    firmataProvider = new ArduinoProviders.ArduinoFirmataProvider();
                                }
                                bool firmataInitOk = false;
                                try
                                {
                                    firmataInitOk = await firmataProvider.InitializeAsync();
                                }
                                catch (Exception e)
                                {
                                    Debug.WriteLine(e.Message);
                                }

                                if (firmataInitOk == true)
                                {
                                    // there is a firmata version on the device now.  Check if it is what we need.
                                    int MajorVersion = firmataProvider.FirmataInstance.getFirmwareVersionMajor();
                                    int MinorVersion = firmataProvider.FirmataInstance.getFirmwareVersionMinor();

                                    String FirmwareName = firmataProvider.FirmataInstance.getFirmwareName();
                                    Debug.WriteLine($"Arduino with Firmata found Version {MajorVersion}.{MinorVersion} {FirmwareName}");
                                    if (String.Compare(FirmwareName, "MakeCodeFirmata.ino", StringComparison.OrdinalIgnoreCase) != 0)
                                    {
                                        // Not the makecode firmware so need to upload it
                                        FirmwareUploadRequired = true;
                                    }
                                    else
                                    {
                                        // Makecode firmware, but is it the required version?
                                        // TODO: Version check
                                    }
                                }
                                else
                                {
                                    // No firmata on the device
                                    FirmwareUploadRequired = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Failed to get Firmata Instance: " + ex.Message);
                                FirmwareUploadRequired = true;
                            }

                            if (FirmwareUploadRequired)
                            {
                                Debug.WriteLine("Firmata update required");
                                // Need to close our current connection if any
                                if (firmataProvider != null)
                                {
                                    firmataProvider.Dispose();
                                    firmataProvider = null;

                                    ArduinoProvider.Close();
                                }

                                Arduino arduino = Arduino.GetArduino(connectedDeviceInformation.Id);

                                await arduino.Connect();

                                var programmer = arduino.GetProgrammer();

                                await programmer.Program("ms-appx:///BlockCode/MakeCodeFirmata/MakeCodeFirmata.ino.standard.hex", 28672);

                                // Now let the arduino go so we can reopen it in non progamming mode.
                                arduino.Dispose();

                                // And we will let it cycle again to verify
                                Debug.WriteLine("Arduino Firmata updated ");
                                return;
                            }
                            else
                            {
                                // Have a good firmware so store it and setup our callback
                                uwpFirmata = firmataProvider.FirmataInstance;
                                uwpFirmata.SysexMessageReceived += UwpFirmata_SysexMessageReceived;
                                retry = 0;
                            }
                        }

                        if (uwpFirmata == null)
                        {
                            // not going to be able to go on.
                            Debug.WriteLine("Arduino Firmata Initalization failed");
                            return;
                        }

                        // Now that we have a good firmata we can do the other connections
                        Windows.Devices.LowLevelDevicesController.DefaultProvider = new ArduinoProviders.ArduinoProvider();

                        gpioController = await GpioController.GetDefaultAsync();

                        pwmController = await PwmController.GetDefaultAsync();

                        adcController = await AdcController.GetDefaultAsync();

                        i2cController = await I2cController.GetDefaultAsync();

                        if (
                            (gpioController != null) &&
                            (pwmController != null) &&
                            (adcController != null) &&
                            (i2cController != null) &&
                            (uwpFirmata != null)
                            )
                        {
                            // We got good initialzation
                            initialized = true;
                        }
                    }
                    else
                    {
                        // Something went wrong with init
                        Debug.WriteLine("Arduino Initalization failed");
                    }
                }

                else
                {
                    // Duplicate initalization, we can just ignore this
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Arduino Initalization failed: " + e.Message);
            }
            finally
            {
                // When the task is ready, release the semaphore. It is vital to ALWAYS release the semaphore when we are ready,
                // or else we will end up with a Semaphore that is forever locked.
                // This is why it is important to do the Release within a try...finally clause;
                // program execution may crash or take a different path, this way you are guaranteed execution
                semaphoreSlim.Release();
            }
        }
Пример #3
0
        static void TestTinyBit()
        {
            var buzzerController = PwmController.FromName(FEZBit.PwmChannel.Controller3.Id);
            var buzzerChannel    = buzzerController.OpenChannel(FEZBit.PwmChannel.Controller3.EdgeP0Channel);
            var lineDetectLeft   = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP13);
            var lineDetectRight  = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP14);
            var voiceSensor      = AdcController.FromName(FEZBit.Adc.Controller1.Id).OpenChannel(FEZBit.Adc.Controller1.EdgeP1);
            var p2remove         = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP1);
            var distanceTrigger  = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP16);
            var distanceEcho     = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.EdgeP15);

            p2remove.SetDriveMode(GpioPinDriveMode.Input);

            var bot = new TinyBitController(
                I2cController.FromName(FEZBit.I2cBus.Edge),
                buzzerChannel,
                voiceSensor,
                lineDetectLeft, lineDetectRight, distanceTrigger, distanceEcho,
                FEZBit.GpioPin.EdgeP12
                );


            new Thread(() => {
                while (true)
                {
                    bot.SetHeadlight(100, 0, 0);
                    Thread.Sleep(200);
                    bot.SetHeadlight(0, 0, 100);
                    Thread.Sleep(300);
                }
            }).Start();

            /*new Thread(() => {
             *  while (true) {
             *      bot.Beep();
             *      Thread.Sleep(2_000);
             *  }
             * }).Start();
             */
            while (true)
            {
                bot.SetMotorSpeed(0.5, 0.5);
                var l = bot.ReadLineSensor(true);
                var r = bot.ReadLineSensor(false);
                var v = bot.ReadVoiceLevel();
                var d = bot.ReadDistance();
                if (d < 20)
                {
                    bot.SetMotorSpeed(-0.5, -0.5);
                    Thread.Sleep(200);
                    bot.SetMotorSpeed(-0.5, 0.5);
                    Thread.Sleep(200);
                    bot.SetMotorSpeed(0, 0);
                    Thread.Sleep(1000);


                    bot.Beep();
                    Thread.Sleep(100);
                    bot.Beep();
                    Thread.Sleep(100);
                    bot.Beep();
                    Thread.Sleep(100);
                }
                Thread.Sleep(10);
            }

            bot.SetHeadlight(30, 100, 100);
            bot.SetColorLeds(1, 200, 0, 0);
            bot.SetMotorSpeed(0.5, 0.5);
            bot.SetMotorSpeed(0.5, -0.5);
            bot.SetMotorSpeed(-0.5, 0.5);
            bot.SetMotorSpeed(0, 0);
            while (true)
            {
                var l = bot.ReadLineSensor(true);
                var r = bot.ReadLineSensor(false);
                var v = bot.ReadVoiceLevel();

                Thread.Sleep(50);
                bot.Beep();
            }
        }
Пример #4
0
        static void TestMaqueen()
        {
            var buzzerController = PwmController.FromName(FEZBit.Timer.Pwm.Controller3.Id);
            var buzzerChannel    = buzzerController.OpenChannel(FEZBit.Timer.Pwm.Controller3.P0);
            var lineDetectLeft   = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P13);
            var lineDetectRight  = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P14);
            var leftHeadlight    = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P8);
            var rightHeadight    = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P12);

            var bot = new GHIElectronics.TinyCLR.Dfrobot.MicroMaqueen.MaqueenController(
                I2cController.FromName(FEZBit.I2cBus.Edge),
                buzzerChannel,
                leftHeadlight, rightHeadight,
                lineDetectLeft, lineDetectRight,
                GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P15)
                );

            bot.Beep();
            bot.SetColorLeds(1, 100, 0, 0);
            bot.SetColorLeds(0, 0, 50, 100);
            new Thread(() => {
                while (true)
                {
                    bot.SetHeadlight(true, true);
                    Thread.Sleep(200);
                    bot.SetHeadlight(false, true);
                    Thread.Sleep(300);
                }
            }).Start();
            new Thread(() => {
                while (true)
                {
                    bot.Beep();
                    Thread.Sleep(5_000);
                }
            }).Start();

            while (true)
            {
                bot.SetMotorSpeed(0.5, 0.5);
                if (bot.ReadLineSensor(true) || bot.ReadLineSensor(false))
                {
                    bot.SetMotorSpeed(-0.5, -0.5);
                    Thread.Sleep(200);
                    bot.SetMotorSpeed(-0.5, 0.5);
                    Thread.Sleep(200);
                    bot.SetMotorSpeed(0, 0);
                    Thread.Sleep(1000);
                }
                Thread.Sleep(10);
            }
            bot.SetMotorSpeed(0.5, 0.5);
            bot.SetMotorSpeed(0.5, -0.5);
            bot.SetMotorSpeed(-0.5, 0.5);
            bot.SetMotorSpeed(0, 0);
            while (true)
            {
                var l = bot.ReadLineSensor(true);
                var r = bot.ReadLineSensor(false);

                Thread.Sleep(50);
                bot.Beep();
            }
        }
Пример #5
0
        static void Main()
        {
            new Thread(Blinker).Start();

            // disable wifi
            var wifien = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.WiFiEnable);

            wifien.SetDriveMode(GpioPinDriveMode.Output);
            wifien.Write(GpioPinValue.High);
            var wifireset = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.WiFiReset);

            wifireset.SetDriveMode(GpioPinDriveMode.Output);
            wifireset.Write(GpioPinValue.High);
            var wifics = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.WiFiChipselect);

            wifics.SetDriveMode(GpioPinDriveMode.Output);
            wifics.Write(GpioPinValue.High);

            //InitDisplay();
            //TestWaveshareDisplay();
            //TestTouchPads();
            //TestYahboomPiano();
            //TestMaqueen();
            TestTinyBit();
            //TestTpBot();
            //TestCuteBot();
            //TestScrollBit();
            //InitBot();


            while (false)
            {
                //bot.SetMotorSpeed(0.5, 0.5);
                //Thread.Sleep(2000);
                //bot.SetMotorSpeed(0.5, -0.5);
                //Thread.Sleep(500);
                //bot.SetMotorSpeed(0, 0);
                //Thread.Sleep(500);
                var d = bot.ReadLineSensor(false);
                bot.Beep();
            }


            // Buzzer ///////////////////
            var pwmController3 = PwmController.FromName(FEZBit.Timer.Pwm.Controller3.Id);
            var buzzer         = pwmController3.OpenChannel(FEZBit.Timer.Pwm.Controller3.Buzzer);

            pwmController3.SetDesiredFrequency(500);
            buzzer.SetActiveDutyCyclePercentage(0.5);
            buzzer.Start();
            for (var f = 500; f < 5_000; f += 300)
            {
                pwmController3.SetDesiredFrequency(f);
                Thread.Sleep(1);
            }
            buzzer.Stop();

            bot.SetMotorSpeed(0.5, -0.9);
            screen.DrawString("Press A", font12, new SolidBrush(Color.Teal), 50, 90);
            screen.Flush();
            // wait for A button //////////////////////
            var buttonA = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.ButtonA);

            buttonA.SetDriveMode(GpioPinDriveMode.InputPullUp);
            while (buttonA.Read() == GpioPinValue.High)
            {
                Thread.Sleep(10);
            }
            bot.SetMotorSpeed(0, -0);

            screen.Clear();

            screen.DrawString("TinyCLR OS", font12, new SolidBrush(Color.Teal), 40, 70);
            for (var i = 0; i < 128; i += 8)
            {
                screen.DrawLine(new Pen(Color.Yellow), i, 0, 0, 128 - i);
                bot.Beep();
                screen.Flush();
            }
            for (var i = 0; i < 128; i += 8)
            {
                screen.DrawLine(new Pen(Color.Purple), 160 - i, 0, 160, 128 - i);
                bot.Beep();
                screen.Flush();
            }
            Thread.Sleep(-1);
        }
Пример #6
0
 public WindowsPwmController(PwmController pwmController)
 {
     m_PwmController = pwmController;
 }
Пример #7
0
        static void TestTpBot()
        {
            var buzzerController = PwmController.FromName(FEZBit.Timer.Pwm.Controller3.Id);
            var buzzerChannel    = buzzerController.OpenChannel(FEZBit.Timer.Pwm.Controller3.P0);
            var lineDetectLeft   = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P13);
            var lineDetectRight  = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P14);
            var voiceSensor      = AdcController.FromName(FEZBit.Adc.Controller1.Id).OpenChannel(FEZBit.Adc.Controller1.P1);
            var p2remove         = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P1);
            var distanceTrigger  = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P16);
            var distanceEcho     = GpioController.GetDefault().OpenPin(FEZBit.GpioPin.P15);

            p2remove.SetDriveMode(GpioPinDriveMode.Input);

            var bot = new TpBotController(
                I2cController.FromName(FEZBit.I2cBus.Edge),
                buzzerChannel,
                lineDetectLeft, lineDetectRight);//, distanceTrigger, distanceEcho);


            new Thread(() => {
                while (true)
                {
                    bot.SetHeadlight(100, 0, 0);
                    Thread.Sleep(200);
                    bot.SetHeadlight(0, 0, 100);
                    Thread.Sleep(300);
                }
            }).Start();

            /*new Thread(() => {
             *  while (true) {
             *      bot.Beep();
             *      Thread.Sleep(2_000);
             *  }
             * }).Start();
             */
            while (true)
            {
                bot.SetMotorSpeed(0.9, 0.9);
                var l = bot.ReadLineSensor(true);
                var r = bot.ReadLineSensor(false);
                //var v = bot.ReadVoiceLevel();

                /*var d = bot.ReadDistance();
                 * if (d < 20) {
                 *  bot.SetMotorSpeed(-0.9, -0.9);
                 *  Thread.Sleep(200);
                 *  bot.SetMotorSpeed(-0.9, 0.9);
                 *  Thread.Sleep(200);
                 *  bot.SetMotorSpeed(0, 0);
                 *  Thread.Sleep(1000);
                 *
                 *
                 *  bot.Beep();
                 *  Thread.Sleep(100);
                 *  bot.Beep();
                 *  Thread.Sleep(100);
                 *  bot.Beep();
                 *  Thread.Sleep(100);
                 * }*/
                Thread.Sleep(10);
            }
        }
Пример #8
0
        /// <summary>
        /// Initializes the RainbowHAT. It will setup all required
        /// GPIO pins.
        ///
        /// Caution:
        ///     This is required before accessing other
        ///     methods in this class.
        /// </summary>
        private async void InitializeAsync()
        {
            Logger.Log(this, "Starting InitializeAsync");

            // Check if drivers are enabled
            Logger.Log(this, "Checking for LightningProvider");
            if (!LightningProvider.IsLightningEnabled)
            {
                Logger.Log(this, "LightningProvider not enabled. Returning.");
                return;
            }

            // Aggregate provider.
            LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();

            // Get default controllers.
            Logger.Log(this, "Getting default controller.");
            pwmController  = (await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider()))[1];
            gpioController = await GpioController.GetDefaultAsync();

            i2cController = await I2cController.GetDefaultAsync();

            // Ensure requiored controllers are available.
            if (gpioController == null || i2cController == null || pwmController == null)
            {
                Logger.Log(this, "One or more controller missing.");
                return;
            }

            // Setup controllers.
            pwmController.SetDesiredFrequency(50);

            // Setup LEDs.
            Logger.Log(this, "Setup LEDs");
            redPin = gpioController.OpenPin(GPIO_NUMBER_RED);
            redPin.Write(GpioPinValue.Low);
            redPin.SetDriveMode(GpioPinDriveMode.Output);
            greenPin = gpioController.OpenPin(GPIO_NUMBER_GREEN);
            greenPin.Write(GpioPinValue.Low);
            greenPin.SetDriveMode(GpioPinDriveMode.Output);
            bluePin = gpioController.OpenPin(GPIO_NUMBER_BLUE);
            bluePin.Write(GpioPinValue.Low);
            bluePin.SetDriveMode(GpioPinDriveMode.Output);

            // Setup buttons
            Logger.Log(this, "Setup buttons");
            buttonAPin = gpioController.OpenPin(21);
            buttonAPin.SetDriveMode(GpioPinDriveMode.Input);
            buttonBPin = gpioController.OpenPin(20);
            buttonBPin.SetDriveMode(GpioPinDriveMode.Input);
            buttonCPin = gpioController.OpenPin(16);
            buttonCPin.SetDriveMode(GpioPinDriveMode.Input);

            // Setup buzzer
            Logger.Log(this, "Setup buzzers / servos / motors");
            buzzerPin = pwmController.OpenPin(GPIO_NUMBER_BUZZER);
            buzzerPin.SetActiveDutyCyclePercentage(0.05);

            // Setup timer.
            Logger.Log(this, "Setup timers");
            captiveButtonsValueReadTimer = ThreadPoolTimer.CreatePeriodicTimer(CaptiveButtonsValueReadTimer_Tick, BUTTON_READ_INTERVAL);
            temperatureValueReadTimer    = ThreadPoolTimer.CreatePeriodicTimer(TemperatureValueReadTimer_Tick, SENSOR_READ_INTERVAL);
            pressureValueReadTimer       = ThreadPoolTimer.CreatePeriodicTimer(PreassureValueReadTimer_Tick, SENSOR_READ_INTERVAL);

            // Initialze child devices
            Logger.Log(this, "Setup APA102");
            apa102.Initialize(gpioController);

            Logger.Log(this, "Setup BMP280");
            await bmp280.InitializeAsync(i2cController);

            Logger.Log(this, "Setup HT16K33");
            ht16k33.Initialize(i2cController);

            // Set device as intialized.
            Logger.Log(this, "Finished InitializeAsync");
            isInitialized = true;
        }
Пример #9
0
 /// <summary>
 /// Gets a collection of <see cref="PwmController"/> instances that represent all controllers returned by all providers.
 /// </summary>
 /// <returns>
 /// An IAsyncOperation that yields the controllers.
 /// </returns>
 public IAsyncOperation <IReadOnlyList <PwmController> > GetControllersAsync()
 {
     return(PwmController.GetControllersAsync(this));
 }
Пример #10
0
 public Buzzer()
 {
     this.controller = PwmController.FromName(Board.BoardType == BoardType.BP2 ? BrainPadBP2.PwmChannel.Controller4.Id : G30.PwmChannel.Controller4.Id);
     this.buzz       = this.controller.OpenChannel(Board.BoardType == BoardType.BP2 ? BrainPadBP2.PwmChannel.Controller4.PB8 : G30.PwmChannel.Controller4.PB8);
 }
Пример #11
0
 public MotorControl(GpioController gpioControllerIn, PwmController pwmControllerIn)
 {
     gpioController = gpioControllerIn;
     pwmController  = pwmControllerIn;
 }
Пример #12
0
        public MainPage()
        {
            this.mOffsetQueue = new Queue <double>();
            this.InitializeComponent();

            this.Sequences = new Dictionary <string, Sequence <double> >
            {
                { "Constant", new Sequence <double>(new double[] { 1 }) },
                { "Step", new Sequence <double>(new double[] { 0, 1 }) },
                { "Step (multi)", new Sequence <double>(new double[] { 0, 0.25, 0, 0.25, 0, 0.5, 0.25, 1 }) },
                { "Sawtooth", new Sequence <double>(new double[] { 0, 0.25, 0.5, 0.75, 1 }) },
                { "Ramp", new Sequence <double>(new double[] { 0, 0.1, 0.25, 0.4, 0.6, 1 }) },
                { "Sinusoidal", new Sequence <double>(SinusoidalSequence()) },
                { "Sinusoidal (multi)", new Sequence <double>(SinusoidalSequence(0.5), SinusoidalSequence(0.7), SinusoidalSequence(0.5), SinusoidalSequence(1)) },
                { "Random", new Sequence <double>(RandomSequence(30, 0, 1)) },
            };
            this.SelectedSequence = Sequences["Constant"];

            // populate the sequence list
            foreach (var entry in this.Sequences.Keys.OrderBy(x => x))
            {
                this.SequenceList.Items.Add(entry);
            }

            Task.Run(async() =>
            {
                try
                {
                    if (!LightningProvider.IsLightningEnabled)
                    {
                        throw new Exception("Requires Lighting to be enabled");
                    }

                    var pwmController = (await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider()))[1];
                    if (pwmController == null)
                    {
                        throw new Exception("No PWM controller");
                    }

                    var gpioController = (await GpioController.GetControllersAsync(LightningGpioProvider.GetGpioProvider()))[0];
                    if (gpioController == null)
                    {
                        throw new Exception("No PWM controller");
                    }

                    pwmController.SetDesiredFrequency(PwmFrequency);
                    var motorAEnable = pwmController.OpenPin(MotorAEnablePin);
                    var motorAInput  = gpioController.OpenPin(MotorAInputPin);
                    motorAInput.SetDriveMode(GpioPinDriveMode.Output);
                    var motorBEnable = pwmController.OpenPin(MotorBEnablePin);
                    var motorBInput  = gpioController.OpenPin(MotorBInputPin);
                    motorBInput.SetDriveMode(GpioPinDriveMode.Output);

                    var motorDriver = new L239D()
                    {
                        Enable12Pin = motorAEnable,
                        Input1Pin   = motorAInput,
                        Enable34Pin = motorBEnable,
                        Input3Pin   = motorBInput,
                    };

                    motorDriver.StartMotor(L239D.InputPins.Input1);
                    motorDriver.StartMotor(L239D.InputPins.Input3);

                    while (true)
                    {
                        var sequence = this.SelectedSequence;
                        foreach (var value in sequence)
                        {
                            var power = this.MinPower + value * (this.MaxPower - this.MinPower);
                            this.mOffsetQueue.Enqueue(power);
                            motorDriver.DriveMotor(L239D.EnablePins.Enable12, power);

                            // handle offset if any
                            while (this.mOffsetQueue.Count > this.MotorOffset)
                            {
                                power = this.mOffsetQueue.Dequeue();
                            }

                            motorDriver.DriveMotor(L239D.EnablePins.Enable34, power);

                            await Task.Delay((int)(MinTime + (MaxTime - MinTime) * (1.0 - this.SpeedFactor)));

                            if (sequence != this.SelectedSequence)
                            {
                                break;
                            }
                        }
                    }

                    motorAEnable.Dispose();
                    motorAInput.Dispose();
                }
                catch (Exception ex)
                {
                    var error = ex.ToString();
                }
            });
        }
Пример #13
0
        public static void Main()
        {
            WatchDog.Start(new TimeSpan(0, 0, 30));

            MinorLed.SetDriveMode(GpioPinDriveMode.Output);
            MajorLed.SetDriveMode(GpioPinDriveMode.Output);

            _lcdShield = new DfRobotLcdShield(20, 4);

            // Create a custom degrees symbol (°), store it on the LCD for later use with the lat/long display
            _lcdShield.CreateChar(0, new byte[] { 0x0, 0x4, 0xa, 0x4, 0x0, 0x0, 0x0, 0x0 });

            // 0 bars are not required as that would just require sending " "
            _lcdShield.CreateChar(1, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1F });
            _lcdShield.CreateChar(2, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1F, 0x1F });
            _lcdShield.CreateChar(3, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x1F, 0x1F, 0x1F });
            _lcdShield.CreateChar(4, new byte[] { 0x0, 0x0, 0x0, 0x0, 0x1F, 0x1F, 0x1F, 0x1F });
            _lcdShield.CreateChar(5, new byte[] { 0x0, 0x0, 0x0, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F });
            _lcdShield.CreateChar(6, new byte[] { 0x0, 0x0, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F });
            _lcdShield.CreateChar(7, new byte[] { 0x0, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F });
            // 8 bars are not required as that would just require sending byte 255.

            _thunderbolt = new ThunderBolt("COM1", AngleUnits.Degrees, AltitudeUnits.Meters, FEZ.GpioPin.D13);

            _lcdShield.OnButtonPressed += LcdShieldOnOnButtonPressed;

            DisplaySplash();

            var pwmController = PwmController.FromName(FEZ.PwmChannel.Controller3.Id);

            pwmController.SetDesiredFrequency(10000);

            var backlight = pwmController.OpenChannel(FEZ.PwmChannel.Controller3.D10);

            backlight.SetActiveDutyCyclePercentage(LcdBrightness / 100d);
            backlight.Start();

            TestLeds();

            _thunderbolt.Open();
            _thunderbolt.TimingMode = TimingModes.UTC;
            _thunderbolt.RequestManufacturingParameters();
            _thunderbolt.RequestFirmwareVersion();
            _thunderbolt.SetupUnitForDisciplining();
            _thunderbolt.RequestTrackedSatelliteStatus();

            _thunderbolt.TimeChanged += ThunderboltOnTimeChanged;

            Thread.Sleep(3000);

            DisplayVersion();

            while (true)
            {
                WatchDog.Reset();
                if (_thunderbolt.IsSerialDataBeingReceived)
                {
                    if (!_isSurveyInProgress && _thunderbolt.IsSurveyInProgress())
                    {
                        // Survey has just started.  Jump to the page displaying survey progress.
                        _previousPageNumber = _pageNumber; // Take note of the page we were on so we can switch back later.
                        _isSurveyInProgress = true;
                        _pageNumber         = 2;           // Set the new page to jump to.
                    }
                    else if (_isSurveyInProgress && !_thunderbolt.IsSurveyInProgress())
                    {
                        // Survey has just finished.  Jump to the previous page we were displaying.
                        _pageNumber         = _previousPageNumber;
                        _isSurveyInProgress = false;
                    }

                    switch (_pageNumber)
                    {
                    case 1:
                        DisplayScreenOne();
                        break;

                    case 2:
                        DisplayScreenTwo();
                        break;

                    case 3:
                        DisplayScreenThree();
                        break;

                    case 4:
                        DisplayScreenFour();
                        break;

                    case 5:
                        DisplaySatelliteSignalScreen();
                        break;

                    case 6:
                        DisplayPRNScreen();
                        break;

                    case 7:
                        DisplayDOPScreen();
                        break;

                    default:
                        DisplayScreenOne();
                        break;
                    }

                    UpdateAlarmIndicators();
                }
                else
                {
                    DisplayNoSerialDataScreen();
                }
            }
        }
Пример #14
0
 public AlarmClock(PwmController pwmController)
 {
     _pwmController = pwmController;
 }
Пример #15
0
 public SignalRConnection(PwmController pwmController)
 {
     _pwmController = pwmController;
 }
Пример #16
0
        static async Task MainAsync()
        {
            try
            {
                string      input = "";
                bool        exit  = input.Equals("exit");
                UpBridge.Up upb   = new UpBridge.Up();
                Console.WriteLine("UWP console PWM test:");
                PwmController controller = await PwmController.GetDefaultAsync();

                pin1.pin = 0;
                //print Board INFO
                Console.WriteLine(upb.BoardGetManufacture() + "\n"
                                  + "Board Name:  " + upb.BoardGetName() + "\n"
                                  + "BIOS Ver:    " + upb.BoardGetBIOSVersion() + "\n"
                                  + "Firmware Ver:" + upb.BoardGetFirmwareVersion().ToString("X") + "\n");
                PwmPin pin = controller.OpenPin(0);

                Console.WriteLine(Usage);
                while (exit == false)
                {
                    Console.Write(pin1.pin.ToString() + ">");
                    input = Console.ReadLine();
                    string[] inputnum = input.Split(' ');
                    switch (inputnum[0].ToLower())
                    {
                    case "list":
                        pwmlist();
                        break;

                    case "set":
                        if (inputnum.Length == 2)
                        {
                            pin.Dispose();
                            int pin_convert;
                            if (int.TryParse(inputnum[1], out pin_convert))
                            {
                                if (pin_convert == pin1.pin)
                                {
                                    Console.WriteLine("This Pin is currently setting");
                                }
                                else
                                {
                                    int pin_current = pin1.pin;
                                    pin1.pin = pin_convert;
                                    try
                                    {
                                        controller = await PwmController.GetDefaultAsync();

                                        pin = controller.OpenPin(pin1.pin);
                                        Console.WriteLine("You select pin   " + pin1.pin + "   to set");
                                    }
                                    catch (Exception e)
                                    {
                                        pin1.pin = pin_current;
                                        pin      = controller.OpenPin(pin1.pin);
                                        Console.WriteLine(e.Message);
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("Please input : set {int}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Please input : set {int}");
                        }
                        break;

                    case "get":
                        if (inputnum.Length == 1)
                        {
                            Console.WriteLine("Pin  " + pin1.pin + "\n");
                            Console.WriteLine("Max Frequency    :   " + controller.MaxFrequency + "\n");
                            Console.WriteLine("Min Frequency    :   " + controller.MinFrequency + "\n");
                            Console.WriteLine("Actual Frequency :   " + controller.ActualFrequency + "\n");
                            Console.WriteLine("Duty Cycle       :   " + pin.GetActiveDutyCyclePercentage() + "\n");
                            Console.WriteLine("Pin Status       :   " + pin.IsStarted + "\n");
                        }
                        else
                        {
                            Console.WriteLine("Please input : get");
                        }
                        break;

                    case "frequency":
                        if (inputnum.Length == 2)
                        {
                            try
                            {
                                if (double.TryParse(inputnum[1], out pin1.pin_ActualFrequency))
                                {
                                    Console.WriteLine("Frequency set : " + pin1.pin_ActualFrequency);
                                    controller.SetDesiredFrequency(pin1.pin_ActualFrequency);
                                    pin.Start();
                                }
                                else
                                {
                                    Console.WriteLine("Please input : frequency {double}");
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Please input : frequency {double}");
                        }
                        break;

                    case "duty":
                        if (inputnum.Length == 2)
                        {
                            try
                            {
                                if (double.TryParse(inputnum[1], out pin1.pin_DutyCycle))
                                {
                                    Console.WriteLine("duty set : " + pin1.pin_DutyCycle);
                                    pin.SetActiveDutyCyclePercentage(pin1.pin_DutyCycle);
                                    pin.Start();
                                }
                                else
                                {
                                    Console.WriteLine("Please input : duty {double}");
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Please input : duty {double}");
                        }
                        break;

                    case "exit":
                        exit = inputnum[0].Equals("exit");
                        pin.Dispose();
                        break;

                    case "help":
                    default:
                        Console.WriteLine(Usage);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }