极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 11284|回复: 3

arduino有啥好的方法同时操作8个IO

[复制链接]
发表于 2015-2-3 10:17:26 | 显示全部楼层 |阅读模式
能否像其它单片机一样直接一个字节赋值。例如P0=0X57这样的。
还是只能定义一个函数来操作:
  1. void CommandWrite(int value) {
  2.   for (int i=1; i <= 8; i++)
  3.         {
  4.    digitalWrite(i,value & 01);
  5.    value >>= 1;
  6.         }
  7. }
复制代码

如果按这种来操作,会和直接赋值性能上有差别吗,正在移植一个STM32的显示驱动到arduino,特来请教。谢谢
回复

使用道具 举报

发表于 2015-2-3 14:28:36 | 显示全部楼层
本帖最后由 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

回复 支持 反对

使用道具 举报

发表于 2015-2-3 21:06:44 | 显示全部楼层
直接端口访问,代码将会更小,IO操作更快速。更适合用于记忆体不足之微控制器。这是一个使用直接端口访问控制74HC595的例子。
  1. const byte BIT_COUNT = 8;
  2. // latchPin=Digital 8(74HC595 pin 12)
  3. // clockPin=Digital 12(74HC595 pin 11)
  4. // dataPin=Digital 11(74HC595 pin 14)

  5. void setup() {
  6. //PORTB maps to Arduino digital pins 8 to 13
  7. //set bits 0,3,4 high, this will set digital pin 8,11,12 as output & all other pins as input
  8. DDRB=B00011001;
  9. }

  10. void loop() {
  11. for (int col = 0; col < BIT_COUNT; col++) {
  12. PORTB &= ~(1<<0); //set latch pin (bit 0) low, all other pin unchange
  13. int data = 1 << col; //bitshift left to generate required serial data
  14. ShiftOutLSBFIRST(data);
  15. PORTB |= 1<<0; //set latch pin (bit 0) high, all other pin unchange
  16. delay(200);
  17. }
  18. }


  19. void ShiftOutLSBFIRST(int data) {
  20. for(int i = 0; i < BIT_COUNT; i++) {
  21. if (data & (1<<i)) { //LSB first
  22. PORTB |= 1<<3; //set data pin (bit 3) high, all other pin unchange
  23. } else {
  24. PORTB &= ~(1<<3); //set data pin (bit 3) low, all other pin unchange

  25. }

  26. // generate a pulse for SERIAL CLOCK
  27. PORTB &= ~(1 << 4); // Set the clockPin low
  28. PORTB |= (1 << 4); // Set the clockPin high
  29. // it can also use the code below to generate SERIAL CLOCK
  30. // ^= toggle bit, doing this twice to generate a high low pulse
  31. // PORTB ^= 1 << 4; //toogle bit 3, all other pin unchange
  32. // PORTB ^= 1 << 4;
  33. }
  34. }
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-2-4 12:28:22 | 显示全部楼层
感谢楼上朋友的帮助,好好学学看
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-17 18:41 , Processed in 0.038417 second(s), 20 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表