构建一层抽象来操作Arduino一系列数字端口输出是很多人需要的,之前为了方便操作任意类型的流水灯,不管怎么跳转,只要把简单的逻辑整理好,操作一个10进制的变量即可。
如果说把Arduino当做黑盒子,来操作数字端口是常见的事情,下面这个例子讲告诉你构建简单抽象的方法与好处。
//to config the quantity of leds const int ledNum = 8; //use an integer array to set the Pin of leds const int ledPin[] = { 2, 3, 4, 5, 6, 7, 8, 9 }; //use every bits of a decimal long interger record leds' state long ledState = 10110001L; //initializing function void setup() { setLedPin(); Serial.begin(9600); } //set all the led ports OUTPUT void setLedPin() { for(int counter = 0; counter < ledNum; counter ++) { pinMode(ledPin[counter], OUTPUT); digitalWrite(ledPin[counter], LOW); } } //this function will be excuted repeatedly void loop() { //detectButton(); lightLed(); } //light the leds void lightLed() { for(int counter = 0; counter < ledNum; counter ++) { digitalWrite(ledPin[counter], true == fetchLedBit(ledState, counter) ? HIGH : LOW); //translate HIGH/LOW to true/false } } //fetch the bitNum of temp, if its 1 return true, else return 0 boolean fetchLedBit(long temp, int bitNum) { for(int counter = 0; counter < bitNum; counter ++) temp /= 10; //ledState /= (long)pow(10, bitNum-1); if ( 1 == ( temp % 10 )) return true; else return false; } //if directionNum -1, ledState Shift right //if directionNum 1, ledState Shift left void shiftNum(int directionNum) { if ( ledState != 1 || ledState != pow(2, ledNum) ) { if( -1 == directionNum ) ledState /= 10; else if( 1 == directionNum ) ledState *= 10; } } //if left button is push, return 1 //if right button is push, return -1 int detectButton() { return 0; } |
你改变一下变量ledState的数值,还可以重新配置ledPin的顺序和位置。多用几次就会体现这种好处了,如果要操纵一群LED灯,这是一种值得提倡的风格。希望对初学者有帮助。