|
|
发表于 2015-2-3 21:06:44
|
显示全部楼层
直接端口访问,代码将会更小,IO操作更快速。更适合用于记忆体不足之微控制器。这是一个使用直接端口访问控制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;
- }
- }
复制代码 |
|