arduino有啥好的方法同时操作8个IO
能否像其它单片机一样直接一个字节赋值。例如P0=0X57这样的。还是只能定义一个函数来操作:
void CommandWrite(int value) {
for (int i=1; i <= 8; i++)
{
digitalWrite(i,value & 01);
value >>= 1;
}
}
如果按这种来操作,会和直接赋值性能上有差别吗,正在移植一个STM32的显示驱动到arduino,特来请教。谢谢 本帖最后由 tzc9338 于 2015-2-3 14:31 编辑
用AVR的写法:
setup中先用DDRx (x:B/C/D)定义对应8位的功能,1是输出,0是输入。比如0xF0就是高4位输出,低4位输入
然后用PORTx (x:B/C/D)来控制每一位的电平
PB0~5对应arduino上的D8~D13
PC0~5对应arduino上的A0~A5
PD0~7对应arduino上的D0~D7
直接端口访问,代码将会更小,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;
}
} 感谢楼上朋友的帮助,好好学学看
页:
[1]