public void Run(IBackgroundTaskInstance taskInstance) { // Connect the Sound Sensor to analog port 0 ISoundSensor sensor = DeviceFactory.Build.SoundSensor(Pin.AnalogPin0); // Loop endlessly while (true) { try { // Check the value of the button, turn it into a string. string sensorvalue = sensor.SensorValue().ToString(); System.Diagnostics.Debug.WriteLine("Sound is " + sensorvalue); } 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()); } } }
private void SoundSensorRead(object sender, object e) { int sensorvalue; lock (senslck) { sensorvalue = soundsensor_mod.SensorValue(); } var timestamp = DateTime.Now; handler.addDATASETtomicrophoneSensor(timestamp, sensorvalue); SendToCloud(new { nodeid = vis.senname.Text, soundvals = new[] { new { timestamp = timestamp, val = sensorvalue } } }); }
private void Timer_Tick(object sender, object e) { ConnectTheDotsSensor sensor = ctdHelper.sensors.Find(item => item.measurename == "Sound"); try { int soundValue = soundsensor.SensorValue(); sensor.value = soundValue; lcd.SetText("S: " + soundValue.ToString()); ctdHelper.SendSensorData(sensor); } catch (Exception) { // Bad sensor read lcd.SetText("Read or send failed"); } }
void MainPageLoaded(object sender, RoutedEventArgs e) { GroveLedBar.Initialize(GrovePi.Sensors.Orientation.GreenToRed); SoundList = new List <DataPoint>(); for (int i = 0; i < DataPointCnt; i++) { SoundList.Add(new DataPoint() { Time = i + 1, Value = 0 }); } IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(async(workItem) => { int sound = 0; while (true) { try { sound = GroveSound.SensorValue(); setLedBar(ConvertSoundToBarLevel(sound)); System.Diagnostics.Debug.WriteLine("Sound: " + sound.ToString()); } catch (Exception ex) { // If you want to see the exceptions uncomment the following: System.Diagnostics.Debug.WriteLine(ex.ToString()); } await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ShiftLeft(SoundList, sound); List <DataPoint> lst = new List <DataPoint>(SoundList); (LineChart.Series[0] as LineSeries).ItemsSource = lst; }); } }); }
public GroveMessage GetSensorValue() { GroveMessage message = new GroveMessage(); try { temphumiSensor.Measure(); message.Temp = temphumiSensor.TemperatureInCelsius; message.Hum = temphumiSensor.Humidity; message.Sound = soundSensor.SensorValue(); message.Light = lightSensor.SensorValue(); message.GasSO = gasSensor.SensorValue(); message.PIR = pirMotion.IsPeopleDetected(); message.Timestamp = DateTime.Now.ToString(); } catch (Exception ex) { throw ex; } return(message); }
private void rpiRun() { try { var tmp = GroveSound.SensorValue(); GroveSoundSensorString = "GroveSoundSensor: " + tmp.ToString(); } catch (Exception /*ex*/) { } var UItask = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { GroveSoundSensorUI.Text = GroveSoundSensorString; //Temperature.Text = temperature; /* * O2PPM.Text = O2; * Moisture.Text = moisture; */ }); }
/* * // Method called every time the app timer interval occurs. It read the sound * // level from the sound sensor; converts it to JSON; sends it asynchronously * // to the Azure IoT hub; and finally updates the UI and GrovePI LCD with the * // new sound values */ private async void Timer_Tick(object sender, object e) { try { int soundValue = soundsensor.SensorValue(); var soundDataPoint = new { deviceId = "GrovePi Sensor", soundLevel = soundValue, }; var messageString = JsonConvert.SerializeObject(soundDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); lcd.SetText("S: " + soundValue.ToString()); await deviceClient.SendEventAsync(message); textBlockSound.Text = soundValue.ToString(); textBlockMessage.Text = "Sensors read; Message sent"; } catch (Exception) { // Bad sensor read lcd.SetText("Read or send failed"); } }
private void Timer_Tick(ThreadPoolTimer timer) { try { // Capture the current ambient noise level soundLevel = soundSensor.SensorValue(); // Check the button state if (button.CurrentState == SensorStatus.On) { // If the button is depressed, turn on the blue LED // and activate the buzzer buzzer.ChangeState(SensorStatus.On); blueLed.ChangeState(SensorStatus.On); // For debugging purposes, log a console message System.Diagnostics.Debug.WriteLine("**** BUTTON ON ****"); } else if (buzzer.CurrentState == SensorStatus.On || blueLed.CurrentState == SensorStatus.On) { // Turn the buzzer and LED off buzzer.ChangeState(SensorStatus.Off); blueLed.ChangeState(SensorStatus.Off); } // Capture the current value from the Light Sensor actualAmbientLight = lightSensor.SensorValue(); // If the actual light measurement is lower than the defined threshold // then define the LED brightness based on the delta between the actual // ambient light and the threshold value if (actualAmbientLight < ambientLightThreshold) { // Use a range mapping method to conver the difference between the // actual ambient light and the threshold to a value between 0 and 255 // (the 8-bit range of the LED on D6 - a PWM pin). // If actual ambient light is low, the differnce between it and the threshold will be // high resulting in a high brightness value. brightness = Map(ambientLightThreshold - actualAmbientLight, 0, ambientLightThreshold, 0, 255); } else { // If the actual ambient light value is above the threshold then // the LED should be completely off. Set the brightness to 0 brightness = 0; } // AnalogWrite uses Pulse Width Modulation (PWM) to // control the brightness of the digital LED on pin D6. redLed.AnalogWrite(Convert.ToByte(brightness)); // Use the brightness value to control the brightness of the RGB LCD backlight byte rgbVal = Convert.ToByte(brightness); display.SetBacklightRgb(rgbVal, rgbVal, rgbVal); // Updae the RGB LCD with the light and sound levels display.SetText(String.Format("Thingy\nL:{0} S:{1}", actualAmbientLight, soundLevel)); } 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 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); } } }
private async void Timer_Tick(ThreadPoolTimer timer) { // record the start time DateTime start = DateTime.Now; // update the display leds.Initialize(GrovePi.Sensors.Orientation.GreenToRed); leds.SetLevel((byte)0); int lightValue = 0; string lightError = string.Empty; // read the light try { lightValue = lightSensor.SensorValue(); // int between 0 (dark) and 1023 (bright) } catch (Exception ex) { lightError = ex.Message; } int soundValue = 0; string soundError = String.Empty; try { soundValue = soundSensor.SensorValue(); } catch (Exception ex) { soundError = ex.Message; } // check if token is still valid // get a new token every 12 minutes - no real need to since we'll usually keep the connection alive if (token == null || token == string.Empty) { token = await fmserver.Authenticate(); tokenRecieved = DateTime.Now; } else if (DateTime.Now > tokenRecieved.AddMinutes(12)) { int logoutResponse = await fmserver.Logout(); token = string.Empty; fmserver = GetFMSInstance(); token = await fmserver.Authenticate(); tokenRecieved = DateTime.Now; } if (token != string.Empty) { // get some data from the RPI itself var processorName = Raspberry.Board.Current.ProcessorName; var rpiModel = Raspberry.Board.Current.Model.ToString(); // write it to FMS var request = fmserver.NewRecordRequest(); if (processorName != null) { request.AddField("rpiProcessor", processorName); } if (rpiModel != null) { request.AddField("rpiModel", rpiModel); } request.AddField("when_start", start.ToString()); request.AddField("sound", soundValue.ToString()); request.AddField("sound_error", soundError); request.AddField("light", lightValue.ToString()); request.AddField("light_error", lightError); request.AddField("when", DateTime.Now.ToString()); // add a script call to calculate the time diff to the previous record request.AddScript(ScriptTypes.after, "calculate_gap_grove"); var response = await request.Execute(); if (fmserver.lastErrorCode != 0) { leds.SetLevel((byte)2); } else { leds.SetLevel((byte)10); } Thread.Sleep(TimeSpan.FromMilliseconds(250)); // no longer logging out after each call // await fmserver.Logout(); // token = string.empty; } // clear the display again leds.SetLevel((byte)1); Thread.Sleep(TimeSpan.FromMilliseconds(250)); }
private void InitWorker() { IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync( async(workItem) => { int work_index = 0; int distance = 0, sound = 0, light = 0, rotary = 0; SensorStatus button = SensorStatus.Off; SensorStatus buzzer = SensorStatus.Off; while (true) { if (work_index < 5) { rotary = GroveRotary.SensorValue(); button = GroveButton.CurrentState; // RotaryValue = rotary; int level = RotaryValue / 100; if (level > 10) { level = 10; } GroveLedBar.SetLevel((byte)level); buzzer = GroveBuzzer.CurrentState; if (RotaryValue > 1000) { if (buzzer != SensorStatus.On) { GroveBuzzer.ChangeState(SensorStatus.On); } } else { if (buzzer != SensorStatus.Off) { GroveBuzzer.ChangeState(SensorStatus.Off); } } if (button == SensorStatus.On) { RelayOnOff = 1; GroveRelay.ChangeState(SensorStatus.On); } else { RelayOnOff = 0; GroveRelay.ChangeState(SensorStatus.Off); } work_index++; } else { // Read temp & humidity GroveTempHumi.Measure(); LastTemp = GroveTempHumi.TemperatureInCelsius; LastHumi = GroveTempHumi.Humidity; distance = GroveRanger.MeasureInCentimeters(); //System.Diagnostics.Debug.WriteLine(distance); sound = GroveSound.SensorValue(); //System.Diagnostics.Debug.WriteLine(sound); light = GroveLight.SensorValue(); //System.Diagnostics.Debug.WriteLine(light); if (distance > 0 && distance < 100) { ShiftLeft(DistanceList, distance); } ShiftLeft(SoundList, sound); ShiftLeft(LightList, light); work_index = 0; } await Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { if (work_index == 0) { UpdataUISlow(); } else { UpdateUIFast(); } }); //Delay.Milliseconds(100); } } ); }