shift_register.c (2444B)
1 /* Copyright 2023 ArthurCyy <https://github.com/ArthurCyy> 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 "shift_register.h" 18 #include <string.h> 19 20 static void shift_out(void); 21 22 static uint8_t shift_values[SHR_SERIES_NUM] = {0}; 23 24 void shift_init(void) { 25 #ifdef SHR_OE_PIN 26 gpio_set_pin_output(SHR_OE_PIN); 27 gpio_write_pin_high(SHR_OE_PIN); 28 #endif 29 gpio_set_pin_output(SHR_DATA_PIN); 30 gpio_set_pin_output(SHR_LATCH_PIN); 31 gpio_set_pin_output(SHR_CLOCK_PIN); 32 } 33 34 void shift_enable(void) { 35 #ifdef SHR_OE_PIN 36 gpio_write_pin_low(SHR_OE_PIN); 37 #endif 38 gpio_write_pin_low(SHR_DATA_PIN); 39 gpio_write_pin_low(SHR_LATCH_PIN); 40 gpio_write_pin_low(SHR_CLOCK_PIN); 41 } 42 43 void shift_disable(void) { 44 #ifdef SHR_OE_PIN 45 gpio_write_pin_high(SHR_OE_PIN); 46 #endif 47 gpio_write_pin_low(SHR_DATA_PIN); 48 gpio_write_pin_low(SHR_LATCH_PIN); 49 gpio_write_pin_low(SHR_CLOCK_PIN); 50 } 51 52 void shift_writePin(pin_t pin, int level) { 53 uint8_t group = (pin - H0) >> 3; 54 uint8_t bit = 0x01 << ((pin - H0)&0x07); 55 56 if(group >= SHR_SERIES_NUM) 57 return; 58 59 if(level) 60 shift_values[group] |= bit; 61 else 62 shift_values[group] &= ~bit; 63 shift_out(); 64 } 65 66 void shift_writeGroup(int group, uint8_t value) { 67 if(group >= SHR_SERIES_NUM) 68 return; 69 70 shift_values[group] = value; 71 shift_out(); 72 } 73 74 void shift_writeAll(int level) { 75 memset(shift_values, level ? 0xFF : 0, sizeof(shift_values)); 76 shift_out(); 77 } 78 79 static void shift_out(void) { 80 uint8_t n = SHR_SERIES_NUM; 81 gpio_write_pin_low(SHR_LATCH_PIN); 82 while(n--){ 83 for (uint8_t i = 0; i < 8; i++) { 84 gpio_write_pin_low(SHR_CLOCK_PIN); 85 gpio_write_pin(SHR_DATA_PIN, shift_values[n] & (0x80 >> i)); 86 gpio_write_pin_high(SHR_CLOCK_PIN); 87 } 88 } 89 gpio_write_pin_high(SHR_LATCH_PIN); 90 }