OpenWRT on BBB(2)

Cheetsheet For Using NFS

Following configuration use the 192.168.1.221’s tftp server and 192.168.1.11’s nfs server, why I use different nfs server because 192.168.1.11 runs ubuntu and could reached by nfs client easily.

setenv ipaddr 192.168.1.16
setenv serverip 192.168.1.221
tftpboot ${fdtaddr} am335x-boneblack.dtb
tftpboot ${kloadaddr} uImage
setenv bootargs console=ttyO0,115200n8 root=/dev/nfs rw nfsroot=192.168.1.11:/srv/nfs4/BBBrootfs ip=192.168.1.1 rootwait
bootm ${kloadaddr} - ${fdtaddr}

How to start more services

Current we only got following output:

procd: - init -
//.......
procd: - init complete -

From the Kernel Source code we know the init startup sequence:

$ cd /media/y/embedded/BBB/svnco/trunk/build_dir/target-arm_cortex-a9+vfpv3_uClibc-0.9.33.2_eabi/linux-omap/linux-3.14.4
$ cd init
$ vim main.c
if (!try_to_run_init_process("/etc/preinit") ||
	    !try_to_run_init_process("/sbin/init") ||
	    !try_to_run_init_process("/etc/init") ||
	    !try_to_run_init_process("/bin/init") ||
	    !try_to_run_init_process("/bin/sh"))
		return 0;

The preinit is called by /etc/preinit, while in this file, we found:

for pi_source_file in /lib/preinit/*; do
        . $pi_source_file
done

This means all of the preinit script is listed under NFS Server’s /lib/preinit/ folder.

Add our own preinit startup file:

[root@TrustyArch preinit]# ls
02_default_set_state  30_failsafe_wait             70_initramfs_test  90_init_console~
10_indicate_failsafe  40_run_failsafe_hook         80_mount_root      99_10_failsafe_login
10_indicate_preinit   50_indicate_regular_preinit  90_init_console    99_10_run_init
[root@TrustyArch preinit]# vim 90_init_console
#!/bin/sh
# Copyright (C) 2006-2010 OpenWrt.org
# Copyright (C) 2010 Vertical Communications

init_console() {
    preinit_echo "Called 90_init_console here!"
    if [ "$pi_suppress_stderr" = "y" ]; then
        exec <$M0 >$M1 2>&0
    else 
        exec <$M0 >$M1 2>$M2
    fi
}

boot_hook_add preinit_essential init_console
[root@TrustyArch preinit]# chmod 777 90_init_console
[root@TrustyArch preinit]# rm -f 90_init_console~ 

Now restart the BBB, to see if really take effects.
Also add a new file named 50_choose_console, with the setted M0 and M1, you could get your console.

$ cat 50_choose_console
#!/bin/sh
# Copyright (C) 2006-2010 OpenWrt.org
# Copyright (C) 2010 Vertical Communications

choose_console() {
    # the shell really doesn't like having stdin/out closed
    # that's why we use /dev/pty/m0 and m1 (or equivalent) as replacement
    # for /dev/console if there's no serial console available

    if grep -q devfs /proc/filesystems; then
        M0=/dev/pty/m0
        M1=/dev/pty/m1
        M2=/dev/pty/m1
    elif [ -x /sbin/hotplug2 ]; then
        M0=/dev/ptmx
        M1=/dev/ptmx
        M2=/dev/ptmx
    elif [ -x /sbin/udevd ]; then
        M0=/dev/pty/ptmx
        M1=/dev/pty/ptmx
        M2=/dev/pty/ptmx
    fi
    dd if=/dev/console of=/dev/null bs=1 count=0 >/dev/null 2>/dev/null && {
        M0=/dev/console
        M1=/dev/console
        M2=/dev/console    
    }
}

boot_hook_add preinit_essential choose_console

But I still cannot get the terminal.

git under proxy

This changes use the socks proxy for git.
Install connect-proxy in aur:

yaourt -S connect-proxy

Edit the proxy definition file:

[Trusty@~]$ cat socks5.sh 
#!/bin/sh
connect -S 127.0.0.1:1394 "$@"

Now directly set the

export GIT_PROXY_COMMAND=/home/Trusty/socks5.sh

Or change the proxy definition via:

[core]
        gitproxy = /home/Trusty/socks5.sh

Use TFTP/NFS Testing BBB Kernel

Prerequisite

You have a tftp server and NFS server configured, in my environment these 2 server runs on ArchLinux, ip address is 10.0.0.221, while BBB takes another ip address, for example, 10.0.0.16.

NFS Server Preparation

Create the nfs server’s rootfs for BBB Black ,and open all of the priviledges :

# pwd
/media/y/embedded/BBB/svnco/trunk/bin/omap
# mkdir /srv/nfs4/BBBrootfs
# tar xzvf openwrt-omap-Default-rootfs.tar.gz -C /srv/nfs4/BBBrootfs/
# chmod 777 -R /srv/nfs4/BBBrootfs/

Now you have the NFS Server available.

TFTP Server Preparation

Since we are using u-boot for booting, we need create uImage, but in OpenWRT, its default generated file is zImage, so we need use following command for generate our own uImage:

# mkimage -A arm -O linux -T kernel -C none -a 0x80008000 -e 0x80008000 -n "Linux" -d ./zImage ./uImage
Image Name:   Linux
Created:      Sun Nov  2 20:39:08 2014
Image Type:   ARM Linux Kernel Image (uncompressed)
Data Size:    1710568 Bytes = 1670.48 kB = 1.63 MB
Load Address: 80008000
Entry Point:  80008000

Also we have to copy the dtd file into our tftp folder:

[root@TrustyArch omap]# pwd
/media/y/embedded/BBB/svnco/trunk/bin/omap
[root@TrustyArch omap]# cp dtbs/am335x-boneblack.dtb /srv/tftp/

Easy Making Script

Following script will easy your life:

$ cat ~/autobuildnfs.sh
# First copy the kernel and dtd files into the tftp server
echo "##### Start copy to /srv/tftp####"
cp /media/y/embedded/BBB/svnco/trunk/bin/omap/openwrt-omap-zImage /srv/tftp/
cp /media/y/embedded/BBB/svnco/trunk/bin/omap/dtbs/am335x-boneblack.dtb /srv/tftp/
echo "###############Finished Copy!!!###############"
# Generate the uImage in /srv/tftp folder
mkimage -A arm -O linux -T kernel -C none -a 0x80008000 -e 0x80008000 -n "Linux" -d /srv/tftp/openwrt-omap-zImage /srv/tftp/uImage
# Remove the BBBrootfs content, all of them should be deleted. 
rm -rf /srv/nfs4/BBBrootfs/
mkdir -p /srv/nfs4/BBBrootfs
# Now extract the newly generatd rootfs into the /srv/nfs4/BBBrootfs
tar xzvf /media/y/embedded/BBB/svnco/trunk/bin/omap/openwrt-omap-Default-rootfs.tar.gz -C /srv/nfs4/BBBrootfs/

U-boot Configuration

CheetSheet

When system startup, click ‘enter’ for getting the u-boot prompt interface, then set following:

setenv ipaddr 10.0.0.16
setenv serverip 10.0.0.221
tftpboot ${fdtaddr} am335x-boneblack.dtb
tftpboot ${kloadaddr} uImage
setenv bootargs console=ttyO0,115200n8 root=/dev/nfs rw nfsroot=10.0.0.221:/srv/nfs4/BBBrootfs ip=10.0.0.16:::::eth0
bootm ${kloadaddr} - ${fdtaddr}

CheetSheet2

setenv ipaddr 192.168.1.16
setenv serverip 192.168.1.221
tftpboot ${fdtaddr} am335x-boneblack.dtb
tftpboot ${kloadaddr} uImage
# For NFS
setenv bootargs console=ttyO0,115200n8 root=/dev/nfs rw nfsroot=192.168.1.221:/srv/nfs4/BBBrootfs ip=192.168.1.16:::::eth0 rootpath=/etc/preinit
# NFS with 192.168.1.1
setenv bootargs console=ttyO0,115200n8 root=/dev/nfs rw nfsroot=192.168.1.221:/srv/nfs4/BBBrootfs ip=192.168.1.1:::::eth0 rootpath=/etc/preinit
# For SD-Card
setenv bootargs console=ttyO0,115200n8 root=/dev/mmcblk0p2 ro rootfstype=ext4 rootwait
bootm ${kloadaddr} - ${fdtaddr}

setting and testing the network

Set the ipaddr, and save it into the u-boot, next time you won’t set it again.

U-Boot# setenv ipaddr 10.0.0.16
U-Boot# printenv ipaddr
ipaddr=10.0.0.16
U-Boot# setenv serverip 10.0.0.221
U-Boot# ping 10.0.0.221
link up on port 0, speed 100, full duplex
Using cpsw device
host 10.0.0.221 is alive
U-Boot# saveenv

Load Files From TFTP

Use following commands for loading uImage and dtb files from 10.0.0.221:

U-Boot# tftpboot ${fdtaddr} am335x-boneblack.dtb
U-Boot# tftpboot ${kloadaddr} uImage

Set NFS Startup Parameter

Following will let the kernel startup from the nfs server.

setenv bootargs console=ttyO0,115200n8 root=/dev/nfs rw nfsroot=10.0.0.221:/srv/nfs4/BBBrootfs ip=10.0.0.16:::::eth0

Now startup:

bootm ${kloadaddr} - ${fdtaddr}

Start Debugging Under NFS

First we met following error:

[    1.015532] List of all partitions:
[    1.019292] No filesystem could mount root, tried: 
[    1.024439] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,255)

This is because we don’t enable NFS and ROOT on NFS in kernel configuration.
File System -> Network File System -> NFS Client Support, etc, see following picture:
/images/nfskernelconfigure.jpg

OpenWRT on BBB

This article will try to build and run OpenWRT on BBB(BeagleBone Black)

Checkout Code

Checkout the code from openwrt.org:

[Trusty@/media/y/embedded/BBB/OpenWRT]$ svn checkout -r 40887 svn://svn.openwrt.org/openwrt/trunk/
......
Checked out revision 40887.

Since the wiki said the only workable version for BBB is r40887, we just checkout this specified version.

Currently only runs with openwrt/trunk (r40887) and kernel 3.14.4. Kernel 3.13.7 (as in r40887 on target/linux/omap) will boot the device, but as soon as you attach a USB device, it will freeze.

Patches

Download the patch file from:http://bpaste.net/show/322887/

$ wget https://bpaste.net/raw/322887
$ wget https://bpaste.net/raw/322885
$ wget https://bpaste.net/raw/322902
$ mv 322885 Config_Kernel
$ mv 322902 Config_WRT
$ mv 322887 Patch_r40887

Notice, the first file should remove the unnecessary lines(patch for the source code).
Apply the patch:

[Trusty@/media/y/embedded/BBB/OpenWRT_r40887]$ ls
Patch_r40887  Patch_r40887~  trunk
[Trusty@/media/y/embedded/BBB/OpenWRT_r40887]$ cd trunk 
[Trusty@/media/y/embedded/BBB/OpenWRT_r40887/trunk]$ patch -p1 <../Patch_r40887
patching file target/linux/omap/Makefile
patching file target/linux/omap/config-default

Now your source file has been patched with the file that you downloaded.

Build OpenWRT

In ArchLinux install quilt:

$ sudo pacman -S quilt

Then initialize the kernel building via:

$ make target/linux/{clean,prepare} V=99
$ make kernel_oldconfig
$ make kernel_menuconfig # kernel config
$ make menuconfig # OpenWRT  config

When make target/linux/{clean, prepare} you should notice configure like this:
/images/parametersKernel.jpg
Then Load the downloaded .config file:
/images/saveKernelConfig.jpg
Save to .config file:
/images/save2KernelConfig.jpg
Your configuration should be seem like this:
/images/yourKernelconfig.jpg

When make the menuconfigs, load our configured kernel patch file.
Make:

$ make V=99 -j4

During building it will hint for some errors, solution is listed as:

1. Enable the network support during make kernel_menuconfig
2. Configure the git under proxy.     

Flash into SD Card

After building, the result should be available at:

$ pwd
/media/y/embedded/BBB/OpenWRT_r40887/trunk/bin/omap
$ ls
dtbs  md5sums  openwrt-omap-Default-rootfs.tar.gz  openwrt-omap-squashfs.img  openwrt-omap-zImage  packages  uboot-omap-am335x_evm  uboot-omap-omap3_beagle  uboot-omap-omap3_overo  uboot-omap-omap4_panda

Now insert a SD card and make the bootable sd card for BBB:
Since the Card we inserted has a Disklabel type of gpt, like following:

Disk /dev/sdd: 7.4 GiB, 7948206080 bytes, 15523840 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: F2D07CAF-BDA3-426B-AD79-DB2F3F27B3B8

So first we want to change it from gpt to dos, just like:

Disklabel type: dos

Use gdisk for converting the partition type from “GPT” to “MBR”, the command should be r(reovery and transformation options)-> g(convert GPT into MBR and exit) -> w(write the MBR partition table to disk and exit) -> y(Confirum).
Now the partition should be:

Device     Boot  Start      End  Sectors  Size Id Type
/dev/sdd1         2048   100351    98304   48M  e W95 FAT16 (LBA)
/dev/sdd2       100352 15523839 15423488  7.4G 83 Linux

Make filesystems via:

# mkfs.vfat -n boot /dev/sdd1
# mkfs.ext4 /dev/sdd2

Copy the existing boot partition (other sd cards) to newly created SD card.

# pwd
/run/media/Trusty/boot
# cp /media/y/embedded/BBB/OpenWRT_r40887/trunk/bin/omap/openwrt-omap-zImage ./zImage

In the second partition(/dev/sdd2), unextract the filesystem:

$ cp /media/y/embedded/BBB/OpenWRT_r40887/trunk/bin/omap/openwrt-omap-Default-rootfs.tar.gz  ./
$ tar xzvf openwrt-omap-Default-rootfs.tar.gz 
$ ls
bin  dev  etc  lib  lost+found  mnt  openwrt-omap-Default-rootfs.tar.gz  overlay  proc  rom  root  sbin  sys  tmp  usr  var  www

Besure your start-up parameter are like:

# For just using the same mmc part 2
console=ttyO0,115200n8
mmcroot=/dev/mmcblk0p2 ro
mmcrootfstype=ext4 rootwait fixrtc

After started the kernel, it will stucked.

Arduino Performance

Program Storage

Classical Blink program:

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the Uno and
  Leonardo, it is attached to digital pin 13. If you're unsure what
  pin the on-board LED is connected to on your Arduino model, check
  the documentation at http://arduino.cc

  This example code is in the public domain.

  modified 8 May 2014
  by Scott Fitzgerald
 */


// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

Compilation size:

Binary sketch size: 1,082 bytes (of a 32,256 byte maximum)

Comment the pinMode(13, OUTPUT), then the compilation size would be:

Binary sketch size: 948 bytes (of a 32,256 byte maximum)

Since PB5 is the output pin for 13, One command for replacing pinMode():

void setup() {
  // initialize digital pin 13 as an output.
  //pinMode(13, OUTPUT);
  bitSet(DDRB, 5);
}

Further:

void loop() {
  //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  bitSet(PINB, 5);
  delay(1000);              // wait for a second
  //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  bitSet(PINB, 5);
  delay(1000);              // wait for a second
}
Binary sketch size: 680 bytes (of a 32,256 byte maximum)

Use bitSet() for reverse the bit, then the size will greatly reduced.

Further reduction will consider replace the delay(1000) with an empty for() loop, which is listed as following:

  //delay(1000);              // wait for a second
  for (int i=0; i<32000; i++);

The binary size is:

Binary sketch size: 478 bytes (of a 32,256 byte maximum)

We could add following declaration:

  for (volatile int i=0; i<32000; i++);

Serial Communication

Origin serial communication source code:

void setup()
{
  Serial.begin(9600);
  Serial.println("Hello World!");
}

void loop()
{
  // Do Nothing.
}

Size is:

Binary sketch size: 2,034 bytes (of a 32,256 byte maximum)

Remove all of the functionality, then the size is:

Binary sketch size: 472 bytes (of a 32,256 byte maximum)

Directly manuplate the serial port hardware:

#define BAUD_RATE 9600
#define BAUD_RATE_DIVISOR (F_CPU/16/BAUD_RATE -1 )

void usart_putc(char c)
{
  loop_until_bit_is_set(UCSR0A, UDRE0);
  UDR0 = c;
}

void setup()
{
  //Serial.begin(9600);
  //Serial.println("Hello World!");
  UCSR0A = 0;
  UCSR0B = 1<<TXEN0;
  UCSR0C = 1<<UCSZ01 | 1<<UCSZ00;
  UBRR0 = BAUD_RATE_DIVISOR;
  usart_putc('!');
    usart_putc('m');
}

void loop()
{
  // Do Nothing.
}

Now the size is:

Binary sketch size: 528 bytes (of a 32,256 byte maximum)

Add one function for output sentence:

#define BAUD_RATE 9600
#define BAUD_RATE_DIVISOR (F_CPU/16/BAUD_RATE -1 )

void usart_putc(char c)
{
  loop_until_bit_is_set(UCSR0A, UDRE0);
  UDR0 = c;
}

void usart_puts(char *s)
{
  while(*s)
  {
    usart_putc(*s);
    s++;
  }
}

void setup()
{
  //Serial.begin(9600);
  //Serial.println("Hello World!");
  UCSR0A = 0;
  UCSR0B = 1<<TXEN0;
  UCSR0C = 1<<UCSZ01 | 1<<UCSZ00;
  UBRR0 = BAUD_RATE_DIVISOR;
  usart_puts("Hello, World!\n");
  //usart_putc('!');
  //usart_putc('m');
}

void loop()
{
  // Do Nothing.
}

The size changes to:

Binary sketch size: 542 bytes (of a 32,256 byte maximum)

Add version for output integers:

#define BAUD_RATE 9600
#define BAUD_RATE_DIVISOR (F_CPU/16/BAUD_RATE -1 )

void usart_putc(char c)
{
  loop_until_bit_is_set(UCSR0A, UDRE0);
  UDR0 = c;
}

void usart_puts(char *s)
{
  while(*s)
  {
    usart_putc(*s);
    s++;
  }
}

void usart_puti(long i)
{
  char s[25];
  itoa(i, s, 10);
  usart_puts(s);
}

void setup()
{
  //Serial.begin(9600);
  //Serial.println("Hello World!");
  UCSR0A = 0;
  UCSR0B = 1<<TXEN0;
  UCSR0C = 1<<UCSZ01 | 1<<UCSZ00;
  UBRR0 = BAUD_RATE_DIVISOR;
  usart_puts("Hello, World!\n");
  usart_puti(1000);
  //usart_putc('!');
  //usart_putc('m');
}

void loop()
{
  // Do Nothing.
}

Because we called itoa(), so in this version the size will greatly improved to:

Binary sketch size: 782 bytes (of a 32,256 byte maximum)

SRAM

Edit the preference of Arduino, under the /root/.arduino/preference.txt:

build.verbose=true

Then build and you will see the tmp file.

Install following packages on Archlinux:

$ sudo pacman -S avr-gcc
$ sudo pacman -S avr-gdb avrdude simavr avr-libc

Then you can use avr-size to view the generated elf file size:

$ avr-size /tmp/build7485065177781002113.tmp/BareMinimum.cpp.elf
   text    data     bss     dec     hex filename
    472       0       9     481     1e1 /tmp/build7485065177781002113.tmp/BareMinimum.cpp.elf

Or more detailed:

$ avr-size -C --mcu=atmega328p /tmp/build7485065177781002113.tmp/BareMinimum.cpp.elf
AVR Memory Usage
----------------
Device: atmega328p

Program:     472 bytes (1.4% Full)
(.text + .data + .bootloader)

Data:          9 bytes (0.4% Full)
(.data + .bss + .noinit)

Add some definition of global variables:

char c;
char msg[]="This is a message";
void setup() {
  // put your setup code here, to run once:
  c = msg[0];

Check the size:

$ avr-size -C --mcu=atmega328p /tmp/build7485065177781002113.tmp/BareMinimum.cpp.elf
AVR Memory Usage
----------------
Device: atmega328p

Program:     498 bytes (1.5% Full)
(.text + .data + .bootloader)

Data:         28 bytes (1.4% Full)
(.data + .bss + .noinit)

Use pgmspace

If we use pgmspace, then the source code would be:

/*
 PROGMEM string demo
 How to store a table of strings in program memory (flash), 
 and retrieve them.

 Information summarized from:
 http://www.nongnu.org/avr-libc/user-manual/pgmspace.html

 Setting up a table (array) of strings in program memory is slightly complicated, but
 here is a good template to follow. 

 Setting up the strings is a two-step process. First define the strings.

*/

#include <avr/pgmspace.h>
prog_char string_0[] PROGMEM = "String 0";   // "String 0" etc are strings to store - change to suit.
prog_char string_1[] PROGMEM = "String 1";
prog_char string_2[] PROGMEM = "String 2";
prog_char string_3[] PROGMEM = "String 3";
prog_char string_4[] PROGMEM = "String 4";
prog_char string_5[] PROGMEM = "String 5";


// Then set up a table to refer to your strings.

PROGMEM const char *string_table[] = 	   // change "string_table" name to suit
{   
  string_0,
  string_1,
  string_2,
  string_3,
  string_4,
  string_5 };

char buffer[30];    // make sure this is large enough for the largest string it must hold

void setup()			  
{
  Serial.begin(9600);
}


void loop()			  
{
  /* Using the string table in program memory requires the use of special functions to retrieve the data.
     The strcpy_P function copies a string from program space to a string in RAM ("buffer"). 
     Make sure your receiving string in RAM  is large enough to hold whatever
     you are retrieving from program space. */


  for (int i = 0; i < 6; i++)
  {
    strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy. 
    Serial.println( buffer );
    delay( 500 );
  }
}

Check the size:

$ avr-size -C --mcu=atmega328p /tmp/build7485065177781002113.tmp/sketch_oct29b.cpp.elf
AVR Memory Usage
----------------
Device: atmega328p

Program:    2324 bytes (7.1% Full)
(.text + .data + .bootloader)

Data:        225 bytes (11.0% Full)
(.data + .bss + .noinit)

Replace back to ordinary conditions:

/*
 PROGMEM string demo
 How to store a table of strings in program memory (flash), 
 and retrieve them.

 Information summarized from:
 http://www.nongnu.org/avr-libc/user-manual/pgmspace.html

 Setting up a table (array) of strings in program memory is slightly complicated, but
 here is a good template to follow. 

 Setting up the strings is a two-step process. First define the strings.

*/

char string_0[] = "String 0";   // "String 0" etc are strings to store - change to suit.
char string_1[] = "String 1";
char string_2[] = "String 2";
char string_3[] = "String 3";
char string_4[] = "String 4";
char string_5[] = "String 5";


// Then set up a table to refer to your strings.

const char *string_table[] = 	   // change "string_table" name to suit
{   
  string_0,
  string_1,
  string_2,
  string_3,
  string_4,
  string_5 };

char buffer[30];    // make sure this is large enough for the largest string it must hold

void setup()			  
{
  Serial.begin(9600);
}


void loop()			  
{
  /* Using the string table in program memory requires the use of special functions to retrieve the data.
     The strcpy_P function copies a string from program space to a string in RAM ("buffer"). 
     Make sure your receiving string in RAM  is large enough to hold whatever
     you are retrieving from program space. */


  for (int i = 0; i < 6; i++)
  {
    //strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy. 
    strcpy(buffer, (char*)(&(string_table[i]))); // Necessary casts and dereferencing, just copy. 
    Serial.println( buffer );
    delay( 500 );
  }
}

Then the size would be:

$ avr-size -C --mcu=atmega328p /tmp/build7485065177781002113.tmp/sketch_oct29c.cpp.elf
AVR Memory Usage
----------------
Device: atmega328p

Program:    2320 bytes (7.1% Full)
(.text + .data + .bootloader)

Data:        291 bytes (14.2% Full)
(.data + .bss + .noinit)


Performance

Use Arduino for test the performance of Arduino:

void setup()
{
  Serial.begin(9600);
  Serial.println("Arduino performance test begins now.");
}
extern volatile unsigned long timer0_millis;

void loop()
{
  unsigned long i = 0;
  unsigned long stop_time;
  
  stop_time= millis() + 1000;
  
  while(timer0_millis <stop_time) i++;
  
  Serial.print(i);
  Serial.println(" loops in one second.");
  while(1);
}

The result from the serial port:

Arduino performance test begins now.
836912 loops in one second.

Test for digitalwrite():

  while(timer0_millis <stop_time) 
  {
    digitalWrite(13, HIGH);
    digitalWrite(13, LOW);
    i++;
  }

Output:

Arduino performance test begins now.
111198 loops in one second.

If we change the functionality into:

  while(timer0_millis <stop_time) 
  {
    //digitalWrite(13, HIGH);
    //digitalWrite(13, LOW);
    bitSet(PORTB, 5);
    bitClear(PORTB, 5);
    i++;
  }

Then the performance result will be:

Arduino performance test begins now.
691362 loops in one second.

Slow Down CPU

We change the prescale clock frequency, thus we could get a power-saving mode, which will consume less power.

/* Slow down the avr cpu speed*/
void setup()
{
  Serial.begin(9600);
  Serial.println("Normal serial communiation at 9600 bps");
  
  pinMode(13, OUTPUT);
  
  noInterrupts();  //disable interrupts temporarily
  CLKPR = 1<<CLKPCE;  // enable clock prescaler write sequence
  CLKPR = 8;  // 62,500(0.0625MHZ), comparing to 16, 000, 000(16MHZ)
  interrupts();  //re-enable interrupts
}

void loop()
{
  digitalWrite(13, HIGH);  //LED is on
  delay(10);  //0.01 second delay
  digitalWrite(13, LOW);  // LED is off
  delay(10);
}

Let CPU sleep

Via set_sleep_mode() and sleep_mode() we could let CPU sleep for power-saving.

/* putting CPU into sleep */
#include <avr/sleep.h>
extern volatile unsigned long timer0_millis;

void setup()
{
  pinMode(13, OUTPUT);   // an LED is attached to D13
  Serial.begin(9600);
}

void loop()
{
  while(timer0_millis<1000)
  {
    set_sleep_mode(SLEEP_MODE_IDLE);  // select "lightly napping "
    sleep_mode();  // go to sleep
  }
  timer0_millis = 0;   // reset millisecond counter
  bitSet(PINB, 5);    // toggle LED
  Serial.println("I am waked!");
}