001// Copyright (c) FIRST and other WPILib contributors. 002// Open Source Software; you can modify and/or share it under the terms of 003// the WPILib BSD license file in the root directory of this project. 004 005package edu.wpi.first.wpilibj; 006 007/** Buffer storage for Addressable LEDs. */ 008public class AddressableLEDBuffer implements LEDReader, LEDWriter { 009 byte[] m_buffer; 010 011 /** 012 * Constructs a new LED buffer with the specified length. 013 * 014 * @param length The length of the buffer in pixels 015 */ 016 public AddressableLEDBuffer(int length) { 017 m_buffer = new byte[length * 3]; 018 } 019 020 /** 021 * Sets a specific led in the buffer. 022 * 023 * @param index the index to write 024 * @param r the r value [0-255] 025 * @param g the g value [0-255] 026 * @param b the b value [0-255] 027 */ 028 @Override 029 public void setRGB(int index, int r, int g, int b) { 030 m_buffer[index * 3] = (byte) r; 031 m_buffer[(index * 3) + 1] = (byte) g; 032 m_buffer[(index * 3) + 2] = (byte) b; 033 } 034 035 /** 036 * Gets the buffer length. 037 * 038 * @return the buffer length 039 */ 040 @Override 041 public int getLength() { 042 return m_buffer.length / 3; 043 } 044 045 /** 046 * Gets the red channel of the color at the specified index. 047 * 048 * @param index the index of the LED to read 049 * @return the value of the red channel, from [0, 255] 050 */ 051 @Override 052 public int getRed(int index) { 053 return m_buffer[index * 3] & 0xFF; 054 } 055 056 /** 057 * Gets the green channel of the color at the specified index. 058 * 059 * @param index the index of the LED to read 060 * @return the value of the green channel, from [0, 255] 061 */ 062 @Override 063 public int getGreen(int index) { 064 return m_buffer[index * 3 + 1] & 0xFF; 065 } 066 067 /** 068 * Gets the blue channel of the color at the specified index. 069 * 070 * @param index the index of the LED to read 071 * @return the value of the blue channel, from [0, 255] 072 */ 073 @Override 074 public int getBlue(int index) { 075 return m_buffer[index * 3 + 2] & 0xFF; 076 } 077 078 /** 079 * Creates a view of a subsection of this data buffer, starting from (and including) {@code 080 * startingIndex} and ending on (and including) {@code endingIndex}. Views cannot be written 081 * directly to an {@link AddressableLED}, but are useful tools for logically separating different 082 * sections of an LED strip for independent control. 083 * 084 * @param startingIndex the first index in this buffer that the view should encompass (inclusive) 085 * @param endingIndex the last index in this buffer that the view should encompass (inclusive) 086 * @return the view object 087 */ 088 public AddressableLEDBufferView createView(int startingIndex, int endingIndex) { 089 return new AddressableLEDBufferView(this, startingIndex, endingIndex); 090 } 091}