Microcontroller C Code Sample

ATtiny85 ควบคุม 7-Segment ด้วย 74HC595 (Shift Register)

วิดีโอ YouTube




/*
* Counter.cpp
*
* Created: 12.04.2013 14:12:59
* Author: Jopi
*/
 
 
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
 
#define LATCH_PIN PB4
#define SHIFT_PIN PB1
#define DATA_PIN PB0
 
#define BUTTON_PIN PB2 //PB2 is INT0
 
uint8_t digits[10] = {
0b00111111,
0b00001100,
0b01101011,
0b01101101,
0b01011100,
0b01110101,
0b01110111,
0b00101100,
0b01111111,
0b01111101
};
 
uint8_t rightDigit = 0;
uint8_t leftDigit = 0;
 
void latch() {
//Set the Latch clock pin to low
PORTB &= ~(1<<LATCH_PIN);
//Set latch pin back to high -> shift register will copy buffer to latch register
PORTB |= 1<<LATCH_PIN;
}
 
void shiftOut(uint8_t data) {
 
for(uint8_t i = 0; i < 8; i++) {
bool state = !((data & (1 << i )) != 0);
//bool state = bit_is_clear(PINB, 1);
if(state) {
//set high signal
PORTB |= 1 << DATA_PIN;
} else { //low or different than 1
//set low signal
PORTB &= ~(1<< DATA_PIN);
}
//pulse shift clock pin -> shift register will shift the current bit in
PORTB |= 1 << SHIFT_PIN;
PORTB &= ~(1<< SHIFT_PIN);
}
 
return;
}
 
void incrementCounter(){
if(rightDigit == 9) { //check if left digit has to be incremented
if(leftDigit == 9) { //99; reset
leftDigit = 0;
rightDigit = -1; //will be set to 0 later by incrementing
} else { //left digit < 9
leftDigit += 1;
rightDigit = -1; //will be set to 0 later by incrementing
}
}
rightDigit += 1;
}
 
void shiftCounter() {
shiftOut(digits[rightDigit]);
shiftOut(digits[leftDigit]);
latch();
}
 
int main(void)
{
//Set PB0 to Output
DDRB = 0b11; //PB0-1 Output
DDRB |= (1 << LATCH_PIN); //Set Latch Pin to Output
//Set Button Pin to Input & HIGH
DDRB &= ~(1 << BUTTON_PIN);
PORTB |= 1 << BUTTON_PIN;
//Set Interrupt for PB2 (INT0)
//Falling Edge:
MCUCR |= 1 << ISC01; //ISC01 to 1
MCUCR &= ~(1 << ISC00); //ISC00 to 0
//Activate Interrupt INT0
GIMSK |= 1 << INT0;
//Activate Interrupts
sei();
//int out[8] = {0, 0, 0, 0, 0, 0, 0, 1}; //Last bit equals Q0, which won't be used for this project
while(1)
{
//for(uint8_t i = 0; i < 100; i++) { // 0 - 99
//incrementCounter();
//
//shiftCounter();
//
//_delay_ms(500);
//}
}
}
 
ISR(INT0_vect) {
incrementCounter();
shiftCounter();
}
เครดิต : https://gist.github.com/Jopi24/a9fdfe68cf4fb64815bf