public MainPage() { GoPiGo = DeviceFactory.BuildGoPiGo(); GoPiGo.MotorController().EnableServo(); _leftLed = DeviceFactory.BuildLed(Pin.LedLeft); _rightLed = DeviceFactory.BuildLed(Pin.LedRight); this.InitializeComponent(); Stopwatch = new Stopwatch(); Stopwatch.Start(); }
public void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); // Connect the LED to digital port 4 led = DeviceFactory.Build.Led(Pin.DigitalPin4); // Create a timer that will 'tick' every one-second timer = ThreadPoolTimer.CreatePeriodicTimer(this.Timer_Tick, TimeSpan.FromSeconds(1)); }
public override void Fade(ILed ledPort) { for (var j = MAX_BRIGHTNESS; j > MIN_BRIGHTNESS; j--) { ledPort.Write(true); DelayFor(j); ledPort.Write(false); DelayFor(MAX_BRIGHTNESS - j); } }
public MainPage() { this.InitializeComponent(); // initialise database try { db = new MySqlConnection("server=us-cdbr-azure-central-a.cloudapp.net;uid=b0a941f833069a;pwd=41561c96;database=as_eb778c54b5aa1fa;SslMode=None;charset=utf8;"); db.Open(); } catch (Exception e) { Debug.WriteLine("Failed to connect to db : " + e.Message); } // colors Blue = new SolidColorBrush(Colors.Blue); Green = new SolidColorBrush(Colors.Green); Red = new SolidColorBrush(Colors.Red); Gray = new SolidColorBrush(Colors.Gray); // initialise hardware _deviceFactory = DeviceFactory.Build; Display = _deviceFactory.RgbLcdDisplay(); Button = _deviceFactory.ButtonSensor(Pin.DigitalPin8); BlueLed = _deviceFactory.Led(Pin.DigitalPin2); GreenLed = _deviceFactory.Led(Pin.DigitalPin3); RedLed = _deviceFactory.Led(Pin.DigitalPin4); LightSensor = _deviceFactory.LightSensor(Pin.AnalogPin2); // line info CurrentWeight = LightSensor.SensorValue(); CurrentLine = 2; dbSet(CurrentLine); // update UI WeightText.Text = CurrentWeight.ToString(); // LED tests DispatcherTimer time = new DispatcherTimer(); time.Interval = TimeSpan.FromMilliseconds(5); time.Tick += tick; time.Start(); // light sensor to simulate weight DispatcherTimer weightUpdater = new DispatcherTimer(); weightUpdater.Interval = TimeSpan.FromSeconds(30); weightUpdater.Tick += updateWeight; weightUpdater.Start(); }
public Indicators(ILed keyA, ILed keyB, ILed selectProject, ILed arm, ILed deploy, ILed deploying, ILed succeeded, ILed failed) { _keyA = keyA; _keyB = keyB; _selectProject = selectProject; _arm = arm; _deploy = deploy; _deploying = deploying; _succeeded = succeeded; _failed = failed; }
public async void Run(IBackgroundTaskInstance taskInstance) { // Initiate the LED on Digital Pin 2. (D2). led = DeviceFactory.Build.Led(Pin.DigitalPin2); while (true) { Task.Delay(1000).Wait(); //Delay 1 second try { // If the LED is on, turn it off. If the LED is off, turn it on. led.ChangeState((led.CurrentState == SensorStatus.Off) ? SensorStatus.On : SensorStatus.Off); } catch (Exception ex) { // Do Nothing if there's an exception. } } }
public abstract void Fade(ILed ledPort);
static async Task Main(string[] args) { IMetaWearBoard board = null; bool succeed = false; int retries = 5; //while (!succeed && retries > 0) { //try { board = MbientLab.MetaWear.NetStandard.Application.GetMetaWearBoard(args[0]); //var board = BLEMetawear.Application.GetMetaWearBoard(args[0]); board.TimeForResponse = 100000; board.OnUnexpectedDisconnect += OnDisconneted; await board.InitializeAsync(); succeed = true; } //catch { retries--; } } ILed led = null; ISensorFusionBosch sensor = null; if (board.IsConnected) { led = board.GetModule <ILed>(); led.EditPattern(MbientLab.MetaWear.Peripheral.Led.Color.Green, MbientLab.MetaWear.Peripheral.Led.Pattern.Solid); led.Play(); sensor = board.GetModule <ISensorFusionBosch>(); sensor.Configure(); var rout = await sensor.EulerAngles.AddRouteAsync(source => { try { source.Stream(data => { var value = data.Value <EulerAngles>(); var AngularRead = (int)value.Roll; var OrbitalRead = (int)value.Pitch; //Console.Clear(); Console.Write($"\rroll: {value.Roll} pitch:{value.Pitch} Yaw:{value.Yaw} "); //Rotate(-value.Pitch, 0 , -value.Yaw); }); } catch (Exception ex) { Console.Write(ex.Message); //LogException(LoggerCategory, ex, "Could not initialize IMU stream callback"); throw; } }); sensor.EulerAngles.Start(); sensor.Start(); } ConsoleKeyInfo key = new ConsoleKeyInfo(); while (key.Key != ConsoleKey.Q) { key = Console.ReadKey(); } if (board.IsConnected) { if (led != null) { led.Stop(true); } if (sensor != null) { sensor.EulerAngles.Stop(); sensor.Stop(); } await board.DisconnectAsync(); //board.TearDown(); } }
public LEDTester(ILed led) { this.led = led; }
public void Breathe(ILed led) { _fadeOut.Fade(led); _fadeIn.Fade(led); }
public async override Task SetUp() { await base.SetUp(); led = metawear.GetModule <ILed>(); }
public void Run(IBackgroundTaskInstance taskInstance) { // // TODO: Insert code to perform background work // // If you start any asynchronous methods here, prevent the task // from closing prematurely by using BackgroundTaskDeferral as // described in http://aka.ms/backgroundtaskdeferral // // Build Sensors IButtonSensor Button = DeviceFactory.Build.ButtonSensor(Pin.DigitalPin6); ILed Red = DeviceFactory.Build.Led(Pin.DigitalPin2); ILed Blue = DeviceFactory.Build.Led(Pin.DigitalPin3); ILed Green = DeviceFactory.Build.Led(Pin.DigitalPin4); IRotaryAngleSensor Potentiometer = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin0); // Set initial values int State = 0; double Speed = 100; while (true) { Speed = Potentiometer.SensorValue(); // Speed can be adjusted between 0-1023 // Adjust values for a range between 100-1000 if (Speed < 100) { Speed = 100; } if (Speed > 1000) { Speed = 1000; } //Get button state string buttonon = Button.CurrentState.ToString(); bool buttonison = buttonon.Equals("On", StringComparison.OrdinalIgnoreCase); if (buttonison) { // Turn off all Leds and then turn on current Led Red.AnalogWrite(Convert.ToByte(0)); Green.AnalogWrite(Convert.ToByte(0)); Blue.AnalogWrite(Convert.ToByte(0)); switch (State) { case 0: Red.AnalogWrite(Convert.ToByte(255)); break; case 1: Blue.AnalogWrite(Convert.ToByte(255)); break; case 2: Green.AnalogWrite(Convert.ToByte(255)); break; } // If State is above 2 reset loop else add 1 if (State == 2) { State = 0; } else { State++; } } // Delay the task according to the Potentiometer value Task.Delay((int)Speed).Wait(); } }
public void Run(IBackgroundTaskInstance taskInstance) { // LCD - This screen is I2C IRgbLcdDisplay LCD = DeviceFactory.Build.RgbLcdDisplay(); LCD.SetBacklightRgb(255, 255, 255); LCD.SetText("Hello world!"); // Not sure what colour this will show up in // LEDs ILed red = DeviceFactory.Build.Led(Pin.DigitalPin2); ILed blue = DeviceFactory.Build.Led(Pin.DigitalPin3); // Ultrasonic IUltrasonicRangerSensor Ultrasonic = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin4); // Temperature and Humidity // TODO: Double check Sensor model number. Assumed DHT11 from the GrovePi+ Starter Kit IDHTTemperatureAndHumiditySensor tempHumidity = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin5, DHTModel.Dht11); // Sound sensor ISoundSensor Sound = DeviceFactory.Build.SoundSensor(Pin.AnalogPin0); // LDR IRotaryAngleSensor LDR = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin1); while (true) { Task.Delay(100).Wait(); try { // Ultrasonic sensor int distance = Ultrasonic.MeasureInCentimeters(); Debug.WriteLine("Distance: " + distance.ToString()); // TODO - tune to distance of door //if(distance < 50) // LDR int lightLevel = LDR.SensorValue(); Debug.WriteLine("Light Level: " + lightLevel.ToString()); // LEDs red.ChangeState(SensorStatus.On); blue.ChangeState(SensorStatus.On); // Temperature Humidity tempHumidity.Measure(); double temp_degC = tempHumidity.TemperatureInCelsius; double humidity = tempHumidity.Humidity; Debug.WriteLine("Temperature: " + temp_degC + "\tHumidity: " + humidity); // Sound sensor int soundLevel = Sound.SensorValue(); Debug.WriteLine("Sound Level: " + soundLevel); // TODO: Send data to Azure } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }
public MeadowClient() { Led = new Led(Device, Device.Pins.OnboardLedGreen); try { sensor = new Sht31D(Device.CreateI2cBus()); var config = new Meadow.Hardware.SpiClockConfiguration( 2000, SpiClockConfiguration.Mode.Mode0); ISpiBus spiBus = Device.CreateSpiBus( Device.Pins.SCK, Device.Pins.MOSI, Device.Pins.MISO, config); Radio.OnDataReceived += Radio_OnDataReceived; Radio.OnTransmitFailed += Radio_OnTransmitFailed; Radio.OnTransmitSuccess += Radio_OnTransmitSuccess; Radio.Initialize(Device, spiBus, Device.Pins.D09, Device.Pins.D10, Device.Pins.D11); Radio.Address = Encoding.UTF8.GetBytes(DeviceAddress); Radio.Channel = nRF24Channel; Radio.PowerLevel = PowerLevel.Low; Radio.DataRate = DataRate.DR250Kbps; Radio.IsEnabled = true; Radio.IsAutoAcknowledge = true; Radio.IsDyanmicAcknowledge = false; Radio.IsDynamicPayload = true; Console.WriteLine($"Address: {Encoding.UTF8.GetString(Radio.Address)}"); Console.WriteLine($"PowerLevel: {Radio.PowerLevel}"); Console.WriteLine($"IsAutoAcknowledge: {Radio.IsAutoAcknowledge}"); Console.WriteLine($"Channel: {Radio.Channel}"); Console.WriteLine($"DataRate: {Radio.DataRate}"); Console.WriteLine($"IsDynamicAcknowledge: {Radio.IsDyanmicAcknowledge}"); Console.WriteLine($"IsDynamicPayload: {Radio.IsDynamicPayload}"); Console.WriteLine($"IsEnabled: {Radio.IsEnabled}"); Console.WriteLine($"Frequency: {Radio.Frequency}"); Console.WriteLine($"IsInitialized: {Radio.IsInitialized}"); Console.WriteLine($"IsPowered: {Radio.IsPowered}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } while (true) { sensor.Update(); Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss}-TX T:{sensor.Temperature:0.0}C H:{sensor.Humidity:0}%"); Led.IsOn = true; string values = "T " + sensor.Temperature.ToString("F1") + ",H " + sensor.Humidity.ToString("F0"); // Stuff the 2 byte header ( payload type & deviceIdentifierLength ) + deviceIdentifier into payload byte[] payload = new byte[1 + Radio.Address.Length + values.Length]; payload[0] = (byte)((1 << 4) | Radio.Address.Length); Array.Copy(Radio.Address, 0, payload, 1, Radio.Address.Length); Encoding.UTF8.GetBytes(values, 0, values.Length, payload, Radio.Address.Length + 1); Radio.SendTo(Encoding.UTF8.GetBytes(BaseStationAddress), payload); Thread.Sleep(periodTime); } }
public FLControl(Led led) { this._led = led; _led.Off(); _state = FLState.Off; }
private void ChangeLedState(ILed led, SensorStatus targetState) { sm.WaitOne(); led.ChangeState(targetState); sm.Release(); }
//------------------------------------------------------------------------------------------------------------------------ #endregion #region Constructor //------------------------------------------------------------------------------------------------------------------------ public Led(GrovePi.Pin pin) { led = DeviceFactory.Build.Led(pin); }
public void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); led = DeviceFactory.Build.Led(Pin.DigitalPin4); timer = ThreadPoolTimer.CreatePeriodicTimer(this.Timer_Tick, TimeSpan.FromSeconds(1)); }
public override void SetUp() { base.SetUp(); led = metawear.GetModule <ILed>(); }
/// <summary> /// Initialises an instance of the <see cref="DataTransferService"/> class. /// </summary> /// <param name="logger"></param> /// <param name="publisher"> /// The client to use for sending messages to a message broker. /// </param> /// <param name="fileHelper"> /// Helper for working with files. /// </param> /// <param name="configuration"> /// The configuration parameters for where the files are located. /// </param> /// <param name="bufferSize"> /// The size of the read buffer to use when loading each data file's contents. /// </param> public DataTransferService(ILogger logger, IMessagePublisher publisher, IFileHelper fileHelper, ILed led, BufferedConfiguration configuration, int bufferSize = 400) : base(logger, typeof(DataTransferService)) { publisher.ShouldNotBeNull(); fileHelper.ShouldNotBeNull(); configuration.ShouldNotBeNull(); led.ShouldNotBeNull(); m_ResourceLoader = new ServicesResourceLoader(); m_FileHelper = fileHelper; m_SyncObject = new object(); m_Publisher = publisher; m_BufferSize = bufferSize; m_Configuration = configuration; m_Led = led; m_TransferLimit = 5; m_MaximumFileSizeInBytes = 1500; }
//// Create a file StartupTask.Secrets.cs with a partial class for this class and add following declaration with the value for the deviceid and the connection string. //private const string DeviceId = ""; //private readonly static string ConnectionString = ""; //private static DeviceClient s_deviceClient; //private readonly static string s_connectionString = ""; public void Run(IBackgroundTaskInstance taskInstance) { redLed = DeviceFactory.Build.Led(Pin.DigitalPin2); greenLed = DeviceFactory.Build.Led(Pin.DigitalPin3); angleSensor = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin2); temperatureSensor = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin1); _deviceClient = DeviceClient.CreateFromConnectionString(ConnectionString, TransportType.Mqtt); //// Initial telemetry values //double minTemperature = 20; //double minHumidity = 60; //Random rand = new Random(); //s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt); // Loop endlessly while (true) { try { var angleValue = angleSensor.SensorValue(); var desiredTemperature = MinDesiredTemperature + ((MaxDesiredTemperature - MinDesiredTemperature) * angleValue / 1024); var currentTemperature = temperatureSensor.TemperatureInCelsius(); System.Diagnostics.Debug.WriteLine("temperature is :" + currentTemperature + ", desired is: " + desiredTemperature); if (currentTemperature < desiredTemperature) { redLed.ChangeState(SensorStatus.On); greenLed.ChangeState(SensorStatus.Off); } else { redLed.ChangeState(SensorStatus.Off); greenLed.ChangeState(SensorStatus.On); } var telemetryDataPoint = new { messageId = _messageId++, //deviceId = DeviceId, temperature = currentTemperature, }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(System.Text.Encoding.ASCII.GetBytes(messageString)); _deviceClient.SendEventAsync(message).Wait(); //double currentTemperature = minTemperature + rand.NextDouble() * 15; //double currentHumidity = minHumidity + rand.NextDouble() * 20; //// Create JSON message //var telemetryDataPoint = new //{ // temperature = currentTemperature, // humidity = currentHumidity //}; //var messageString = JsonConvert.SerializeObject(telemetryDataPoint); //var message = new Message(Encoding.ASCII.GetBytes(messageString)); //// Add a custom application property to the message. //// An IoT hub can filter on these properties without access to the message body. //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); //// Send the tlemetry message //s_deviceClient.SendEventAsync(message).Wait(); //Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); Task.Delay(1000).Wait(); } catch (Exception ex) { // NOTE: There are frequent exceptions of the following: // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '. // This appears to be caused by the rapid frequency of writes to the GPIO // These are being swallowed here/ // If you want to see the exceptions uncomment the following: System.Diagnostics.Debug.WriteLine(ex.ToString()); } } }
public CommandParser(IGoPiGo goPiGo, ILed leftLed, ILed rightLed) { _goPiGo = goPiGo; _leftLed = leftLed; _rightLed = rightLed; }
public static void CreateLEDTester(this Emulation emulation, string name, ILed led) { emulation.ExternalsManager.AddExternal(new LEDTester(led), name); }
public LedBreather(int maxCycles, ILed led, IBreather breather) { _maxCycles = maxCycles; _led = led; _breather = breather; }