/// <summary>
        ///   Initializes a new instance of the <see cref="MultiplexedHBridge" /> class.
        /// </summary>
        /// <param name="speedControl">The PWM channel that will control the output power (5KHz max).</param>
        /// <param name="outputShiftRegister">The output shift register that controls the L293D H-Bridge.</param>
        /// <param name="directionA">The bit number in the shift register output that controls IN1 on the L293D.</param>
        /// <param name="directionB">The bit number in the shift register output that controls IN2 on the L293D.</param>
        public MultiplexedHBridge(PWM speedControl,
                                  SerialShiftRegister outputShiftRegister,
                                  ushort directionA,
                                  ushort directionB)
        {
            this.speedControl        = speedControl;
            this.outputShiftRegister = outputShiftRegister;
            this.directionA          = directionA;
            this.directionB          = directionB;
            // For efficiency, initialise some direction transactions ready for use later.
            forwardTransaction = new[]
            {
                new ShiftRegisterOperation(directionA, true),
                new ShiftRegisterOperation(directionB, false)
            };
            reverseTransaction = new[]
            {
                new ShiftRegisterOperation(directionA, false),
                new ShiftRegisterOperation(directionB, true)
            };
            brakeTransaction = new[]
            {
                new ShiftRegisterOperation(directionA, true),
                new ShiftRegisterOperation(directionB, true)
            };
            releaseTransaction = new[]
            {
                new ShiftRegisterOperation(directionA, false),
                new ShiftRegisterOperation(directionB, false)
            };

            InitializeOutputs(); // Ensure the outputs are in a sane, safe state.
        }
示例#2
0
        /// <summary>
        /// During development, Main() acts as the ConsoleBootLoader, making it easy to debug the game.
        /// When game development is complete, comment out the content Main() to remove the overhead
        /// </summary>
        public static void Main() {
#if dev
            var joystickLeft = new AnalogJoystick(xAxisPin: Pins.GPIO_PIN_A0, yAxisPin: Pins.GPIO_PIN_A1);
            var joystickRight = new AnalogJoystick(xAxisPin: Pins.GPIO_PIN_A2, yAxisPin: Pins.GPIO_PIN_A3);
            var matrix = new Max72197221(chipSelect: Pins.GPIO_PIN_D8);
            var speaker = new PWM(Pins.GPIO_PIN_D5);
            var resourceLoader = new SDResourceLoader();
            var buttonLeft = new PushButton(Pins.GPIO_PIN_D0, Port.InterruptMode.InterruptEdgeLevelLow, null, Port.ResistorMode.PullUp);
            var buttonRight = new PushButton(Pins.GPIO_PIN_D1, Port.InterruptMode.InterruptEdgeLevelLow, null, Port.ResistorMode.PullUp);
            var args = new object[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.Size];

            var index = 0;
            args[index++] = CartridgeVersionInfo.CurrentVersion;
            args[index++] = joystickLeft;
            args[index++] = joystickRight;
            args[index++] = matrix;
            args[index++] = speaker;
            args[index++] = resourceLoader;
            args[index++] = buttonLeft;
            args[index] = buttonRight;

            matrix.Shutdown(Max72197221.ShutdownRegister.NormalOperation);
            matrix.SetDecodeMode(Max72197221.DecodeModeRegister.NoDecodeMode);
            matrix.SetDigitScanLimit(7);
            matrix.SetIntensity(8);

            Run(args);
#endif
        }
        public static void Main()
        {
            const uint period      = 20000; //20ms in us
            const uint minDuration = 530;   //0.53ms in us
            const uint maxDuration = 2350;  //2.35ms in us

            var servo = new PWM(Cpu.PWMChannel.PWM_0, period, minDuration,
                                PWM.ScaleFactor.Microseconds, false);

            servo.Start();

            uint step = 30;

            for (uint angle = 0;; angle += step)
            {
                if (angle > 180)
                {
                    step = (uint)-step;
                    continue;
                }

                servo.Duration = Map(angle, 0, 180, minDuration, maxDuration);
                Thread.Sleep(2000);
            }
        }
示例#4
0
 public PanTilter(Cpu.Pin panPin, int panMin, int panMax, Cpu.Pin tiltPin, int tiltMin, int tiltMax)
 {
     this.tilter  = new PWM(tiltPin);
     this.tiltMin = tiltMin;
     this.tiltMax = tiltMax;
     this.tilter.SetDutyCycle(0);
 }
示例#5
0
        public static void Main()
        {
            AnalogInput capt        = new AnalogInput((Cpu.AnalogChannel)Cpu.AnalogChannel.ANALOG_0);
            OutputPort  dir         = new OutputPort(FEZSpider.Socket8.Pin9, true);
            InputPort   microswitch = new InputPort(FEZSpider.Socket4.Pin3, false, Port.ResistorMode.PullDown);

            double frequence       = 38000; // Période en microseconde
            double rapportCyclique = 0.5;   // Période en microseconde

            PWM motorDriver = new PWM(FEZSpider.Socket8.Pwm7, frequence, rapportCyclique, false);

            motorDriver.Stop();


            while (true)
            {
                if (microswitch.Read())
                {
                    motorDriver.Stop();
                }

                Debug.Print("Distance : " + capt.Read().ToString());

                Debug.Print(microswitch.Read().ToString());
                Thread.Sleep(50);
            }
        }
示例#6
0
        public static void Main()
        {
            PWM redLed   = new PWM(PWMChannels.PWM_PIN_D11, 100, 0, false);
            PWM greenLed = new PWM(PWMChannels.PWM_PIN_D10, 100, 0, false);
            PWM blueLed  = new PWM(PWMChannels.PWM_PIN_D9, 100, 0, false);

            double dutyCycleMax = .3;             // RGB Led doesn't seem to get much brighter than at 30%

            while (true)
            {
                redLed.Start();
                greenLed.Start();
                blueLed.Start();

                double r, g, b;

                for (int i = 0; i < 360; i++)
                {
                    HsvToRgb(i, 1, 1, out r, out g, out b);

                    redLed.DutyCycle   = (r * dutyCycleMax);
                    greenLed.DutyCycle = (g * dutyCycleMax);
                    blueLed.DutyCycle  = (b * dutyCycleMax);

                    // for a fun, fast rotation through the hue spectrum:
                    //Thread.Sleep (1);
                    // for a gentle walk through the forest of colors;
                    Thread.Sleep(18);
                }
            }
        }
示例#7
0
 /// <summary>
 /// Piezo speaker driver and notes and playback manager
 /// </summary>
 /// <param name="pin">From the SecretLabs.NETMF.Hardware.NetduinoPlus.PWMChannels namespace</param>
 /// <param name="name">Unique identifying name for command and control</param>
 public Piezo(Cpu.PWMChannel pin, string name)
     : base(name, "piezo")
 {
     //_piezo = new PWM(pin, 2048, 0, PWM.ScaleFactor.Milliseconds, false);
     _piezo = new PWM(pin, 2048, 0, false);
     _piezo.Start();
 }
        /// <summary>
        /// This method visits an expressionterm node
        /// First it checks the type on the lefthand side of the expression is either Apin or Dpin
        /// If also checks if an input is attempted to be uses as an output
        /// The input for Apin or Dpin is then accepted and written to the file
        /// Lastly the lefthand side of the expression is accepted
        /// </summary>
        /// <param name="expressionTermNode">The name of the node</param>
        /// <returns>It returns the left side of an expression</returns>
        public override object Visit(ExpressionTerm expressionTermNode)
        {
            string exp = "";

            if (expressionTermNode.LeftHand.IsType(typeof(APinNode)) || expressionTermNode.LeftHand.IsType(typeof(DPinNode)))
            {
                string pin = ((PinNode)expressionTermNode.LeftHand).Value;
                if (PinDefs.Any(def => def.Contains(pin) && def.Contains("OUTPUT")))
                {
                    new InvalidCodeException($"Pin {pin} was defined as OUTPUT but is also used as INPUT at {expressionTermNode.Line}:{expressionTermNode.Offset}");
                }
                if (expressionTermNode.LeftHand.Type == TokenType.APIN)
                {
                    PinDefs.Add($"pinMode({pin}, INPUT);");
                    exp += $"analogRead({pin})";
                }
                else
                {
                    PinDefs.Add($"pinMode({pin}, INPUT);");
                    if (PWM.Contains(pin))
                    {
                        exp += $"analogRead({pin})";
                    }
                    else
                    {
                        exp += $"digitalRead({pin})";
                    }
                }
                return(exp);
            }
            exp += expressionTermNode.LeftHand.Accept(this);
            return(exp);
        }
示例#9
0
        public static void Main()
        {
            var serial   = new SerialPort("COM1", 9800, Parity.None, 8, StopBits.One);
            var power    = new PWM(Pins.GPIO_PIN_D9);
            var motorIn8 = new OutputPort(Pins.GPIO_PIN_D8, false);

            serial.DataReceived += Serial_DataReceived;
            motorIn8.Write(true);
            while (true)
            {
                try
                {
                    var value = MotorPower;
                    if (!serial.IsOpen)
                    {
                        serial.Open();
                    }
                    power.SetPulse(20000, value);
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    var mes = ex.Message;
                }
            }
        }
示例#10
0
 public PwmSpeaker(PWM pwm)
 {
     _pwm           = pwm;
     _pwm.Frequency = 50;
     _pwm.DutyCycle = 0;
     _pwm.Start();
 }
示例#11
0
 public void TestCreateLimitsLower()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() =>
     {
         var pwm = new PWM(-1);
     });
 }
示例#12
0
 /// <summary>
 /// Use higher period, means faster response, not supported by all ESC
 /// </summary>
 /// <param name="pin">PWM pin</param>
 /// <param name="period">Period</param>
 public BrushlessMotor(PWM.Pin pin, Period period)
 {
     _precalc = (Max - Min) / _scale;
     Period = (uint)period;
     this._pwmPin = new PWM(pin);
     this._pwmPin.SetPulse(Period, Min);
 }
示例#13
0
        public static void Rick()
        {
            PWM myPWM = new PWM(FEZSpiderII.Socket11.Pwm9, frequence, 0.5, false);

            myPWM.Start();
            myPWM.Frequency = Fa;
            Thread.Sleep(750);
            myPWM.Frequency = Sol;
            Thread.Sleep(750);
            myPWM.Frequency = Do;
            Thread.Sleep(500);
            myPWM.Frequency = Sol;
            Thread.Sleep(750);
            myPWM.Frequency = La;
            Thread.Sleep(750);

            myPWM.Frequency = Do1;
            Thread.Sleep(180);
            myPWM.Frequency = Sib;
            Thread.Sleep(180);
            myPWM.Frequency = La;
            Thread.Sleep(300);

            myPWM.Frequency = Fa;
            Thread.Sleep(750);
            myPWM.Frequency = Sol;
            Thread.Sleep(750);
            myPWM.Frequency = Do;
            Thread.Sleep(1000);


            myPWM.Stop();
        }
示例#14
0
 public void TestCreateLimitsLower()
 {
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         var pwm = new PWM(-1);
     });
 }
        /// <summary>
        /// Costruttore
        /// </summary>
        /// <param name="frequency"></param>
        /// <param name="destination"></param>
        public SoftPWM(int frequency, Cpu.Pin destination)
        {
            if (_allocatedCount >= RealPWMCount)
            {
                throw new ArgumentOutOfRangeException("Impossibile allocare un nuovo canale PWM");
            }

            _index = _allocatedCount;
            Destinations[_index] = new OutputPort((Cpu.Pin)destination, false);
            Sources[_index]      = new PWM(RealPWM[_index], frequency, 0.0, false);

            int port = (int)Sources[_index].Pin / 16; // porta A(0), B(1) o C(2)
            int bit  = (int)Sources[_index].Pin % 16; // bit nel range [0,15]

            SourcePorts[_index] = port;
            SourceBits[_index]  = (uint)(1 << bit);

            port = (int)destination / 16; // porta A(0), B(1) o C(2)
            bit  = (int)destination % 16; // bit nel range [0,15]

            DestinationPorts[_index] = port;
            DestinationBits[_index]  = (uint)(1 << bit);

            _allocatedCount++;
        }
示例#16
0
    /// <summary>
    /// Main Method of the UAV Control Logic
    /// Will be called when the System is fully loaded and running
    /// If this Mehthod is completed the Program will exit :-(
    /// </summary>
    public override void run()
    {
        initialised = true;                 // Wir sind fertig mit dem Laden und Starten unser eigentliches Programm daher erlauben wir auch den Empfang von Daten der Bodenstation
        servo1.ConnectHardware();
        //// public ParameterPID (UAVParameter pG, UAVParameter iG, UAVParameter dG, UAVParameter pv, UAVParameter diff, UAVParameter output,UAVParameter sp)
        //PID_Höhe = new PID(kp_Höhe, ki_Höhe, kd_Höhe, lagesensor["theta"], lagesensor ["gyroalphastrich"],PID_Out_Höhe, sp_Höhe);
        //PID_Quer = new PID(kp_Quer, ki_Quer, kd_Quer, lagesensor["phi"], lagesensor ["gyrogammastrich"],PID_Out_Quer, sp_Quer);

        ////starte 100Hz Schleife  //keine Ahnung wie das geht
        //  lagesensor.DataRecieved+=new UAVCommons.UAVStructure.ValueChangedHandler(Ausgaberoutine);
        //    servo1.DoubleValue = -100;
        counter = 0;
        do       // läuft immer durch damit run nicht beendet und somit das Programm beendet wird
        {
            Thread.Sleep(10);
            // Console.WriteLine("Counter: " + servo1.DoubleValue);
            counter++;
            //  servo1.DoubleValue++;
            servo1.DoubleValue = counter;
            servo2.DoubleValue = counter;
            servo3.DoubleValue = counter;
            servo4.DoubleValue = counter;
            servo5.DoubleValue = counter;

            PWM.UpdateServos();
            Console.WriteLine("throttle" + this.kd_Höhe.MaxDoubleValue);
            //  servo1.DoubleValue = counter;
            //  servo1.DoubleValue = counter;
            if (counter == 99)
            {
                counter = 0;
            }
        } while (running == true);
    }
示例#17
0
 public static void SendMessage(PWM infraredOut, string message)
 {
     foreach (char c in message)
     {
         SendBit(infraredOut, c);
     }
 }
示例#18
0
        /* Constructor */
        protected Stepper(ConnectorPin protection, ConnectorPin direction, ConnectorPin impulse, ConnectorPin reset, ConnectorPin enable)
        {
            _logger = new Logger(nameof(Stepper));
            /* Config pins */
            _protectionPin = new GPIOInstance(protection, PinDirection.Input);
            _directionPin  = new GPIOInstance(direction, PinDirection.Output);
            _impulsePin    = new GPIOInstance(impulse, PinDirection.Output);
            _resetPin      = new GPIOInstance(reset, PinDirection.Output);
            _enablePin     = new GPIOInstance(enable, PinDirection.Output);

            /* Disable motor by default to prevent heating */
            Enable(false);

            /* Set direction as FORWARD by default */
            SetDirection(Direction.Forward);

            /* Reset pin */
            _resetPin.Write(true);

            /* Launch PWM */
            _gpio_pwm = 23;
            System.Diagnostics.Process.Start("/usr/sbin/pi-blaster", "--gpio 23").WaitForExit();
            _pwm = new PWM(_gpio_pwm);
            _pwm.SetDuty(0);
        }
        public MainWindow()
        {
            InitializeComponent();
            _rpi             = new RPi();
            _startKnap       = new Key(_rpi, Key.ID.P1);
            _pwm             = new PWM(_rpi);
            _pulseReader     = new PulseReader(_rpi, _pwm);
            _sevenSeg        = new SevenSeg(_rpi);
            _hundredeDisplay = new Led(_rpi, Led.ID.LD1);
            standartFontSize = 18;
            enabledColor     = new SolidColorBrush(Color.FromArgb(255, 211, 47, 47));
            annuller_BT      = new Button();
            cStyle           = new Style(typeof(Border));


            // Definerer "Annuller"-knappens udseende
            annuller_BT.Click              += annullerBT_Click;
            annuller_BT.Width               = 185;
            annuller_BT.Height              = 55;
            annuller_BT.Content             = "ANNULLER";
            annuller_BT.FontFamily          = new FontFamily("Yu Gothic");
            annuller_BT.FontSize            = standartFontSize;
            annuller_BT.Name                = "ANNULLER";
            annuller_BT.HorizontalAlignment = HorizontalAlignment.Left;
            annuller_BT.VerticalAlignment   = VerticalAlignment.Top;
            annuller_BT.Margin              = new Thickness(40, 170, 0, 0);

            cStyle.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(50.0)));
            annuller_BT.Resources.Add(typeof(Border), cStyle);

            _sevenSeg.Init_SevenSeg();
            _pwm.InitPWM();
        }
示例#20
0
 /// <summary>
 /// Common RGB-led
 /// </summary>
 /// <param name="RedPin">The PWM-pin connected to Red</param>
 /// <param name="GreenPin">The PWM-pin connected to Green</param>
 /// <param name="BluePin">The PWM-pin connected to Blue</param>
 /// <param name="CommonAnode">Specifies if the led is common anode</param>
 public RGBLed(Cpu.Pin RedPin, Cpu.Pin GreenPin, Cpu.Pin BluePin, bool CommonAnode = true)
 {
     this._Red         = new PWM(RedPin);
     this._Green       = new PWM(GreenPin);
     this._Blue        = new PWM(BluePin);
     this._CommonAnode = CommonAnode;
 }
        /// <summary>
        /// 更新硬件
        /// </summary>
        public void UpdateHardware()
        {
            if (Scope?.IsConnect != true)
            {
                Scope?.Connect();
            }

            if (Power?.IsConnect != true)
            {
                Power?.Connect();
            }

            if (PLC?.IsConnect != true)
            {
                PLC?.Connect();
            }

            if (PWM?.IsConnect != true)
            {
                PWM?.Connect();
            }

            NotifyOfPropertyChange(() => IsHardwareValid);
            NotifyOfPropertyChange(() => CanMeasure);
        }
示例#22
0
        /// <summary>
        /// During development, Main() acts as the ConsoleBootLoader, making it easy to debug the game.
        /// When game development is complete, comment out the content Main() to remove the overhead
        /// </summary>
        public static void Main()
        {
#if dev
            var joystickLeft   = new AnalogJoystick(xAxisPin: Pins.GPIO_PIN_A0, yAxisPin: Pins.GPIO_PIN_A1);
            var joystickRight  = new AnalogJoystick(xAxisPin: Pins.GPIO_PIN_A2, yAxisPin: Pins.GPIO_PIN_A3);
            var matrix         = new Max72197221(chipSelect: Pins.GPIO_PIN_D8);
            var speaker        = new PWM(Pins.GPIO_PIN_D5);
            var resourceLoader = new SDResourceLoader();
            var buttonLeft     = new PushButton(Pins.GPIO_PIN_D0, Port.InterruptMode.InterruptEdgeLevelLow, null, Port.ResistorMode.PullUp);
            var buttonRight    = new PushButton(Pins.GPIO_PIN_D1, Port.InterruptMode.InterruptEdgeLevelLow, null, Port.ResistorMode.PullUp);
            var args           = new object[(int)CartridgeVersionInfo.LoaderArgumentsVersion100.Size];

            var index = 0;
            args[index++] = CartridgeVersionInfo.CurrentVersion;
            args[index++] = joystickLeft;
            args[index++] = joystickRight;
            args[index++] = matrix;
            args[index++] = speaker;
            args[index++] = resourceLoader;
            args[index++] = buttonLeft;
            args[index]   = buttonRight;

            matrix.Shutdown(Max72197221.ShutdownRegister.NormalOperation);
            matrix.SetDecodeMode(Max72197221.DecodeModeRegister.NoDecodeMode);
            matrix.SetDigitScanLimit(7);
            matrix.SetIntensity(8);

            Run(args);
#endif
        }
示例#23
0
        public Nokia_5110(bool useBacklight, Cpu.Pin latch, Cpu.Pin backlight,
                          Cpu.Pin reset, Cpu.Pin dataCommand)
        {
            if (useBacklight)
            {
                this.backlight = new PWM(backlight);
            }

            SPI.Configuration spiConfiguration = new SPI.Configuration(
                latch,              // chip select port
                false,              // IC is accessed when chip select is low
                0,                  // setup time 1 ms
                0,                  // hold chip select 1 ms after transfer
                false,              // clock line is low if device is not selected
                true,               // data is sampled at leading edge of clock
                4000,               // clockrate is 15 MHz
                SPI.SPI_module.SPI1 // use first SPI bus
                );

            spi = new SPI(spiConfiguration);

            this.reset    = new OutputPort(reset, true);
            this.dataMode = new OutputPort(dataCommand, true);
            Initialize();
        }
示例#24
0
        private void SetSpeed(PWM motor, OutputPort direction, int speed, bool isLeft)
        {
            motor.Stop();

            motor.Frequency = MOTOR_BASE_FREQUENCY;

            if (speed == 0)
            {
                direction.Write(false);
                motor.DutyCycle = 0.01;
            }
            else if (speed < 0)
            {
                direction.Write(isLeft ? true : false);
                motor.DutyCycle = speed / -100.0;

                motor.Start();
            }
            else
            {
                direction.Write(isLeft ? false : true);
                motor.DutyCycle = speed / 100.0;

                motor.Start();
            }
        }
示例#25
0
        public static void Main()
        {
            SLH.AnalogInput pot      = new SLH.AnalogInput(Pins.GPIO_PIN_A1);
            PWM             redLed   = new PWM(PWMChannels.PWM_PIN_D11, 100, 0, false);
            PWM             greenLed = new PWM(PWMChannels.PWM_PIN_D10, 100, 0, false);
            PWM             blueLed  = new PWM(PWMChannels.PWM_PIN_D9, 100, 0, false);

            double dutyCycleMax = .3;             // RGB Led doesn't seem to get much brighter than at 30%
            int    hue          = 0;

            // set our range to be the range of possible hues
            pot.SetRange(0, 360);

            redLed.Start();
            greenLed.Start();
            blueLed.Start();


            while (true)
            {
                double r, g, b;

                hue = pot.Read();

                Debug.Print("Hue: " + hue.ToString());

                HsvToRgb(hue, 1, 1, out r, out g, out b);

                redLed.DutyCycle   = (r * dutyCycleMax);
                greenLed.DutyCycle = (g * dutyCycleMax);
                blueLed.DutyCycle  = (b * dutyCycleMax);
            }
        }
示例#26
0
 public void TestCreateLimitsUpper()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() =>
     {
         var pwm = new PWM(PwmChannels);
     });
 }
示例#27
0
        //This loop polls the aio value set by the trimpot to determine the duty cycle which
        // determines the amplitude on the sin curve of a given itteration.
        private void SinLEDLoop(AnalogInput pot, PWM led, OutputPort relay, LCD_Display display)
        {
            double startValue = 0;
            bool   laststate  = false;
            double potValue   = 0.0;

            TimeSpan lastPeak = Utility.GetMachineTime();

            while (true)
            {
                potValue = pot.Read();

                startValue += .5 * potValue;

                if (startValue > 2 * System.Math.PI)
                {
                    startValue = 0;
                    laststate  = !laststate;
                    //relay.Write(laststate);

                    if (display != null)
                    {
                        display.writeValue("Frequency: " + getFreq(lastPeak) + " Hz");
                    }
                    lastPeak = Utility.GetMachineTime();
                }
                Thread.Sleep(5);


                led.DutyCycle = System.Math.Max(0, System.Math.Sin(startValue));
            }
        }
 // Opretter cunstructoren. Denne tager 2 parametre, som er RPI'en og den givne pulsbreddemodulation
 public PulseReader(RPi rpi, PWM pwm)
 {
     _pwm = pwm;
     _rpi = rpi;
     puls = new Puls(rpi);
     // antalPuls = puls.ReadPuls();
 }
示例#29
0
 public void TestCreateLimitsUpper()
 {
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         var pwm = new PWM(PwmChannels);
     });
 }
示例#30
0
 /// <summary>
 /// Sets the frequency and duty cycle of the <see cref="PWMOutput"/> interface and starts the PWM signal.
 /// </summary>
 /// <param name="frequency">Required frequency in Hertz.</param>
 /// <param name="dutyCycle">Duty cycle from 0-1.</param>
 public void Set(int frequency, double dutyCycle)
 {
     if (frequency < 0)
     {
         throw new ArgumentException("frequency");
     }
     if (dutyCycle < 0 || dutyCycle > 1)
     {
         throw new ArgumentException("dutyCycle");
     }
     if (pwm == null)
     {
         pwm = new PWM(pwmChannel, frequency, dutyCycle, invert);
         pwm.Start();
         started = true;
     }
     else
     {
         if (started)
         {
             pwm.Stop();
         }
         pwm.Frequency = frequency;
         pwm.DutyCycle = dutyCycle;
         pwm.Start();
         started = true;
     }
 }
示例#31
0
 public override void Set(double frequency, double dutyCycle)
 {
     if (frequency < 0.0)
     {
         throw new ArgumentException("frequency");
     }
     if ((dutyCycle < 0.0) || (dutyCycle > 1.0))
     {
         throw new ArgumentException("dutyCycle");
     }
     if (this._port == null)
     {
         this._port = new PWM(this._channel, frequency, dutyCycle, this._invert);
         this._port.Start();
         this._started = true;
     }
     else
     {
         if (this._started)
         {
             this._port.Stop();
         }
         this._port.Frequency = frequency;
         this._port.DutyCycle = dutyCycle;
         this._port.Start();
         this._started = true;
     }
 }
        /** Creates RGB LEDStripController for Port 3 of HERO) */
        public LEDStripController(CTRE.HERO.Port3Definition port3)
        {
            /* Duration of pulse */
            uint duration = 0;

            //Gadgeteer Drive Module
            //PIN   J2     isPWM
            //3     P1
            //4     P2       Y
            //5     P3
            //6     P4       Y      Red
            //7     P5       Y      Green
            //8     P6       Y      Blue
            //9     ---      Y

            /* PWM Pin 6 from Hero port 3 to P4 of Driver Module */
            _pwms[0] = new PWM(port3.PWM_Pin6, period, duration, PWM.ScaleFactor.Microseconds, false);
            /* PWM Pin 7 from Hero port 3 to P5 of Driver Module */
            _pwms[1] = new PWM(port3.PWM_Pin7, period, duration, PWM.ScaleFactor.Microseconds, false);
            /* PWM Pin 8 from Hero port 3 to P6 of Driver Module */
            _pwms[2] = new PWM(port3.PWM_Pin8, period, duration, PWM.ScaleFactor.Microseconds, false);

            /* Start all PWM Pins */
            foreach (PWM pwm in _pwms)
            {
                pwm.Start();
            }
        }
示例#33
0
        public static void Main()
        {
            var lcd = new FEZ_Components.LCD2x16(
                FEZ_Pin.Digital.Di3, FEZ_Pin.Digital.Di2, FEZ_Pin.Digital.Di1, FEZ_Pin.Digital.Di0, FEZ_Pin.Digital.Di7, FEZ_Pin.Digital.Di6);
            lcd.Clear();

            using (var servo0 = new FEZ_Components.ServoMotor(FEZ_Pin.Digital.Di13))
            {
                servo0.SetPosition(0);
                Thread.Sleep(1000);
            }

            for (int ii = 10; ii >= 0; ii--)
            {
                lcd.CursorHome();
                lcd.Print("Downcount: " + ii + " ");
                Thread.Sleep(1000);
            }

            var piezo = new PWM((PWM.Pin) FEZ_Pin.PWM.Di10);

            using (var servo0 = new FEZ_Components.ServoMotor(FEZ_Pin.Digital.Di13))
            {
                servo0.SetPosition(180);
                Thread.Sleep(1000);
            }

            piezo.Set(5000, 50);
            Thread.Sleep(500);
            piezo.Set(1000, 50);
            Thread.Sleep(500);
            piezo.Set(500, 50);
            Thread.Sleep(500);
            piezo.Set(50, 50);
            Thread.Sleep(500);
            piezo.Set(0, 0);

            using (var servo0 = new FEZ_Components.ServoMotor(FEZ_Pin.Digital.Di13))
            {
                servo0.SetPosition(0);
                Thread.Sleep(1000);
            }

            lcd.Clear();

            // Blink board LED
            //bool ledState = false;
            //OutputPort led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED, ledState);

            //while (true)
            //{
            //    // Sleep for 500 milliseconds
            //    Thread.Sleep(500);

            //    // toggle LED state
            //    ledState = !ledState;
            //    led.Write(ledState);
            //}
        }
示例#34
0
 public void TestSetPeriodMultiplier(PeriodMultiplier setting, int expected)
 {
     using (PWM pwm = NewPWM())
     {
         pwm.PeriodMultiplier = setting;
         //Assert.AreEqual(expected, PWMData().PeriodScale);
     }
 }
示例#35
0
 public void TestGetRaw()
 {
     using (PWM pwm = NewPWM())
     {
         //PWMData().RawValue = 1234;
         //Assert.AreEqual(pwm.GetRaw(), 1234);
     }
 }
		public void TestConstructor () {
			PWM pwm = new PWM( "test", alpha, 0.0 );
			double[] w1 = { 1.0, 2.0, 3.0 };
			double[] w2 = { 2.0, 4.0, 6.0 };
			pwm.Add( 'a', w1 );
			pwm.Add( 'c', w2 );
			Assert.AreEqual( 3, pwm.WeightedVectorLength );
			Assert.AreEqual( 2, pwm.SymbolNumber );
		}
示例#37
0
 public void TestPWMCreate()
 {
     using (PWM pwm = new PWM(5))
     {
         Assert.AreEqual(pwm.Channel, 5);
         Assert.IsFalse(pwm.DeadbandElimination);
         //TODO: Test Reporting
     }
 }
示例#38
0
        public void Run()
        {
            var p = new PWM(PWM.Pin.PWM1);

            var freq = 60;
            byte duty = 12;

            p.Set(freq, duty);
        }
示例#39
0
 public void TestAllocateError()
 {
     using (PWM pwm = new PWM(5))
     {
         Assert.Throws<AllocationException>(() =>
         {
             var p2 = new PWM(5);
         });
     }
 }
		/** Tests the calc. of a PWM on base of a motif */
		public void TestConstructorMotif () {
			PWM pwm = new PWM( "PWM1", alpha, "A[TG]", 0.0 );
			Assert.AreEqual( 100.0, pwm.Get( 'a', 0 ), 1e-3 );
			Assert.AreEqual( 1.0, pwm.Get( 'c', 0 ), 1e-3 );
			Assert.AreEqual( 1.0, pwm.Get( 't', 0 ), 1e-3 );
			Assert.AreEqual( 1.0, pwm.Get( 'g', 0 ), 1e-3 );
			Assert.AreEqual( 1.0, pwm.Get( 'a', 1 ), 1e-3 );
			Assert.AreEqual( 1.0, pwm.Get( 'c', 1 ), 1e-3 );
			Assert.AreEqual( 100.0, pwm.Get( 't', 1 ), 1e-3 );
			Assert.AreEqual( 100.0, pwm.Get( 'g', 1 ), 1e-3 );
		}
示例#41
0
        public void Start()
        {
            _pwmDutyCycle = 0;

            _led = new PWM(Pins.GPIO_PIN_D5);

            _pwmTimer = new Timer(
                PwmTimerCallback,
                null,
                PwmPeriod,
                PwmPeriod);
        }
        public static void Main()
        {
            var ledR = new PWM(Pins.GPIO_PIN_D9);
            var ledG = new PWM(Pins.GPIO_PIN_D6);
            var ledB = new PWM(Pins.GPIO_PIN_D5);

            while (true)
            {
                for (double i = 0; i < 1; i += 0.003)
                {
                    var c = ColorRGB.Hsl2Rgb(i, 1.0, 0.5);

                    ledR.SetPulse(255, c.R);
                    ledG.SetPulse(255, c.G);
                    ledB.SetPulse(255, c.B);

                    Thread.Sleep(25);
                }
            }
        }
		/** Tests the adding and getting of weights */
		public void TestAddGet () {
			PWM pwm = new PWM( "test", alpha, 0.0 );
			double[] w1 = { 1.0, 2.0, 3.0 };
			double[] w2 = { 2.0, 4.0, 6.0 };
			pwm.Add( 'a', w1 );
			pwm.Add( alpha['c'], w2 );
			Assert.AreEqual( w1, pwm.Get( alpha['a'] ) );
			Assert.AreEqual( null, pwm.Get( alpha['z'] ) );
			Assert.AreEqual( w2, pwm.Get( 'c' ) );
			Assert.AreEqual( 3, pwm.WeightedVectorLength );
			Assert.AreEqual( 2, pwm.SymbolNumber );
			Assert.AreEqual( 1.0, pwm.Get( 'a', 0 ), 1e-3 );
			Assert.AreEqual( 2.0, pwm.Get( 'a', 1 ), 1e-3 );
			Assert.AreEqual( 3.0, pwm.Get( 'a', 2 ), 1e-3 );
			Assert.AreEqual( 2.0, pwm.Get( 'c', 0 ), 1e-3 );
			Assert.AreEqual( 4.0, pwm.Get( 'c', 1 ), 1e-3 );
			Assert.AreEqual( 6.0, pwm.Get( 'c', 2 ), 1e-3 );

			Assert.AreEqual( 1.0, pwm.Get( 't', 0 ), 1e-3 );
			Assert.AreEqual( 2.0, pwm.Get( 't', 1 ), 1e-3 );
			Assert.AreEqual( 3.0, pwm.Get( 't', 2 ), 1e-3 );
		}
示例#44
0
        public static void Main()
        {
            var sensor = new HCSR04(Stm32F4Discovery.FreePins.PC2, Stm32F4Discovery.FreePins.PC1);

            //crash detect: red led on or off
            var crashLed = new OutputPort(Stm32F4Discovery.LedPins.Red, false);
            var scanPeriod = new TimeSpan(0, 0, 0, 0, 100);//100ms
            var detector = new CollisionDetector(sensor, scanPeriod) { Barier = 10 }; //10cm
            detector.StateChanged += crashLed.Write;

            //pwm frequency display (green led linear blink): far->lo freq, near->hi freq
            var distancePwm = new PWM(Cpu.PWMChannel.PWM_0, 1, 0, false);
            distancePwm.Start();
            
            //print distance every 1s and change pwm freq
            DateTime nextPrint = DateTime.Now;
            for(;;)
            {
                TimeSpan pulse = sensor.Ping();

                if (DateTime.Now > nextPrint)
                {
                    float cm = HCSR04.ToCentimeters(pulse);
                    string cmStr = cm.Equals(Single.MaxValue) ? "?" : cm.ToString("F1");

                    float inch = HCSR04.ToInches(pulse);
                    string inStr = inch.Equals(Single.MaxValue) ? "?" : inch.ToString("F1");

                    Debug.Print("Distance: " + cmStr + " cm = " + inStr + " in");
                    nextPrint = DateTime.Now.AddSeconds(1);
                }

                distancePwm.Frequency = ToFrequency(pulse);
                distancePwm.DutyCycle = 0.5;

                Thread.Sleep(200);
            }
        }
示例#45
0
        /// <summary>
        /// Plays a raw RTTL string by converting it into PWN tones
        /// Derived from http://code.google.com/p/rogue-code/source/browse/Arduino/libraries/Tone/trunk/examples/RTTTL/RTTTL.pde
        /// and Ian Lintner's port to C# https://github.com/ianlintner/Netduino-Ring-Tone-Player
        /// </summary>
        public void Play(PWM channel)
        {
            char[] charParserArray; //used for parsing the current section
            const int defaultDuration = 4;
            const int defaultOctave = 6;
            var tone = new RttlTone();

            foreach (var rttlNote in _rttlNotes) {
                charParserArray = rttlNote.ToLower().ToCharArray();

                // Parse each note... and play it!
                for (var i = 0; i < rttlNote.Length; i++) {
                    var durationParseNumber = 0;
                    int currentScale;
                    var currentNote = 0;
                    const int octaveOffset = 0;

                    // first, get note duration, if available
                    while (i < charParserArray.Length && IsDigit(charParserArray[i])) {
                        //construct the duration
                        durationParseNumber = (durationParseNumber * 10) + (charParserArray[i++] - '0');
                    }

                    var currentDuration = durationParseNumber > 0 ? durationParseNumber : defaultDuration;

                    // c is first note i.e. c = 1
                    // b = 12
                    // pause or undefined = 0
                    if (i < charParserArray.Length) {
                        switch (charParserArray[i]) {
                            case 'c':
                                currentNote = 1;
                                break;
                            case 'd':
                                currentNote = 3;
                                break;
                            case 'e':
                                currentNote = 5;
                                break;
                            case 'f':
                                currentNote = 6;
                                break;
                            case 'g':
                                currentNote = 8;
                                break;
                            case 'a':
                                currentNote = 10;
                                break;
                            case 'b':
                                currentNote = 12;
                                break;
                            case 'p':
                                currentNote = 0;
                                break;
                            default:
                                currentNote = 0;
                                break;
                        }
                    }

                    i++;

                    // process whether the note is sharp
                    if (i < charParserArray.Length && charParserArray[i] == '#') {
                        currentNote++;
                        i++;
                    }

                    // is it dotted note, divide the duration in half
                    if (i < charParserArray.Length && charParserArray[i] == '.') {
                        currentDuration += currentDuration / 2;
                        i++;
                    }

                    // now, get octave
                    if (i < charParserArray.Length && IsDigit(charParserArray[i])) {
                        currentScale = charParserArray[i] - '0';
                        i++;
                    } else {
                        currentScale = defaultOctave;
                    }

                    //offset if necessary
                    currentScale += octaveOffset;

                    // Setup the tone by calculating the note's location in the RTTTL note array
                    tone.SetTone((uint)RttlNotes[(currentScale - 1) * 12 + currentNote], (uint)currentDuration);

                    // Play the tone
                    PlayTone(tone, channel);
                }
            }
        }
示例#46
0
 /// <summary>
 /// Play an single tone on a given channel 
 /// </summary>
 /// <param name="tone">A RttlTone object</param>
 /// <param name="channel">Any PWN pin</param>
 public void PlayTone(RttlTone tone, PWM channel)
 {
     if (tone.Note != 0) {
         channel.SetPulse(tone.Period, tone.Period / 2);
         Thread.Sleep(tone.GetDelay(Tempo));
         channel.SetDutyCycle(0);
     } else {
         channel.SetDutyCycle(0);
         Thread.Sleep(tone.GetDelay(Tempo));
     }
 }
示例#47
0
        /// <summary>
        /// Plays the song
        /// </summary>
        /// <param name="channel">The PWN pin connected to the speaker</param>
        /// <param name="asynchronous">True: play the song on a separate thread and return immediately. False: play the song and return when done.</param>
        /// <returns>If asynchronous == true, returns a reference to the thread playing the song or a null reference if asynchronous == false.</returns>
        public Thread Play(PWM channel, bool asynchronous = false)
        {
            if (asynchronous) {
                var thread = new Thread(() => Play(channel));
                thread.Start();
                return thread;
            }

            Play(channel);
            return null;
        }
示例#48
0
 public Motor(PWM.Pin pin, int frequency)
 {
     m_pin = new PWM(pin);
     m_frequency = frequency;
 }
		/** Tests the adding of weights as strings */
		public void TestAddString () {
			PWM pwm = new PWM( "test", alpha, 0.0 );

			pwm.Add( 'a', "1 2 3" );
			pwm.Add( alpha['c'], "2 4 6" );
			Assert.AreEqual( 3, pwm.WeightedVectorLength );
			Assert.AreEqual( 2, pwm.SymbolNumber );
			Assert.AreEqual( 1.0, pwm.Get( 'a', 0 ), 1e-3 );
			Assert.AreEqual( 2.0, pwm.Get( 'a', 1 ), 1e-3 );
			Assert.AreEqual( 3.0, pwm.Get( 'a', 2 ), 1e-3 );
			Assert.AreEqual( 2.0, pwm.Get( 'c', 0 ), 1e-3 );
			Assert.AreEqual( 4.0, pwm.Get( 'c', 1 ), 1e-3 );
			Assert.AreEqual( 6.0, pwm.Get( 'c', 2 ), 1e-3 );
		}
示例#50
0
文件: PWM.cs 项目: ianlee74/IO60P16
 public void Stop(PWM[] ports)
 {
 }
示例#51
0
 public Servo(FEZ_Pin.PWM pin)
 {
     pwm = new PWM((PWM.Pin)pin);
 }
示例#52
0
        private static void BoundPWM(PWM pwm)
        {
#pragma warning disable 618
            pwm.SetBounds(1500, 1050, 1000, 950, 500);
#pragma warning restore 618
        }
        /// <summary>
        /// 
        /// Reads a pattern from a starting specified node. This method
        /// recursivly calls the reading methods of the different patterns.
        /// </summary>
        /// <param name="node">Node of the pattern the reading starts with.</param>
        /// <param name="definition">Pattern definition which pattern list will be extended 
        /// with the pattern and all its sub-patterns read.
        /// </param>
        /// <returns>The read pattern or null if there is no pattern to read.</returns>
        /// <exception cref="System.SystemException">Thrown when unknown pattern was found</exception>
        public static IPattern ReadPattern
                    (XmlNode node, Definition definition)
        {
            while (node != null
                    && node.NodeType != XmlNodeType.Element)

                node = node.NextSibling; //Iterate thru the list of nodes until it is an element

            IPattern pattern = null;
            String mode = XMLHelper.GetAttrValueString(node, "mode");

            switch (node.Name)
            {
                case "Any":
                    pattern = new Any();
                    break;

                case "Alignment":
                    pattern = new Alignment();
                    break;

                case "Composition" :
                    pattern = new Composition();
                    break;

                case "Constraint":
                    pattern = new Constraint();
                    break;

                case "Iteration":
                    pattern = new Iteration();
                    break;

                case "Logic":
                    pattern = new Logic();
                    break;

                case "Motif":
                    pattern = new Motif();
                    break;

                case "PWM":
                    pattern = new PWM();
                    break;

                case "Regex":
                    pattern = new RegularExp();
                    break;

                case "Prosite":
                    pattern = new Prosite();
                    break;

                case "Block":
                    pattern = new Block();
                    break;

                case "Gap":
                    pattern = new Gap();
                    break;

                case "Repeat":
                    pattern = new Repeat();
                    break;

                case "Series":
                    pattern = mode.Equals("ALL") ? 
                        pattern = new SeriesAll() : pattern = new SeriesBest();
                    break;

                case "Set":
                    pattern = mode.Equals("ALL") ?
                       pattern = new SetAll() : pattern = new SetBest();
                    break;

                case "Void":
                    pattern = new VoidPattern();
                    break;

                case "Use":
                    pattern = new Use();
                    break;

                throw new SystemException
                    ("Unknown pattern found: " + node.Name);
 
            }

 
            pattern.ReadNode(node, definition);      // read the node data and initialize the pattern
            definition.Patterns.Add
                            (0, pattern); //Always adding the element to last index
 
            return pattern;
        }
示例#54
0
 public Piezo(FEZ_Pin.PWM pin)
 {
     pwm = new PWM((PWM.Pin)pin);
 }
示例#55
0
文件: Piezo.cs 项目: ducas/Robbo
 /// <summary>
 /// Creates an instance of the Piezo buzzer.
 /// </summary>
 /// <param name="pin">The PWM pin connected to the buzzer.</param>
 public Piezo(PWM.Pin pin)
 {
     pwm = new PWM(pin);
 }
示例#56
0
文件: PWM.cs 项目: ianlee74/IO60P16
        private void SetPwm(byte port, byte pin, byte period, byte pulseWidth, PWM.PwmClockSource clock, byte clockDivider = 0)
        {
            //_parentModule.Write(port, pin, false);                      // Why was this here???

            _parentModule.WriteRegister(0x18, port);                      // Select port

            var b = _parentModule.ReadRegister(0x1a)[0];
            b |= (byte)((1 << pin));
            _parentModule.WriteRegister(0x1a, b);                         // select PWM for port output

            b = _parentModule.ReadRegister(0x1C)[0];
            b &= (byte)(~(1 << pin));
            _parentModule.WriteRegister(0x1C, b);                         // Set pin for output.

            _parentModule.WriteRegister(0x28, (byte)(0x08 + pin));        // Select the PWM pin to configure.

            _parentModule.WriteRegister(0x29, (byte)clock);               // Config PWM (select 32kHz clock source)
            if (clockDivider > 0) _parentModule.WriteRegister(0x2c, clockDivider);     // Set the clock divider (if using 367.6 Hz clock)
            _parentModule.WriteRegister(0x2a, period);                    // set the period (0-256)
            _parentModule.WriteRegister(0x2b, pulseWidth);                // set the pulse width (0-(period-1))

            //_parentModule.Write(port, pin, true);
        }
示例#57
0
 public MotorizedWindow(PWM.Pin pwmPin)
 {
     _window = new Servomotor(pwmPin);
 }
示例#58
0
文件: PWM.cs 项目: ianlee74/IO60P16
 public static void Start(PWM[] ports)
 {
 }
示例#59
0
 public PWMMotor(PWM.PWM pwmOutput, MotorSettings settings)
 {
     _pwmOutput = pwmOutput;
     _settings = settings;
     SetSafe();
 }
示例#60
0
 /// <summary>
 /// Uses 50Hz
 /// </summary>
 /// <param name="pin">PWM Pin</param>
 public BrushlessMotor(PWM.Pin pin)
     : this(pin, Omnicopter.Period.P50Hz)
 {
 }