lyy-cy 发表于 2013-10-17 21:53:55

01 两个闪灯实验的比较

本帖最后由 lyy-cy 于 2013-10-17 21:55 编辑

    Arduino的好处自然不用再说,但是很多人说它效率低什么的。刚好在学单片机,也对arduino感兴趣,于是就做了个比较。先看第一段代码:
/*
作者:极客工坊
时间:2012年5月18日
发表地址:www.geek-workshop.com
程序说明:
使一个Led亮一秒,灭一秒,如此往复。
*/

void setup() {               
// 初始化数字引脚,使其为输出状态。
// 大部分Arduino控制板上,数字13号引脚都有一颗Led。
pinMode(13, OUTPUT);   
}

void loop() {
digitalWrite(13, HIGH);   // 使Led亮
delay(1000);            // 持续1秒钟
digitalWrite(13, LOW);    // 使Led灭
delay(1000);            // 持续1秒钟。
}




然后看下面的这一段:


#include <avr/io.h>
#include <util/delay.h>   //GCC内置的延时函数


int main(void)
{
PORTB &= ~(1<<5) ; //PB5 清零
DDRB |= (1<<5);

while(1)
{
    PORTB |= (1<<5) ;      //PB5 高电平
    _delay_ms(50);   //调用延时函数
    PORTB &= ~(1<<5) ;   //PB5 清零
    _delay_ms(50);   //调用延时函数   
   }
   
}


功能相似,但是生成的二进制文件大小却很大的差别。























以后用GCC来写一些我们力所能及的代码,这样可以保持效率。
然后又可以借用arduino丰富的库。岂不……


yyy_zc 发表于 2013-10-17 22:19:08

光一个 setup() 就要做很多事情

Damn_intuition 发表于 2013-10-17 22:19:35

谢谢分享,
不过感觉实际上对于一般的玩家,两者差距不大,制约我们的一般不是硬件的空间和速度,而是好的创意。
嘿嘿

公孙林 发表于 2013-10-18 05:59:08

http://www.geek-workshop.com/thread-1064-1-1.html
我也写过一个类似的

学慧放弃 发表于 2013-10-18 13:50:09

arduino有些库调试出错很麻烦啊啊啊

rick_hou 发表于 2013-10-19 02:53:04

这个有点意义,可以深究下运行的速度。我觉得这个值得好好研究,甚至会改变一些人的编程习惯

smching 发表于 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;
}
}

tahoroom 发表于 2013-11-23 16:08:28

《Arduino技术内幕》这本书对于代码的优化讲的挺细致的,楼主可以看一下
页: [1]
查看完整版本: 01 两个闪灯实验的比较