Esempio n. 1
0
        /// <summary>
        /// Move a stepper. Only one param between steps and msec but be set different from 0.
        /// Blocking call.
        /// </summary>
        /// <param name="which">Which stepper to drive</param>
        /// <param name="mode">Stepping mode</param>
        /// <param name="speed">Number of ms between each step (0 : no pause=max speed)</param>
        /// <param name="direction">True = foward, False = backward</param>
        /// <param name="steps">If non-zero, number of steps to run</param>
        /// <param name="msec">If non-zero, number of ms to run</param>
        /// <param name="hold">True if stepper shall stay energized when task done</param>
        /// <returns>Number of steps ran</returns>
        //public uint StepperMove(Steppers which, BipolarStepping mode, int speed, bool direction, int steps, int msec, bool hold = false)
        //{
        //    byte[] MotorSteps = BipolarSteppingWaveDrive[(byte)which]; // Get the stepping pattern
        //    if (mode == BipolarStepping.HiTorque) MotorSteps = BipolarSteppingHiTorque[(byte)which];
        //    if (mode == BipolarStepping.HalfStep) MotorSteps = BipolarSteppingHalfStep[(byte)which];

        //    // Find where we stopped last time
        //    byte last;
        //    int pos;
        //    uint step = 0;
        //    if (which == 0) last = (byte)(latch_state & 0x1E);
        //    else last = (byte)(latch_state & 0xE1);
        //    for (pos = 0; pos < MotorSteps.Length; pos++) if (MotorSteps[pos] == last) break;
        //    if (pos == MotorSteps.Length) pos = 0;

        //    if (which == 0) { Motor1A.Write(true); Motor1B.Write(true); }
        //    else { Motor2A.SetDutyCycle(100); Motor2B.SetDutyCycle(100); }

        //    byte Mask = (byte)((which == 0) ? 0xE1 : 0x1E);

        //    if (steps > 0) // user chose to move from a number of steps
        //    {
        //        for (; step < steps; step++)
        //        {
        //            if (direction) pos = (pos + 1) % MotorSteps.Length;
        //            else if (--pos < 0) pos = MotorSteps.Length - 1;
        //            latch_state = (byte)((latch_state & Mask) | MotorSteps[pos]);
        //            latch_tx();
        //            if (speed > 0) Thread.Sleep(speed);
        //        }

        //    }
        //    else // So no number of steps, the user must have given a time to run
        //    {
        //        long endtime = DateTime.Now.Ticks + msec * TimeSpan.TicksPerMillisecond;
        //        for (; DateTime.Now.Ticks < endtime; step++)
        //        {
        //            if (direction) pos = (pos + 1) % MotorSteps.Length;
        //            else if (--pos < 0) pos = MotorSteps.Length - 1;
        //            latch_state = (byte)((latch_state & Mask) | MotorSteps[pos]);
        //            latch_tx();
        //            if (speed > 0) Thread.Sleep(speed);
        //        }
        //    }

        //    if (!hold) // Remove energy from stepper
        //    {
        //        if (which == 0) { Motor1A.Write(false); Motor1B.Write(false); }
        //        else { Motor2A.SetDutyCycle(0); Motor2B.SetDutyCycle(0); }
        //    }

        //    return step;
        //}

        ///// <summary>
        ///// Control a motor; Non-blocking call. Set speed to 0 to stop.
        ///// Frequency might need to be adjusted deppending on motor, or to match other PWMs
        ///// </summary>
        ///// <param name="which">Which motor to drive</param>
        ///// <param name="speed">Steed, between 0 and 255 (0 to stop, 255 = max speed)</param>
        ///// <param name="direction">True = foward, False = backward</param>
        ///// <param name="freq">Frequency in Hz of the PWM controlling the motor</param>
        //public void MotorControl(Motors which, byte speed, bool direction, int freq = 100)
        //{
        //    uint period = (uint)(1000000D / (double)freq);
        //    switch (which)
        //    {
        //        case Motors.M1:
        //            latch_state = (byte)((latch_state & 0xF3) | (direction ? 4 : 8));
        //            latch_tx();
        //            Motor1A.Write(speed > 0);
        //            break;

        //        case Motors.M2:
        //            latch_state = (byte)((latch_state & 0xED) | (direction ? 2 : 16));
        //            latch_tx();
        //            Motor1B.Write(speed > 0);
        //            break;
        //        case Motors.M3: // This motor can have its speed controlled through PWM
        //            if (speed == 0) Motor2A.SetDutyCycle(0);
        //            else
        //            {
        //                latch_state = (byte)((latch_state & 0xBE) | (direction ? 1 : 64));
        //                latch_tx();
        //                Motor2A.SetPulse(period, (uint)(period * (double)speed / 255D));
        //            }
        //            break;
        //        case Motors.M4: // This motor can have its speed controlled through PWM
        //            if (speed == 0) Motor2B.SetDutyCycle(0);
        //            else
        //            {
        //                latch_state = (byte)((latch_state & 0x5F) | (direction ? 32 : 128));
        //                latch_tx();
        //                Motor2B.SetPulse(period, (uint)(period * (double)speed / 255D));
        //            }
        //            break;
        //    }
        //}

        public void BothMotors(int motor3Speed, int motor4Speed)
        {
            if (motor3Speed == 0)
            {
                Motor2A.SetDutyCycle(0);
            }
            if (motor4Speed == 0)
            {
                Motor2A.SetDutyCycle(0);
            }

            var motor3Dir = motor3Speed > 0;
            var motor4Dir = motor4Speed > 0;

            //var motor3latch_state = (byte) ((latch_state & 0xBE) | (motor3Dir ? 1 : 64));

            //var motor4latch_state = (byte) ((latch_state & 0x5F) | (motor4Dir ? 32 : 128));


            //latch_state = (byte) (motor3latch_state & motor4latch_state);

            latch_state = (byte)((latch_state & 0xBE) | (motor3Dir ? 1 : 64));
            latch_tx();
            Motor2A.SetDutyCycle((uint)Math.Abs(motor3Speed));

            latch_state = (byte)((latch_state & 0x5F) | (motor4Dir ? 32 : 128));
            latch_tx();

            Motor2B.SetDutyCycle((uint)Math.Abs(motor4Speed));
        }
Esempio n. 2
0
        public static void Main()
        {
            int duty = 0;

            //define the PWM out
            var pwm = new PWM(Pins.GPIO_PIN_D5);

            pwm.SetDutyCycle((uint)duty);

            //define the input port for the "decrement" button
            var btnDec = new AutoRepeatInputPort(
                port: Pins.GPIO_PIN_D8,
                resistor: Port.ResistorMode.PullUp,
                activeLevel: false);

            btnDec.InitialDelay  = 1000;
            btnDec.StateChanged += (s, e) =>
            {
                if (e.State != AutoRepeatInputPort.AutoRepeatState.Release)
                {
                    duty--;
                    if (duty < 0)
                    {
                        duty = 0;
                    }

                    pwm.SetDutyCycle((uint)duty);
                }
            };

            //define the input port for the "increment" button
            var btnInc = new AutoRepeatInputPort(
                port: Pins.GPIO_PIN_D9,
                resistor: Port.ResistorMode.PullUp,
                activeLevel: false);

            btnInc.InitialDelay  = 1000;
            btnInc.StateChanged += (s, e) =>
            {
                if (e.State != AutoRepeatInputPort.AutoRepeatState.Release)
                {
                    duty++;
                    if (duty > 100)
                    {
                        duty = 100;
                    }

                    pwm.SetDutyCycle((uint)duty);
                }
            };

            //do nothing
            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 3
0
 public void forward()
 {
     pwmM1.SetDutyCycle(0);
     pwmM2.SetDutyCycle(0);
     dirM1.Write(true);
     dirM2.Write(false);
     pwmM1.SetDutyCycle(speed + bias);
     pwmM2.SetDutyCycle(speed - bias);
 }
Esempio n. 4
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));
     }
 }
Esempio n. 5
0
 public void TurnOff()
 {
     // take the pin low, so the speaker
     // doesn't make any noise until we
     // ask it to
     _pin.SetDutyCycle(0);
 }
Esempio n. 6
0
 public override void BackLight(uint dutyCycle)
 {
     if (_backLight != null)
     {
         _backLight.SetDutyCycle(dutyCycle & 0xFF);
     }
 }
Esempio n. 7
0
 public HS6635HBServo(Cpu.Pin pwmPin, uint minPulse = 900, uint centerPulse = 1500, uint maxPulse = 2100)
 {
     _servo = new PWM((Cpu.Pin)pwmPin);
     _servo.SetDutyCycle(0);
     MinRangePulse      = minPulse;
     CenterRangePulse   = centerPulse;
     MaxRangePulse      = maxPulse;
     PulseRefreshRateMs = 20;
 }
Esempio n. 8
0
        public static void Main()
        {
            var axisX         = new AnalogInput(Pins.GPIO_PIN_A0);
            var axisY         = new AnalogInput(Pins.GPIO_PIN_A1);
            var axisZ         = new AnalogInput(Pins.GPIO_PIN_A2);
            var IrFloorSensor = new AnalogInput(Pins.GPIO_PIN_A3);


            var out1 = new OutputPort(Pins.GPIO_PIN_D1, false);
            var out2 = new OutputPort(Pins.GPIO_PIN_D12, false);


            var in1 = new InputPort(Pins.GPIO_PIN_D2, false, Port.ResistorMode.Disabled);
            var in2 = new InputPort(Pins.GPIO_PIN_D4, false, Port.ResistorMode.PullUp);


            var servo1 = new PWM(Pins.GPIO_PIN_D9);

            servo1.SetDutyCycle(0);
            var servo2 = new PWM(Pins.GPIO_PIN_D10);

            servo2.SetDutyCycle(0);


            var stopWatch = Stopwatch.StartNew();

            stopWatch.Start();
            int  i        = 0;
            bool digState = false;


            while (i < 5000)
            {
                axisX.Read();
                axisY.Read();
                axisZ.Read();
                IrFloorSensor.Read();


                in1.Read();
                in2.Read();


                digState = !digState;
                out1.Write(digState);
                out2.Write(digState);


                servo1.SetPulse(20000, 1500);
                servo2.SetPulse(20000, 1500);


                i++;
            }
            stopWatch.Stop();
            Debug.Print("Elapsed: " + stopWatch.ElapsedMilliseconds.ToString());
        }
Esempio n. 9
0
        /// <summary>
        /// Set the speed of the DC motor
        /// </summary>
        /// <param name="speed">The percentage of full speed at which to run (0-100)</param>
        public void SetSpeed(uint speed)
        {
            if (speed > 100)
            {
                speed = 100;
            }

            pwm.SetDutyCycle(speed);
        }
Esempio n. 10
0
    public PiezoSpeaker(Cpu.Pin pin)
    {
        _pin = new PWM(pin);

        // take the pin low, so the speaker
        // doesn't make any noise until we
        // ask it to
        _pin.SetDutyCycle(0);
    }
Esempio n. 11
0
        public static void Main()
        {
            Hashtable scale = new Hashtable();

            // low octave
            scale.Add("c", 1915u);
            scale.Add("d", 1700u);
            scale.Add("e", 1519u);
            scale.Add("f", 1432u);
            scale.Add("g", 1275u);
            scale.Add("a", 1136u);
            scale.Add("b", 1014u);

            // high octave
            scale.Add("C", 956u);
            scale.Add("D", 851u);
            scale.Add("E", 758u);

            // silence ("hold note")
            scale.Add("h", 0u);

            int beatsPerMinute          = 90;
            int beatTimeInMilliseconds  = 60000 / beatsPerMinute; // 60,000 ms per min
            int pauseTimeInMilliseconds = (int)(beatTimeInMilliseconds * 0.1);

            // define the song(letter of note followed by length of note)
            string song = "C1C1C1g1a1a1g2E1E1D1D1C2";

            // define the speaker
            PWM speaker = new PWM(Pins.GPIO_PIN_D5);

            while (true)
            {
                for (int i = 0; i < song.Length; i += 2)
                {
                    // song loop
                    // extract each note and its length in beats
                    string note      = song.Substring(i, 1);
                    int    beatCount = int.Parse(song.Substring(i + 1, 1));

                    // look up the note duration(in microseconds)
                    uint noteDuration = (uint)scale[note];

                    // play the note for the desired number of beats
                    speaker.SetPulse(noteDuration * 2, noteDuration);
                    Thread.Sleep(beatTimeInMilliseconds * beatCount - pauseTimeInMilliseconds);

                    // pause for 1/10th of a beat in between every note.
                    speaker.SetDutyCycle(0);
                    Thread.Sleep(pauseTimeInMilliseconds);
                }

                //Thread.Sleep(Timeout.Infinite);
                Thread.Sleep(1000);
            }
        }
Esempio n. 12
0
 public void SetColor(Color rgbValue, int delay = 0)
 {
     if (CommonAnode == true)
     {
         _blue.SetDutyCycle((uint)(255 - ((int)rgbValue & 0xFF)));
         _green.SetDutyCycle((uint)(255 - (((int)rgbValue >> 8) & 0xFF)));
         _red.SetDutyCycle((uint)(255 - (((int)rgbValue >> 16) & 0xFF)));
     }
     else
     {
         _blue.SetDutyCycle((uint)rgbValue & 0xFF);
         _green.SetDutyCycle((uint)((int)rgbValue >> 8) & 0xFF);
         _red.SetDutyCycle((uint)((int)rgbValue >> 16) & 0xFF);
     }
     if (delay != 0)
     {
         Thread.Sleep(delay);
     }
 }
Esempio n. 13
0
        static void irrx_InfraredMessageDecoded(
            object sender,
            InfraredMessageDecodedEventArgs e)
        {
            var message = (LegoMessage)e.Message;

            //Debug.Print(message.Mode + " " + message.Func);

            switch (message.Func & 0x03)
            {
            case 0:
                _wheelLeft.SetDutyCycle(0);
                _red.Write(false);
                break;

            case 1:
                _wheelLeft.SetDutyCycle(100);
                break;

            case 2:
                _red.Write(true);
                break;
            }

            switch (message.Func & 0x0C)
            {
            case 0:
                _wheelRight.SetDutyCycle(0);
                _green.Write(false);
                break;

            case 4:
                _wheelRight.SetDutyCycle(100);
                break;

            case 8:
                _green.Write(true);
                break;
            }
        }
Esempio n. 14
0
        public ServoController(Cpu.Pin pin, int minDuration, int maxDuration, uint period = 20000, int startDegree = 0)
        {
            _minDuration = minDuration;
            _maxDuration = maxDuration;
            _range       = maxDuration - minDuration;
            _period      = period;
            _servo       = new PWM(pin);
            _servo.SetDutyCycle(0);

            if (startDegree > 0)
            {
                Rotate(startDegree);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Play a note
        /// </summary>
        public void PlayNote(uint period, uint duration, int beatCount)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("Piezzo buzzer");
            }

            // Play the note for the desired number of beats
            speaker.SetPulse(period, duration);
            Thread.Sleep(BeatTimeInMilliseconds * beatCount - PauseTimeInMilliseconds);

            // Pause for 1/10th of a beat in between every note.
            speaker.SetDutyCycle(0);
            Thread.Sleep(PauseTimeInMilliseconds);
        }
Esempio n. 16
0
        public static void Main()
        {
            uint watchdogTimer = 1000;

            PWM umbrella = new PWM(Pins.GPIO_PIN_D10); //Right controller

            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 4444));
            byte[] rxData    = new byte[10]; // Incoming data buffer
            double raw_speed = 0;

            while (true) /* Main program loop */
            {
                /* Try to receive new data - spend 100uS waiting */
                if (receiveSocket.Poll(100, SelectMode.SelectRead))
                {
                    int rxCount = receiveSocket.Receive(rxData);
                    watchdogTimer = 0;
                }

                if (watchdogTimer < 200)   // Only enable the robot if data was received recently
                {
                    // 900 (full rev) to 2100 (full fwd), 1500 is neutral

                    raw_speed += (rxData[0] - 127.5) * .001; // Add the value of the stick to the current speed
                    // Mediate added speed to negative if it's below center line(on ipgamepad). Make the added speed very little because the mount of UDP packets is large.
                    // map function only accept input between 0-255
                    if (raw_speed < 0)
                    {
                        raw_speed = 0;
                    }
                    else if (raw_speed > 255)
                    {
                        raw_speed = 255;
                    }
                    // Stick maintains speed unless calibrate changes.
                    umbrella.SetPulse(20000, map((uint)raw_speed, 0, 255, 1500, 2100)); // Right controller 1500-2100 -- only positive

                    watchdogTimer++;
                }
                else
                {
                    // Disable the robot
                    umbrella.SetDutyCycle(0);
                }
            }
        }
Esempio n. 17
0
        //// changing the blinking speed with potentiomenter
        //public static void Main()
        //{
        //    OutputPort led = new OutputPort(Pins.GPIO_PIN_D0, false);

        //    AnalogInput pot = new AnalogInput(Pins.GPIO_PIN_A0);

        //    int potValue = 0;

        //    pot.SetRange(100, 250);
        //    while (true)
        //    {
        //        potValue = pot.Read();
        //        led.Write(true);

        //        Thread.Sleep(potValue);
        //        led.Write(false);

        //        Thread.Sleep(potValue);
        //    }
        //}

        // Dimming the LED light with potetniometer
        public static void Main()
        {
            PWM led = new PWM(Pins.GPIO_PIN_D5);

            AnalogInput pot = new AnalogInput(Pins.GPIO_PIN_A0);

            int potValue = 0;

            pot.SetRange(0, 100);

            while (true)
            {
                potValue = pot.Read();
                led.SetDutyCycle((uint)potValue);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Create the PWM pin, set it low and configure timings
        /// </summary>
        /// <param name="pin"></param>
        public ServoControl(Cpu.Pin pin)
        {
            try
            {
                // Init the PWM pin
                servo = new PWM(pin);

                servo.SetDutyCycle(0);

                // Typical settings
                range[0] = 1000;
                range[1] = 2000;
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 19
0
 private static void PlaySong()
 {
     for (int i = 0; i < song.Length; i += 2)
     {
         // extract each note and its length in beats
         string note      = song.Substring(i, 1);
         int    beatCount = int.Parse(song.Substring(i + 1, 1));
         // look up the note duration (in microseconds)
         uint noteDuration = (uint)scale[note];
         // play the note for the desired number of beats
         speaker.SetPulse(noteDuration * 2, noteDuration);
         Thread.Sleep(
             beatTimeInMilliseconds * beatCount - pauseTimeInMilliseconds);
         // pause for 1/10th of a beat in between every note.
         speaker.SetDutyCycle(0);
         Thread.Sleep(pauseTimeInMilliseconds);
     }
 }
Esempio n. 20
0
    /// <summary>
    /// Play a particular frequency for a defined
    /// time period
    /// </summary>
    /// <param name="frequency">The frequency (in hertz) of the note to be played</param>
    /// <param name="duration">How long (in milliseconds: 1000 = 1 second) the note is to play for</param>
    public void Play(float frequency, int duration)
    {
        if (!_busy)
        {
            _busy = true;

            // calculate the actual period and turn the
            // speaker on for the defined period of time
            uint period = (uint)(1000000 / frequency);
            _pin.SetPulse(period, period / 2);

            Thread.Sleep(duration);

            // turn the speaker off
            _pin.SetDutyCycle(0);
            _busy = false;
        }
    }
Esempio n. 21
0
        //----------------- Constructor ------------------------------
        public Robot()
        {
            // Initialize the robot in a start state
            RMasterState = RobotState.Start;

            RightMotorPWM.SetDutyCycle(0);
            LeftMotorPWM.SetDutyCycle(0);

            // Create the lock object for the queue Lock
            RCmdLock = new Object();
            //Create the command queue object
            RCmdQueue = new Queue();  // Create the Robot Command queue object.  The queue holds the commands the robot needs to follow.

            // Set initial state of robot
            RMasterState = RobotState.Start;
        }
Esempio n. 22
0
        public static void Main()
        {
            int dashLength             = 3;
            int pauseBetweenElements   = 1;
            int pauseBetweenCharacters = 2;
            int pauseBetweenWords      = 7;
            int duration = 90;

            PWM speaker = new PWM(Pins.GPIO_PIN_D5);

            while (true)
            {
                foreach (char curChar in "HELLO PO")
                {
                    for (int index = ",ETINAMSDRGUKWOHBL,F,PJVXCQZYAA54A3AAA2AAAAAAA16AAAAAAA7AAA8A90".IndexOf(curChar); index > 0; index /= 2)
                    {
                        speaker.SetPulse(851u * 2, 851u);
                        if ("-."[index-- % 2] == '.')
                        {
                            Thread.Sleep(duration);
                            Debug.Print(".");
                        }
                        else
                        {
                            Thread.Sleep(duration * dashLength);
                            Debug.Print("-");
                        }
                        speaker.SetDutyCycle(0);
                        Thread.Sleep(duration * pauseBetweenElements);
                    }
                    Thread.Sleep(duration * pauseBetweenCharacters);
                    Debug.Print(" ");
                    if (curChar.Equals(' '))
                    {
                        Thread.Sleep(duration * pauseBetweenWords);
                    }
                }
                Thread.Sleep(1400);
            }
        }
Esempio n. 23
0
        byte latch_state;                                                // Actual 74HCT595 output state

        // Steper sequences for each stepper. Have a look here : http://www.stepperworld.com/Tutorials/pgBipolarTutorial.htm
        //private byte[][] BipolarSteppingWaveDrive = new byte[][] {  new byte [] {4,2,8,16},
        //                                                            new byte [] {1,128,64,32}};
        //private byte[][] BipolarSteppingHiTorque = new byte[][] {   new byte [] {20,24,10,6},
        //                                                            new byte [] {129,192,96,33}};
        //private byte[][] BipolarSteppingHalfStep = new byte[][] {   new byte [] {4,20,16,24,8,10,2,6},
        //                                                            new byte [] {1,129,128,192,64,96,32,33}};

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="driver"> Which driver to initialize : 1=driver 1, 2=driver 2, 3=both</param>
        public Mshield()
        {
            //UsedDriver = driver;
            //if (driver == Drivers.Driver1 || driver == Drivers.Both)
            //{
            //    Motor1A = new OutputPort(Pins.GPIO_PIN_D11, false);
            //    Motor1B = new OutputPort(Pins.GPIO_PIN_D3, false);
            //}
            //if (driver == Drivers.Driver2 || driver == Drivers.Both)
            //{
            Motor2A = new PWM(Pins.GPIO_PIN_D5);
            Motor2A.SetDutyCycle(0);
            Motor2B = new PWM(Pins.GPIO_PIN_D6);
            Motor2B.SetDutyCycle(0);
            //}
            MotorLatch  = new OutputPort(Pins.GPIO_PIN_D12, true);
            MotorEnable = new OutputPort(Pins.GPIO_PIN_D7, false);
            MotorClk    = new OutputPort(Pins.GPIO_PIN_D4, true);
            MotorData   = new OutputPort(Pins.GPIO_PIN_D8, true);

            latch_state = 0;
            latch_tx();
        }
Esempio n. 24
0
        public static void Main()
        {
            Thread.Sleep(1000);
            led.Write(false);

            if (isCharging.Read())
            {
                PWM printerLight = new PWM(Pins.GPIO_PIN_D5);

                printerLight.SetPulse(100, 0);
                printerLight.SetDutyCycle(100);
                while (true)
                {
                    for (int pulse = 0; pulse < 15; pulse++)
                    {
                        for (uint i = 0; i < 100; i++)
                        {
                            printerLight.SetDutyCycle(i);
                            Thread.Sleep(15);
                        }

                        for (uint i = 0; i < 100; i++)
                        {
                            printerLight.SetDutyCycle(100 - i);
                            Thread.Sleep(10);
                        }
                        Thread.Sleep(2000);
                    }
                }
            }

            try
            {
                System.Text.Encoding enc = System.Text.Encoding.UTF8;

                int fileNum    = randy.Next(19999);
                var fileStream = File.Open(@"SD\rand.txt", FileMode.Open);

                byte[] randNum = new byte[30];

                fileStream.Read(randNum, 0, 30);

                int seed = int.Parse(new string(enc.GetChars(randNum)).Trim());

                randy = new Random(seed);

                fileStream.Close();

                fileStream = File.OpenWrite(@"SD\rand.txt");

                byte[] tempToWriteInt = enc.GetBytes((seed + 1).ToString() + "          ");

                fileStream.Write(tempToWriteInt, 0, tempToWriteInt.Length);

                fileStream.Close();

                var    stream = File.Open(@"SD\chain\" + fileNum + ".txt", FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[1024];

                stream.Read(buffer, 0, buffer.Length);


                stream.Close();

                PrintText = new string(enc.GetChars(buffer));
            }
            catch (Exception e)
            {
                PrinterTest("Could not access SD Card. Or other issues related to generating text");
            }

            while (true)
            {
                iRobotTest();
                //there is text to be printed!

                // todo: stop robot

                // todo: start lights flashing (probably around the printer)
                PWM printerLight = new PWM(Pins.GPIO_PIN_D5);

                printerLight.SetPulse(100, 0);
                printerLight.SetDutyCycle(100);

                for (int pulse = 0; pulse < 10; pulse++)
                {
                    for (uint i = 0; i < 100; i++)
                    {
                        printerLight.SetDutyCycle(i);
                        Thread.Sleep(3);
                    }

                    for (uint i = 0; i < 100; i++)
                    {
                        printerLight.SetDutyCycle(100 - i);
                        Thread.Sleep(3);
                    }
                }

                if (PRINT)
                {
                    Thread.Sleep(1500);
                    PrintPoem(PrintText);
                }
                for (int pulse = 0; pulse < 15; pulse++)
                {
                    for (uint i = 0; i < 100; i++)
                    {
                        printerLight.SetDutyCycle(i);
                        Thread.Sleep(10);
                    }

                    for (uint i = 0; i < 100; i++)
                    {
                        printerLight.SetDutyCycle(100 - i);
                        Thread.Sleep(10);
                    }
                }

                printerLight.SetDutyCycle(0);

                PowerState.RebootDevice(false);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Move the stepper one step
        /// </summary>
        /// <param name="dir">The direction in which to move</param>
        /// <param name="style">The type of stepping to use</param>
        /// <returns>Current step count</returns>
        public uint OneStep(MotorDirection dir, StepType style = StepType.Single)
        {
            byte a, b, c, d;
            byte ocrb, ocra;

            ocra = ocrb = 255;
            switch (stepperPort)
            {
            /*
             * case StepperPorts.M1_M2;
             *  a = (1<<(int)MotorBits.Motor1_A);
             *  b = (1<<(int)MotorBits.Motor2_A);
             *  c = (1<<(int)MotorBits.Motor1_B);
             *  d = (1<<(int)MotorBits.Motor2_B);
             *  break;
             */
            case StepperPorts.M3_M4:
                a = (1 << (int)MotorBits.Motor3_A);
                b = (1 << (int)MotorBits.Motor4_A);
                c = (1 << (int)MotorBits.Motor3_B);
                d = (1 << (int)MotorBits.Motor4_B);
                break;

            default:
                return(0);
            }

            // next determine what sort of stepping procedure we're up to
            if (style == StepType.Single)
            {
                if ((currentStep / (microsteps / 2)) % 2 == 0) // we're at an odd step, weird. Shouldn't happen, but just in case...
                {
                    currentStep += (dir == MotorDirection.Forward) ? (uint)(microsteps / 2) : (uint)(-microsteps / 2);
                }
                else // go to the next even step
                {
                    currentStep += (dir == MotorDirection.Forward) ? (uint)(microsteps) : (uint)(-microsteps);
                }
            }

            else if (style == StepType.Double)
            {
                if ((currentStep / (microsteps / 2) % 2) != 0) // we're at an even step, weird.  Just in case...
                {
                    currentStep += (dir == MotorDirection.Forward) ? (uint)(microsteps / 2) : (uint)(-microsteps / 2);
                }
                else  // go to the next odd step
                {
                    currentStep += (dir == MotorDirection.Forward) ? (uint)(microsteps) : (uint)(-microsteps);
                }
            }

            else if (style == StepType.Interleave)
            {
                currentStep += (dir == MotorDirection.Forward) ? (uint)(microsteps) : (uint)(-microsteps);
            }

            if (style == StepType.Microstep)
            {
                if (dir == MotorDirection.Forward)
                {
                    currentStep++;
                }
                else
                {
                    // BACKWARDS
                    currentStep--;
                }

                currentStep += microsteps * 4;
                currentStep %= microsteps * 4;

                ocra = ocrb = 0;
                if ((currentStep >= 0) && (currentStep < microsteps))
                {
                    ocra = microstepCurve[microsteps - currentStep];
                    ocrb = microstepCurve[currentStep];
                }
                else if ((currentStep >= microsteps) && (currentStep < microsteps * 2))
                {
                    ocra = microstepCurve[currentStep - microsteps];
                    ocrb = microstepCurve[microsteps * 2 - currentStep];
                }
                else if ((currentStep >= microsteps * 2) && (currentStep < microsteps * 3))
                {
                    ocra = microstepCurve[microsteps * 3 - currentStep];
                    ocrb = microstepCurve[currentStep - microsteps * 2];
                }
                else if ((currentStep >= microsteps * 3) && (currentStep < microsteps * 4))
                {
                    ocra = microstepCurve[currentStep - microsteps * 3];
                    ocrb = microstepCurve[microsteps * 4 - currentStep];
                }
            }

            currentStep += microsteps * 4;
            currentStep %= microsteps * 4;

            coilA.SetDutyCycle(ocra);
            coilB.SetDutyCycle(ocrb);

            // release all
            latchState &= (byte)(~a & ~b & ~c & ~d); // all motor pins to 0

            //Serial.println(step, DEC);
            if (style == StepType.Microstep)
            {
                if ((currentStep >= 0) && (currentStep < microsteps))
                {
                    latchState |= (byte)(a | b);
                }
                if ((currentStep >= microsteps) && (currentStep < microsteps * 2))
                {
                    latchState |= (byte)(b | c);
                }
                if ((currentStep >= microsteps * 2) && (currentStep < microsteps * 3))
                {
                    latchState |= (byte)(c | d);
                }
                if ((currentStep >= microsteps * 3) && (currentStep < microsteps * 4))
                {
                    latchState |= (byte)(d | a);
                }
            }
            else
            {
                switch (currentStep / (microsteps / 2))
                {
                case 0:
                    latchState |= (byte)(a);     // energize coil 1 only
                    break;

                case 1:
                    latchState |= (byte)(a | b);     // energize coil 1+2
                    break;

                case 2:
                    latchState |= (byte)(b);     // energize coil 2 only
                    break;

                case 3:
                    latchState |= (byte)(b | c);     // energize coil 2+3
                    break;

                case 4:
                    latchState |= (byte)(c);     // energize coil 3 only
                    break;

                case 5:
                    latchState |= (byte)(c | d);     // energize coil 3+4
                    break;

                case 6:
                    latchState |= (byte)(d);     // energize coil 4 only
                    break;

                case 7:
                    latchState |= (byte)(d | a);     // energize coil 1+4
                    break;
                }
            }


            latch_tx(latchState);
            return(currentStep);
        }
Esempio n. 26
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));
     }
 }
Esempio n. 27
0
 private void TimerTick(object state)
 {
     pwm.SetDutyCycle(0);
     timer.Dispose();
     timer = null;
 }
 public void Release()
 {
     servo.SetDutyCycle(0);
 }
Esempio n. 29
0
 /// <summary>
 /// Disengage the servo.
 /// The servo motor will stop trying to maintain an angle
 /// </summary>
 public void Disengage()
 {
     // See what the Netduino team say about this...
     servo.SetDutyCycle(0);
 }
Esempio n. 30
0
        public static void Main()
        {
            var dummyTest = true;
            //Connect real Input Ports to ground !

            //3 Examples:
            //    1. "normal"
            //    2. interrupt driven
            //    3. PWM driven on port D5 !!

            var runSample = 1;

            switch (runSample)
            {   // "normal"
            case 1:
                switchPort = new InputPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled);
                while (dummyTest)
                {
                    if (!switchPort.Read() || !realSwitchPort.Read() || !realSwitchPort1.Read() || !realSwitchPort2.Read())
                    {
                        ledPort.Write(true);
                        realLedPort.Write(true);
                        sleepTime = 500;
                        if (!realSwitchPort1.Read())
                        {
                            sleepTime = 300;
                        }
                        if (!realSwitchPort2.Read())
                        {
                            sleepTime = 100;
                        }
                    }
                    Thread.Sleep(sleepTime);
                    ledPort.Write(false);
                    realLedPort.Write(false);
                    Thread.Sleep(sleepTime);
                }
                break;

            case 2:
                // Interrupt Sample:
                interruptPort              = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
                interruptPort.OnInterrupt += new NativeEventHandler(interruptPort_OnInterrupt);
                while (dummyTest)
                {
                }
                break;

            case 3:
                // use PWM Port ..
                var  realLedPortPWM = new PWM(Pins.GPIO_PIN_D5);
                uint outPWM = 0; bool up = true;
                while (dummyTest)
                {
                    if (up)
                    {
                        outPWM++;
                        if (outPWM >= 100)
                        {
                            up = false;
                        }
                    }
                    else
                    {
                        outPWM--;
                        if (outPWM <= 0)
                        {
                            up = true;
                        }
                    }
                    realLedPortPWM.SetDutyCycle(outPWM);
                    Thread.Sleep(8);
                }
                break;

            default:
                Debug.Print("This is no choice -- you are doomed!");
                break;
            }
        }
Esempio n. 31
0
        public static void Main()
        {
            const int millisecIncrement    = 100;
            const int millisecElapsedLimit = 60000;

            var millisecCounter = 0;
            var currentHeat     = HighHeat;

            var currentHeaterStatus  = false;
            var previousHeaterStatus = true;
            var initialize           = true;

            _ledHighHeat.SetDutyCycle(0);
            _ledLowHeat.SetDutyCycle(0);

            InitializeClock();

            Log("\r\nWater Heater Controller v1.0\r\n");
            Log("Initializing...");
            LoadSchedule();

            PowerServo(true);
            Log("Centering servo");
            _servo.Center();
            Log("Setting heater on high heat by default");
            _servo.Move(Center, currentHeat);
            Log("Running...");
            PowerServo(false);

            while (true)
            {
                if (_serialUI.SerialErrorReceived == true)
                {
                    _serialUI.Dispose();
                    _serialUI     = new SerialUserInterface();
                    _showMainMenu = true;
                    Log("Serial error received: serial UI object recycled");
                }

                if (_showMainMenu == true)
                {
                    _showMainMenu = false;
                    MainMenu(null);
                }

                millisecCounter += millisecIncrement;

                if (millisecCounter >= millisecElapsedLimit || _scheduleChange == true)
                {
                    millisecCounter     = 0;
                    currentHeaterStatus = _schedule.GetHeaterStatus(_clock.Get());
                }

                if (currentHeaterStatus != previousHeaterStatus || _scheduleChange == true || initialize == true)
                {
                    Log("Heater state change");

                    _ledOverride.Write(_schedule.WaterHeaterManualOverride);

                    if (currentHeaterStatus)
                    {
                        Log("Setting heater on high");
                        PowerServo(true);
                        _servo.Move(currentHeat, HighHeat);
                        PowerServo(false);
                        _ledHighHeat.SetDutyCycle(50);
                        _ledLowHeat.SetDutyCycle(0);
                        currentHeat = HighHeat;
                    }
                    else
                    {
                        Log("Setting heater on low");
                        PowerServo(true);
                        _servo.Move(currentHeat, LowHeat);
                        PowerServo(false);
                        _ledHighHeat.SetDutyCycle(0);
                        _ledLowHeat.SetDutyCycle(50);
                        currentHeat = LowHeat;
                    }
                    previousHeaterStatus = currentHeaterStatus;
                    _scheduleChange      = false;
                    initialize           = false;
                }

                if (_shutdown)
                {
                    Log("Shutting down");
                    Log("Moving servo to center...");
                    _ledHighHeat.SetDutyCycle(50);
                    _ledLowHeat.SetDutyCycle(50);
                    PowerServo(true);
                    _servo.Move(currentHeat, Center);
                    PowerServo(false);

                    Log("Shutdown complete");
                    Log("Cycle power to restart.");

                    var dutyCycle = 0;
                    var direction = 1;

                    while (true)
                    {
                        _ledHighHeat.SetDutyCycle((uint)dutyCycle);
                        _ledLowHeat.SetDutyCycle((uint)dutyCycle);
                        dutyCycle += direction;
                        if (dutyCycle == 50)
                        {
                            direction = -1;
                        }
                        else if (dutyCycle == 0)
                        {
                            direction = 1;
                        }
                        Thread.Sleep(50);
                    }
                }

                Thread.Sleep(millisecIncrement);
            }
        }