protected override void Load(ContainerBuilder builder) { builder.Register(_ => new XGpioControl( new XGpio(0, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_0>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(1, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_1>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(2, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_2>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(3, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_3>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(4, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_4>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(5, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_6>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(6, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_7>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(7, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_7>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(8, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_9>() .SingleInstance(); builder.Register(_ => new XGpioControl( new XGpio(10, GpioController.GetDefault(), GpioSharingMode.Exclusive, GpioPinDriveMode.Output))) .As <IXGpio_10>() .SingleInstance(); base.Load(builder); }
public Relay(int GpioPinNumber) { Pin = GpioController.GetDefault().OpenPin(GpioPinNumber); Pin.Write(GpioPinValue.Low); Pin.SetDriveMode(GpioPinDriveMode.Output); }
/// <summary> /// Constructor of DisplayN18 /// </summary> /// <param name="resetPin">Pin 3 of S Socket</param> /// <param name="backlightPin">Pin 4 of S Socket</param> /// <param name="controlPin">Pin 5 of S Socket</param> /// <param name="spiLine">Spi line of S Socket</param> /// <param name="chipSelectPin">Pin 6 of S Socket</param> public DisplayN18(int resetPin, int backlightPin, int controlPin, string spiLine, int chipSelectPin) { _buffer1 = new byte[1]; _buffer2 = new byte[2]; _buffer4 = new byte[4]; _clearBuffer = new byte[160 * 2 * 16]; _characterBuffer1 = new byte[80]; _characterBuffer2 = new byte[320]; _characterBuffer4 = new byte[1280]; _controlPin = GpioController.GetDefault().OpenPin(controlPin); _controlPin.SetDriveMode(GpioPinDriveMode.Output); _resetPin = GpioController.GetDefault().OpenPin(resetPin); _resetPin.SetDriveMode(GpioPinDriveMode.Output); _backlightPin = GpioController.GetDefault().OpenPin(backlightPin); _backlightPin.SetDriveMode(GpioPinDriveMode.Output); _backlightPin.Write(GpioPinValue.Low); _spi = SpiController.FromName(spiLine).GetDevice(new SpiConnectionSettings() { ChipSelectLine = chipSelectPin, ClockFrequency = 12000000, DataBitLength = 8, Mode = SpiMode.Mode0 }); Reset(); WriteCommand(0x11); //Sleep exit Thread.Sleep(120); // ST7735R Frame Rate WriteCommand(0xB1); WriteData(0x01); WriteData(0x2C); WriteData(0x2D); WriteCommand(0xB2); WriteData(0x01); WriteData(0x2C); WriteData(0x2D); WriteCommand(0xB3); WriteData(0x01); WriteData(0x2C); WriteData(0x2D); WriteData(0x01); WriteData(0x2C); WriteData(0x2D); WriteCommand(0xB4); // Column inversion WriteData(0x07); // ST7735R Power Sequence WriteCommand(0xC0); WriteData(0xA2); WriteData(0x02); WriteData(0x84); WriteCommand(0xC1); WriteData(0xC5); WriteCommand(0xC2); WriteData(0x0A); WriteData(0x00); WriteCommand(0xC3); WriteData(0x8A); WriteData(0x2A); WriteCommand(0xC4); WriteData(0x8A); WriteData(0xEE); WriteCommand(0xC5); // VCOM WriteData(0x0E); WriteCommand(0x36); // MX, MY, RGB mode WriteData(MadctlMx | MadctlMy | MadctlBgr); // ST7735R Gamma Sequence WriteCommand(0xe0); WriteData(0x0f); WriteData(0x1a); WriteData(0x0f); WriteData(0x18); WriteData(0x2f); WriteData(0x28); WriteData(0x20); WriteData(0x22); WriteData(0x1f); WriteData(0x1b); WriteData(0x23); WriteData(0x37); WriteData(0x00); WriteData(0x07); WriteData(0x02); WriteData(0x10); WriteCommand(0xe1); WriteData(0x0f); WriteData(0x1b); WriteData(0x0f); WriteData(0x17); WriteData(0x33); WriteData(0x2c); WriteData(0x29); WriteData(0x2e); WriteData(0x30); WriteData(0x30); WriteData(0x39); WriteData(0x3f); WriteData(0x00); WriteData(0x07); WriteData(0x03); WriteData(0x10); WriteCommand(0x2a); WriteData(0x00); WriteData(0x00); WriteData(0x00); WriteData(0x7f); WriteCommand(0x2b); WriteData(0x00); WriteData(0x00); WriteData(0x00); WriteData(0x9f); WriteCommand(0xF0); //Enable test command WriteData(0x01); WriteCommand(0xF6); //Disable ram power save mode WriteData(0x00); WriteCommand(0x3A); //65k mode WriteData(0x05); // Rotate WriteCommand(St7735Madctl); WriteData(MadctlMv | MadctlMy); WriteCommand(0x29); //Display on Thread.Sleep(50); Clear(); }
private async void StartActuator() { try { Log.Informational("Starting application."); XmppCredentials Credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(App).GetTypeInfo().Assembly); Log.Informational("Connecting to XMPP server."); xmppClient = new XmppClient(Credentials, "en", typeof(App).GetTypeInfo().Assembly); if (Credentials.Sniffer && MainPage.Sniffer != null) { xmppClient.Add(MainPage.Sniffer); } if (!string.IsNullOrEmpty(Credentials.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, Credentials.Events, false)); } if (!string.IsNullOrEmpty(Credentials.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(xmppClient, Credentials.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic)); this.RaiseOwnershipChanged(); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; this.Register(); // Will call this.OwnershipChanged() after successful registration. }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); }; } if (!string.IsNullOrEmpty(Credentials.Provisioning)) { provisioningClient = new ProvisioningClient(xmppClient, Credentials.Provisioning); } Timer ConnectionTimer = new Timer((P) => { if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating) { try { Log.Informational("Reconnecting."); xmppClient.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); xmppClient.OnStateChanged += (sender, NewState) => { Log.Informational(NewState.ToString()); switch (NewState) { case XmppState.Connected: connected = true; if (!registered && this.thingRegistryClient != null) { this.Register(); } break; case XmppState.Offline: immediateReconnect = connected; connected = false; if (immediateReconnect) { xmppClient.Reconnect(); } break; } }; xmppClient.OnPresenceSubscribe += (sender, e) => { Log.Informational("Subscription request received from " + e.From + "."); e.Accept(); // TODO: Provisioning RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID); if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) { xmppClient.RequestPresenceSubscription(e.FromBareJID); } xmppClient.SetPresence(Availability.Chat); }; xmppClient.OnPresenceUnsubscribe += (sender, e) => { Log.Informational("Unsubscription request received from " + e.From + "."); e.Accept(); }; xmppClient.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) { xmppClient.RemoveRosterItem(e.BareJid); } }; gpio = GpioController.GetDefault(); if (gpio != null) { int c = gpio.PinCount; int i; for (i = 0; i < c; i++) { if (gpio.TryOpenPin(i, GpioSharingMode.Exclusive, out GpioPin Pin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { gpioPins[i] = new KeyValuePair <GpioPin, KeyValuePair <TextBlock, TextBlock> >(Pin, MainPage.Instance.AddPin("GPIO" + i.ToString(), Pin.GetDriveMode(), Pin.Read().ToString())); Pin.ValueChanged += async(sender, e) => { if (!this.gpioPins.TryGetValue(sender.PinNumber, out KeyValuePair <GpioPin, KeyValuePair <TextBlock, TextBlock> > P)) { return; } PinState Value = e.Edge == GpioPinEdge.FallingEdge ? PinState.LOW : PinState.HIGH; if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { DateTime TP = DateTime.Now; string s = "GPIO" + sender.PinNumber.ToString(); this.sensorServer.NewMomentaryValues( new EnumField(ThingReference.Empty, TP, s, Value, FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Value.Text = Value.ToString()); }; } } } DeviceInformationCollection Devices = await Microsoft.Maker.Serial.UsbSerial.listAvailableDevicesAsync(); foreach (DeviceInformation DeviceInfo in Devices) { if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino")) { Log.Informational("Connecting to " + DeviceInfo.Name); arduinoUsb = new UsbSerial(DeviceInfo); arduinoUsb.ConnectionEstablished += () => { Log.Informational("USB connection established."); }; arduino = new RemoteDevice(arduinoUsb); arduino.DeviceReady += async() => { Log.Informational("Device ready."); Dictionary <int, bool> DisabledPins = new Dictionary <int, bool>(); Dictionary <string, KeyValuePair <Enum, string> > Values = new Dictionary <string, KeyValuePair <Enum, string> >(); PinMode Mode; PinState State; string s; ushort Value; foreach (byte PinNr in arduino.DeviceHardwareProfile.DisabledPins) { DisabledPins[PinNr] = true; } foreach (byte PinNr in arduino.DeviceHardwareProfile.AnalogPins) { if (DisabledPins.ContainsKey(PinNr)) { continue; } s = "A" + (PinNr - arduino.DeviceHardwareProfile.AnalogOffset).ToString(); if (arduino.DeviceHardwareProfile.isAnalogSupported(PinNr)) { arduino.pinMode(s, PinMode.ANALOG); } Mode = arduino.getPinMode(s); Value = arduino.analogRead(s); Values[s] = new KeyValuePair <Enum, string>(Mode, Value.ToString()); } foreach (byte PinNr in arduino.DeviceHardwareProfile.DigitalPins) { if (DisabledPins.ContainsKey(PinNr) || (PinNr > 6 && PinNr != 13)) // Not sure why this limitation is necessary. Without it, my Arduino board (or the Microsoft Firmata library) stops providing me with pin update events. { continue; } if (PinNr == 13) { arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. arduino.digitalWrite(13, PinState.HIGH); } else { if (arduino.DeviceHardwareProfile.isDigitalInputSupported(PinNr)) { arduino.pinMode(PinNr, PinMode.INPUT); } } s = "D" + PinNr.ToString(); Mode = arduino.getPinMode(PinNr); State = arduino.digitalRead(PinNr); Values[s] = new KeyValuePair <Enum, string>(Mode, State.ToString()); } await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (arduinoPins) { foreach (KeyValuePair <string, KeyValuePair <Enum, string> > P in Values) { arduinoPins[P.Key] = MainPage.Instance.AddPin(P.Key, P.Value.Key, P.Value.Value); } } }); this.SetupControlServer(); }; arduino.AnalogPinUpdated += async(pin, value) => { KeyValuePair <TextBlock, TextBlock> P; DateTime TP = DateTime.Now; lock (this.arduinoPins) { if (!this.arduinoPins.TryGetValue(pin, out P)) { return; } } if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { this.sensorServer.NewMomentaryValues( new Int32Field(ThingReference.Empty, TP, pin + ", Raw", value, FieldType.Momentary, FieldQoS.AutomaticReadout), new QuantityField(ThingReference.Empty, TP, pin, value / 10.24, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString()); }; arduino.DigitalPinUpdated += async(pin, value) => { KeyValuePair <TextBlock, TextBlock> P; DateTime TP = DateTime.Now; string s = "D" + pin.ToString(); lock (this.arduinoPins) { if (!this.arduinoPins.TryGetValue("D" + pin.ToString(), out P)) { return; } } if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { this.sensorServer.NewMomentaryValues( new EnumField(ThingReference.Empty, TP, s, value, FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString()); }; arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); break; } } sensorServer = new SensorServer(xmppClient, provisioningClient, true); sensorServer.OnExecuteReadoutRequest += (Sender, Request) => { DateTime Now = DateTime.Now; LinkedList <Field> Fields = new LinkedList <Field>(); DateTime TP = DateTime.Now; string s; bool ReadMomentary = Request.IsIncluded(FieldType.Momentary); bool ReadStatus = Request.IsIncluded(FieldType.Status); Log.Informational("Readout requested", string.Empty, Request.Actor); foreach (KeyValuePair <GpioPin, KeyValuePair <TextBlock, TextBlock> > Pin in gpioPins.Values) { if (ReadMomentary && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString())) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, Pin.Key.Read(), FieldType.Momentary, FieldQoS.AutomaticReadout)); } if (ReadStatus && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString() + ", Mode")) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, Pin.Key.GetDriveMode(), FieldType.Status, FieldQoS.AutomaticReadout)); } } if (arduinoPins != null) { foreach (KeyValuePair <string, KeyValuePair <TextBlock, TextBlock> > Pin in arduinoPins) { byte i; if (ReadMomentary && Request.IsIncluded(s = Pin.Key)) { if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i)) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.digitalRead(i), FieldType.Momentary, FieldQoS.AutomaticReadout)); } else { ushort Raw = arduino.analogRead(s); double Percent = Raw / 10.24; Fields.AddLast(new Int32Field(ThingReference.Empty, TP, s + ", Raw", Raw, FieldType.Momentary, FieldQoS.AutomaticReadout)); Fields.AddLast(new QuantityField(ThingReference.Empty, TP, s, Percent, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout)); } } if (ReadStatus && Request.IsIncluded(s = Pin.Key + ", Mode")) { if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i)) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.getPinMode(i), FieldType.Status, FieldQoS.AutomaticReadout)); } else { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.getPinMode(s), FieldType.Status, FieldQoS.AutomaticReadout)); } } } } Request.ReportFields(true, Fields); }; if (arduino == null) { this.SetupControlServer(); } xmppClient.Connect(); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await Dialog.ShowAsync(); } }
public void Run(IBackgroundTaskInstance taskInstance) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; this.logging.LogEvent("Application starting"); // Log the Application build, OS version information etc. LoggingFields startupInformation = new LoggingFields(); startupInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName); startupInformation.AddString("OSVersion", Environment.OSVersion.VersionString); startupInformation.AddString("MachineName", Environment.MachineName); // This is from the application manifest Package package = Package.Current; PackageId packageId = package.Id; PackageVersion version = packageId.Version; startupInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}")); try { // see if the configuration file is present if not copy minimal sample one from application directory if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null) { StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result; templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask(); } IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(Path.Combine(localFolder.Path, ConfigurationFilename), false, true).Build(); this.azureCognitiveServicesEndpoint = configuration.GetSection("AzureCognitiveServicesEndpoint").Value; startupInformation.AddString("AzureCognitiveServicesEndpoint", this.azureCognitiveServicesEndpoint); this.azureCognitiveServicesSubscriptionKey = configuration.GetSection("AzureCognitiveServicesSubscriptionKey").Value; startupInformation.AddString("AzureCognitiveServicesSubscriptionKey", this.azureCognitiveServicesSubscriptionKey); this.interruptPinNumber = int.Parse(configuration.GetSection("InterruptPinNumber").Value); startupInformation.AddInt32("Interrupt pin", this.interruptPinNumber); this.interruptTriggerOn = (GpioPinEdge)Enum.Parse(typeof(GpioPinEdge), configuration.GetSection("interruptTriggerOn").Value); startupInformation.AddString("Interrupt Trigger on", this.interruptTriggerOn.ToString()); this.displayPinNumber = int.Parse(configuration.GetSection("DisplayPinNumber").Value); startupInformation.AddInt32("Display pin", this.interruptPinNumber); this.debounceTimeout = TimeSpan.Parse(configuration.GetSection("debounceTimeout").Value); startupInformation.AddTimeSpan("Debounce timeout", this.debounceTimeout); } catch (Exception ex) { this.logging.LogMessage("JSON configuration file load or settings retrieval failed " + ex.Message, LoggingLevel.Error); return; } try { this.faceClient = new FaceClient( new Microsoft.Azure.CognitiveServices.Vision.Face.ApiKeyServiceClientCredentials(this.azureCognitiveServicesSubscriptionKey), new System.Net.Http.DelegatingHandler[] { }) { Endpoint = this.azureCognitiveServicesEndpoint, }; } catch (Exception ex) { this.logging.LogMessage("Azure Cognitive Services Face Client configuration failed " + ex.Message, LoggingLevel.Error); return; } try { this.mediaCapture = new MediaCapture(); this.mediaCapture.InitializeAsync().AsTask().Wait(); } catch (Exception ex) { this.logging.LogMessage("Camera configuration failed " + ex.Message, LoggingLevel.Error); return; } this.displayOffTimer = new Timer(this.TimerCallback, null, Timeout.Infinite, Timeout.Infinite); try { GpioController gpioController = GpioController.GetDefault(); this.interruptGpioPin = gpioController.OpenPin(this.interruptPinNumber); this.interruptGpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp); this.interruptGpioPin.ValueChanged += this.InterruptGpioPin_ValueChanged; this.displayGpioPin = gpioController.OpenPin(this.displayPinNumber); this.displayGpioPin.SetDriveMode(GpioPinDriveMode.Output); this.displayGpioPin.Write(GpioPinValue.Low); } catch (Exception ex) { this.logging.LogMessage("Digital input configuration failed " + ex.Message, LoggingLevel.Error); return; } this.logging.LogEvent("Application started", startupInformation); // enable task to continue running in background this.backgroundTaskDeferral = taskInstance.GetDeferral(); }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(ObjectSerializer).GetTypeInfo().Assembly, // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book. typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(ICoapContentFormat).GetTypeInfo().Assembly, typeof(IDtlsCredentials).GetTypeInfo().Assembly, typeof(Lwm2mClient).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000); Database.Register(db); await db.RepairIfInproperShutdown(null); await db.Start(); #if GPIO gpio = GpioController.GetDefault(); if (gpio != null) { if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output)) { this.gpioPin.SetDriveMode(GpioPinDriveMode.Output); this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low); this.digitalOutput0?.Set(this.output.Value); this.actuation0?.Set(this.output.Value); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); } else { Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString()); } } else { Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString()); } } #else DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo is null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += async() => { try { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW); this.digitalOutput0?.Set(this.output.Value); this.actuation0?.Set(this.output.Value); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. } catch (Exception ex) { Log.Critical(ex); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } #endif this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); /************************************************************************************ * To create an unencrypted CoAP Endpoint on the default CoAP port: * * this.coapEndpoint = new CoapEndpoint(); * * To create an unencrypted CoAP Endpoint on the default CoAP port, * with a sniffer that outputs communication to the window: * * this.coapEndpoint = new CoapEndpoint(new LogSniffer()); * * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using * the users defined in the IUserSource users: * * this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users); * * To create a CoAP endpoint, that listens to both the default CoAP port, for * unencrypted communication, and the default CoAPS port, for encrypted, * authenticated and authorized communication, using * the users defined in the IUserSource users. Only users having the given * privilege (if not empty) will be authorized to access resources on the endpoint: * * this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, * new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false); * ************************************************************************************/ this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false); this.outputResource = this.coapEndpoint.Register("/Output", (req, resp) => { string s; if (this.output.HasValue) { s = this.output.Value ? "true" : "false"; } else { s = "-"; } resp.Respond(CoapCode.Content, s, 64); }, async(req, resp) => { try { string s = req.Decode() as string; if (s is null && req.Payload != null) { s = Encoding.UTF8.GetString(req.Payload); } if (s is null || !CommonTypes.TryParse(s, out bool Output)) { resp.RST(CoapCode.BadRequest); } else { resp.Respond(CoapCode.Changed); await this.SetOutput(Output, req.From.ToString()); } } catch (Exception ex) { Log.Critical(ex); } }, Notifications.Acknowledged, "Digital Output.", null, null,
private void InitGPIO() { var gpio = GpioController.GetDefault(); // Show an error if there is no GPIO controller if (gpio == null) { GPIO.Text = "There is no GPIO controller on this device."; //disable buttons as no gpio controller, example run on local Machine PC, (not raspberry pi 3) // GPIO_02.IsEnabled = false; GPIO_03.IsEnabled = false; GPIO_04.IsEnabled = false; GPIO_05.IsEnabled = false; GPIO_06.IsEnabled = false; GPIO_07.IsEnabled = false; GPIO_08.IsEnabled = false; GPIO_09.IsEnabled = false; GPIO_10.IsEnabled = false; GPIO_11.IsEnabled = false; GPIO_12.IsEnabled = false; GPIO_13.IsEnabled = false; GPIO_16.IsEnabled = false; GPIO_17.IsEnabled = false; GPIO_18.IsEnabled = false; GPIO_19.IsEnabled = false; GPIO_20.IsEnabled = false; GPIO_21.IsEnabled = false; GPIO_22.IsEnabled = false; GPIO_23.IsEnabled = false; GPIO_24.IsEnabled = false; GPIO_25.IsEnabled = false; GPIO_26.IsEnabled = false; GPIO_27.IsEnabled = false; return; } //set all pins to default value to Low // //GPIO 02 - PIN 03 Pin_3 = gpio.OpenPin(GPIO02); pinValue = GpioPinValue.Low; Pin_3.Write(pinValue); Pin_3.SetDriveMode(GpioPinDriveMode.Output); //GPIO 03 - PIN 05 Pin_5 = gpio.OpenPin(GPIO03); pinValue = GpioPinValue.Low; Pin_5.Write(pinValue); Pin_5.SetDriveMode(GpioPinDriveMode.Output); //GPIO 04 - PIN 07 Pin_7 = gpio.OpenPin(GPIO04); pinValue = GpioPinValue.Low; Pin_7.Write(pinValue); Pin_7.SetDriveMode(GpioPinDriveMode.Output); //GPIO 05 - PIN 29 Pin_29 = gpio.OpenPin(GPIO05); pinValue = GpioPinValue.Low; Pin_29.Write(pinValue); Pin_29.SetDriveMode(GpioPinDriveMode.Output); //GPIO 06 - PIN 31 Pin_31 = gpio.OpenPin(GPIO06); pinValue = GpioPinValue.Low; Pin_31.Write(pinValue); Pin_31.SetDriveMode(GpioPinDriveMode.Output); //GPIO 07 - PIN 26 Pin_26 = gpio.OpenPin(GPIO07); pinValue = GpioPinValue.Low; Pin_26.Write(pinValue); Pin_26.SetDriveMode(GpioPinDriveMode.Output); //GPIO 08 - PIN 24 Pin_24 = gpio.OpenPin(GPIO08); pinValue = GpioPinValue.Low; Pin_24.Write(pinValue); Pin_24.SetDriveMode(GpioPinDriveMode.Output); //GPIO 09 - PIN 21 Pin_21 = gpio.OpenPin(GPIO09); pinValue = GpioPinValue.Low; Pin_21.Write(pinValue); Pin_21.SetDriveMode(GpioPinDriveMode.Output); //GPIO 10 - PIN 19 Pin_19 = gpio.OpenPin(GPIO10); pinValue = GpioPinValue.Low; Pin_19.Write(pinValue); Pin_19.SetDriveMode(GpioPinDriveMode.Output); //GPIO 11 - PIN 23 Pin_23 = gpio.OpenPin(GPIO11); pinValue = GpioPinValue.Low; Pin_23.Write(pinValue); Pin_23.SetDriveMode(GpioPinDriveMode.Output); //GPIO 12 - PIN 32 Pin_32 = gpio.OpenPin(GPIO12); pinValue = GpioPinValue.Low; Pin_32.Write(pinValue); Pin_32.SetDriveMode(GpioPinDriveMode.Output); //GPIO 13 - PIN 33 Pin_33 = gpio.OpenPin(GPIO13); pinValue = GpioPinValue.Low; Pin_33.Write(pinValue); Pin_33.SetDriveMode(GpioPinDriveMode.Output); //GPIO 16 - PIN 36 Pin_36 = gpio.OpenPin(GPIO16); pinValue = GpioPinValue.Low; Pin_36.Write(pinValue); Pin_36.SetDriveMode(GpioPinDriveMode.Output); //GPIO 17 - PIN 11 Pin_11 = gpio.OpenPin(GPIO17); pinValue = GpioPinValue.Low; Pin_11.Write(pinValue); Pin_11.SetDriveMode(GpioPinDriveMode.Output); //GPIO 18 - PIN 12 Pin_12 = gpio.OpenPin(GPIO18); pinValue = GpioPinValue.Low; Pin_12.Write(pinValue); Pin_12.SetDriveMode(GpioPinDriveMode.Output); //GPIO 19 - PIN 35 Pin_35 = gpio.OpenPin(GPIO19); pinValue = GpioPinValue.Low; Pin_35.Write(pinValue); Pin_35.SetDriveMode(GpioPinDriveMode.Output); //GPIO 20 - PIN 38 Pin_38 = gpio.OpenPin(GPIO20); pinValue = GpioPinValue.Low; Pin_38.Write(pinValue); Pin_38.SetDriveMode(GpioPinDriveMode.Output); //GPIO 21 - PIN 40 Pin_40 = gpio.OpenPin(GPIO21); pinValue = GpioPinValue.Low; Pin_40.Write(pinValue); Pin_40.SetDriveMode(GpioPinDriveMode.Output); //GPIO 22 - PIN 15 Pin_15 = gpio.OpenPin(GPIO22); pinValue = GpioPinValue.Low; Pin_15.Write(pinValue); Pin_15.SetDriveMode(GpioPinDriveMode.Output); //GPIO 23 - PIN 16 Pin_16 = gpio.OpenPin(GPIO23); pinValue = GpioPinValue.Low; Pin_16.Write(pinValue); Pin_16.SetDriveMode(GpioPinDriveMode.Output); //GPIO 24 - PIN 18 Pin_18 = gpio.OpenPin(GPIO24); pinValue = GpioPinValue.Low; Pin_18.Write(pinValue); Pin_18.SetDriveMode(GpioPinDriveMode.Output); //GPIO 25 - PIN 22 Pin_22 = gpio.OpenPin(GPIO25); pinValue = GpioPinValue.Low; Pin_22.Write(pinValue); Pin_22.SetDriveMode(GpioPinDriveMode.Output); //GPIO 26 - PIN 37 Pin_37 = gpio.OpenPin(GPIO26); pinValue = GpioPinValue.Low; Pin_37.Write(pinValue); Pin_37.SetDriveMode(GpioPinDriveMode.Output); //GPIO 27 - PIN 13 Pin_13 = gpio.OpenPin(GPIO27); pinValue = GpioPinValue.Low; Pin_13.Write(pinValue); Pin_13.SetDriveMode(GpioPinDriveMode.Output); GPIO.Text = "GPIO pins initialized correctly."; }
/// <summary> /// Инициализирует логические входы и выходы общего назначения /// </summary> private void InitGPIO() { UpdateStartLEDs(GPIOLED, Colors.Yellow); try { gpio = GpioController.GetDefault(); TriggerPin = gpio.OpenPin(GlobalVars.TriggerPin); EchoPin = gpio.OpenPin(GlobalVars.EchoPin); EchoPin.SetDriveMode(GpioPinDriveMode.InputPullDown); TriggerPin.SetDriveMode(GpioPinDriveMode.Output); TriggerPin.Write(GpioPinValue.Low); WaterFlowSensorPin = gpio.OpenPin(GlobalVars.WaterFlowSensorPin); WaterFlowSensorPin.SetDriveMode(GpioPinDriveMode.InputPullUp); WaterFlowSensorPin.ValueChanged += WaterFlowCounter.WaterFlowSensorPin_ValueChanged; StartLEDPin = gpio.OpenPin(GlobalVars.StartLEDPin); StopLEDPin = gpio.OpenPin(GlobalVars.StopLEDPin); EndLEDPin = gpio.OpenPin(GlobalVars.EndLEDPin); StartLEDPin.SetDriveMode(GpioPinDriveMode.Output); StopLEDPin.SetDriveMode(GpioPinDriveMode.Output); EndLEDPin.SetDriveMode(GpioPinDriveMode.Output); StartLEDPin.Write(GpioPinValue.High); StopLEDPin.Write(GpioPinValue.High); EndLEDPin.Write(GpioPinValue.High); StartButtonPin = gpio.OpenPin(GlobalVars.StartButtonPin); StopButtonPin = gpio.OpenPin(GlobalVars.StopButtonPin); EndButtonPin = gpio.OpenPin(GlobalVars.EndButtonPin); StartButtonPin.SetDriveMode(GpioPinDriveMode.InputPullDown); StopButtonPin.SetDriveMode(GpioPinDriveMode.InputPullDown); EndButtonPin.SetDriveMode(GpioPinDriveMode.InputPullDown); StartButtonPin.DebounceTimeout = TimeSpan.FromMilliseconds(50); StopButtonPin.DebounceTimeout = TimeSpan.FromMilliseconds(50); EndButtonPin.DebounceTimeout = TimeSpan.FromMilliseconds(50); StartButtonPin.ValueChanged += StartButtonPin_ValueChanged; StopButtonPin.ValueChanged += StopButtonPin_ValueChanged; EndButtonPin.ValueChanged += EndButtonPin_ValueChanged; PumpPin = gpio.OpenPin(GlobalVars.PumpPin); HeaterPin = gpio.OpenPin(GlobalVars.HeaterPin); FillPumpPin = gpio.OpenPin(GlobalVars.FillPumpPin); WaterValvePin = gpio.OpenPin(GlobalVars.WaterValvePin); MDBPin = gpio.OpenPin(GlobalVars.MDBPin); HeartBeatPin = gpio.OpenPin(GlobalVars.HeartBeatPin); ExternalLightPin = gpio.OpenPin(GlobalVars.ExternalLightPin); //ReservedPin1 = gpio.OpenPin(GlobalVars.ReservedPin1); //ReservedPin2 = gpio.OpenPin(GlobalVars.ReservedPin2); PumpPin.SetDriveMode(GpioPinDriveMode.Output); HeaterPin.SetDriveMode(GpioPinDriveMode.Output); FillPumpPin.SetDriveMode(GpioPinDriveMode.Output); WaterValvePin.SetDriveMode(GpioPinDriveMode.Output); MDBPin.SetDriveMode(GpioPinDriveMode.Output); //ReservedPin1.SetDriveMode(GpioPinDriveMode.Output); //ReservedPin2.SetDriveMode(GpioPinDriveMode.Output); ExternalLightPin.SetDriveMode(GpioPinDriveMode.Output); HeartBeatPin.SetDriveMode(GpioPinDriveMode.Output); HeartBeatPin.Write(GpioPinValue.High); UpdateStartLEDs(GPIOLED, Colors.Green); AddItemToLogBox("Настройка контроллера GPIO завершена"); UpdateProgress(10); } catch (Exception ex) { UpdateStartLEDs(GPIOLED, Colors.Red); AddItemToLogBox("Ошибка контроллера GPIO: " + ex.Message); gpio = null; } }
public static void SetupDTH11() { _pin = GpioController.GetDefault().OpenPin(4, GpioSharingMode.Exclusive); _dht = new Dht11(_pin, GpioPinDriveMode.Input); }
private void InitializeGPIO() { var gpio = GpioController.GetDefault(); // Show an error if there is no GPIO controller if (gpio == null) { statusLabel.Text = "There is no GPIO controller on this device."; return; } #region Hall Pin this.hallPin = gpio.OpenPin(HALL_LED); if (this.hallPin == null) { statusLabel.Text = "Could not initialize hall pin"; return; } #endregion #region Hallway Pin this.hallwayPin = gpio.OpenPin(HALLWAY_LED); if (this.hallwayPin == null) { statusLabel.Text = "Could not initialize hallway pin"; return; } #endregion #region Kitchen Pin this.kitchenPin = gpio.OpenPin(KITCHEN_LED); if (this.kitchenPin == null) { statusLabel.Text = "Could not initialize kitchen pin"; return; } #endregion #region Garden Pin this.gardenPin = gpio.OpenPin(GARDEN_LED); if (this.gardenPin == null) { statusLabel.Text = "Could not initialize garden pin"; return; } #endregion #region Bedroom Pin this.bedroomPin = gpio.OpenPin(BEDROOM_LED); if (this.bedroomPin == null) { statusLabel.Text = "Could not initialize bedroom pin"; return; } #endregion #region Button Pin buttonPin = gpio.OpenPin(BUTTON_PIN); // Check if input pull-up resistors are supported if (buttonPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp)) { buttonPin.SetDriveMode(GpioPinDriveMode.InputPullUp); } else { buttonPin.SetDriveMode(GpioPinDriveMode.Input); } // Set a debounce timeout to filter out switch bounce noise from a button press buttonPin.DebounceTimeout = TimeSpan.FromMilliseconds(50); // Register for the ValueChanged event so our buttonPin_ValueChanged // function is called when the button is pressed buttonPin.ValueChanged += ButtonPin_ValueChanged;; #endregion statusLabel.Text = "GPIO pins initialized correctly."; }
public I2cControllerSoftwareProvider(int sdaPinNumber, int sclPinNumber, bool usePullups) : this(GpioController.GetDefault(), sdaPinNumber, sclPinNumber, usePullups) { }
private bool DoTestWifi() { this.UpdateStatusText("Checking wifi firmware...", true); if (this.doTestWifiPassed) { return(true); } var gpioController = GpioController.GetDefault(); var resetPin = gpioController.OpenPin(SC20260.GpioPin.PC3); var csPin = gpioController.OpenPin(SC20260.GpioPin.PA6); var intPin = gpioController.OpenPin(SC20260.GpioPin.PF10); var enPin = gpioController.OpenPin(SC20260.GpioPin.PA8); enPin.SetDriveMode(GpioPinDriveMode.Output); resetPin.SetDriveMode(GpioPinDriveMode.Output); enPin.Write(GpioPinValue.Low); resetPin.Write(GpioPinValue.Low); Thread.Sleep(100); enPin.Write(GpioPinValue.High); resetPin.Write(GpioPinValue.High); var result = false; var settings = new GHIElectronics.TinyCLR.Devices.Spi.SpiConnectionSettings() { ChipSelectLine = csPin, ClockFrequency = 4000000, Mode = GHIElectronics.TinyCLR.Devices.Spi.SpiMode.Mode0, ChipSelectType = GHIElectronics.TinyCLR.Devices.Spi.SpiChipSelectType.Gpio, ChipSelectHoldTime = TimeSpan.FromTicks(10), ChipSelectSetupTime = TimeSpan.FromTicks(10) }; var networkCommunicationInterfaceSettings = new SpiNetworkCommunicationInterfaceSettings { SpiApiName = SC20260.SpiBus.Spi3, GpioApiName = "GHIElectronics.TinyCLR.NativeApis.STM32H7.GpioController\\0", SpiSettings = settings, InterruptPin = intPin, InterruptEdge = GpioPinEdge.FallingEdge, InterruptDriveMode = GpioPinDriveMode.InputPullUp, ResetPin = resetPin, ResetActiveState = GpioPinValue.Low }; var networkInterfaceSetting = new WiFiNetworkInterfaceSettings() { Ssid = " ", Password = "******", }; networkInterfaceSetting.Address = new IPAddress(new byte[] { 192, 168, 1, 122 }); networkInterfaceSetting.SubnetMask = new IPAddress(new byte[] { 255, 255, 255, 0 }); networkInterfaceSetting.GatewayAddress = new IPAddress(new byte[] { 192, 168, 1, 1 }); networkInterfaceSetting.DnsAddresses = new IPAddress[] { new IPAddress(new byte[] { 75, 75, 75, 75 }), new IPAddress(new byte[] { 75, 75, 75, 76 }) }; //networkInterfaceSetting.MacAddress = new byte[] { 0x00, 0x04, 0x00, 0x00, 0x00, 0x00 }; networkInterfaceSetting.DhcpEnable = true; networkInterfaceSetting.DynamicDnsEnable = true; var networkController = NetworkController.FromName("GHIElectronics.TinyCLR.NativeApis.ATWINC15xx.NetworkController"); networkController.SetInterfaceSettings(networkInterfaceSetting); networkController.SetCommunicationInterfaceSettings(networkCommunicationInterfaceSettings); networkController.SetAsDefaultController(); var firmware = Winc15x0Interface.GetFirmwareVersion(); if (firmware.IndexOf("19.5.") == 0 || (firmware.IndexOf("19.6.") == 0)) { result = true; } resetPin.Dispose(); csPin.Dispose(); intPin.Dispose(); enPin.Dispose(); this.doTestWifiPassed = result; return(result); }
static void Main() { var buffer = new byte[512]; DIRA = GpioController.GetDefault().OpenPin(FEZ.GpioPin.D2); DIRA.SetDriveMode(GpioPinDriveMode.Output); DIRB = GpioController.GetDefault().OpenPin(FEZ.GpioPin.D4); DIRB.SetDriveMode(GpioPinDriveMode.Output); var cont = GpioController.GetDefault(); var reset = cont.OpenPin(FEZ.GpioPin.WiFiReset); var irq = cont.OpenPin(FEZ.GpioPin.WiFiInterrupt); var spi = SpiDevice.FromId(FEZ.SpiBus.WiFi, SPWF04SxInterface.GetConnectionSettings(FEZ.GpioPin.WiFiChipSelect)); led1 = cont.OpenPin(FEZ.GpioPin.Led1); btn1 = cont.OpenPin(FEZ.GpioPin.Btn1); led1.SetDriveMode(GpioPinDriveMode.Output); btn1.SetDriveMode(GpioPinDriveMode.InputPullUp); wifi = new SPWF04SxInterface(spi, irq, reset); wifi.TurnOn(); //wifi.JoinNetwork("GHI", "ghi555wifi."); Debug.WriteLine("WaitForButton"); WaitForButton(); var speed = 90; var id = wifi.OpenSocket("192.168.1.152", 80, SPWF04SxConnectionyType.Tcp, SPWF04SxConnectionSecurityType.None); StringBuilder builder = new StringBuilder(); while (true) { if (wifi.QuerySocket(id) is var avail && avail > 0) { wifi.ReadSocket(id, buffer, 0, Math.Min(avail, buffer.Length)); for (var k = 0; k < buffer.Length; k++) { if (buffer[k] != 0) { char result = (char)buffer[k]; builder.Append(result); buffer[k] = 0; } } Debug.WriteLine(builder.ToString()); } string command = builder.ToString(); builder.Clear(); switch (command) { case "forvard": SetMotorDuty(Servo.A, speed, Direction.Forvard); SetMotorDuty(Servo.B, speed, Direction.Forvard); break; case "backward": SetMotorDuty(Servo.A, speed, Direction.Back); SetMotorDuty(Servo.B, speed, Direction.Back); break; case "left": SetMotorDuty(Servo.A, speed, Direction.Forvard); StopMotor(Servo.B); Thread.Sleep(500); break; case "right": SetMotorDuty(Servo.B, speed, Direction.Forvard); StopMotor(Servo.A); Thread.Sleep(500); break; case "stop": StopMotor(Servo.B); StopMotor(Servo.A); Thread.Sleep(500); break; default: break; } Thread.Sleep(100); } }
/// <summary> /// Main display. /// </summary> public MainPage() { InitializeComponent(); // Initialize CC1101 rf = new CC1101(); GpioController gpio = GpioController.GetDefault(); txPin = gpio.OpenPin(CCRegister.CC1101_GDO0); var tmp = txPin.PinNumber; txPin.SetDriveMode(GpioPinDriveMode.Output); var test1 = txPin.IsDriveModeSupported(GpioPinDriveMode.OutputOpenDrain); test1 = txPin.IsDriveModeSupported(GpioPinDriveMode.OutputOpenDrainPullUp); test1 = txPin.IsDriveModeSupported(GpioPinDriveMode.OutputOpenSource); test1 = txPin.IsDriveModeSupported(GpioPinDriveMode.OutputOpenSourcePullDown); //rf.SetBaudRate(1); //rf.SetCarrierFrequency(433); //rf.SetDeviationFrequencySetting(1); rf.InitAll(); //rf.SetTxState(); //rf.SetIdleState(); //rf.Reset(); //rf.FlushRx(); //rf.FlushTx(); //rf.Info(); //var part = rf.PartNumber; //var ver = rf.Version; //rf.SetupPATABLE(); //rf.SetIdleState(); //rf.SetupPATABLE(); //rf.GetCarrierFrequency(); // Initialize the display //tft = new ILI9340(); //tft.Rotation = true; //tft.InitAll(); rf.SetTxState(); while (true) { //rf.SendData(new byte[] { 0 }); //rf.SendData(new byte[] { 0b0000_1111 }); //rf.SendData(new byte[] { 0b1111_0000 }); //rf.SendData(new byte[] { 0b1111_1111 }); //rf.SendData(new byte[] { 0b1000_0000 }); //rf.SendData(new byte[] { 0b0000_0111 }); txPin.Write(GpioPinValue.High); rf.ShortWait(1); txPin.Write(GpioPinValue.Low); rf.ShortWait(1); } // Create timer to refresh display DispatcherTimer dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Interval = refreshRate; dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Start(); }
public override void Execute(State S) { BeforeLog(); var rand = new Random(); int tmp = rand.Next(1, 101); if (tmp > Probability) { return; } var gpio = GpioController.GetDefault(); if (gpio == null) { return; } if (executing) { stopExecution = true; while (executing) { } } stopExecution = false; executing = true; List <GpioPin> pins = new List <GpioPin>(); //GpioPin pin; foreach (var num in pinsNums) { var pin = gpio.OpenPin(num); pin.SetDriveMode(GpioPinDriveMode.Output); pin.Write(GpioPinValue.Low); pins.Add(pin); } long startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds(); if (yesNoRequest) { yesNoLastStartTime = startTime; inYesNo = true; } if (yesNoCancel) { yesNoLastStartTime = 0L; inYesNo = false; } string debug = ""; for (int i = 0; i < 4; ++i) { if (Signal[i] == 1) { pins[i].Write(GpioPinValue.High); } debug += pins[i].Read().ToString(); } LogLib.Log.Trace($"Sended {debug}"); Task.Run(() => { while (DateTimeOffset.Now.ToUnixTimeMilliseconds() - startTime < Time) { if (stopExecution) { break; } } foreach (var pin in pins) { pin.Write(GpioPinValue.Low); pin.Dispose(); } LogLib.Log.Trace("Disposed"); executing = false; }); LogLib.Log.Trace("Exited GPIO"); AfterLog(); }
public static void Main() { ///////////////////////////////////////////////////////////// // mind to set a pin that exists on the board being tested // ///////////////////////////////////////////////////////////// // PJ5 is LD2 in STM32F769I_DISCO GpioPin led = GpioController.GetDefault().OpenStm32Pin('J', 5); // PD15 is LED6 in DISCOVERY4 //GpioPin led = GpioController.GetDefault().OpenStm32Pin('D', 15); // PG14 is LEDLD4 in F429I_DISCO //GpioPin led = GpioController.GetDefault().OpenStm32Pin('G', 6); // PE15 is LED1 in QUAIL //GpioPin led = GpioController.GetDefault().OpenStm32Pin('E', 15); // PB75 is LED2 in STM32F746_NUCLEO //GpioPin led = GpioController.GetDefault().OpenStm32Pin('B', 7); // PA5 is LED_GREEN in STM32F091RC //GpioPin led = GpioController.GetDefault().OpenStm32Pin('A', 5); led.SetDriveMode(GpioPinDriveMode.Output); led.Write(GpioPinValue.High); // query target about wake-up reason switch (STM32.Power.WakeupReason) { case STM32.Power.WakeupReasonType.FromPin: Console.WriteLine("[INFO] Device woke-up on GPIO event."); break; case STM32.Power.WakeupReasonType.FromStandby: Console.WriteLine("[INFO] Device woke-up from standby (possibly from alarm)."); break; case STM32.Power.WakeupReasonType.Undetermined: Console.WriteLine("[INFO] Couldn't determine woke-up reason."); break; } // enable wake-up from GPIO pin STM32.Power.EnableWakeupPin(STM32.Power.WakeupPin.Pin1); // start a thread blinking the LED to check that something is happening new Thread(() => { while (true) { Thread.Sleep(125); led.Toggle(); } }).Start(); // set alarm time for 30 seconds from now DateTime alarmTime = DateTime.UtcNow.AddSeconds(30); STM32.RTC.SetAlarm(alarmTime); Console.WriteLine($"Setting alarm to {alarmTime.ToString("u")}"); // read back alarm setting, just to be sure var alarmTimeCheck = STM32.RTC.GetAlarm(); if ((alarmTimeCheck.Year != alarmTime.Year) || (alarmTimeCheck.Month != alarmTime.Month) || (alarmTimeCheck.Day != alarmTime.Day) || (alarmTimeCheck.Hour != alarmTime.Hour) || (alarmTimeCheck.Minute != alarmTime.Minute) || (alarmTimeCheck.Second != alarmTime.Second)) { Console.WriteLine($"!!!! ERROR: alarm time read from target is different from the set one: {alarmTimeCheck.ToString("u")}"); } else { Console.WriteLine($"Alarm was set to {alarmTime.ToString("u")}"); // sleep here for 10 seconds to allow the LED to blink after wakeup Thread.Sleep(10000); Console.WriteLine($"Going to standby mode now..."); // this call never returns // after this the target will enter SMT32 CPU standby mode and will be waked by the RTC alarm in 30 - 10 seconds STM32.Power.EnterStandbyMode(); } Thread.Sleep(Timeout.Infinite); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously protected override async Task InitializeInternal(XElement configFragment) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { this.gpio = GpioController.GetDefault(); if (null == this.gpio) { throw new NullReferenceException(); } var rsPinElement = configFragment.Descendants("RsPin").FirstOrDefault(); var enablePinElement = configFragment.Descendants("EnablePin").FirstOrDefault(); var d0PinElement = configFragment.Descendants("D0Pin").FirstOrDefault(); var d1PinElement = configFragment.Descendants("D1Pin").FirstOrDefault(); var d2PinElement = configFragment.Descendants("D2Pin").FirstOrDefault(); var d3PinElement = configFragment.Descendants("D3Pin").FirstOrDefault(); var d4PinElement = configFragment.Descendants("D4Pin").FirstOrDefault(); var d5PinElement = configFragment.Descendants("D5Pin").FirstOrDefault(); var d6PinElement = configFragment.Descendants("D6Pin").FirstOrDefault(); var d7PinElement = configFragment.Descendants("D7Pin").FirstOrDefault(); try { int[] dataPinNumbers = null; if (null != rsPinElement && null != enablePinElement && null != d4PinElement && null != d5PinElement && null != d6PinElement && null != d7PinElement) { int rsPin = Convert.ToInt32(rsPinElement.Value); int enablePin = Convert.ToInt32(enablePinElement.Value); int d4Pin = Convert.ToInt32(d4PinElement.Value); int d5Pin = Convert.ToInt32(d5PinElement.Value); int d6Pin = Convert.ToInt32(d6PinElement.Value); int d7Pin = Convert.ToInt32(d7PinElement.Value); if (null != d0PinElement && null != d1PinElement && null != d2PinElement && null != d3PinElement) { dataPinNumbers = new int[8]; int d0Pin = Convert.ToInt32(d0PinElement.Value); int d1Pin = Convert.ToInt32(d1PinElement.Value); int d2Pin = Convert.ToInt32(d2PinElement.Value); int d3Pin = Convert.ToInt32(d3PinElement.Value); dataPinNumbers[0] = d0Pin; dataPinNumbers[1] = d1Pin; dataPinNumbers[2] = d2Pin; dataPinNumbers[3] = d3Pin; dataPinNumbers[4] = d4Pin; dataPinNumbers[5] = d5Pin; dataPinNumbers[6] = d6Pin; dataPinNumbers[7] = d7Pin; this.bitMode = BitMode.Eight; } else { dataPinNumbers = new int[4]; dataPinNumbers[0] = d4Pin; dataPinNumbers[1] = d5Pin; dataPinNumbers[2] = d6Pin; dataPinNumbers[3] = d7Pin; this.bitMode = BitMode.Four; } this.initializePins(enablePin, rsPin, dataPinNumbers); await this.initializeChip(); } } catch (FormatException) { Debug.WriteLine("HD44780GpioDriver: Pin config is invalid"); } catch (OverflowException) { Debug.WriteLine("HD44780GpioDriver: Pin config is invalid"); } catch (FileLoadException) { Debug.WriteLine("HD44780GpioDriver: Pin is already open"); } }
public GPIOSnap() { gpio = GpioController.GetDefault(); }
static public void IOInicializar(int pinNum, string tipoIO) { var gpio = GpioController.GetDefault();
private void CreateEthernet() { this.isRunning = true; // MikroBus 1 var gpioController = GpioController.GetDefault(); var start = DateTime.Now; try { Thread.Sleep(100); this.resetPin = gpioController.OpenPin(SC20260.GpioPin.PI8); this.csPin = gpioController.OpenPin(SC20260.GpioPin.PG12); this.intPin = gpioController.OpenPin(SC20260.GpioPin.PG6); this.enPin = gpioController.OpenPin(SC20260.GpioPin.PI0); this.enPin.SetDriveMode(GpioPinDriveMode.Output); this.resetPin.SetDriveMode(GpioPinDriveMode.Output); this.enPin.Write(GpioPinValue.Low); this.resetPin.Write(GpioPinValue.Low); Thread.Sleep(100); this.enPin.Write(GpioPinValue.High); this.resetPin.Write(GpioPinValue.High); var settings = new GHIElectronics.TinyCLR.Devices.Spi.SpiConnectionSettings() { ChipSelectLine = this.csPin, ClockFrequency = 4000000, Mode = GHIElectronics.TinyCLR.Devices.Spi.SpiMode.Mode0, ChipSelectType = GHIElectronics.TinyCLR.Devices.Spi.SpiChipSelectType.Gpio, ChipSelectHoldTime = TimeSpan.FromTicks(10), ChipSelectSetupTime = TimeSpan.FromTicks(10) }; this.networkCommunicationInterfaceSettings.SpiApiName = SC20260.SpiBus.Spi3; this.networkCommunicationInterfaceSettings.GpioApiName = "GHIElectronics.TinyCLR.NativeApis.STM32H7.GpioController\\0"; this.networkCommunicationInterfaceSettings.SpiSettings = settings; this.networkCommunicationInterfaceSettings.InterruptPin = this.intPin; this.networkCommunicationInterfaceSettings.InterruptEdge = GpioPinEdge.FallingEdge; this.networkCommunicationInterfaceSettings.InterruptDriveMode = GpioPinDriveMode.InputPullUp; this.networkCommunicationInterfaceSettings.ResetPin = this.resetPin; this.networkCommunicationInterfaceSettings.ResetActiveState = GpioPinValue.Low; var networkInterfaceSetting = new WiFiNetworkInterfaceSettings() { Ssid = this.ssid.Text, Password = this.password.Text, }; networkInterfaceSetting.Address = new IPAddress(new byte[] { 192, 168, 1, 122 }); networkInterfaceSetting.SubnetMask = new IPAddress(new byte[] { 255, 255, 255, 0 }); networkInterfaceSetting.GatewayAddress = new IPAddress(new byte[] { 192, 168, 1, 1 }); networkInterfaceSetting.DnsAddresses = new IPAddress[] { new IPAddress(new byte[] { 75, 75, 75, 75 }), new IPAddress(new byte[] { 75, 75, 75, 76 }) }; networkInterfaceSetting.MacAddress = new byte[] { 0x00, 0x04, 0x00, 0x00, 0x00, 0x00 }; networkInterfaceSetting.DhcpEnable = true; networkInterfaceSetting.DynamicDnsEnable = true; this.networkController.SetInterfaceSettings(networkInterfaceSetting); this.networkController.SetCommunicationInterfaceSettings(this.networkCommunicationInterfaceSettings); this.networkController.SetAsDefaultController(); this.networkController.NetworkAddressChanged += this.NetworkController_NetworkAddressChanged; this.networkController.NetworkLinkConnectedChanged += this.NetworkController_NetworkLinkConnectedChanged; var firmware = Winc15x0Interface.GetFirmwareVersion(); if (firmware.IndexOf("255.255.255.65535") == 0) { this.resetPin.Dispose(); this.csPin.Dispose(); this.intPin.Dispose(); this.enPin.Dispose(); Application.Current.Dispatcher.Invoke(TimeSpan.FromMilliseconds(100), _ => { this.canvas.Children.Remove(this.status); Canvas.SetLeft(this.status, this.Width / 2 - this.Width / 4 - this.Width / 8 - this.Width / 16); Canvas.SetTop(this.status, this.Height - 40); this.canvas.Children.Add(this.status); this.status.TextContent = "Please reset application and type ssid, password correctly!"; this.status.Invalidate(); return(null); }, null); goto _return; } this.networkController.Enable(); } catch { } while ((DateTime.Now - start).TotalSeconds < 20) { if (this.isWifiConnected) { break; } Application.Current.Dispatcher.Invoke(TimeSpan.FromMilliseconds(100), _ => { this.status.TextContent = "Please wait..." + (int)((DateTime.Now - start).TotalSeconds) + " / 20"; this.status.Invalidate(); return(null); }, null); Thread.Sleep(1000); } if (this.isWifiConnected == false) { Application.Current.Dispatcher.Invoke(TimeSpan.FromMilliseconds(100), _ => { this.status.TextContent = "Wifi connection failed."; this.status.Invalidate(); return(null); }, null); this.resetPin.Dispose(); this.csPin.Dispose(); this.intPin.Dispose(); this.enPin.Dispose(); //var gpioControllerApi = new GpioControllerApiWrapper(NativeApi.Find(NativeApi.GetDefaultName(NativeApiType.GpioController), NativeApiType.GpioController)); //gpioControllerApi.ClosePin(SC20260.GpioPin.PB3); //gpioControllerApi.ClosePin(SC20260.GpioPin.PB4); //gpioControllerApi.ClosePin(SC20260.GpioPin.PB5); //gpioController.Dispose(); } _return: this.isRunning = false; }
private void InitGPIO() { GpioController gpio = GpioController.GetDefault(); { if (gpio == null) { Status.Text = "There is no GPIO controller on this device."; TerminalMode = TerminalModes.RFCOMMChat; Status.Text = "RFCOMM Chat Mode"; return; } //Can set in MainPage() if (TerminalMode == TerminalModes.none) { using (var pin2 = gpio.OpenPin(2)) { //Physical Pin 3 using (var pin3 = gpio.OpenPin(3)) { //Physical Pin 5 using (var pin4 = gpio.OpenPin(4)) { //Physical Pin 7 using (var pin17 = gpio.OpenPin(17)) //Physical Pin 11 { //Nb: Physical Pin 1 = Vcc(3.3) & Physical Pin 9 = Gnd //Need to ground all but the required pinX input //Nb: pinX X is the GPIO number not the physical pin // eg. pin2 is GPIO2 = physical pin 3 etc. //Seems that all bar GPIO17 float high. //So might get away with only defintely setting its state and driving other ones low as required pin2.SetDriveMode(GpioPinDriveMode.Input); pin3.SetDriveMode(GpioPinDriveMode.Input); pin4.SetDriveMode(GpioPinDriveMode.Input); pin17.SetDriveMode(GpioPinDriveMode.Input); var a0 = pin2.Read(); var a1 = pin3.Read(); var a2 = pin4.Read(); var a3 = pin17.Read(); if (a0 == GpioPinValue.Low) { TerminalMode = TerminalModes.BT; Status.Text = "BT Mode"; } else if (a1 == GpioPinValue.Low) { TerminalMode = TerminalModes.USBSerial; Status.Text = "USB Serial Mode"; } else if (a2 == GpioPinValue.Low) { TerminalMode = TerminalModes.Socket; Status.Text = "Socket Mode"; } else if (a3 == GpioPinValue.Low) { TerminalMode = TerminalModes.RFCOMMChat; Status.Text = "RFCOMM Chat Mode"; } else { TerminalMode = TerminalModes.none; Status.Text = "Need to set one of GPIO 2,3,4, 17 to High. Pins 3,5,7,11 respectively"; } } } } } } } }
private void InitGPIO() { pin = GpioController.GetDefault().OpenPin(LED_PIN); pin.Write(GpioPinValue.High); pin.SetDriveMode(GpioPinDriveMode.Output); }
protected override void Configure() { _kernel = new Ninject.StandardKernel(); _kernel.Bind <IEventAggregator>().To <EventAggregator>().InSingletonScope(); _eventAggregator = _kernel.Get <IEventAggregator>(); // Singletons _kernel.Bind <Settings>().ToSelf().InSingletonScope(); _kernel.Bind <PumpController>().ToSelf().InSingletonScope(); _kernel.Bind <ElementController>().ToSelf().InSingletonScope(); _kernel.Bind <Hardware>().ToSelf().InSingletonScope(); _kernel.Bind <HardwareInitializer>().ToSelf().InSingletonScope(); var settings = _kernel.Get <Settings>(); // Use real hardware if we have a GpioController - else use fakeys var shouldUseRealHardware = (GpioController.GetDefault() != null); if (shouldUseRealHardware) { // Configure the ADC for inputs // _kernel.Bind<IAnalogToDigitalConvertor>().To<Mcp3208>(); _kernel.Bind <IAnalogToDigitalConvertor>().To <Mcp3008>().InSingletonScope(); // Configure the GPIO for outputs var gpioController = GpioController.GetDefault(); var pumpGpioPin = gpioController.OpenPin(settings.PumpGpioPin); var pumpLedGpioPin = gpioController.OpenPin(settings.PumpLedPin); var elementGpioPin = gpioController.OpenPin(settings.ElementGpioPin); var elementLedGpioPin = gpioController.OpenPin(settings.ElementLedPin); // Use real inputs/outputs where requested _kernel.Bind <IOutputConnection>().To <GpioOutputConnection>(); _kernel.Bind <ITemperatureReader>().To <ThermistorTemperatureReader>(); // Get and configure the hardware object with correct pins etc var hardware = _kernel.Get <Hardware>(); // - GPIO Outputs (hardware.PumpOutputConnection as GpioOutputConnection)?.Configure(pumpGpioPin); (hardware.PumpLedOutputConnection as GpioOutputConnection)?.Configure(pumpLedGpioPin); (hardware.ElementOutputConnection as GpioOutputConnection)?.Configure(elementGpioPin); (hardware.ElementLedOutputConnection as GpioOutputConnection)?.Configure(elementLedGpioPin); // - ADC inputs ((ThermistorTemperatureReader)hardware.RoofTemperatureReader).PinNumber = settings.RoofThermistorAdcPin; ((ThermistorTemperatureReader)hardware.TankTemperatureReader).PinNumber = settings.TankThermistorAdcPin; ((ThermistorTemperatureReader)hardware.InletTemperatureReader).PinNumber = settings.InletThermistorAdcPin; // - Thermistor model parameters ((ThermistorTemperatureReader)hardware.RoofTemperatureReader).ThermistorModelParameters = settings.RoofThermistorModelParameters; ((ThermistorTemperatureReader)hardware.TankTemperatureReader).ThermistorModelParameters = settings.TankThermistorModelParameters; ((ThermistorTemperatureReader)hardware.InletTemperatureReader).ThermistorModelParameters = settings.InletThermistorModelParameters; } else { // Use fake inputs / outputs where requested _kernel.Bind <IOutputConnection>().To <FakeOutputConnection>(); _kernel.Bind <ITemperatureReader>().To <FakeTemperatureReader>(); // Setup some initial values for fake readings var hardware = _kernel.Get <Hardware>(); ((FakeTemperatureReader)hardware.RoofTemperatureReader).FakeTemperatureDegC = 50; ((FakeTemperatureReader)hardware.InletTemperatureReader).FakeTemperatureDegC = 40; ((FakeTemperatureReader)hardware.TankTemperatureReader).FakeTemperatureDegC = 30; ((FakeOutputConnection)hardware.PumpOutputConnection).State = false; ((FakeOutputConnection)hardware.ElementOutputConnection).State = false; } }
static void Main() { // Use low cpu frequency //https://docs.ghielectronics.com/software/tinyclr/tutorials/power-management.html // Cave: Do not activate both code alternatives together to change System Clock // If the board gets unresponsive erase application in loader mode (ldr button) // var PersistClock = true; if (Power.GetSystemClock() == SystemClock.High) { Power.SetSystemClock(SystemClock.Low, PersistClock); Power.Reset(); } /* * if (Power.GetSystemClock() == SystemClock.Low) * { * Power.SetSystemClock(SystemClock.High, false); * Power.Reset(); * } */ // Print System.Clock state Debug.WriteLine(Power.GetSystemClock() == SystemClock.Low ? "Using low cpu-frequency" : "Using high cpu-frequency"); var LED = GpioController.GetDefault().OpenPin(SC20100.GpioPin.PE11); LED.SetDriveMode(GpioPinDriveMode.Output); // Signals start of program (for tests) for (int i = 0; i < 5; i++) { LED.Write(GpioPinValue.High); Thread.Sleep(600); LED.Write(GpioPinValue.Low); Thread.Sleep(600); } myCloudStorageAccount = myCloudStorageAccount = new CloudStorageAccount(storageAccountName, storageKey, useHttps: Azure_useHTTPS); //SetupEnc28_SC20260D_MicroBus1(); #if UseWifiModule SetupWiFi7Click_SC20100_MicroBus1(); //Print the version of the installed WiFi firmware: Debug.WriteLine("Winc1500 Firmware Version: " + GHIElectronics.TinyCLR.Drivers.Microchip.Winc15x0.Winc15x0Interface.GetFirmwareVersion()); Debug.WriteLine("Supported Firmware Versions are: "); for (int i = 0; i < GHIElectronics.TinyCLR.Drivers.Microchip.Winc15x0.Winc15x0Interface.FirmwareSupports.Length; i++) { System.Diagnostics.Debug.WriteLine("Supported firmware version #" + (i + 1).ToString() + ": " + GHIElectronics.TinyCLR.Drivers.Microchip.Winc15x0.Winc15x0Interface.FirmwareSupports[i].ToString()); } #else SetupEnc28_SC20260D_MicroBus1(); #endif TimeService.SystemTimeChanged += TimeService_SystemTimeChanged; TimeService.SystemTimeChecked += TimeService_SystemTimeChecked; SetAppTime(timeZoneOffset, TimeServer_1, TimeServer_2); // Settings for one OnOffSensor, must be created for OnOffSensor02 - OnOffSensor04 if needed OnOffSensor01 = GpioController.GetDefault().OpenPin(SC20260.GpioPin.PB7); OnOffSensor01.SetDriveMode(GpioPinDriveMode.InputPullUp); OnOffSensor01.ValueChanged += OnOffSensor01_ValueChanged; getSensorDataTimer = new System.Threading.Timer(new TimerCallback(getSensorDataTimer_tick), null, readInterval * 1000, readInterval * 1000); // start timer to write analog data to the Cloud writeAnalogToCloudTimer = new System.Threading.Timer(new TimerCallback(writeAnalogToCloudTimer_tick), null, 5 * 1000, Timeout.Infinite); // readLastAnalogRowTimer is started in writeAnalogToCloudTimer_tick event readLastAnalogRowTimer = new System.Threading.Timer(new TimerCallback(readLastAnalogRowTimer_tick), null, Timeout.Infinite, Timeout.Infinite); Thread.Sleep(-1); }
public void InitGPIO() { //if (LightningProvider.IsLightningEnabled) //{ // LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider(); //} // Get the default GPIO controller on the system GpioController gpio = GpioController.GetDefault(); if (gpio == null) { return; // GPIO not available on this system } // Open GPIO 25 testPin = gpio.OpenPin(19); // Latch HIGH value first. This ensures a default value when the pin is set as output testPin.Write(GpioPinValue.High); // Set the IO direction as output testPin.SetDriveMode(GpioPinDriveMode.Output); // Open GPIO 27 - CLK listener CLK2 = gpio.OpenPin(27); CLK2.SetDriveMode(GpioPinDriveMode.Input); // Open GPIO 24 - FSO input FSO2 = gpio.OpenPin(24); FSO2.SetDriveMode(GpioPinDriveMode.InputPullDown); // Open GPIO 5 - DOUT input DOUT2 = gpio.OpenPin(5); DOUT2.SetDriveMode(GpioPinDriveMode.InputPullDown); // Open GPIO 12 - SCLK input SCLK2 = gpio.OpenPin(12); SCLK2.SetDriveMode(GpioPinDriveMode.InputPullDown); // Open GPIO 22 - OTR input OTR2 = gpio.OpenPin(22); OTR2.SetDriveMode(GpioPinDriveMode.InputPullDown); // Open GPIO 17 - issue SYNC pulse to ADC SYNC2 = gpio.OpenPin(17); SYNC2.Write(GpioPinValue.Low); SYNC2.SetDriveMode(GpioPinDriveMode.Output); //Set PowerDown pin high to enable opamp and ADC _PD = gpio.OpenPin(26); _PD.Write(GpioPinValue.High); _PD.SetDriveMode(GpioPinDriveMode.Output); //// Open GPIO 8 - issue _CS0 pulse to PGA //_CS0 = gpio.OpenPin(8); //_CS0.Write(GpioPinValue.High); //_CS0.SetDriveMode(GpioPinDriveMode.Output); //// Open GPIO 11 - issue SCLK pulse to PGA //aSCLK = gpio.OpenPin(11); //aSCLK.Write(GpioPinValue.Low); //aSCLK.SetDriveMode(GpioPinDriveMode.Output); //// Open GPIO 10 - master DIO communication line to PGA //DIO = gpio.OpenPin(10); //DIO.Write(GpioPinValue.Low); //DIO.SetDriveMode(GpioPinDriveMode.Output); }
static void SetupWiFi7Click_SC20100_MicroBus1() { var enablePin = GpioController.GetDefault().OpenPin(SC20100.GpioPin.PA8); enablePin.SetDriveMode(GpioPinDriveMode.Output); enablePin.Write(GpioPinValue.High); SpiNetworkCommunicationInterfaceSettings networkCommunicationInterfaceSettings = new SpiNetworkCommunicationInterfaceSettings(); var cs = GHIElectronics.TinyCLR.Devices.Gpio.GpioController.GetDefault(). OpenPin(GHIElectronics.TinyCLR.Pins.SC20260.GpioPin.PD15); var settings = new GHIElectronics.TinyCLR.Devices.Spi.SpiConnectionSettings() { ChipSelectLine = cs, ClockFrequency = 4000000, Mode = GHIElectronics.TinyCLR.Devices.Spi.SpiMode.Mode0, ChipSelectType = GHIElectronics.TinyCLR.Devices.Spi.SpiChipSelectType.Gpio, ChipSelectHoldTime = TimeSpan.FromTicks(10), ChipSelectSetupTime = TimeSpan.FromTicks(10) }; networkCommunicationInterfaceSettings.SpiApiName = GHIElectronics.TinyCLR.Pins.SC20100.SpiBus.Spi3; networkCommunicationInterfaceSettings.GpioApiName = GHIElectronics.TinyCLR.Pins.SC20100.GpioPin.Id; networkCommunicationInterfaceSettings.SpiSettings = settings; networkCommunicationInterfaceSettings.InterruptPin = GHIElectronics.TinyCLR.Devices.Gpio.GpioController.GetDefault(). OpenPin(GHIElectronics.TinyCLR.Pins.SC20100.GpioPin.PB12); networkCommunicationInterfaceSettings.InterruptEdge = GpioPinEdge.FallingEdge; networkCommunicationInterfaceSettings.InterruptDriveMode = GpioPinDriveMode.InputPullUp; networkCommunicationInterfaceSettings.ResetPin = GHIElectronics.TinyCLR.Devices.Gpio.GpioController.GetDefault(). OpenPin(GHIElectronics.TinyCLR.Pins.SC20100.GpioPin.PB13); networkCommunicationInterfaceSettings.ResetActiveState = GpioPinValue.Low; var networkController = NetworkController.FromName ("GHIElectronics.TinyCLR.NativeApis.ATWINC15xx.NetworkController"); WiFiNetworkInterfaceSettings networkInterfaceSetting = new WiFiNetworkInterfaceSettings() { Ssid = wiFiSSID_1, Password = wiFiKey_1, }; networkInterfaceSetting.Address = new IPAddress(new byte[] { 192, 168, 1, 122 }); networkInterfaceSetting.SubnetMask = new IPAddress(new byte[] { 255, 255, 255, 0 }); networkInterfaceSetting.GatewayAddress = new IPAddress(new byte[] { 192, 168, 1, 1 }); networkInterfaceSetting.DnsAddresses = new IPAddress[] { new IPAddress(new byte[] { 75, 75, 75, 75 }), new IPAddress(new byte[] { 75, 75, 75, 76 }) }; //networkInterfaceSetting.MacAddress = new byte[] { 0x00, 0x4, 0x00, 0x00, 0x00, 0x00 }; networkInterfaceSetting.MacAddress = new byte[] { 0x4A, 0x28, 0x05, 0x2A, 0xA4, 0x0F }; networkInterfaceSetting.DhcpEnable = true; networkInterfaceSetting.DhcpEnable = true; networkInterfaceSetting.TlsEntropy = new byte[] { 1, 2, 3, 4 }; networkController.SetInterfaceSettings(networkInterfaceSetting); networkController.SetCommunicationInterfaceSettings (networkCommunicationInterfaceSettings); networkController.SetAsDefaultController(); networkController.NetworkAddressChanged += NetworkController_NetworkAddressChanged; networkController.NetworkLinkConnectedChanged += NetworkController_NetworkLinkConnectedChanged; networkController.Enable(); while (linkReady == false) { ; } // Network is ready to used }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(XmppClient).GetTypeInfo().Assembly, typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly, typeof(XML).GetTypeInfo().Assembly, typeof(Waher.Script.Expression).GetTypeInfo().Assembly, typeof(Waher.Script.Graphs.Graph).GetTypeInfo().Assembly, typeof(Waher.Script.Persistence.SQL.Select).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000)); #if GPIO gpio = GpioController.GetDefault(); if (gpio != null) { if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output)) { this.gpioPin.SetDriveMode(GpioPinDriveMode.Output); this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.gpioPin.Write(this.output ? GpioPinValue.High : GpioPinValue.Low); await MainPage.Instance.OutputSet(this.output); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output)); } else { Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString()); } } else { Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString()); } } #else DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo is null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += async() => { try { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output)); this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. } catch (Exception ex) { Log.Critical(ex); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } #endif this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); string Host = await RuntimeSettings.GetAsync("XmppHost", "waher.se"); int Port = (int)await RuntimeSettings.GetAsync("XmppPort", 5222); string UserName = await RuntimeSettings.GetAsync("XmppUserName", string.Empty); string PasswordHash = await RuntimeSettings.GetAsync("XmppPasswordHash", string.Empty); string PasswordHashMethod = await RuntimeSettings.GetAsync("XmppPasswordHashMethod", string.Empty); if (string.IsNullOrEmpty(Host) || Port <= 0 || Port > ushort.MaxValue || string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PasswordHash) || string.IsNullOrEmpty(PasswordHashMethod)) { await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await this.ShowConnectionDialog(Host, Port, UserName)); } else { this.xmppClient = new XmppClient(Host, Port, UserName, PasswordHash, PasswordHashMethod, "en", typeof(App).GetTypeInfo().Assembly) // Add "new LogSniffer()" to the end, to output communication to the log. { AllowCramMD5 = false, AllowDigestMD5 = false, AllowPlain = false, AllowScramSHA1 = true }; this.xmppClient.OnStateChanged += this.StateChanged; this.xmppClient.OnConnectionError += this.ConnectionError; this.AttachFeatures(); Log.Informational("Connecting to " + this.xmppClient.Host + ":" + this.xmppClient.Port.ToString()); this.xmppClient.Connect(); } this.minuteTimer = new Timer((State) => { if (this.xmppClient != null && (this.xmppClient.State == XmppState.Error || this.xmppClient.State == XmppState.Offline)) { this.xmppClient.Reconnect(); } }, null, 60000, 60000); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await Dialog.ShowAsync()); } }
public PushButtonPressedBehavior() { isTypePresent = (GpioController.GetDefault() != null); }
/// <summary> /// Use this constructor when sensor has continous power /// </summary> /// <param name="MOISTURE_PIN_READING">GPIO Pin that sensor reading (out) is connected to</param> public MoistureSensor(int MOISTURE_PIN_READING) { //MOISTURE GPIO pinMOISTURE = GpioController.GetDefault().OpenPin(MOISTURE_PIN_READING); pinMOISTURE.SetDriveMode(GpioPinDriveMode.Input); }
/// <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> public BiHallClick(Hardware.Socket socket) { _interrupt = GpioController.GetDefault().OpenPin(socket.Int); _interrupt.SetDriveMode(GpioPinDriveMode.InputPullDown); _interrupt.ValueChanged += Interrupt_ValueChanged; }