1 Why pure C?
The popularity of Arduino is mainly because of its beginner-friendly IDE. The Arduino IDE automatically sets up the compiling process so that your sketch is compiled together with the Arduino Core C++ library code.
The IDE hides both the lib code and the compiling process, so beginners find it so simple to start writing a sketch. But for a seasoned programmer, the IDE makes what actually happens under the hood invisible and confusing.
Also, the framework provided by Arduino Core lib limits the flexibility of your project design. And the C++ part makes many pure C programmers frustrated.
What's more, for a command-line user, a GUI IDE is not acceptable.
So, as a result, a more low-level Arduino programming environment is necessary for many developers.
2 C toolchains for Arduino
Fortunately, all the real work behind the IDE is done by command-line tools.
- avr-gcc is the C compiler
- avr-gcc-c++ is the C++ compiler ( It's not needed for our Pure C env)
- avr-binutils is the binary tools including the linker.
- avr-libc is the standard C lib
- avrdude is used for uploading your program to the Arduino board.
avrdude works with many different programmers ( the device, not human here). For Arduino UNO, a bootloader is already in place on the built-in flash memory of Atmega328P MCU. This bootloader is used as an ISP tool to write your program into the Atmega328p's flash. avrdude works well with this bootloader. Actually, the Arduino IDE uses avrdude too.
All these packages are free and open-sourced!
3 Set up a development environment
3.1 Install packages
The following steps are for CentOS 7.
$ yum install avr-binutils
$ yum install avr-gcc
$ yum install avr-libc
$ yum install avrdude
3.2 user config
From the developing computer's view, the Arduino board is actually a USB to COM device.
$ ls -l /dev/ttyACM0
crw-rw----. 1 root dialout 166, 0 Jun 11 02:42 /dev/ttyACM0
In order for a user to have permission to use this device, it must belong to the "dialout" group.
e.g the user is named user01, then
$ sudo usermod -aG dialout user01
Then logout and re-login user01 to make sure the settings are effective.
4 First pure C example: led.c
led.c:
#include <avr/io.h>
#define F_CPU 16000000UL
#include <util/delay.h>
int main (void)
{
// Arduino digital pin 13 (pin 5 of PORTB) for output
DDRB |= 0B100000;
while(1) {
// turn LED on
PORTB |= 0B100000;
_delay_ms(1000);
// turn LED off
PORTB &= ~ 0B100000;
_delay_ms(1000);
}
}
The compile process is as below.
# compile
$ avr-gcc -Os -mmcu=atmega328p -c -o led.o led.c
# link
$ avr-gcc -mmcu=atmega328p -o led
# generate hex format file
$ avr-objcopy -O ihex -R .eeprom led lex.hex
# upload to Arduino board
$ avrdude -F -V -c arduino -p atmega328p -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex
No comments:
Post a Comment