public void SetPinValue(int pin, PinValue pinValue, TimeSpan? timeout = null) { if (!Available) return; if (pins[pin] == null) pins[pin] = gpioController.OpenPin(pin); pins[pin].Write(pinValue == PinValue.High ? GpioPinValue.High : GpioPinValue.Low); pinValues[pin] = pinValue; }
/// <summary> /// 更新按键状态 /// </summary> /// <param name="key">按键</param> /// <param name="state">状态</param> /// <param name="tick">时间戳</param> public void updateKeyState(GamepadKey key, PinValue state, UInt32 tick) { var value = state == PinValue.Low ? KEY_STATE.PRESSED : KEY_STATE.NONE; if (key.state == value) { if (value == KEY_STATE.NONE) { return; } if (this.keyRepeatPressEvent == 0 || tick - key.lastupdate < this.keyRepeatPressEvent) { return; } key.count++; key.duration = tick - key.timestamp; key.lastupdate = tick; } else { if (value == KEY_STATE.PRESSED) { // 按下瞬间 if (tick - key.lastupdate < 50000) { return; } } else { // 抬起瞬间 从按下到抬起 时间太短的话 过滤掉 if (tick - key.timestamp < 100000) { return; } } key.count = 1; key.state = value; key.timestamp = tick; key.duration = null; key.lastupdate = tick; } // 触发事件 this.onKeyChange?.Invoke(key); }
protected override void Write(int pinNumber, PinValue value) { if (pinNumber == 0) { SetLedState(LedKey.NumLock, value); } if (pinNumber == 1) { SetLedState(LedKey.ScrollLock, value); } if (pinNumber == 2) { SetLedState(LedKey.CapsLock, value); } }
public void WritePin(EnumLed led, PinValue pinValue) { switch (led) { case EnumLed.Red: this.redLed.WritePin(pinValue); break; case EnumLed.Yellow: this.yellowLed.WritePin(pinValue); break; case EnumLed.Green: this.greenLed.WritePin(pinValue); break; } }
public void InformThatSignalChanged(PinValue signalValue) { if (ValueSetExternaly || val == PinValue.UNDEFINED || (val == PinValue.HIGHZ && signalValue == SetValue)) { lock (this.parentPort) { if (val == PinValue.UNDEFINED) { ValueSetExternaly = true; } OldVal = val; val = signalValue; Monitor.PulseAll(Form1.LockObject); } } }
/// <summary> /// Writes a value to a pin. /// </summary> /// <param name="pinNumber">The pin number in the controller's numbering scheme.</param> /// <param name="value">The value to be written to the pin.</param> public virtual void Write(int pinNumber, PinValue value) { if (!IsPinOpen(pinNumber)) { throw new InvalidOperationException($"Can not write to pin {pinNumber} because it is not open."); } int logicalPinNumber = GetLogicalPinNumber(pinNumber); _openPins[pinNumber] = value; if (_driver.GetPinMode(logicalPinNumber) != PinMode.Output) { return; } _driver.Write(logicalPinNumber, value); }
private void ReadBtn() { using var controller = new GpioController(); controller.OpenPin(config.BtnPin, PinMode.Input); bool noHigh = true; bool callSuccess = false; while (noHigh || !callSuccess) { PinValue btnVal = controller.Read(config.BtnPin); noHigh = btnVal == PinValue.Low; if (!noHigh) { callSuccess = CallWebApi(); } Thread.Sleep(200); } }
private static void Driver_ButtonPullDown(GpioDriver driver) { const int button = 18; const int led = 26; using (driver) { driver.SetPinMode(button, PinMode.InputPullDown); driver.SetPinMode(led, PinMode.Output); Stopwatch watch = Stopwatch.StartNew(); while (watch.Elapsed.TotalSeconds < 15) { PinValue value = driver.Input(button); driver.Output(led, value); } } }
public void Send(byte data) { gpio.SetPinMode(sda, PinMode.Output); int i = 0; byte temp = data; for (i = 0; i < 8; i++) { gpio.Write(scl, PinValue.Low); System.Threading.Thread.Sleep(I2C_IDLE); if ((temp & 0x80) == 0) { //Console.WriteLine("0"); gpio.Write(sda, PinValue.Low); System.Threading.Thread.Sleep(I2C_IDLE); } else { //Console.WriteLine("1"); gpio.Write(sda, PinValue.High); System.Threading.Thread.Sleep(I2C_IDLE); } gpio.Write(scl, PinValue.High); System.Threading.Thread.Sleep(I2C_IDLE); gpio.Write(scl, PinValue.Low); System.Threading.Thread.Sleep(I2C_IDLE); temp = (byte)(temp * 2); } gpio.Write(scl, PinValue.Low); System.Threading.Thread.Sleep(I2C_IDLE); gpio.Write(scl, PinValue.High); System.Threading.Thread.Sleep(I2C_IDLE); gpio.SetPinMode(sda, PinMode.Input); PinValue ack = gpio.Read(sda); //Console.WriteLine(ack.ToString()); gpio.Write(scl, PinValue.Low); }
public async Task SetLight(bool enabled, TimeSpan?milliseconds = null) { //var oldValue = this.gpioController.Read(this.Config.LedPin); var newValue = enabled ? PinValue.High : PinValue.Low; this.gpioController.Write(this.Config.LedPin, newValue); if (milliseconds.HasValue) { await Task.Delay(milliseconds.Value); this.gpioController.Write(this.Config.LedPin, this.oldValue); } else { this.oldValue = newValue; } }
private static void Driver_ButtonPullDown(GpioDriver driver) { using (driver) { driver.OpenPin(s_buttonPinNumber); driver.SetPinMode(s_buttonPinNumber, PinMode.InputPullDown); driver.OpenPin(s_ledPinNumber); driver.SetPinMode(s_ledPinNumber, PinMode.Output); Stopwatch watch = Stopwatch.StartNew(); while (watch.Elapsed.TotalSeconds < 15) { PinValue value = driver.Input(s_buttonPinNumber); driver.Output(s_ledPinNumber, value); } } }
/// <inheritdoc/> protected override void Write(int pinNumber, PinValue value) { (int GpioNumber, int Port, int PortNumber)unmapped = UnmapPinNumber(pinNumber); // data register (GPIO_SWPORT_DR) offset is 0x0000 uint *dataPointer = (uint *)_gpioPointers[unmapped.GpioNumber]; uint dataValue = *dataPointer; if (value == PinValue.High) { dataValue |= 0b1U << (unmapped.Port * 8 + unmapped.PortNumber); } else { dataValue &= ~(0b1U << (unmapped.Port * 8 + unmapped.PortNumber)); } *dataPointer = dataValue; }
private string ConvertPinValueToSysFs(PinValue value) { string result = string.Empty; switch (value) { case PinValue.High: result = "1"; break; case PinValue.Low: result = "0"; break; default: throw new ArgumentException($"Invalid pin value {value}"); } return(result); }
public void Init(int pinNumber, PinValue startValue) { this.pinNumber = pinNumber; this.pinValue = startValue; init = true; var gpio = GpioController.GetDefault(); // Show an error if there is no GPIO controller if (gpio == null) { throw new InvalidOperationException("There is no GPIO controller on this device."); } gpioPin = gpio.OpenPin(pinNumber); gpioPin.SetDriveMode(GpioPinDriveMode.Output); gpioPin.Write(pinValue == PinValue.High ? GpioPinValue.High : GpioPinValue.Low); }
/// <summary> /// Informs pins that value of the signal has changed. /// </summary> /// <param name="pin"> /// Pin that changed value of the signal. /// </param> public void InformOtherPins(Pin pin = null) { if (pin != null && pin.Val == PinValue.UNDEFINED) { } var foundConflict = false; foreach (var p in pins.Where(tp => tp != pin)) { if (pin.Val != PinValue.UNDEFINED && p.Val != PinValue.UNDEFINED && p.Val != PinValue.HIGHZ && p.Val != pin.Val && !p.ValueSetExternaly) { val = PinValue.HIGHZ; foundConflict = true; break; } } if (foundConflict) { foreach (var p in pins) { p.SetHighZ(); } SetColor(Color.Yellow); return; } foreach (Pin p in pins) { if (pin == null || p != pin) { p.InformThatSignalChanged(val); } } foreach (var s in ConnectedSignals) { s.InformOtherPins(); } }
public static bool WaitForValue(GpioController gpio, int pinNumber, PinValue value, int timeOutMillisecond = 50) { try { var outstime = DateTime.Now.Millisecond; do { var outseime = DateTime.Now.Millisecond; if ((outseime - outstime) > timeOutMillisecond) { return(false); } } while (gpio.Read(pinNumber) == value); return(true); } catch (Exception) { throw; } }
private string PinValueToStringValue(PinValue value) { string result; switch (value) { case PinValue.Low: result = "0"; break; case PinValue.High: result = "1"; break; default: throw new ArgumentException($"Invalid GPIO pin value '{value}'"); } return(result); }
public bool IsLEDON() { if (_gpioController == null) { return(false); } _gpioController.OpenPin(_Gpio_Pin_Num, PinMode.Output); PinValue pinValue = _gpioController.Read(_Gpio_Pin_Num); if (pinValue == PinValue.High) { return(true); } else { return(false); } }
protected internal override PinValue Input(int bcmPinNumber) { if (bcmPinNumber < 0 || bcmPinNumber >= PinCount) { throw new ArgumentOutOfRangeException(nameof(bcmPinNumber)); } Initialize(); //var value = GetBit(RegisterViewPointer->GPLEV, pin); int index = bcmPinNumber / 32; int shift = bcmPinNumber % 32; uint register = _registerViewPointer->GPLEV[index]; uint value = (register >> shift) & 1; PinValue result = Convert.ToBoolean(value) ? PinValue.High : PinValue.Low; return(result); }
private void HandleSwitchChange(PinValueChangedEventArgs pinValueChangedEventArgs) { this.Logger.LogInformation("Switch event: " + pinValueChangedEventArgs.ChangeType); PinValue switchState = this.Controller.Read(pinValueChangedEventArgs.PinNumber); if (switchState != this.SwitchState) { this.SwitchState = switchState; if (this.SwitchState == PinValue.High) { this.Logger.LogInformation("Switch released"); this.OnChanged(new RotaryChangeEventArgs(RotaryChangeEventType.SwitchReleased)); } else { this.Logger.LogInformation("Switch pressed"); this.OnChanged(new RotaryChangeEventArgs(RotaryChangeEventType.SwitchPressed)); } } }
/************ low level data pushing commands **********/ // write either command or data, with automatic 4/8-bit selection private void Send(byte value, PinValue mode) { DigitalWrite(_rsPin, mode); // if there is a RW pin indicated, set it low to Write if (_rwPin != null) { DigitalWrite(_rwPin, PinValue.Low); } if (HasFlag(_displayFunction, LCD_8BITMODE)) { Write8bits(value); } else { Write4bits((byte)(value >> 4)); Write4bits(value); } }
private void GpioValueChanged(string id, PinValue value) { if (!this.stopwatch.IsRunning) { return; } if (value == PinValue.High) { RelativeTimeToRisingEdge = stopwatch.ElapsedTicks; } else { long timeEnd = stopwatch.ElapsedTicks; this.TimeOfFlightTicks = timeEnd - RelativeTimeToRisingEdge; stopwatch.Stop(); this.DistanceToObject = CalculateDistanceInCm(this.TimeOfFlightTicks); this.OnData?.Invoke(this.UniqueId, this.DistanceToObject); this.logger.Debug($"In {this.UniqueId}: tof={TimeOfFlightTicks} = {timeEnd}-{RelativeTimeToRisingEdge}"); } }
/// <summary> /// Writes a value to a pin. /// </summary> /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param> /// <param name="value">The value to be written to the pin.</param> protected internal override void Write(int pinNumber, PinValue value) { string valuePath = $"{GpioBasePath}/gpio{pinNumber + s_pinOffset}/value"; if (File.Exists(valuePath)) { try { string sysFsValue = ConvertPinValueToSysFs(value); File.WriteAllText(valuePath, sysFsValue); } catch (UnauthorizedAccessException e) { throw new UnauthorizedAccessException("Reading a pin value requires root permissions.", e); } } else { throw new InvalidOperationException("There was an attempt to write to a pin that is not open."); } }
protected override WaitForEventResult WaitForEvent(int pinNumber, PinEventTypes eventTypes, CancellationToken cancellationToken) { PinValue oldState = Read(pinNumber); while (!cancellationToken.IsCancellationRequested) { PinValue newState = Read(pinNumber); if (oldState != newState) { if (eventTypes == PinEventTypes.Rising && newState == PinValue.High) { return(new WaitForEventResult() { EventTypes = PinEventTypes.Rising, TimedOut = false }); } else if (eventTypes == PinEventTypes.Falling && newState == PinValue.Low) { return(new WaitForEventResult() { EventTypes = PinEventTypes.Falling, TimedOut = false }); } else { return(new WaitForEventResult() { EventTypes = newState == PinValue.High ? PinEventTypes.Rising : PinEventTypes.Falling, TimedOut = false }); } } } return(new WaitForEventResult() { TimedOut = true }); }
public string DeserializeState(string state, IList <GpioPin> targetPins) { StringBuilder log = new StringBuilder(); if (state != null) { string[] lines = state.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string[] fields = line.Split(SEPARATOR); if (fields.Length == 5) { try { int pinNumber = Int32.Parse(fields[0]); PinMode pinMode = (PinMode)Enum.Parse(typeof(PinMode), fields[1]); PinValue pinValue = (PinValue)Enum.Parse(typeof(PinValue), fields[2]); PullMode pullMode = (PullMode)Enum.Parse(typeof(PullMode), fields[3]); string tag = fields[4]; GpioPin pin = targetPins[pinNumber]; pin.Tag = tag; pin.SetMode(pinMode); pin.SetPullMode(pullMode); pin.Write(pinValue); log.AppendFormat("Pin {0} set to mode {1}, pull {2}, value {3}", pinNumber, pinMode, pullMode, pinValue); } catch (Exception e) { log.AppendFormat("Error: {0}", e.Message); } log.AppendLine(); } } } return(log.ToString()); }
private void SetLedState(LedKey key, PinValue state) { int virtualKey = 0; if (key == LedKey.NumLock) { virtualKey = Interop.VK_NUMLOCK; } else if (key == LedKey.CapsLock) { virtualKey = Interop.VK_CAPITAL; } else if (key == LedKey.ScrollLock) { virtualKey = Interop.VK_SCROLL; } else { throw new NotSupportedException("No such key"); } // Bit 1 indicates whether the LED is currently on or off (or, whether Scroll lock, num lock, caps lock is on) int currentKeyState = Interop.GetKeyState(virtualKey) & 1; if ((state == PinValue.High && currentKeyState == 0) || (state == PinValue.Low && currentKeyState != 0)) { // Simulate a key press Interop.keybd_event((byte)virtualKey, 0x45, Interop.KEYEVENTF_EXTENDEDKEY | 0, IntPtr.Zero); // Simulate a key release Interop.keybd_event((byte)virtualKey, 0x45, Interop.KEYEVENTF_EXTENDEDKEY | Interop.KEYEVENTF_KEYUP, IntPtr.Zero); } }
//Fonction pour ecouter les actions sur le bouton private static void bouton() { //Creation d'un controller pour gerer les inputs outputs using var gpioController = new GpioController(); while (true) { //Lit la valeur du bouton gpioController.OpenPin(BTN_PIN, PinMode.Input); PinValue valeurBouton = gpioController.Read(BTN_PIN); gpioController.ClosePin(BTN_PIN); //Si le bouton est appuye if ((valeurBouton == PinValue.Low)) { if (CallWebApi()) { //Allume la LED gpioController.OpenPin(LED_PIN, PinMode.Output); gpioController.Write(LED_PIN, PinValue.High); //Attend afin de ne pas spammer le serveur Thread.Sleep(500); gpioController.ClosePin(LED_PIN); Console.WriteLine("Debug sonette High"); } else { //Eteint la LED gpioController.OpenPin(LED_PIN, PinMode.Output); gpioController.Write(LED_PIN, PinValue.Low); //Attend afin de ne pas spammer le serveur Thread.Sleep(500); gpioController.ClosePin(LED_PIN); Console.WriteLine("Debug sonette Low"); } } } }
private static void OnPinValueChanged2(object sender, PinValueChangedEventArgs e) { s_currentLedValue = s_currentLedValue == PinValue.High ? PinValue.Low : PinValue.High; Console.WriteLine($"Button pressed! Led value {s_currentLedValue}"); if (sender is GpioDriver) { GpioDriver driver = sender as GpioDriver; driver.Output(s_ledPinNumber, s_currentLedValue); } else if (sender is GpioPin) { GpioPin button = sender as GpioPin; GpioController controller = button.Controller; GpioPin led = controller[s_ledPinNumber]; led.Write(s_currentLedValue); } else { throw new ArgumentException(nameof(sender)); } }
/// <summary> /// Reads the current value of a pin. /// </summary> /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param> /// <returns>The value of the pin.</returns> protected internal override PinValue Read(int pinNumber) { PinValue result = default; string valuePath = $"{GpioBasePath}/gpio{pinNumber + s_pinOffset}/value"; if (File.Exists(valuePath)) { try { string valueContents = File.ReadAllText(valuePath); result = ConvertSysFsValueToPinValue(valueContents); } catch (UnauthorizedAccessException e) { throw new UnauthorizedAccessException("Reading a pin value requires root permissions.", e); } } else { throw new InvalidOperationException("There was an attempt to read from a pin that is not open."); } return(result); }
public bool Configure(RelayHwSettings settings) { _pin = settings.GpioPin; // First use of the method initialises GPIO controller with hardware _isGpioInitialised = _gpio.Initialise(); // This sets which output state (high or low) is configured as 'active' state. _activeState = settings.ActiveState; try { if (_isGpioInitialised) { _gpio.OpenPin(settings.GpioPin, _activeState); return(true); } _logger.LogError("GPIO not initialised."); return(false); } catch (Exception e) { _logger.LogError(e, "Open pin {Pin} failed", _pin); return(false); } }
public bool HitLEDSwitch() { if (_gpioController == null) { return(false); } _gpioController.OpenPin(_Gpio_Pin_Num, PinMode.Output); PinValue pinValue = _gpioController.Read(_Gpio_Pin_Num); if (pinValue == PinValue.High) { _gpioController.Write(_Gpio_Pin_Num, PinValue.Low); return(false); } else { _gpioController.Write(_Gpio_Pin_Num, PinValue.High); return(true); } }
public void Write(PinValue value) { Console.WriteLine(value); _value = value; }
private GpioPinValue ToGpioiPinValue(PinValue value) { return value == PinValue.High ? GpioPinValue.High : GpioPinValue.Low; }
public void Write(PinValue value) { _pin.Write(ToGpioiPinValue(value)); }
public void SetValue(int pin, PinValue value) { WriteToFSLocation(GPIOFSLocation + "gpio" + pin.ToString() + "/value", ((int)value).ToString()); }
private void Timer_Tick(object state) { value = (value == PinValue.High) ? PinValue.Low : PinValue.High; pin.Write(value); }