|
发表于 2013-10-20 11:17:46
|
显示全部楼层
digitalwrite的运行速度是超慢的,尤其是通过多个74HC595控制LED,你可能会看到闪烁。此时必须使用Direct Port Access(寄存器直接访问)
例:使用寄存器直接访问来控制74HC595 - const byte BIT_COUNT = 8;
- // latchPin=Digital 8(74HC595 pin 12)
- // clockPin=Digital 12(74HC595 pin 11)
- // dataPin=Digital 11(74HC595 pin 14)
- void setup() {
- //PORTB maps to Arduino digital pins 8 to 13
- //set bits 0,3,4 high, this will set digital pin 8,11,12 as output & all other pins as input
- DDRB=B00011001;
- }
- void loop() {
- for (int col = 0; col < BIT_COUNT; col++) {
- PORTB &= ~(1<<0); //set latch pin (bit 0) low, all other pin unchange
- int data = 1 << col; //bitshift left to generate required serial data
- ShiftOutLSBFIRST(data);
- PORTB |= 1<<0; //set latch pin (bit 0) high, all other pin unchange
- delay(200);
- }
- }
- void ShiftOutLSBFIRST(int data) {
- for(int i = 0; i < BIT_COUNT; i++) {
- if (data & (1<<i)) { //LSB first
- PORTB |= 1<<3; //set data pin (bit 3) high, all other pin unchange
- } else {
- PORTB &= ~(1<<3); //set data pin (bit 3) low, all other pin unchange
- }
- // generate a pulse for SERIAL CLOCK
- PORTB &= ~(1 << 4); // Set the clockPin low
- PORTB |= (1 << 4); // Set the clockPin high
- // it can also use the code below to generate SERIAL CLOCK
- // ^= toggle bit, doing this twice to generate a high low pulse
- // PORTB ^= 1 << 4; //toogle bit 3, all other pin unchange
- // PORTB ^= 1 << 4;
- }
- }
复制代码 |
|