leds.c (2628B)
1 /* Copyright 2018 James Laird-Wah 2 * 3 * This program is free software: you can redistribute it and/or modify 4 * it under the terms of the GNU General Public License as published by 5 * the Free Software Foundation, either version 2 of the License, or 6 * (at your option) any later version. 7 * 8 * This program is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 */ 16 17 #include "leds.h" 18 #include "i2c_master.h" 19 #include "led_tables.h" 20 #include "rgb_matrix.h" 21 #include <string.h> 22 #include "model01.h" 23 24 #define I2C_TIMEOUT 1000 25 26 void set_all_leds_to(uint8_t r, uint8_t g, uint8_t b) { 27 uint8_t buf[] = { 28 TWI_CMD_LED_SET_ALL_TO, 29 b, g, r 30 }; 31 i2c_transmit(I2C_ADDR(LEFT), buf, sizeof(buf), I2C_TIMEOUT); 32 i2c_transmit(I2C_ADDR(RIGHT), buf, sizeof(buf), I2C_TIMEOUT); 33 _delay_us(10); 34 } 35 36 void set_led_to(int led, uint8_t r, uint8_t g, uint8_t b) { 37 uint8_t buf[] = { 38 TWI_CMD_LED_SET_ONE_TO, 39 led & 0x1f, 40 b, g, r 41 }; 42 int hand = (led >= 32) ? RIGHT : LEFT; 43 i2c_transmit(I2C_ADDR(hand), buf, sizeof(buf), I2C_TIMEOUT); 44 _delay_us(10); 45 } 46 47 #ifdef RGB_MATRIX_ENABLE 48 49 static struct { 50 uint8_t b; 51 uint8_t g; 52 uint8_t r; 53 } __attribute__((packed)) led_state[64]; 54 55 static void set_color(int index, uint8_t r, uint8_t g, uint8_t b) { 56 led_state[index].r = r; 57 led_state[index].g = g; 58 led_state[index].b = b; 59 } 60 61 static void set_color_all(uint8_t r, uint8_t g, uint8_t b) { 62 for (int i=0; i<RGB_MATRIX_LED_COUNT; i++) 63 set_color(i, r, g, b); 64 } 65 66 static void init(void) { 67 // Enable high current pathway to LEDs - this does violate the USB spec though! (1.6 amps...) 68 gpio_set_pin_output(E6); 69 gpio_write_pin_low(E6); 70 71 // Overcurrent check input 72 gpio_set_pin_input(B4); 73 } 74 75 static void flush(void) { 76 uint8_t *bank_data = (uint8_t*)&led_state[0]; 77 uint8_t command[1 + 8*3]; 78 for (int hand=0; hand<2; hand++) { 79 int addr = I2C_ADDR(hand); 80 81 for (int bank=0; bank<4; bank++) { 82 command[0] = TWI_CMD_LED_BASE + bank; 83 memcpy(&command[1], bank_data, 8*3); 84 i2c_transmit(addr, command, sizeof(command), I2C_TIMEOUT); 85 _delay_us(100); 86 87 bank_data += 8*3; 88 } 89 } 90 } 91 92 const rgb_matrix_driver_t rgb_matrix_driver = { 93 .init = init, 94 .flush = flush, 95 .set_color = set_color, 96 .set_color_all = set_color_all 97 }; 98 99 #endif 100 101 /* vim: set ts=2 sw=2 et: */