Coding C for Arduino

Intro to C(++) and Arduino IDE

Emre Sener

2017-10-01

Introduction

If you’ve gone through the Arduino Pin by Pin tutorial, you’ve already used the Arduino IDE (Integrated Developing Environment). Understanding how to manipulate the hardware side of things using code is the key to using the UNO as a sensing platform. As programming is better “learned” than “taught” we’ll just jump in straight away^1 If you’re experienced in programming, you can pretty much skip everything in this document. Even so, make sure that you do understand the peculiarities of programming for microcontrollers vs. fully fledged computers!

My First Error Message

First things first, open up the Arduino IDE (version 3). Connect the UNO and select in the IDE using Tools->Port->your UNO port . Hopefully on your screen you’re seeing the code below

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

The comments^2 Comments start with two forward slashes (//) and are not evaluated, they’re there only to explain parts of code, sprinkle comments liberally within your code so that other people (and future you) can understand what’s going on explain the basic structure of our code very well. The setup chunk runs only once and anything in the loop section runs repeatedly.

As an example project we’ll be combining the PWM feature of the UNO and the Analog inputs to make a dimmable LED. A good way to start out is to write down, in broad terms, what we’ll need to code for this to work.

The wiring will look like this, use a 100-200 ohm resistor to limit LED current also watch out for LED polarity.

So lets be direct and write what we want down. Maybe the IDE is smart enough to parse English.

void setup() {
  
  Set pin A0 as input, set pin 3 as output.
}

void loop() {
  
  Read pin A0 adjust pin 3 accordingly
}

Copy this in and press the uplad button (arrow on the top left corner). A second later you should get an error message at the bottom that reads like this.


Users/Emre/Documents/Arduino/sketch_sep10b/sketch_sep10b.ino: In function 'void setup()':
sketch_sep10b:3: error: 'Set' was not declared in this scope
   Set pin A0 as input, set pin 3 as output.
   ^
/Users/Emre/Documents/Arduino/sketch_sep10b/sketch_sep10b.ino: In function 'void loop()':
sketch_sep10b:8: error: 'Read' was not declared in this scope
   Read pin A0 adjust pin 3 accordingly
   ^
exit status 1
'Set' was not declared in this scope

Not great, we seemed to have made a couple of mistakes. Lets fix them!