loading

Step 12: Write your own code

To write your own code, you will need to learn some basic programming language syntax. In other words, you have to learn how to properly form the code for the programmer to understand it. You can think of this kind of like understanding grammar and punctuation. You can write an entire book without proper grammar and punctuation, but no one will be abler to understand it, even if it is in English.

Some important things to keep in mind when writing your own code:

  • An Arduino program is called a sketch.
  • All code in an Arduino sketch is processed from top to bottom.
  • Arduino sketches are typically broken into five parts.
  1. The sketch usually starts with a header that explains what the sketch is doing, and who wrote it.
  2. Next, it usually defines global variables. Often, this is where constant names are given to the different Arduino pins.
  3. After the initial variables are set, the Arduino begins the setup routine. In the setup function, we set initial conditions of variables when necessary, and run any preliminary code that we only want to run once. This is where serial communication is initiated, which is required for running the serial monitor.
  4. From the setup function, we go to the loop routine. This is the main routine of the sketch. This is not only where your main code goes, but it will be executed over and over, so long as the sketch continues to run.
  5. Below the loop routine, there is often other functions listed. These functions are user-defined and only activated when called in the setup and loop routine. When these functions are called, the Arduino processes all of the code in the function from top to bottom and then goes back to the next line in the sketch where it left off when the function was called. Functions are good because they allow you to run standard routines - over and over - without having to write the same lines of code over and over. You can simply call upon a function multiple times, and this will free up memory on the chip because the function routine is only written once. It also makes code easier to read. To learn how to form your own functions, check out this page.
  • All of that said, the only two parts of the sketch which are mandatory are the Setup and Loop routines.
  • Almost all statements written in the Arduino language must end with a ;
  • Variables are storage compartments for numbers. You can pass values into and out of variables. Variables must be defined (stated in the code) before they can be used and need to have a data type associated with it. To learn some of the basic data types, review the Language Page.

Okay! So let us say we want to write code that reads a photocell connected to pin A0, and use the reading we get from the photocell to control the brightness of an LED connected to pin D9.

First, we want to open the BareMinimum sketch, which can be found at:

File --> Examples --> 1.Basic --> BareMinimum

The BareMinimum Sketch should look like this:
<pre>void setup() {
  // put your setup code here, to run once:

}

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

Next, lets put a header on the code, so other people know about what we are making, why, and under what terms:
<pre>/*
LED Dimmer
by Genius Arduino Programmer
2012

Controls the brightness of an LED on pin D9
based on the reading of a photocell on pin A0

This code is in the Public Domain
*/

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

}

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

Once that is all squared away, let us define the pin names, and establish variables:
<pre>/*
LED Dimmer
by Genius Arduino Programmer
2012

Controls the brightness of an LED on pin D9
based on the reading of a photocell on pin A0

This code is in the Public Domain
*/

// name analog pin 0 a constant name
const int analogInPin = A0; 

// name digital pin 9 a constant name
const int LEDPin = 9; 

//variable for reading a photocell
int photocell;

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

}

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

Now that variables and pin names are set, let us write the actual code:
<pre>/*
LED Dimmer
by Genius Arduino Programmer
2012

Controls the brightness of an LED on pin D9
based on the reading of a photocell on pin A0

This code is in the Public Domain
*/

// name analog pin 0 a constant name
const int analogInPin = A0; 

// name digital pin 9 a constant name
const int LEDPin = 9; 

//variable for reading a photocell
int photocell;

void setup() {
//nothing here right now

}

void loop() {
  //read the analog in pin and set the reading to the photocell variable
  photocell = analogRead(analogInPin);
  
  //control the LED pin using the value read by the photocell
  analogWrite(LEDPin, photocell);
  
  //pause the code for 1/10 second
  //1 second = 1000
  delay(100);  
}

If we want to see what numbers the analog pin is actually reading from the photocell, we will need to use the serial monitor. Let's activate the serial port and output those numbers:
<pre>/*
LED Dimmer
by Genius Arduino Programmer
2012

Controls the brightness of an LED on pin D9
based on the reading of a photocell on pin A0

This code is in the Public Domain
*/

// name analog pin 0 a constant name
const int analogInPin = A0; 

// name digital pin 9 a constant name
const int LEDPin = 9; 

//variable for reading a photocell
int photocell;

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

}

void loop() {
  //read the analog in pin and set the reading to the photocell variable
  photocell = analogRead(analogInPin);
 
  //print the photocell value into the serial monitor
  Serial.print("Photocell = " );                       
  Serial.println(photocell); 
  
  //control the LED pin using the value read by the photocell
  analogWrite(LEDPin, photocell);
  
  //pause the code for 1/10 second
  //1 second = 1000
  delay(100);  
}

For more information about formulating code, visit the Foundations Page. If you need help with the Arduino Language, then the Language Page is the place for you.

Also, the Example Sketch Page is a great place to start messing around with code. Don't be afraid to change things and experiment.

<p>Thanks for this Instructable. </p>
<p>Thanks for this Instructable. </p>
<p>Thanks for this Instructable. </p>
Learned how to use arduino. <br><br>now thevtime for make a arduino yourself
<p>I'm just getting started with Arduino and this Intro helped a lot. You made it simple and easy to understand. Thanks for writing it.</p>
<p>Hi, Your article was the mos comprehensive and easy to understand. </p><p>Can i have your permision to make video tutorial based on your article ? Please let me know</p><p>thnks</p>
<p>This article was the most comprehensive and easy-to-understand one I ever read, thanks!!</p>
<p>how can i code arduino uno for my project automatic alarm system connected to lcd 16x2 and rtc ds1302 controlled by arduino uno bluetooth?</p>
<p>I am new to arduino say me step to glow led and run motor </p><p>i have arduino uno R3 and arduino Mega 2560</p><p>also say simple project using LED, LDR, </p>
<p>Browse for a number of projects. You can do wonders with Arduino... Try them with interest. Definitely you will learn a lot.</p>
<p>Hi,</p><p>If you're looking for a tool to help you create the circuit schematics or code snippets, check this one:</p><p><a href="http://www.circuito.io/" rel="nofollow">www.circuito.io</a></p><p>It's free and fast</p>
<p>This is the best guide for beginners that I have come across. It will be a big help when I start creating my project. A former coworker bought me an Arduino UNO about 5 years ago and it was just sitting here collecting dust, I finally came up with a project to utilize it. I will be creating a ham radio repeater controller, which shouldn't be too hard to do for the basic controller but could get complex as I add more features to it.<br></p><p>I'll be doing this project in two stages.</p><p><br>First Stage Goals:</p><p>■ When the receiver squelch is triggered the arduino needs to trigger the transmitter to start transmitting (COR will go high or low, I need to check the radios to see if it goes high or low, when the radio receives a signal)<br>■ Route receive audio to transmitter <br>■ Every 10 minutes inject morse code audio into the transmit audio to satisfy FCC requirements<br><br>Second Stage Goals:<br>■ Add a couple second hang timer onto the end of each transmission (This will keep the transmitter keyed up for a couple seconds after the squelch signal is pulled low or high after it stops receiving a signal)<br>■ Add a courtesy tone at the end of each transmission<br>■ Add a time out timer (I might be able to do this on the radio but I prefer to try and do it on the Arduino)<br>■ Add DTMF decode functions to shut down the repeater (not sure if this will be doable)<br><br>For radios I will be using my set of Yaesu FT-7800r dual band radios, these radios have a 6 pin mini din connector on the back that will give me access to all the lines I will need.</p>
<p>Great info, thanks.</p>
<p>/port is not recognized by my laptop??</p><p>can i know what will be the reason??</p>
It might be because you don't have the right drivers for your laptop:)
<p>Thank you,found helpful............</p>
<p>how much small dc motors can I control with the arduino uno r3 I want the numper of motors that I can control with pwm and without pwm with on and off and direction</p>
THANK YOU! Really interesting and usefull.
<p>slt je suis terminale et mon projet un suiveur photovoltaique bi axiele mon probleme et le programme arduino pour 1 moteur pas &agrave; pas unipolaire tourne 9 h ( 7h &agrave; 16h) et puis retoure &agrave; l'etat initiale est attendre 14 h (16h &agrave; 7h ) et merciiiiii bcp </p>
<p>LOL: Step 12: You can think of this kind of like understanding grammar and punctuation. You can write an entire book without proper grammar and punctuation, but no one will be abler* to understand it, even if it is in English.</p><p>Great tutorial! Learned a lot.</p>
<p>I am considering building a collection of instructables on beginning Arduino.</p><p>Do I have your permission to include this instructable?</p>
Hi, I'm running Windows and I can't select the port for arduino uno. What could be wrong?
is arduino uno better than arduino mega
can I use arduino mega like arduino uno
<p>YES <br>ONLY DIFFERENCE IS THAT MEGA HAS MORE INPUT OUTPUT PINS</p>
<p>And more space than Uno ( 8x more space ) </p>
<p>GREAT INTRO FOR ARDUINO</p>
<p>Thanks! This is a great place to get started in the amazing world of Arduino. Bookmarked.</p>
Good. Guys you may visit this site to get more tutorials for free. http://electro.nitishdash.com
<p>great! like it</p>
sir. this arduino uno can transmit or send information to another computer?
So awesome
so helpful:-)
sir can me make a arduino at home????
<p>yes its possible...it will cost you around $8,here is the link </p><p>http://www.instructables.com/id/How-to-make-an-Arduino-from-scratch/?ALLSTEPS</p>
simply awesome
I bought a new Uno board, and it plugs in and lights up, but the serial port command is greyed out. <br> <br>I did select the Uno as my board. I reset it, I unplugged and replugged. <br> <br>I still cannot get the serial port to allow me to make a choice. <br> <br>Suggestions?
<p>The same thing happened to me, I had to reinstall the drivers. This helped</p><p>http://forum.arduino.cc/index.php?topic=104698.0</p>
...exchange it for a new one?
i obtained a 2nd one and same issue. I have windows 7, and downloaded the latest software. i will check for an update.
you might need to manually update the drivers, thats what i had to do with my mega 2560
<p>Exactly what I was looking for. Thanks.</p>
<p>my arduino does not seem to be connecting to the program i selected arduino uno and the program wont let me select a serial port NEED HELP PLEASE!!!</p>
<p>fantastic tutorial, Please keep inform us</p>
<p>I must say awesome article. The tutorial is fantastic very clear and understandable. The way you write is awesome. I understand almost everything what you taught in this tutorial. I must say thanks a lot for sharing your knowledge.</p>

About This Instructable

651,049views

2,449favorites

License:

Bio: My name is Randy and I founded the Instructables Design Studio. I'm also the author of the books 'Simple Bots,' and '62 Projects to ... More »
More by randofo:Beginner Electronics Projects DIY Candles Fun Robot Projects 
Add instructable to: