private int Callback(IntPtr context, IntPtr deviceProfile, HotplugEvent e, IntPtr userData) { //Task.Run(() => //{ if (e == HotplugEvent.DeviceArrived) { var newBoard = new TreehopperUsb(new LibUsbConnection(deviceProfile)); Debug.WriteLine("Adding " + newBoard); if (currentContext == null) { Boards.Add(newBoard); } else { currentContext.Post( delegate { Boards.Add(newBoard); }, null); } } else if (e == HotplugEvent.DeviceLeft) { var devicePath = deviceProfile.ToString(); Debug.WriteLine("Removing devicePath " + devicePath); RemoveDevice(devicePath); } //}); return(0); }
static async void RunApp() { Console.Write("Waiting for board to be connected..."); TreehopperUsb board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Board found:" + board); await board.ConnectAsync(); board.Pwm1.Enabled = true; board.HardwarePwmManager.Frequency = HardwarePwmFrequency.Freq61Hz; int step = 5; int rate = 1; while (true) { for (int i = 0; i < 256; i = i + step) { board.Pwm1.DutyCycle = i / 255.0; await Task.Delay(rate); } for (int i = 255; i > 0; i = i - step) { board.Pwm1.DutyCycle = i / 255.0; await Task.Delay(rate); } } }
public RotaryEncoder(LibrariesPage page, TreehopperUsb Board = null) : base("Rotary Encoder", page) { this.Board = Board; Board.Connection.UpdateRate = 0; // go real fast! InitializeComponent(); BindingContext = this; }
private void InitialAdd() { IntPtr deviceProfilePtrPtr; var ret = NativeMethods.GetDeviceList(context, out deviceProfilePtrPtr); if (ret > 0 || deviceProfilePtrPtr == IntPtr.Zero) { for (var i = 0; i < ret; i++) { // calculate the offset pointer var deviceProfilePtr = Marshal.ReadIntPtr(new IntPtr(deviceProfilePtrPtr.ToInt64() + i * IntPtr.Size)); var desc = new LibUsbDeviceDescriptor(); NativeMethods.GetDeviceDescriptor(deviceProfilePtr, desc); if (desc.idVendor == TreehopperUsb.Settings.Vid && desc.idProduct == TreehopperUsb.Settings.Pid) { var board = new TreehopperUsb(new LibUsbConnection(deviceProfilePtr)); Debug.WriteLine("Adding " + board); Boards.Add(board); } } } }
static async void RunApp() { Console.Write("Starting Ds18b20 temperature sensor demo..."); board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + board); await board.ConnectAsync(); await Ds18b20.FindAll(board.Uart); Console.WriteLine("Found temperature sensors at addresses:"); foreach(var addr in Ds18b20.AddressList) { Console.WriteLine(addr); } Console.WriteLine("\n"); while (board.IsConnected) { try { Console.WriteLine("Collecting readings... (press any key to exit)"); Dictionary<ulong, double> temps = await Ds18b20.GetAllTemperatures(board.Uart); foreach (KeyValuePair<ulong, double> item in temps) { Console.WriteLine(String.Format("Sensor {0} reports a temperature of {1} °C ({2} °F)", item.Key, item.Value, Ds18b20.CelsiusToFahrenheit(item.Value))); } Console.WriteLine("\n"); } catch(Exception ex) { Console.WriteLine(ex.Message); } } }
public async Task StartApp() { Board = await ConnectionService.Instance.GetFirstDeviceAsync(); await Start(); ConnectionService.Instance.Boards.CollectionChanged += Boards_CollectionChanged; }
public int DeviceAdded(IOObject usbDevice, string name, string serialNumber) { var board = new TreehopperUsb(new MacUsbConnection(usbDevice, name, serialNumber)); Boards.Add(board); return(Boards.IndexOf(board)); }
private async void Boards_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { if (Board != null) { return; // we already have a board, thank you. } Board = (TreehopperUsb)e.NewItems[0]; Device.BeginInvokeOnMainThread(async() => { await Start(); }); } else if (e.Action == NotifyCollectionChangedAction.Remove) { Board.Disconnect(); Device.BeginInvokeOnMainThread(() => { Navigation.PopToRootAsync(); //ledSwitch.Toggled -= LedSwitch_Toggled; Debug.WriteLine("Board disconnected!"); //boardViewer.IsVisible = false; connectMessage.IsVisible = true; //Pins.Clear(); Board = null; }); Debug.WriteLine("Board disconnected!"); Board = null; } }
static async void Run() { Console.Write("Looking for board..."); board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Board found."); await board.ConnectAsync(); var pin = board[19]; pin.Mode = PinMode.SoftPwm; pin.DutyCycle = 0.8; int step = 10; int rate = 25; while (true) { for (int i = 0; i < 256; i = i + step) { pin.DutyCycle = i / 255.0; await Task.Delay(rate); } for (int i = 255; i > 0; i = i - step) { pin.DutyCycle = i / 255.0; await Task.Delay(rate); } } }
static async Task App() { board = await ConnectionService.Instance.GetFirstDeviceAsync(); await board.ConnectAsync(); Console.WriteLine("Board connected: " + board); var mux = new I2cAnalogMux(board.I2c, board.Pins[0], board.Pins[1]); var temp1 = new Mlx90615(mux.Ports[0]); var temp2 = new Mlx90615(mux.Ports[1]); var temp3 = new Mlx90615(mux.Ports[2]); var temp4 = new Mlx90615(mux.Ports[3]); Console.WriteLine("Press any key to close"); while (!Console.KeyAvailable) { Console.WriteLine("Temperature Sensor #1: " + temp1.Object); Console.WriteLine("Temperature Sensor #2: " + temp2.Object); Console.WriteLine("Temperature Sensor #3: " + temp3.Object); Console.WriteLine("Temperature Sensor #4: " + temp4.Object); await Task.Delay(1000); } }
static async Task RunBlink() { while (true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. Board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + Board); Console.WriteLine("Version: " + Board.VersionString); // You must explicitly connect to a board before communicating with it await Board.ConnectAsync(); Console.WriteLine("Start blinking. Press any key to stop."); while (Board.IsConnected && !Console.KeyAvailable) { // toggle the LED. Board.Led = !Board.Led; await Task.Delay(100); } Board.Disconnect(); } }
/// <summary> /// Initialize and run a sketch /// </summary> /// <param name="board">The Treehopper board to use</param> /// <param name="throwExceptions">Whether unimplemented or miscalled functions should throw exceptions or fail silently</param> public Sketch(TreehopperUsb board, bool throwExceptions = true) { Board = board; this.throwExceptions = throwExceptions; board.ConnectAsync().Wait(); Serial = new SerialShim(board); }
static async void Connect() { Console.Write("Waiting for board to be connected..."); board = await ConnectionService.Instance.First(); Console.WriteLine("Board found:" + board); await board.Connect(); await RunApp(); }
private async void SetupApp(TreehopperUsb treehopperBoard) { board = treehopperBoard; board.SPI.ChipSelect = board.Pin4; display = new SevenSegSpi(board.SPI); await display.Init(); IsConnected = true; }
private static async Task <bool> SelfTestAsync(TreehopperUsb board) { Console.WriteLine($"Beginning self-test of {board}"); bool retVal = true; await board.ConnectAsync().ConfigureAwait(false); // make each pin an input foreach (var pin in board.Pins) { await pin.MakeAnalogInAsync().ConfigureAwait(false); await board.AwaitPinUpdateAsync().ConfigureAwait(false); await Task.Delay(10).ConfigureAwait(false); if (pin.AnalogValue < 0.1) { retVal = false; Console.WriteLine($"{pin.Name} shorted to ground."); } } for (int i = 0; i < board.Pins.Count - 1; i++) { board.Pins[i].Mode = PinMode.PushPullOutput; await board.Pins[i].WriteDigitalValueAsync(false).ConfigureAwait(false); await Task.Delay(10).ConfigureAwait(false); await board.AwaitPinUpdateAsync().ConfigureAwait(false); if (board.Pins[i + 1].AnalogValue < 0.1) { Console.WriteLine($"Short detected on pins {i} and {i + 1}."); retVal = false; } await board.Pins[i].WriteDigitalValueAsync(true).ConfigureAwait(false); } if (retVal == false) { Console.WriteLine("Errors found during self-test!"); } else { Console.WriteLine("Self-test passed!"); } return(retVal); }
public LibrariesPage(TreehopperUsb Board) { InitializeComponent(); this.Board = Board; components.ItemsSource = Components; foreach (Type type in typeof(LibraryComponent).GetTypeInfo().Assembly.GetTypes().Where(type => typeof(LibraryComponent).IsAssignableFrom(type) && type != typeof(LibraryComponent))) { LibraryComponent item = (LibraryComponent)Activator.CreateInstance(type, new object[] { this, Board }); ComponentList.Add(item.Title, type); } }
public SignalPage(TreehopperUsb board) { Board = board; InitializeComponent(); ledSwitch.Toggled += LedSwitch_Toggled; foreach (var pin in board.Pins) { Pins.Add(new PinViewModel(pin)); } pins.ItemsSource = Pins; pins.ItemSelected += Pins_ItemSelected; }
public ConnectedPage(TreehopperUsb Board) { this.Board = Board; Title = Board.ToString(); On <Xamarin.Forms.PlatformConfiguration.Android>().SetIsSwipePagingEnabled(false); Children.Add(new Pages.SignalPage(Board)); Children.Add(new Pages.LibrariesPage(Board)); NavigationPage.SetHasBackButton(this, false); this.BarBackgroundColor = Color.FromRgb(0x8b, 0xc3, 0x4a); //if(Device.RuntimePlatform != Device.GTK) // this.BarTextColor = Color.White; InitializeComponent(); }
static async Task App() { Console.Write("Waiting for board to be connected..."); board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Board found:" + board); await board.ConnectAsync(); Pin AdcPin = board.Pins[0]; // equivalent to Pin AdcPin = board[1]; AdcPin.ReferenceLevel = AdcReferenceLevel.Vref_3V3; AdcPin.Mode = PinMode.AnalogInput; while (!Console.KeyAvailable) { double voltage = await AdcPin.AwaitAnalogVoltageChangeAsync(); Console.WriteLine($"New analog voltage: {voltage}V"); } }
private void Selector_OnBoardConnected(object sender, BoardConnectedEventArgs e) { Data.Clear(); board = e.Board; board.Connection.UpdateRate = sampleRate; for (int i = 0; i < 20; i++) { if(ChannelEnabled[i]) board.Pins[i].Mode = PinMode.AnalogInput; else board.Pins[i].Mode = PinMode.Unassigned; } board.OnPinValuesUpdated += Board_OnPinValuesUpdated; sw.Restart(); timer.Start(); }
static async Task App() { while (true) { Console.Write("Waiting for board..."); board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Board Found! Serial: " + board.SerialNumber + "."); Console.Write("Connecting..."); await board.ConnectAsync(); Console.WriteLine("Connected. Starting application..."); var servo = new HobbyServo(board.Pins[0], 650, 2600); while (board.IsConnected) { Console.WriteLine("Clockwise..."); for (int i = 0; i < 180; i++) { if (!board.IsConnected) { break; } servo.Angle = i; await Task.Delay(10); } Console.WriteLine("Counterclockwise..."); for (int i = 180; i > 0; i--) { if (!board.IsConnected) { break; } servo.Angle = i; await Task.Delay(10); } } } }
static async void RunApp() { Console.Write("Starting Ds18b20 temperature sensor demo..."); board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + board); await board.ConnectAsync(); var group = new Ds18b20.Group(board.Uart); Console.WriteLine("Found temperature sensors at addresses:"); var sensors = await group.FindAllAsync(); foreach (var sensor in sensors) { Console.WriteLine(sensor.Address); // disable auto-update so we can access multiple temperature properties without doing re-reads. // Consequently, we must explicitly call Update() to read the result sensor.AutoUpdateWhenPropertyRead = false; } Console.WriteLine("\n"); while (board.IsConnected) { Console.WriteLine("Starting sampling... (press any key to exit)"); using (await group.StartConversionAsync()) // this triggers simultaneous conversion on all sensors { foreach (var temp in sensors) { await temp.UpdateAsync(); // retrieve the conversion Console.WriteLine( $"Sensor {temp.Address} reports a temperature of {temp.Celsius} °C ({temp.Fahrenheit} °F)"); } } Console.WriteLine("\n"); } }
protected async override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button>(Resource.Id.MyButton); GetSystemService(Context.UsbService); board = await ConnectionService.Instance.GetFirstDeviceAsync(); await board.ConnectAsync(); board[0].Mode = PinMode.PushPullOutput; board[0].DigitalValue = false; button.Click += Button_Click; }
static async Task App() { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. TreehopperUsb Board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + Board); // You must explicitly open a board before communicating with it await Board.ConnectAsync(); Board.Uart.Mode = UartMode.OneWire; Board.Uart.Enabled = true; List <UInt64> addresses = await Board.Uart.OneWireSearchAsync(); Console.WriteLine("Found addresses: "); foreach (var address in addresses) { Console.WriteLine(address); } Board.Disconnect(); }
static async Task App() { board = await ConnectionService.Instance.GetFirstDeviceAsync(); await board.ConnectAsync(); var nunchuk = new WiiNunchuk(board.I2c); // Let a Poller take care of the updating using (var poller = new Poller <WiiNunchuk>(nunchuk)) { // Hook onto some fun events nunchuk.JoystickChanged += Nunchuk_JoystickChanged; nunchuk.C.OnPressed += C_OnPressed; nunchuk.Z.OnPressed += Z_OnPressed; Console.WriteLine("Starting demo. Press any key to stop..."); while (board.IsConnected && !Console.KeyAvailable) { await Task.Delay(100); } } }
static async Task RunBlink() { while (true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. Board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + Board); Console.WriteLine("Version: " + Board.Version); // You must explicitly connect to a board before communicating with it await Board.ConnectAsync(); Console.WriteLine("Start blinking. Press any key to stop."); while (Board.IsConnected && !Console.KeyAvailable) { // toggle the LED. Board.Led = !Board.Led; await Task.Delay(100); } } }
internal Pin(TreehopperUsb board, byte pinNumber) { this.board = board; this.PinNumber = pinNumber; SoftPwm = new SoftPwm(Board, this); AdcValueChangedThreshold = 10; AnalogVoltageChangedThreshold = 0.1; AnalogValueChangedThreshold = 0.05; this.ReferenceLevel = AdcReferenceLevel.VREF_3V3; }
private void addDeviceToCollection(TreehopperUsb board) { }
public Accelerometer(LibrariesPage page, TreehopperUsb Board = null) : base("Accelerometer", page) { this.Board = Board; InitializeComponent(); BindingContext = this; }
internal Uart(TreehopperUsb device) { this.device = device; }
/// <summary> /// Construct a new instance of SerialShim. /// </summary> /// <param name="board">the board to reference for hardware UART transactions</param> public SerialShim(TreehopperUsb board) { this.board = board; }
public Blink(TreehopperUsb board, bool throwExceptions = true) : base(board, throwExceptions) { }
internal HardwarePwmManager(TreehopperUsb treehopperUSB) { this.board = treehopperUSB; }
public Display(LibrariesPage page, TreehopperUsb Board = null) : base("Display", page) { this.Board = Board; InitializeComponent(); BindingContext = this; }
private void Rescan() { foreach (UsbRegistry regDevice in UsbDevice.AllDevices) { if (regDevice.Vid != TreehopperUsb.Settings.Vid || regDevice.Pid != TreehopperUsb.Settings.Pid) continue; if (regDevice.Device == null) continue; if (Boards.Where(i => i.Connection.DevicePath == regDevice.SymbolicName).Count() == 0) { if(regDevice.Device.Info.SerialString != null && regDevice.Device.Info.SerialString.Length > 0) { var board = new TreehopperUsb(new UsbConnection(regDevice)); Debug.WriteLine("Added board: " + board); Boards.Add(board); } else { } } } foreach (var board in Boards.ToList()) { bool deviceFound = false; foreach (UsbRegistry dev in UsbDevice.AllDevices) { if (dev.Vid != TreehopperUsb.Settings.Vid || dev.Pid != TreehopperUsb.Settings.Pid) continue; if (dev.SymbolicName == board.Connection.DevicePath) deviceFound = true; } if (!deviceFound) { Debug.WriteLine("Removing board: " + board); Boards.Remove(board); board.Dispose(); } } }
internal SoftPwmManager(TreehopperUsb board) { this.board = board; pins = new Dictionary<int, SoftPwmPinConfig>(); }
internal HardwareI2c(TreehopperUsb device) { this.device = device; }
static async Task App() { board = await ConnectionService.Instance.GetFirstDeviceAsync(); await board.ConnectAsync(); Console.WriteLine("Board connected: " + board); var mag = new Hmc5883l(board.I2c); mag.Range = Hmc5883l.RangeSetting.GAIN_0_88; Console.WriteLine("We'll start by doing a rudimentary magnetometer calibration. " + "Once prompted, move the accelerometer around in all orientations to enable the software " + "to capture the min and max values in all directions. This process will run for 10 seconds"); Console.WriteLine("Press any key to start calibration."); Console.WriteLine(); var response = Console.ReadKey(); // wait for a key Console.WriteLine("Now calibrating. Move magnetometer around for 10 seconds..."); min.X = float.MaxValue; min.Y = float.MaxValue; min.Z = float.MaxValue; max.X = float.MinValue; max.Y = float.MinValue; max.Z = float.MinValue; for (int i = 0; i < 100; i++) { var reading = mag.Magnetometer; if (reading.X < min.X) { min.X = reading.X; } if (reading.Y < min.Y) { min.Y = reading.Y; } if (reading.Z < min.Z) { min.Z = reading.Z; } if (reading.X > max.X) { max.X = reading.X; } if (reading.Y > max.Y) { max.Y = reading.Y; } if (reading.Z > max.Z) { max.Z = reading.Z; } await Task.Delay(100); } Console.WriteLine("Calibration done."); Console.WriteLine("Press any key to stop demo."); Vector3 offset = (max + min) / 2f; while (!Console.KeyAvailable) { var reading = mag.Magnetometer; var normalizedX = Numbers.Map(reading.X, min.X, max.X, -1, 1); var normalizedY = Numbers.Map(reading.Y, min.Y, max.Y, -1, 1); var angle = Math.Atan2(normalizedY, normalizedX); angle = angle * (180 / Math.PI); angle -= (3.0 + (10.0 / 60.0)); Console.WriteLine($"{angle:0.00} degrees ({reading.X:0.00}, {reading.Y:0.00}, {reading.Z:0.00})"); await Task.Delay(100); } }
public LedBlinkerViewModel(TreehopperUsb board) { this.board = board; }
void StartWatcher() { //deviceWatcher = DeviceInformation.CreateWatcher(UsbDevice.GetDeviceSelector(0x04d8, 0xf426)); deviceWatcher = DeviceInformation.CreateWatcher(UsbDevice.GetDeviceSelector(TreehopperUsb.Settings.Vid, TreehopperUsb.Settings.Pid)); // Hook up handlers for the watcher events before starting the watcher handlerAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) => { Debug.WriteLine("Device added: " + deviceInfo.Name); UsbConnection newConnection = new UsbConnection(deviceInfo); TreehopperUsb newBoard = new TreehopperUsb(newConnection); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { connectedDevices.Add(newBoard); }); try { if (boardAddedSignal.CurrentCount == 0) boardAddedSignal.Release(); } catch { } }); deviceWatcher.Added += handlerAdded; handlerUpdated = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) => { Debug.WriteLine("Device updated"); }); deviceWatcher.Updated += handlerUpdated; handlerRemoved = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) => { Debug.WriteLine("Device removed"); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { connectedDevices.Where(board => ((UsbConnection)(board.Connection)).DevicePath == deviceInfoUpdate.Id).ToList().All(i => { i.Disconnect(); connectedDevices.Remove(i); return true; } ); }); }); deviceWatcher.Removed += handlerRemoved; handlerEnumCompleted = new TypedEventHandler<DeviceWatcher, Object>((watcher, obj) => { Debug.WriteLine("Enum completed"); }); deviceWatcher.EnumerationCompleted += handlerEnumCompleted; handlerStopped = new TypedEventHandler<DeviceWatcher, Object>((watcher, obj) => { Debug.WriteLine("Device or something stopped"); }); deviceWatcher.Stopped += handlerStopped; Debug.WriteLine("Starting the wutchah"); deviceWatcher.Start(); }
internal ParallelInterface(TreehopperUsb board) { this.board = board; }
public Apa102(LibrariesPage page, TreehopperUsb Board = null) : base("APA102 RGB LEDs", page) { this.Board = Board; InitializeComponent(); BindingContext = this; }
void manager_BoardAdded(object sender, TreehopperUsb board) { myBoard = board; myBoard.Open(); colorSensor = new ColorSensor_ADJDS311(board.I2C, board.Pin1); }
public Altitude(LibrariesPage page, TreehopperUsb Board = null) : base("Altitude", page) { this.Board = Board; InitializeComponent(); BindingContext = this; }
public Flir(LibrariesPage page, TreehopperUsb Board = null) : base("FLIR Lepton", page) { this.Board = Board; InitializeComponent(); BindingContext = this; }