bool shifting = false;
int shift_count = 0;
byte data = 0;
void setup()
{
DDRD = 0b01110000; //pin 4, 5, 6 output
// arduino pin 4 connects to 74HC595 serial input pin
// arduino pin 5 connects to 74HC595 output register clock pin
// arduino pin 6 connects to 74HC595 shift register clock pin
Serial.begin(9600);
//shift register clock
TCCR1A = 0b00000000; //TCCR1A bit 0, 1 and TCCR1B bit 3, 4 set timer mode
TCCR1B = 0b00001101; //Set mode to be clear on compare. set scaler to be clock/1024
OCR1A = 1562; //period = (OCR1A/B + 1)*scaler*62.5ns = 0.1s
TIMSK1 = 0b00000010; //enable timer counter
sei();
}
void loop()
{
//updateShiftRegister();
shifting = true;
data = random(0, 255);
printBin(data);
Serial.println();
delay(8000);
}
//shift register clock
ISR(TIMER1_COMPA_vect){
PORTD ^= 0b01000000; //toggle pin 6(shift register clock)
if(shifting){
//if shift register clock is high
if(PIND & 0b01000000){
PORTD = PIND & 0b11011111; //set output register clock low
//if data bit is high
if(bitRead(data, 7-shift_count)){
//set serial input pin high
PORTD = PIND | 0b00010000;
}
//if data bit is low
else{
//set serial input pin low
PORTD = PIND & 0b11101111;
}
shift_count++;
}
//if shift register clock is low
else{
//if data bit is read
if(shift_count >0){
PORTD = PIND | 0b00100000; //set output register clock high
//if all 8 data bits are read
if(shift_count == 9){
shifting = false;
shift_count = 0;
}
}
}
}
}
void printBin(byte aByte) {
for (int8_t aBit = 7; aBit >= 0; aBit--)
Serial.write(bitRead(aByte, aBit) ? '1' : '0');
}
reference:
timer interrupt
port manipulation
No comments:
Post a Comment