Daniel Porrey
Published © GPL3+

Discover i2c Devices on the Raspberry Pi

Scan the i2c bus to discover devices that are connected to a Raspberry Pi running Windows 10 IoT Core.

BeginnerProtip1 hour13,067
Discover i2c Devices on the Raspberry Pi

Things used in this project

Story

Read more

Schematics

Image from Microsft Example

Sample of how to connect an i2c device to the Raspberry Pi. All i2c devices will connect in te same manner. https://developer.microsoft.com/en-us/windows/iot/samples/i2caccelerometer
File missing, please reupload.

Code

C# Code

C#
This is the same code snipet found within the article. This can be pasted into your project and adapted as necessary.
public static async Task<IEnumerable<byte>> FindDevicesAsync() 
{ 
	IList<byte> returnValue = new List<byte>(); 
	
	// *** 
	// *** Get a selector string that will return all I2C controllers on the system
	// *** 
	string aqs = I2cDevice.GetDeviceSelector();
	
	// *** 
	// *** Find the I2C bus controller device with our selector string 
	// *** 
	var dis = await DeviceInformation.FindAllAsync(aqs).AsTask();
	
	if (dis.Count > 0) 
	{ 
		const int minimumAddress = 0x08; 
		const int maximumAddress = 0x77;
		
		for (byte address = minimumAddress; address <= maximumAddress; address++) 
		{ 
			var settings = new I2cConnectionSettings(address); 
			settings.BusSpeed = I2cBusSpeed.FastMode; 
			settings.SharingMode = I2cSharingMode.Shared; 
			
			// *** 
			// *** Create an I2cDevice with our selected bus controller and I2C settings 
			// *** 
			using (I2cDevice device = await I2cDevice.FromIdAsync(dis[0].Id, settings)) 
			{ 
				if (device != null) 
				{ 
					try 
					{ 
						byte[] writeBuffer = new byte[1] { 0 }; 
						device.Write(writeBuffer);
						
						// *** 
						// *** If no exception is thrown, there is 
						// *** a device at this address. 
						// *** 
						returnValue.Add(address); 
					} 
					catch 
					{ 
						// *** 
						// *** If the address is invalid, an exception will be thrown. 
						// *** 
					} 
				} 
			} 
		} 
	}
	
	return returnValue; 
}

DHT Tiny

The code in this library uses the technique outlined in this article to find devices on the i2c bus.

Credits

Daniel Porrey

Daniel Porrey

50 projects • 314 followers
I lead a software development team for a large Chicago based organization. I also develop applications personally.
Thanks to Microsoft.

Comments