Arduino Embedded C

Introduction

A few years ago I finally broke down and bought an Arduino microprocessor board. It seemed a good, economical way of brushing up on my microprocessor skills, and with all the available accessories I could even expand my horizons a bit. Since then I’ve gone the usual route with blinking LEDs and buzzing buzzers galore. I’ve even explored networked devices with my trusty Ethernet shield.

Up until now, I’ve been using the Arduino IDE which is a good, painless way of getting programs running on the board. It uses a subset of the ‘C’ language with easy access to several software libraries and on-board functions such as timers and I/O ports. The ease of operation however, comes at the expense of some of the efficiency of full scale embedded ‘C’, and hides some useful details of the microprocessor from the user. In the loop() routine for example, not only are the functions of the program carried out but the routine continually checks background functions like the serial port and timers. The analogRead() function always selects the analog channel before doing a conversion, which significantly slows down operation.

There are ways around these issues of course, but by the time you’ve implemented them, your code starts to resemble an embedded ‘C’ program, so it might be time to bite the bullet and start programming in C. Another reason for programming microprocessors in C is that C has become the de-facto standard for microprocessor development, so if you switch devices you will have running start at your new environment.

That said I looked around for different C programming environments for Arduino sand AVR microprocessors. I’m familiar with IDE style development systems for Microchip and T.I. devices, and even PC development systems like Visual C++ and Java, so I finally settled on the Atmel Visual Studio 7 system. It meets my requirements, and the price is right (free).

What follows is a brief outline of the installation, and configuration of the system with a couple of small examples thrown in. Most of the content is based on sources from around the Web, particularly: https://slightlyovercomplicated.com/2015/11/13/programming-arduino-with-atmel-studio-7/

I’ve added some clarification where necessary.

It’s also a requirement that the Arduino IDE is installed on your PC, since Visual Studio 7 uses some of its libraries.

1. Installation

Atmel studio can be found at Atmel’s webite here http://www.atmel.com/microsite/atmel-studio/. Clicking the ‘Download’ button takes you to the ‘Overview’ page which outlines the requirements of the system and allows a choice of installation methods. I opted for the Web installation method for my Windows 10 operating system. Once the download is complete, follow the installation steps

2. Find the Arduino COM Port

Make sure the Arduino board is plugged into the PC. Visual Studio will need the COM port number to talk to the Arduino. There are two ways to find this:

  • Use the Arduino IDE
    Make sure the Arduino is plugged into the PC via the USB cable. Go to the Tools menu on the Arduino IDE, and read the Port Number. In this case COM3.

  • Using the Windows Control Panel
    With the Arduino plugged into the PC, go to the PC’s Control Panel. Click the System icon, then the Device Manager icon. Expand Ports (COM & LPT). The Arduino COM port should be listed here (COM3).

 

3. Configuring Programming Tools

The Arduino IDE uses a program called AVRDude to write a compiled HEX file to the microprocessor via the device programmer. Atmel studio uses the same program which needs to be configured in the IDE.

To configure AVRDude, perform the following steps:

  • Launch Atmel Studio and once loaded, click Tools > External Tools….
  • In Title text box enter an appropriate description (Arduino COM3 in this example) and click Add.
  • In Command text box enter full path to AVRdude executable. This should be located in the hardware\tools\avr\bin subdirectory of Arduino IDE installation directory. If you haven’t changed Arduino IDE’s default installation, the file should be located as per the below:
C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe
  • In the Arguments text box add the following parameters and values (note that parameters are case-sensitive):

-C<Path_to_avrdude.conf> – a path to avrdude.conf, you can find this file in Arduino IDE’s installation directory. Ensure you enter the path in quotes in case there are any spaces in your path.
-p<part number> – AVR processor model
-c<programmer type> – programmer type being used to program the board
-P<port> – COM port you should have noted in stage 2
-b<baud rate> – baud rate for the programmer
-D – disables auto erase for flash memory (required for wiring programmer used with Arduino ATMega 328)
-U<memorytype>:<operation>:<path to HEX file>:<format> – this is where you should leverage Atmel Studio’s variables to always point to freshly complied and generated HEX file. List of variables and their descriptions can be found at Atmel’s help page.

Based on the above, the command for an Arduino UNO with an ATMega329p microprocessor takes following form:

-C"C:\Program Files (x86)\Arduino\hardware\tools\avr\etc\avrdude.conf" -patmega328p -carduino -P\\.\COM3 -b115200 -D -Uflash:w:"$(ProjectDir)Debug\$(TargetName).hex":i

  • As shown above, I’ve de-selected the remaining options except ‘Use Output Window’. This displays compiler information (errors etc.) in a text box at the bottom of the IDE. De-selecting will display messages in a command prompt, so its largely personal preference.
  • Click OK to accept the changes and close the window.

4. Create a new project and test the upload

  • In Atmel Studio select File > New Project….
  • From the left hand pane highlight C/C++, select GCC C Executable Project and name your project accordingly.
  • Ensure Create directory for solution tick box is selected and click OK.
  • Select the Device -> Atmega328p
  •  From Solution Explorer window open main.c file.
  •  Copy and paste the following code to make the on-board LED (digital pin 13) blink. The code is applicable for Arduino Uno, but may be tweaked for different pin-outs and setup.
/*
 * Blink.c
 *
 */ 

#define F_CPU 16000000L // Specify oscillator frequency
#include <avr/io.h>
#include <util/delay.h>


int main(void)
{
 DDRB = 0b00100000; // configure pin 5 of PORTB as output (digital pin 13 on the Arduino UNO)
 
 while(1)
 {
 PORTB = 0b00100000; // set 5th bit to HIGH
 _delay_ms(500);
 PORTB = 0b00000000; // set 5th bit to LOW
 _delay_ms(500);
 }
}
  • Compile your project by selecting Build > Build Solution (or by simply pressing F7).
  • Check the Output window at the bottom and ensure the project has compiled successfully.
Build succeeded. 
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
  • Program your board by selecting Tools > Arduino COM3.
  • Check the output window at the bottom and ensure it flashed the memory successfully and be amazed by the blinking LED!
avrdude.exe: safemode: Fuses OK (E:00, H:00, L:00)
 avrdude.exe done. Thank you.

5. The Terminal Window Extension

One of the more useful features of the Arduino IDE is the Serial Monitor. It is the main link for testing and debugging programs, and interfacing with the PC. While there is no default serial monitor with Atmel Studio, its easy to add one.
The Terminal Window can be installed by performing the following steps:

  • From the Atmel Studio Tools menu, click on Extensions and Updates. The menu below will show a variety of available extensions including the Terminal Window.

  • Select Terminal for Atmel Studio and click Download and follow the installation steps. You may have to re-start Atmel Sudio.
  • After re-starting, the Terminal Window should be found in the IDE View menu. From there you can configure the baud-rate and data format.

6. Testing the Terminal Window
No tutorial would be complete without a “Hello World” program, so here’s a small, self contained, not very useful one which will test the Terminal Window.

  • From the File menu, select New->Project. Name the project HelloWorld, and select the device to  Atmega328p.
  • Enter the following program into main.c:
    #include <avr/io.h>
    
    #define BAUD 0x33
    
    void usart_init(void)
    {
     UCSR0B = (1<<TXEN0);
     UCSR0C = (1<<UCSZ01) | (1<<UCSZ00);
     UBRR0L = BAUD;
    }
    
    void usart_send(unsigned char ch)
    {
     while (!(UCSR0A & (1<<UDRE0)));
     UDR0 = ch;
    }
    
    int main(void)
    {
     unsigned char str[30] = "Hello World";
     unsigned char strLength = 13;
     unsigned char i = 0;
     
     usart_init();
     
     while (1)
     {
     usart_send(str[i++]);
     if (i >= strLength) i = 0;
     }
    }
  • Program the Arduino via Tools->Arduino COM3
  • From the View menu, select Terminal Window. Set the baud rate to 19200, and the data format to ASCII.
  • Click the Connect button, and watch the Arduino print out “Hello World” ad nauseam. When the excitement has died down, click the Disconnect button to stop the serial transfer, then clear the receive window.

Conclusion

This tutorial has covered the basics of C programming for the Arduino. A good next step might be to try converting some Arduino IDE type programs to embedded C. If you use an Arduino, you also have a fair development platform which can be used as a stepping stone to custom microprocessor projects using any of the Atmel devices.