Esempio n. 1
0
 //===========================MOTION SENSOR=========================
 static void motion_OnInterrupt(uint data1, uint data2, DateTime time)
 {
     try
     {
         port.EnableInterrupt();
         port.DisableInterrupt();
         DateTime startTime = DateTime.Now;
         // Some execution process
         DateTime endTime        = DateTime.Now;
         TimeSpan totalTimeTaken = endTime.Subtract(startTime);
         Debug.Print("Motion detected! Alarm sounding");
         sendDataUsingCOMPort("MOTION STATUS=" + "MOTION DETECTED FOR " + totalTimeTaken + "s ");
         //spUART.Flush();
         port.EnableInterrupt();
         //Thread.Sleep(5000);
         //uint duration1 = 1000, duration2 = 1000;
         //speaker.SetPulse(duration1 * 2, duration1);
         //speaker.SetPulse(duration2 * 2, duration2);
         //Thread.Sleep(250);
         //speaker.SetDutyCycle(0);
         //MovementDetected = true;
         Debug.Print("Alarm sounding");
         //OutputPort redLED = new OutputPort(Pins.GPIO_PIN_D9, false);
         //for (int i = 0; i < 3; i++)
         // {
         //   redLED.Write(true);
         //   Thread.Sleep(300);
         //   redLED.Write(false);
         //}
     }
     catch (Exception ex)
     {
         Debug.Print(ex.Message);
     }
 }
Esempio n. 2
0
        /// <summary>
        ///     Default constructor
        /// </summary>
        /// <param name="socket">The socket in which the USB UART click board is inserted into.</param>
        /// <param name="baudRate">Baud Rate enumeration of usable baud rates (ones that actually work), see <see cref="System.IO.Ports.SerialPort.BaudRate"/></param>
        /// <param name="handshake">Optional - Handshake, defaults to None, see <see cref="System.IO.Ports.Handshake"/>. <see cref="System.IO.Ports.Handshake.RequestToSend "/> is not functional and will be set to <see cref="Handshake.None"/>.</param>
        /// <exception cref="PinInUseException">A <see cref="PinInUseException"/> will be thrown if the Tx, Rx, Rst, Int, Cs, Pwm are used in a stacked module arrangement.</exception>
        public USBUARTClick(Hardware.Socket socket, BaudRate baudRate, Handshake handshake)
        {
            try
            {
                // Rst Pin is connected to FT232RL CTS Pin, Int Pin is connected to FT232RL RTS Pin, Pwm Pin is connected to FT232RL CBUS3 Pin (USB Power), Cs Pin is connected to FT232RL CBUS4 Pin (USB Sleep/Suspend)
                Hardware.CheckPins(socket, socket.Tx, socket.Rx, socket.Rst, socket.Int, socket.Cs, socket.Pwm);
                _serial = new SimpleSerial(socket.ComPort, (int)baudRate)
                {
                    Handshake = handshake == Handshake.RequestToSend ? Handshake.None : handshake
                };

                _serial.DataReceived  += _serial_DataReceived;
                _serial.ErrorReceived += _serial_ErrorReceived;
                _serial.Open();

                _powerPin = new InterruptPort(socket.Pwm, true, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeBoth);
                _sleepPin = new InterruptPort(socket.Cs, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);

                _powerPin.OnInterrupt += powerPin_OnInterrupt;
                _sleepPin.OnInterrupt += sleepPin_OnInterrupt;

                _powerPin.EnableInterrupt();
                _sleepPin.EnableInterrupt();
            }
            catch (PinInUseException ex)
            {
                throw new PinInUseException(ex.Message);
            }
        }
Esempio n. 3
0
        protected void AciSend(AciOpCode opCode, params byte[] data)
        {
            if (data.Length > 30)
            {
                throw new ArgumentOutOfRangeException("data", "The maximum amount of data bytes is 30.");
            }

            // Create ACI packet
            var packet = new byte[data.Length + 2];

            packet[0] = (byte)(data.Length + 1);
            packet[1] = (byte)opCode;
            Array.Copy(data, 0, packet, 2, data.Length);

            // Request transfer
            _rdy.DisableInterrupt();
            _req.Write(false);

            // Wait for RDY to go low
            while (_rdy.Read())
            {
                ;
            }

            _spi.WriteLsb(packet);

            _req.Write(true);

            // Wait for RDY to go high
            while (!_rdy.Read())
            {
                ;
            }
            _rdy.EnableInterrupt();
        }
Esempio n. 4
0
 private void SetEnabled()
 {
     //cal netejat interrupcions?
     // _irqPin.ClearInterrupt();
     _irqPin.EnableInterrupt();
     _cePin.Write(true);
 }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JoystickClick"/> class.
        /// </summary>
        /// <param name="socket">The socket on which the JoystickClick module is plugged on MikroBus.Net board</param>
        /// <param name="address">The address of the module.</param>
        /// <param name="clockRateKHz">The clock rate of the I²C device. <seealso cref="ClockRatesI2C"/></param>
        public JoystickClick(Hardware.Socket socket, Byte address = 0x40, ClockRatesI2C clockRateKHz = ClockRatesI2C.Clock100KHz)
        {
            try
            {
                // Checks if needed I²C pins are available.
                Hardware.CheckPinsI2C(socket, socket.Int, socket.Rst, socket.Cs);

                // Create the driver's I²C configuration
                _config = new I2CDevice.Configuration(address, (Int32)clockRateKHz);

                _reset = new OutputPort(socket.Rst, true);
                Reset(ResetModes.Hard);

                Sensitivity = 0x3F; // Max sensitivity
                Scaling     = 0x09; // 100% scaling

                Button = new InterruptPort(socket.Cs, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
                Button.EnableInterrupt();

                PowerMode     = PowerModes.On;  // Interrupt mode
                InterruptLine = new InterruptPort(socket.Int, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
                TimeBase      = 3;
                ReadRegister(0x11);     // Don't care about the first data available
                InterruptLine.EnableInterrupt();
            }
            // Catch only the PinInUse exception, so that program will halt on other exceptions
            // Send it directly to the caller
            catch (PinInUseException) { throw new PinInUseException(); }
        }
Esempio n. 6
0
 static void pushBtn_OnInterrupt(uint data1, uint data2, DateTime time)
 {
     pushBtn.DisableInterrupt();
     // hold = (data2 == 1) ? true : false;
     inside += 1;
     hold    = !hold;
     pushBtn.EnableInterrupt();
 }
Esempio n. 7
0
        public static void Main()
        {
            InterruptPort buttonInterruptPort = new InterruptPort(DiscoveryF4.UserButton, true, Port.ResistorMode.PullDown,
                                                                  Port.InterruptMode.InterruptEdgeHigh);

            buttonInterruptPort.OnInterrupt += buttonInterruptPort_OnInterrupt;
            buttonInterruptPort.EnableInterrupt();
            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 8
0
        /// <summary>
        /// Retrieves measured data from the sensor.
        /// </summary>
        /// <returns>
        /// <c>true</c> if the operation succeeds and the data is valid, otherwise <c>false</c>.
        /// </returns>
        public bool Read()
        {
            if (disposed)
            {
                throw new ObjectDisposedException();
            }
            // The 'bitMask' also serves as edge counter: data bit edges plus
            // extra ones at the beginning of the communication (presence pulse).
            bitMask = 1L << 41;

            data = 0;
            // lastTicks = 0; // This is not really needed, we measure duration
            // between edges and the first three values are ignored anyway.

            // Initiate communication
            portOut.Active = true;
            portOut.Write(false);       // Pull bus low
            Thread.Sleep(StartDelay);
            portIn.EnableInterrupt();   // Turn on the receiver
            portOut.Active = false;     // Release bus

            bool dataValid = false;

            // Now the interrupt handler is getting called on each falling edge.
            // The communication takes up to 5 ms, but the interrupt handler managed
            // code takes longer to execute than is the duration of sensor pulse
            // (interrupts are queued), so we must wait for the last one to finish
            // and signal completion. 20 ms should be enough, 50 ms is safe.
            if (dataReceived.WaitOne(50, false))
            {
                // TODO: Use two short-s ?
                bytes[0] = (byte)((data >> 32) & 0xFF);
                bytes[1] = (byte)((data >> 24) & 0xFF);
                bytes[2] = (byte)((data >> 16) & 0xFF);
                bytes[3] = (byte)((data >> 8) & 0xFF);

                byte checksum = (byte)(bytes[0] + bytes[1] + bytes[2] + bytes[3]);
                if (checksum == (byte)(data & 0xFF))
                {
                    dataValid = true;
                    Convert(bytes);
                }
                else
                {
                    Debug.Print("DHT sensor data has invalid checksum.");
                }
            }
            else
            {
                portIn.DisableInterrupt();               // Stop receiver
                Debug.Print("DHT sensor data timeout."); // TODO: TimeoutException?
            }
            return(dataValid);
        }
Esempio n. 9
0
 public void enableInterrupt(string s)
 {
     lock (_inport)
     {
         _interruptDisableCount--;
         if (_interruptDisableCount == 0)
         {
             _inport.EnableInterrupt();
         }
         // Debug.Print(s+ " Enable: " + _interruptDisableCount);
     }
 }
        public CC3100SpiTransport(SPI.SPI_module spiBusID, Cpu.Pin csPinID, Cpu.Pin intPinID)
        {
            // create our chip select pin and SPI bus objects
            _chipSelectPin = new OutputPort(csPinID, !_chipSelectActiveLevel);
            _spi           = new SPI(new SPI.Configuration(Cpu.Pin.GPIO_NONE, false, 0, 0, false, true, 20000, spiBusID));

            // wire up our interrupt
            _interruptPin              = new InterruptPort(intPinID, true, Port.ResistorMode.PullDown, Port.InterruptMode.InterruptEdgeBoth);
            _interruptPin.OnInterrupt += _interruptPin_OnInterrupt;
            _interruptPin.EnableInterrupt();

            // start our ProcessIncomingData thread.
            _notifyDataReceivedThread = new Thread(NotifyDataReceived);
            _notifyDataReceivedThread.Start();
        }
Esempio n. 11
0
        private void port_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            _port.DisableInterrupt();

            if (data2 > 0)
            {
                OnPressed();
            }
            else
            {
                OnReleased();
            }

            _port.EnableInterrupt();
            _port.ClearInterrupt();
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ColorClick"/> class.
        /// </summary>
        /// <param name="socket">The socket on which the Color Click board is plugged on MikroBus.Net board</param>
        /// <param name="address">The address of the display. Default to 0x29.</param>
        /// <param name="clockRateKHz">The clock rate of the I²C device. Default to ClockRatesI2C.Clock100KHz. <seealso cref="ClockRatesI2C"/></param>
        public ColorClick(Hardware.Socket socket, Byte address = 0x29, ClockRatesI2C clockRateKHz = ClockRatesI2C.Clock100KHz)
        {
            Hardware.CheckPinsI2C(socket, socket.Int, socket.An, socket.Cs, socket.Pwm);

            _config = new I2CDevice.Configuration(address, (Int32)clockRateKHz);

            Init();
            LedR = new OutputPort(socket.An, false);
            LedG = new OutputPort(socket.Cs, false);
            LedB = new OutputPort(socket.Pwm, false);
            var dataReady = new InterruptPort(socket.Int, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh);

            dataReady.OnInterrupt += _dataReady_OnInterrupt;

            dataReady.EnableInterrupt();
        }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BiHallClick"/> class.
        /// </summary>
        /// <param name="socket">The <see cref="Hardware.Socket"/> that the AltitudeClick is inserted into.</param>
        /// <exception cref="PinInUseException">A PinInUseException will be thrown if the Int pin is being used by another driver on the same socket.</exception>
        public BiHallClick(Hardware.Socket socket)
        {
            try
            {
                Hardware.CheckPins(socket, socket.Int);

                _interrupt              = new InterruptPort(socket.Int, true, Port.ResistorMode.PullDown, Port.InterruptMode.InterruptEdgeBoth);
                _interrupt.OnInterrupt += _interrupt_OnInterrupt;

                _interrupt.EnableInterrupt();
            }
            // Catch only the PinInUse exception, so that program will halt on other exceptions
            // Send it directly to caller
            catch (PinInUseException ex)
            {
                throw new PinInUseException(ex.Message);
            }
        }
Esempio n. 14
0
        public static void Main()
        {
            try
            {
                var timeSet = false;
                NTP.UpdateTimeFromNtpServer("pool.ntp.org", 1);

                ReadConfiguration();
                ReadValueCache(System.DateTime.Today.ToString("ddMMyyyy"));

                loggingEndpoint = HttpClient.GetIPEndPoint(loggingHostName, loggingPortNumber);

                s0Port              = new InterruptPort(Pins.GPIO_PIN_D12, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
                s0Port.OnInterrupt += new NativeEventHandler(S0PulseReceived);
                s0Port.EnableInterrupt();

                var messageReader = new P1MessageReader();
                messageReader.MessageReceived += new P1MessageReader.MessageReceivedDelegate(messageReader_MessageReceived);
                messageReader.Start();

                while (true)
                {
                    Thread.Sleep(60000);

                    // Resync time and s0Counter at 3 o'clock at night
                    if (!timeSet && System.DateTime.Now.Hour == 3)
                    {
                        timeSet   = NTP.UpdateTimeFromNtpServer("pool.ntp.org", 1);
                        s0Counter = 0;
                    }
                    else if (timeSet && System.DateTime.Now.Hour > 3)
                    {
                        timeSet = false;
                    }

                    CacheValuesOnSd(System.DateTime.Today.ToString("ddMMyyyy"));
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.ToString());
            }
        }
Esempio n. 15
0
        public int TakeReading()
        {
            _pulseWidthMm = 0;

            //_callback = callback;
            _reset = new ManualResetEvent(false);

            _echoPin.EnableInterrupt();
            _triggerPin.Write(false);
            Thread.Sleep(2);
            _triggerPin.Write(true);
            Thread.Sleep(10);
            _triggerPin.Write(false);
            Thread.Sleep(2);


            _reset.WaitOne(500, false);

            return(_pulseWidthMm);
        }
Esempio n. 16
0
        /// <summary>
        /// The interrupt fires on a high edge when the button is pressed by default.
        /// If using a button other than the built-in one, you should connect pull-down resistors to the switch.
        /// Lady Ada has an excellent tutorial on this subject: http://www.ladyada.net/learn/arduino/lesson5.html
        /// </summary>
        /// <param name="pin">A digital pin connected to the actual push-button.</param>
        /// <param name="intMode">Defines the type of edge-change triggering the interrupt.</param>
        /// <param name="target">The event handler called when an interrupt occurs.</param>
        /// <param name="resistorMode">Internal pullup resistor configuration</param>
        /// <param name="glitchFilter">Input debouncing filter</param>
        public PushButton(
            Cpu.Pin pin,
            Port.InterruptMode intMode     = Port.InterruptMode.InterruptEdgeBoth,
            NativeEventHandler target      = null,
            Port.ResistorMode resistorMode = Port.ResistorMode.Disabled,
            bool glitchFilter = true
            )
        {
            Input = new InterruptPort(pin, glitchFilter, resistorMode, intMode);

            if (target == null)
            {
                Input.OnInterrupt += InternalInterruptHandler;
            }
            else
            {
                Input.OnInterrupt += target;
            }

            Input.EnableInterrupt();
        }
Esempio n. 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DCMotorClick"/> class.
        /// </summary>
        /// <param name="socket">The socket on which the DCMotor Click board is plugged on MikroBus.Net</param>
        /// <param name="frequency">The frequency of the PWM output. Default value is 1000 Hz</param>
        /// <param name="dutyCycle">The initial duty cycle of PWM. Default to 0.0 %, that is : motor stopped</param>
        public DCMotorClick(Hardware.Socket socket, Double frequency = 1000.0, Double dutyCycle = 0.0)
        {
            try
            {
                Hardware.CheckPins(socket, socket.An, socket.Rst, socket.Cs, socket.Pwm, socket.Int);

                // Select1/2 : selection of decay modes. Only Fast decay implemented here.
                _select1            = new OutputPort(socket.Rst, false);
                _select2            = new OutputPort(socket.Cs, false);
                _sleep              = new OutputPort(socket.An, true);                                                                           // Sleep mode : OFF by default
                _pwmOut             = new PWM(socket.PwmChannel, frequency, dutyCycle, false);                                                   // PWM Output
                _fault              = new InterruptPort(socket.Int, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLevelLow); // Fault interrupt line
                _fault.OnInterrupt += Fault_OnInterrupt;                                                                                         // Subscribe to event in order to detect a fault
                _fault.EnableInterrupt();                                                                                                        // Enable interrupts
                IsMoving   = false;                                                                                                              // Motor not running
                _powerMode = PowerModes.On;
            }
            // Catch only the PinInUse exception, so that program will halt on other exceptions
            // Send it directly to caller
            catch (PinInUseException) { throw new PinInUseException(); }
        }
Esempio n. 18
0
        /// <summary>
        /// A private function called by the constructor to initialize the sensor for operation and starts measurements
        /// </summary>
        private void InitSensor(Boolean autoStart)
        {
            // Bypass the FIFO
            WriteRegister(RegisterMap.FIFO_CTL, 0x0F); // Bypass FIFO, Trigger on Int1 and 32 FIFO samples

            // Setup freefall thresholds
            WriteRegister(RegisterMap.THRESH_FF, 0x05); // 315mg
            WriteRegister(RegisterMap.TIME_FF, 0x14);   // 100ms
            _freefallEnabled = true;

            // Enable the 3 axis in tap detection
            WriteRegister(RegisterMap.TAP_AXES, 0x07);

            //Setup some default values for tap events
            WriteRegister(RegisterMap.DUR, 0x30);
            WriteRegister(RegisterMap.THRESH_TAP, 0x40);
            WriteRegister(RegisterMap.LATENT, 0x60);
            WriteRegister(RegisterMap.WINDOW, 0x80);
            _singleTapEnabled = true;
            _doubleTapEnabled = true;

            // Write interrupt table
            WriteRegister(RegisterMap.INT_ENABLE, (Byte)(InterruptSource.FREE_FALL | InterruptSource.SINGLE_TAP | InterruptSource.DOUBLE_TAP));

            // Setup data format
            WriteRegister(RegisterMap.DATA_FORMAT, (Byte)OutputResolutions.FullResolution | (Byte)AccelerationRanges.SixteenG); // 16g Full Res Mode

            // Enable measurement
            WriteRegister(RegisterMap.POWER_CTL, 0x00);
            Thread.Sleep(100);
            WriteRegister(RegisterMap.POWER_CTL, 0x08);

            _int1.OnInterrupt += ADXL345_Interrupt_OnInterrupt;
            _int1.EnableInterrupt();

            if (autoStart)
            {
                Start();
            }
        }
Esempio n. 19
0
        private void PulseCounter(uint data1, uint data2, DateTime time)
        {
            _geigerCounter.DisableInterrupt();

            _stats.Clicks++;

            if (_ticksCount < _ticks.Length)
            {
                _ticks[_ticksCount++] = time.Ticks;
            }
            else
            {
                _ticksCount = 0;
                _flipper   ^= true;

                var Interval1 = _ticks[1] - _ticks[0];
                var Interval2 = _ticks[3] - _ticks[2];

                if (Interval1 != Interval2)
                {
                    _randomNumber <<= 1;
                    if (_flipper)
                    {
                        _randomNumber |= (Interval1 < Interval2) ? 0 : 1;
                    }
                    else
                    {
                        _randomNumber |= (Interval1 > Interval2) ? 0 : 1;
                    }
                }
            }

            // TO DO:
            // Remove delay.
            // Use a small capacitor instead (value?) on the pin reading the pulses from the geiger counter.
            Thread.Sleep(14);

            _geigerCounter.EnableInterrupt();
        }
Esempio n. 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RFIDClick"/> class.
        /// </summary>
        /// <param name="socket">The socket on which the RFID Click board is plugged on MikroBus.Net board</param>
        /// <exception cref="System.InvalidOperationException">Thrown if some pins are already in use by another board on the same socket</exception>
        /// <exception cref="MBN.Exceptions.DeviceInitialisationException">RFID module not detected</exception>
        public RFIDClick(Hardware.Socket socket)
        {
            Hardware.CheckPins(socket, socket.Miso, socket.Mosi, socket.Cs, socket.Sck, socket.An, socket.Rst, socket.Int);

            _rBuffer = new Byte[260];

            // Set SPI mode on the chip
            new OutputPort(socket.Rst, true);
            new OutputPort(socket.An, false);
            IRQ_IN = new OutputPort(socket.Pwm, true);
            Thread.Sleep(1);
            ToggleIRQ_IN();

            // Now that the chip is in SPI mode, we can create the NETMF configuration and talk to the module
            _spiConfig = new SPI.Configuration(socket.Cs, false, 0, 0, false, true, 2000, socket.SpiModule);
            if (Hardware.SPIBus == null)
            {
                Hardware.SPIBus = new SPI(_spiConfig);
            }

            _dataReady              = new InterruptPort(socket.Int, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
            _dataReady.OnInterrupt += DataReady_OnInterrupt;
            _dataReady.EnableInterrupt();

            if (Echo() != 0x55)
            {
                throw new DeviceInitialisationException("RFID device not found");
            }

            IndexMod_Gain();
            AutoFDet();
            _protocol        = RFIDProtocol.NONE; // Protocol can't be set before calibration has been done
            _calibrationDone = false;
            _powerMode       = PowerModes.On;
            _lastTag         = "";
        }
                /// <summary>
                /// Initializes the DaisyLink bus, resetting all devices on it and assigning them new addresses.
                /// Any existing GTM.DaisyLinkModule devices will no longer work, and they should be constructed again.
                /// </summary>
                internal void Initialize()
                {
                    lock (portLock)
                    {
                        bool lastFound    = false;
                        byte modulesFound = 0;

                        // Reset all modules in the chain and place the first module into Setup mode
                        SendResetPulse();

                        // For all modules in the chain
                        while (!lastFound)
                        {
                            if (DaisyLinkVersionImplemented != ReadRegister(defaultI2cAddress, (byte)DaisyLinkRegister.DaisyLinkVersion, LengthErrorBehavior.SuppressException))
                            {
                                lastFound = true;       // If the correct version can't be read back from a device, there are no more devices in the chain
                            }

                            if (modulesFound != 0)      // If a device is left in Standby mode
                            {
                                byte[] data = new byte[2] {
                                    (byte)DaisyLinkRegister.Config, (byte)(lastFound ? 1 : 0)
                                };
                                Write((byte)(totalNodeCount + modulesFound), data);     // Enable/disable I2C pull-ups depending on whether last in chain (place module in Active mode)
                            }

                            if (!lastFound)
                            {
                                // Next module in chain is in Setup mode so start setting it up
                                modulesFound++;         // Increase the total number of modules found connected to this socket

                                byte[] data = new byte[2] {
                                    (byte)DaisyLinkRegister.Address, (byte)(totalNodeCount + modulesFound)
                                };
                                Write(defaultI2cAddress, data);     // Set the I2C ID of the next module in the chain (place module in Standby mode)
                            }
                        }

                        this.StartAddress  = (byte)(totalNodeCount + 1);
                        this.NodeCount     = modulesFound;
                        this.ReservedCount = 0;
                        totalNodeCount    += modulesFound;
                        Ready = true;
                        if (modulesFound != 0)
                        {
                            socketModuleList = new DaisyLinkModule[modulesFound];       // Keep track of all DaisyLinkModules attached to this socket
                            try
                            {
                                daisyLinkInterruptPort = new InterruptPort(daisyLinkCpuPin, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
                            }

                            catch (Exception e)
                            {
                                throw new Socket.InvalidSocketException("There is an issue connecting the DaisyLink module to socket " + Socket +
                                                                        ". Please check that all modules are connected to the correct sockets or try connecting the DaisyLink module to a different socket", e);
                            }
                            daisyLinkInterruptPort.OnInterrupt += new NativeEventHandler(daisyLinkInterruptPort_OnInterrupt);
                            daisyLinkInterruptPort.EnableInterrupt();
                        }
                    }
                }
Esempio n. 22
0
        // this function restarts and initializes our network chip
        void Initialize()
        {
            _isInitialized = false;

            // hardware-reset our network chip
            if (_resetPin == null)
            {
                _resetPin = new OutputPort(_resetPinID, false);
            }
            else
            {
                _resetPin.Write(false);
            }
            // sleep for at least 200us; we are sleeping for 2ms+ instead
            System.Threading.Thread.Sleep(2); // 2000us (2ms) should be plenty of time
            // take our hardware chip out of reset
            _resetPin.Write(true);

            // attempt to connect to network chip for 1000ms
            Int64  startTicks = Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks;
            ushort psr;
            bool   chipIsReady = false;

            do
            {
                psr = ReadGlobalRegister(AX88796CRegister.PSR);
                if (((psr & (UInt16)AX88796CRegisterBits.PSR_DEVICE_READY) == (UInt16)AX88796CRegisterBits.PSR_DEVICE_READY) && (psr != 0xFFFF))
                {
                    chipIsReady = true;
                    break;
                }
            } while ((Utility.GetMachineTime().Ticks - startTicks) / System.TimeSpan.TicksPerMillisecond < 1000);

            if (!chipIsReady)
            {
                throw new Exception(); /* TODO: throw the proper exception for "could not connect to network interface */
            }
            // enable RX packet processing
            UInt16 rpper = ReadGlobalRegister(AX88796CRegister.RPPER);

            rpper |= (UInt16)AX88796CRegisterBits.RPPER_RX_PACKET_ENABLE;
            WriteGlobalRegister(AX88796CRegister.RPPER, rpper);

            // disable RX bridge stuffing.  We only read one packet from the RX buffer at a time; buffer stuffing is designed to deal with synchronization issues during multi-packet DMA requests.
            UInt32 rxbspcr = ReadGlobalRegister(AX88796CRegister.RXBSPCR);

            rxbspcr &= ~(uint)AX88796CRegisterBits.RXBSPCR_ENABLE_STUFFING;
            WriteGlobalRegister(AX88796CRegister.RXBSPCR, (UInt16)rxbspcr);

            // set our MAC address
            WriteGlobalRegister(AX88796CRegister.MACASR0, (ushort)(((ushort)_macAddress[4]) << 8 + _macAddress[5]));
            WriteGlobalRegister(AX88796CRegister.MACASR1, (ushort)(((ushort)_macAddress[2]) << 8 + _macAddress[3]));
            WriteGlobalRegister(AX88796CRegister.MACASR2, (ushort)(((ushort)_macAddress[0]) << 8 + _macAddress[1]));

            // set checksum options
            UInt16 coercr0 = (UInt16)(AX88796CRegisterBits.COERCR0_RXIPCE | AX88796CRegisterBits.COERCR0_RXTCPE | AX88796CRegisterBits.COERCR0_RXUDPE); // enable IPv4, TCP and UDP checksum checks

            WriteGlobalRegister(AX88796CRegister.COERCR0, coercr0);
            //UInt16 coetcr0 = AX88796CRegisterBits.COETCR0_TXIP | AX88796CRegisterBits.COETCR0_TXTCP | AX88796CRegisterBits.COETCR0_TXUDP; // enable IPv4, TCP and UDP checksum insertions
            //WriteGlobalRegister(AX88796CRegister.COETCR0, coetcr0);

            /* TODO: if desired, disable RX IP header alignment function; see FER register for details */

            /* TODO: once we complete our IP stack, configure RXCR so that we don't get all packets forwarded to us--but only unicast packets and multicast/broadcast packets--including ARP/DHCP--that we want */
            // configure RX packet reception
            //UInt32 rxcr = ReadGlobalRegister(AX88796CRegister.RXCR);
            //rxcr &= ~(UInt32)AX88796CRegisterBits.RXCR_PACKET_TYPE_PROMISCUOUS; // disable promiscuous mode
            //rxcr |= (UInt32)(AX88796CRegisterBits.RXCR_PACKET_TYPE_BROADCAST | AX88796CRegisterBits.RXCR_PACKET_TYPE_ALLMULTICAST); // enable broadcast and (all?) multicast frames
            //WriteGlobalRegister(AX88796CRegister.RXCR, (UInt16)rxcr);

            /* TODO: if desired, drop CRC from received packets; see FER register for details */

            // enable byte swap within word on data port bridge
            UInt16 fer = ReadGlobalRegister(AX88796CRegister.FER);

            fer |= (UInt16)AX88796CRegisterBits.FER_BRIDGE_BYTE_SWAP;
            WriteGlobalRegister(AX88796CRegister.FER, fer);

            // enable RX and TX functions
            fer  = ReadGlobalRegister(AX88796CRegister.FER);
            fer |= (UInt16)(AX88796CRegisterBits.FER_RX_BRIDGE_ENABLE | AX88796CRegisterBits.FER_TX_BRIDGE_ENABLE);
            WriteGlobalRegister(AX88796CRegister.FER, fer);

            /* INITIALIZE PHY */
            // set power saving mode [cable disconnect mode 2]
            UInt32 pscr = ReadGlobalRegister(AX88796CRegister.PSCR);

            pscr &= ~(UInt32)AX88796CRegisterBits.PSCR_POWER_SAVING_CONFIG_MASK;
            pscr |= (UInt16)AX88796CRegisterBits.PSCR_POWER_SAVING_LEVEL_2;
            WriteGlobalRegister(AX88796CRegister.PSCR, (UInt16)pscr);
            //
            // configure LEDs /* TODO: configure these based on current speed, user settings, etc.*/
            UInt16 lcr0 = (UInt16)AX88796CRegisterBits.LCR0_LED0_OPTION_DISABLED;

            WriteGlobalRegister(AX88796CRegister.LCR0, lcr0);
            UInt16 lcr1 = (UInt16)AX88796CRegisterBits.LCR1_LED2_OPTION_LINKACT;

            WriteGlobalRegister(AX88796CRegister.LCR1, lcr1);
            //
            // configure PHY control register options
            UInt16 pcr = ReadGlobalRegister(AX88796CRegister.PCR);

            // retrieve our PHY ID
            _phyID = (byte)((pcr >> 8) & 0x1F); // retrieve our PHY ID
            // enable PHY auto polling and PHY auto polling flow control
            pcr |= (UInt16)(AX88796CRegisterBits.PCR_AUTO_POLL_ENABLE | AX88796CRegisterBits.PCR_POLL_FLOW_CONTROL);
            // select our auto polling register (MR0 vs MR4)
            pcr |= (UInt16)AX88796CRegisterBits.PCR_POLL_SELECT_MR0; /* TODO: do extensive testing, make sure this is giving us the data we're looking for */
            WriteGlobalRegister(AX88796CRegister.PCR, pcr);
            //
            // set PHY speed
            // NOTE: we may need to validate MACCR, althought it should auto-poll from PHY.
            /* TODO: should we be setting Opmode in PCR instead? and then setting this to AUTO in the PHY register? */
            switch (_phySpeed)
            {
            case PhySpeedOption.AutoNegotiate:
                WritePhyRegister(AX88796CPhyRegister.MR4, (UInt16)AX88796CPhyRegisterBits.MR4_SPEED_DUPLEX_AUTO);
                break;

            case PhySpeedOption.Speed10:
                WritePhyRegister(AX88796CPhyRegister.MR4, (UInt16)AX88796CPhyRegisterBits.MR4_SPEED_DUPLEX_10ANY);
                break;

            case PhySpeedOption.Speed100:
                WritePhyRegister(AX88796CPhyRegister.MR4, (UInt16)AX88796CPhyRegisterBits.MR4_SPEED_DUPLEX_100ANY);
                break;
            }
            // enable and restart auto-negotiation
            UInt16 mr0 = (UInt16)(AX88796CPhyRegisterBits.MR0_FULL_DUPLEX | AX88796CPhyRegisterBits.MR0_RESTART_AUTONEGOTIATION | AX88796CPhyRegisterBits.MR0_AUTO_NEGOTIATION_ENABLE | AX88796CPhyRegisterBits.MR0_SPEED_SELECTION_100);

            WritePhyRegister(AX88796CPhyRegister.MR0, mr0);

            // configure interrupts for INT pin (trigger on packet RX and link change)
            UInt32 imr = ReadGlobalRegister(AX88796CRegister.IMR);

            imr &= ((~(UInt32)(AX88796CRegisterBits.IMR_RXPCT_MASK | AX88796CRegisterBits.IMR_LINKCHANGE_MASK)) & 0xFFFF);
            WriteGlobalRegister(AX88796CRegister.IMR, (UInt16)imr);
            // enable our interrupt pin
            _interruptPin.EnableInterrupt();

            // we are now initialized
            _isInitialized = true;
        }
Esempio n. 23
0
 private void SetEnabled()
 {
     _irqPin.EnableInterrupt();
     _cePin.Write(true);
 }
Esempio n. 24
0
 /// <summary>
 /// Starts the interrupt pin scanning
 /// </summary>
 /// <example> This sample shows how to call the StartIRQ() method.
 /// <code language="C#">
 ///             _thunder = new ThunderClick(Hardware.SocketOne);
 ///
 ///             // Subscribe to events
 ///             _thunder.LightningDetected += TH_LightningDetected;
 ///             _thunder.DisturbanceDetected += TH_DisturbanceDetected;
 ///             _thunder.NoiseDetected += TH_NoiseDetected;
 ///
 ///             // Start scanning IRQ pin for an event
 ///             _thunder.StartIRQ();
 /// </code>
 /// </example>
 public void StartIRQ()
 {
     IRQ.EnableInterrupt();
 }
Esempio n. 25
0
        private bool Read(bool raiseEvent = true)
        {
            // The 'bitMask' also serves as edge counter: data bit edges plus extra ones at the beginning of the communication (presence pulse).
            _bitMask    = 1L << 42;
            _sensorData = 0;
            bool dataValid = false;

            // Initiate communication
            if (_portOut.Active == false)
            {
                _portOut.Active = true;
            }
            _portOut.Write(false);     // Pull pin low
            Thread.Sleep(5);           // At lest 1 mSec.
            _portIn.EnableInterrupt(); // Turn on the receiver
            if (_portOut.Active)
            {
                _portOut.Active = false;
            }

            // Now the interrupt handler is getting called on each falling edge.
            // The communication takes up to 5 ms, but the interrupt handler managed
            // code takes longer to execute than is the duration of sensor pulse
            // (interrupts are queued), so we must wait for the last one to finish
            // and signal completion. 20 ms should be enough, 50 ms is safe.
            // Set to 50 to minimize checksum and timeout errors. The higher the value
            // the less timeout errors, consequently longer conversion time.
            if (_dataReceived.WaitOne(200, true))
            {
                DataBytes[0] = (byte)((_sensorData >> 32) & 0xFF);
                DataBytes[1] = (byte)((_sensorData >> 24) & 0xFF);
                DataBytes[2] = (byte)((_sensorData >> 16) & 0xFF);
                DataBytes[3] = (byte)((_sensorData >> 8) & 0xFF);

                var checksum = (byte)(DataBytes[0] + DataBytes[1] + DataBytes[2] + DataBytes[3]);
                if (checksum == (byte)(_sensorData & 0xFF))
                {
                    dataValid = true;
                    Convert(DataBytes, raiseEvent);
                }
                else
                {
                    if (SensorError != null)
                    {
                        SensorError(this, "RHT sensor data has invalid checksum.");
                    }
                    _temperature = float.MinValue;
                    _humidity    = float.MinValue;
                }
            }
            else
            {
                //_temperature = float.MinValue;
                //_humidity = float.MinValue;

                _portIn.DisableInterrupt(); // Stop receiver
                if (SensorError != null)
                {
                    SensorError(this, "RHT sensor data timeout.");
                }
                return(false);
            }
            return(dataValid);
        }