Skip to content

Instantly share code, notes, and snippets.

@euronay

euronay/Program.cs

Created Mar 28, 2019
Embed
What would you like to do?
Control WS2812B strip on a Raspberry Pi
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>hello_ws2812</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Device.Gpio" Version="0.1.0-prerelease*" />
<PackageReference Include="Iot.Device.Bindings" Version="0.1.0-prerelease*" />
</ItemGroup>
</Project>
using System;
using System.Device.Spi;
using System.Device.Spi.Drivers;
using System.Drawing;
using Iot.Device.Graphics;
using Iot.Device.Ws28xx;
namespace hello_ws2812
{
class Program
{
private const int count = 30;
static void Main()
{
var settings = new SpiConnectionSettings(0, 0) {
ClockFrequency = 2_400_000,
Mode = SpiMode.Mode0,
DataBitLength = 8
};
var spi = new UnixSpiDevice(settings);
var device = new Ws2812b(spi, count);
// Display basic colors for 5 sec
BitmapImage image = device.Image;
image.Clear();
image.SetPixel(0, 0, Color.Orange);
image.SetPixel(1, 0, Color.Red);
image.SetPixel(2, 0, Color.Green);
image.SetPixel(3, 0, Color.Blue);
image.SetPixel(4, 0, Color.Yellow);
image.SetPixel(5, 0, Color.Cyan);
image.SetPixel(6, 0, Color.Magenta);
image.SetPixel(7, 0, Color.FromArgb(unchecked((int)0xffff8000)));
device.Update();
System.Threading.Thread.Sleep(5000);
// Chase some blue leds
for(int i=0; i<10; i++)
{
image.Clear();
for(int j=0; j<count; j++)
{
image.SetPixel(j, 0, Color.LightBlue);
device.Update();
System.Threading.Thread.Sleep(10);
image.SetPixel(j, 0, Color.Blue);
device.Update();
System.Threading.Thread.Sleep(25);
}
}
// Color Fade
int r=255;
int g=0;
int b=0;
while (! Console.KeyAvailable) {
if(r > 0 && b == 0){
r--;
g++;
}
if(g > 0 && r == 0){
g--;
b++;
}
if(b > 0 && g == 0){
r++;
b--;
}
image.Clear(Color.FromArgb(r,g,b));
device.Update();
System.Threading.Thread.Sleep(10);
}
image.Clear();
device.Update();
Console.WriteLine("Hello Pi!");
}
}
}
@BradenEverson

This comment has been minimized.

Copy link

@BradenEverson BradenEverson commented Aug 20, 2020

Where in the code does it bind to a specific GPIO pin?

@dannysilence

This comment has been minimized.

Copy link

@dannysilence dannysilence commented Sep 9, 2020

Where in the code does it bind to a specific GPIO pin?

I believe the iot library handles it based on given SpiConnectionSettings, so the code is:
var settings = new SpiConnectionSettings(0, 0) { ClockFrequency = 2_400_000, Mode = SpiMode.Mode0, DataBitLength = 8 };

Author's post with some more details on this scenario: https://jamesnaylor.dev/Posts/Read?id=pi-ws2812-with-net-core

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment