Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Threading.Tasks;
- using Windows.Devices.Enumeration;
- using Windows.Devices.Spi;
- namespace LedStripAnimator.Raspberry
- {
- public class DotStarController
- {
- private byte[] _buffer;
- private byte[] _startBuffer;
- private byte[] _ledBuffer;
- private int _ledBufferSize;
- private SpiDevice _dotStar;
- private Stopwatch _stopwatch;
- public DotStarController(int ledCount)
- {
- _ledBufferSize = 4 * ledCount;
- _startBuffer = new byte[] { 0x00, 0x00, 0x00, 0x00 };
- _ledBuffer = new byte[_ledBufferSize];
- _buffer = new byte[_ledBufferSize + _startBuffer.Length];
- for (int i = 0; i < _ledBufferSize; i++)
- _ledBuffer[i] = 0xff;
- CombineBuffers();
- _stopwatch = new Stopwatch();
- }
- private void CombineBuffers()
- {
- Buffer.BlockCopy(_startBuffer, 0, _buffer, 0, 4);
- Buffer.BlockCopy(_ledBuffer, 0, _buffer, 4, _ledBufferSize);
- }
- public async Task<bool> InitializeAndConnectSpi()
- {
- try
- {
- var settings = new SpiConnectionSettings(0);
- settings.Mode = SpiMode.Mode0;
- settings.ClockFrequency = 125000000;
- string deviceSelector = SpiDevice.GetDeviceSelector();
- var deviceInformation = await DeviceInformation.FindAllAsync(deviceSelector);
- _dotStar = await SpiDevice.FromIdAsync(deviceInformation[0].Id, settings);
- if(_dotStar != null)
- return true;
- }
- catch (Exception ex)
- {
- Debug.WriteLine(">> Initialize: " + ex.Message);
- }
- return false;
- }
- internal void DoTestAnimation()
- {
- var ledLights = new LedLight[240];
- }
- public void Show()
- {
- #if DEBUG
- _stopwatch.Restart();
- #endif
- _dotStar.Write(_buffer);
- #if DEBUG
- Debug.WriteLine("Elapsed: {0}ms ({1} ticks)", _stopwatch.ElapsedMilliseconds, _stopwatch.ElapsedTicks);
- #endif
- }
- internal void ReplaceBuffer(byte[] newBuffer)
- {
- _ledBufferSize = newBuffer.Length;
- _ledBuffer = newBuffer;
- CombineBuffers();
- }
- public void TurnOff()
- {
- SetColor(0, 0, 0);
- Show();
- }
- public void SetColor(byte red, byte green, byte blue)
- {
- var index = 1;
- do
- {
- _ledBuffer[index++] = blue;
- _ledBuffer[index++] = green;
- _ledBuffer[index++] = red;
- index++;
- } while (index < _ledBufferSize);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement