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 * 4]; 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 * 4] = (byte) b; 031 m_buffer[(index * 4) + 1] = (byte) g; 032 m_buffer[(index * 4) + 2] = (byte) r; 033 m_buffer[(index * 4) + 3] = 0; 034 } 035 036 /** 037 * Gets the buffer length. 038 * 039 * @return the buffer length 040 */ 041 @Override 042 public int getLength() { 043 return m_buffer.length / 4; 044 } 045 046 /** 047 * Gets the red channel of the color at the specified index. 048 * 049 * @param index the index of the LED to read 050 * @return the value of the red channel, from [0, 255] 051 */ 052 @Override 053 public int getRed(int index) { 054 return m_buffer[index * 4 + 2] & 0xFF; 055 } 056 057 /** 058 * Gets the green channel of the color at the specified index. 059 * 060 * @param index the index of the LED to read 061 * @return the value of the green channel, from [0, 255] 062 */ 063 @Override 064 public int getGreen(int index) { 065 return m_buffer[index * 4 + 1] & 0xFF; 066 } 067 068 /** 069 * Gets the blue channel of the color at the specified index. 070 * 071 * @param index the index of the LED to read 072 * @return the value of the blue channel, from [0, 255] 073 */ 074 @Override 075 public int getBlue(int index) { 076 return m_buffer[index * 4] & 0xFF; 077 } 078 079 /** 080 * Creates a view of a subsection of this data buffer, starting from (and including) {@code 081 * startingIndex} and ending on (and including) {@code endingIndex}. Views cannot be written 082 * directly to an {@link AddressableLED}, but are useful tools for logically separating different 083 * sections of an LED strip for independent control. 084 * 085 * @param startingIndex the first index in this buffer that the view should encompass (inclusive) 086 * @param endingIndex the last index in this buffer that the view should encompass (inclusive) 087 * @return the view object 088 */ 089 public AddressableLEDBufferView createView(int startingIndex, int endingIndex) { 090 return new AddressableLEDBufferView(this, startingIndex, endingIndex); 091 } 092}