Advertisement
Guest User

Untitled

a guest
Sep 6th, 2015
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.93 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading.Tasks;
  4. using Windows.Devices.Enumeration;
  5. using Windows.Devices.Spi;
  6.  
  7. namespace LedStripAnimator.Raspberry
  8. {
  9. public class DotStarController
  10. {
  11. private byte[] _buffer;
  12. private byte[] _startBuffer;
  13. private byte[] _ledBuffer;
  14. private int _ledBufferSize;
  15. private SpiDevice _dotStar;
  16. private Stopwatch _stopwatch;
  17.  
  18. public DotStarController(int ledCount)
  19. {
  20. _ledBufferSize = 4 * ledCount;
  21. _startBuffer = new byte[] { 0x00, 0x00, 0x00, 0x00 };
  22. _ledBuffer = new byte[_ledBufferSize];
  23. _buffer = new byte[_ledBufferSize + _startBuffer.Length];
  24.  
  25. for (int i = 0; i < _ledBufferSize; i++)
  26. _ledBuffer[i] = 0xff;
  27.  
  28. CombineBuffers();
  29. _stopwatch = new Stopwatch();
  30. }
  31.  
  32. private void CombineBuffers()
  33. {
  34. Buffer.BlockCopy(_startBuffer, 0, _buffer, 0, 4);
  35. Buffer.BlockCopy(_ledBuffer, 0, _buffer, 4, _ledBufferSize);
  36. }
  37.  
  38. public async Task<bool> InitializeAndConnectSpi()
  39. {
  40. try
  41. {
  42. var settings = new SpiConnectionSettings(0);
  43. settings.Mode = SpiMode.Mode0;
  44. settings.ClockFrequency = 125000000;
  45.  
  46. string deviceSelector = SpiDevice.GetDeviceSelector();
  47. var deviceInformation = await DeviceInformation.FindAllAsync(deviceSelector);
  48. _dotStar = await SpiDevice.FromIdAsync(deviceInformation[0].Id, settings);
  49.  
  50. if(_dotStar != null)
  51. return true;
  52. }
  53. catch (Exception ex)
  54. {
  55. Debug.WriteLine(">> Initialize: " + ex.Message);
  56. }
  57. return false;
  58. }
  59.  
  60. internal void DoTestAnimation()
  61. {
  62. var ledLights = new LedLight[240];
  63.  
  64.  
  65. }
  66.  
  67. public void Show()
  68. {
  69. #if DEBUG
  70. _stopwatch.Restart();
  71. #endif
  72.  
  73. _dotStar.Write(_buffer);
  74.  
  75. #if DEBUG
  76. Debug.WriteLine("Elapsed: {0}ms ({1} ticks)", _stopwatch.ElapsedMilliseconds, _stopwatch.ElapsedTicks);
  77. #endif
  78. }
  79.  
  80. internal void ReplaceBuffer(byte[] newBuffer)
  81. {
  82. _ledBufferSize = newBuffer.Length;
  83. _ledBuffer = newBuffer;
  84. CombineBuffers();
  85. }
  86.  
  87. public void TurnOff()
  88. {
  89. SetColor(0, 0, 0);
  90. Show();
  91. }
  92.  
  93. public void SetColor(byte red, byte green, byte blue)
  94. {
  95. var index = 1;
  96. do
  97. {
  98. _ledBuffer[index++] = blue;
  99. _ledBuffer[index++] = green;
  100. _ledBuffer[index++] = red;
  101. index++;
  102. } while (index < _ledBufferSize);
  103. }
  104. }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement