A library for interfacing with the SN74HC595N Shift register. Includes functions for writing bits, bytes, animation and bits at spesified positions.
ShiftOut.cpp
- Committer:
- benrammok
- Date:
- 2015-12-25
- Revision:
- 3:a0df8989ffa2
- Parent:
- 0:e576e892f0ca
- Child:
- 4:61198ffab8ca
File content as of revision 3:a0df8989ffa2:
#include "mbed.h" #include "ShiftOut.h" #define SET_LATCH() (LATCH = 0) #define RESET_LATCH() (LATCH = 1) #define ENABLE_RESET() (RESET = 0) #define DISABLE_RESET() (RESET = 1) static char stateArr[8] = {0}; static bool hasChanged = false; ShiftOut::ShiftOut(PinName ser, PinName srclk, PinName rclk, PinName oe, PinName reset) : DSERIAL(ser), LATCH(oe), SRCLK(srclk), RCLK(rclk), RESET(reset) { writeByte(0x00); // Reset the values of the registers to 0 if(RESET != NC){ DISABLE_RESET(); } } //Pulses the register void ShiftOut::updateRegister(){ SRCLK = 1; wait_us(2); SRCLK = 0; } void ShiftOut::updateOutput(){ RCLK = 1; wait_us(2); RCLK = 0; } void ShiftOut::writeByte(unsigned char byte){ hasChanged = true; for(int i = 0; i<8; i++){ DSERIAL = (byte & 0x01<<i)>>i; updateRegister(); } updateOutput(); } void ShiftOut::writeBit(unsigned char bit){ DSERIAL = bit & 0x01; updateRegister(); updateOutput(); } void ShiftOut::animate(int arr[][8], int lines, int delay_ms){ hasChanged = true; for(int i = 0; i < lines; i++){ for(int j = 0; j < 8; j++){ writeBit(arr[i][j]); } wait_ms(delay_ms); } } void ShiftOut::animationExample(){ hasChanged = true; int strobe[][8]= {{1,0,0,0,0,0,0,0}, {0,1,0,0,0,0,0,0}, {0,0,1,0,0,0,0,0}, {0,0,0,1,0,0,0,0}, {0,0,0,0,1,0,0,0}, {0,0,0,0,0,1,0,0}, {0,0,0,0,0,0,1,0}, {0,0,0,0,0,0,0,1}}; int nightrider[18][8]= {{1,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0}, {1,1,1,0,0,0,0,0}, {0,1,1,1,0,0,0,0}, {0,0,1,1,1,0,0,0}, {0,0,0,1,1,1,0,0}, {0,0,0,0,1,1,1,0}, {0,0,0,0,0,1,1,1}, {0,0,0,0,0,0,1,1}, {0,0,0,0,0,0,0,1}, {0,0,0,0,0,0,1,1}, {0,0,0,0,0,1,1,1}, {0,0,0,0,1,1,1,0}, {0,0,0,1,1,1,0,0}, {0,0,1,1,1,0,0,0}, {0,1,1,1,0,0,0,0}, {1,1,1,0,0,0,0,0}, {1,1,0,0,0,0,0,0}}; animate(nightrider, 18, 50); wait(1); animate(strobe, 8, 200); } void ShiftOut::writeBitAtPos(unsigned char pin, bool state){ if(!hasChanged){ clearStateArray(); hasChanged = false; } if(pin < 8){ stateArr[pin] = state; } writeArray(stateArr); } void ShiftOut::writeArray(char arr[8]){ for(int i = 7; i >= 0; i--) { writeBit(arr[i]); } } void ShiftOut::clearStateArray(){ for(int i = 0; i < 8; i++){ stateArr[i] = 0; } }