Archive for April, 2008

Structuring Arduino code

Posted on April 23rd, 2008 in programming | No Comments »

One of the most important things in programming is writing understandable and readable code. Despite the fact that usually when you deal with electronics you have to write the code in very low level language, Arduino syntax is very close to such high level programming languages as C and PHP. If you know any of these languages, I bet there will be no problems for you.
The basic way of structuring your Arduino code is writing a normal procedural code. If we recall the example arduino code from the previous post, it was something like this:

if (condition){
    digitalWrite(ledPin, HIGH);
    delay(300);
    digitalWrite(ledPin, LOW);
    delay(300);
    digitalWrite(ledPin, HIGH);
    delay(300);
    digitalWrite(ledPin, LOW);
    delay(300);
}else{
    digitalWrite(ledPin, HIGH);
    delay(300);
    digitalWrite(ledPin, LOW);
    delay(300);
}

There is no problem with the code unless you want to give it to other people or be satisfied with the job you have done. The trick is that you can easily replace the identical parts with functions. Normally you can replace the 4 lines with just one function call:

if (condition){
    blinkLed(300);
    blinkLed(300);
}else{
    blinkLed(300);
}

or even better

if (condition){
    blinkLed(2, 300);
}else{
    blinkLed(1, 300);
}

And the definition of the function:

void function blinkLed(times, lengthms){
    for (int i = 0; i < times, i++){
        digitalWrite(ledPin, HIGH);
        delay(lengthms);
        digitalWrite(ledPin, LOW);
        delay(lengthms);
    }
}

The idea is simple - you choose the time in milliseconds the led will be on and the number of times the blink operation should be done. That’s it. Now if we include this code in the previous example, the code looks cleaner as well as is readable easier:

int ledPin = 13;
int usbnumber = 0;
void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    if (Serial.available() > 0) {
        usbnumber = Serial.read();
    }

    if (usbnumber > 0) {
        if (usbnumber % 2 == 0){
            blinkLed(1,300);
        }else{
            blinkLed(2,300);
        }
        usbnumber = 0;
    }
}

void function blinkLed(times, lengthms){
    for (int i = 0; i < times, i++){
        digitalWrite(ledPin, HIGH);
        delay(lengthms);
        digitalWrite(ledPin, LOW);
        delay(lengthms);
    }
}

I don’t think it’s worth to rewrite the arduino website here, so go on and check out the function declaration manual.

Controlling Arduino via USB using PHP

Posted on April 21st, 2008 in programming | No Comments »

As stated before, I have rather good experience in PHP programming. I’ve done many different things using PHP, starting from simple web applications to huge social network applications with tens of thousands simultaneous online users. I’ve also done some PHP applications that are used as servers for other software and even some basic desktop applications. With all that in mind, today I wanted to play around with Arduino and PHP. This might sound sick, but if you’ve read the previous posts, then you already know that PHP is my language of choice. The reason for this is simple - PHP can do a lot more than simple web applications. And if I know PHP, why do I need to learn other languages? Besides that I believe there are other programmers just like me - learning Arduino and having PHP experience in background. Actually the following post will work with any other programming language that can access serial ports.

Ok, enough talking, let’s get to the task. Actually I would like to divide it into two separate tasks:

  1. Learn to communicate to Arduino using PHP
  2. Write some PHP code and Arduino program that works together

Tying together the Arduino and PHP

Normally you can’t access directly USB devices, like you were able to connect and directly write some data to printer or COM port. For most USB devices you need to have a special driver that does the dirty job for you. Fortunately the designers of Arduino have done the USB connection a bit different way. Actually Arduino is working via USB serial controller, which means that you can open the USB port and write data directly to Arduino just like you can do it with LPT, and COM ports. If we remember our task, it’s exactly what we need - directly write some data from PHP to Arduino and process them on the board without any driver usage.

The next thing is to get the PHP to write some data to the USB port. When you open up your Arduino development environment, you can see which “com” port the Arduino board is connected to. Check once more the number of the port used and look at the code below:

$fp =fopen("com3", "w");
fwrite($fp, chr(1));
flose($fp);

The communication with COM ports from PHP is straightforward. Just open a file pointer to “comX” where X is the number of COM port and write some data to that COM port. In the example above we connect to COM3 port and write integer number 1 to that port (notice the chr(x) function - we can’t just directly write the integer, we need to encode it into ASCII character and chr() does just that).

So far so good. Now we need to decide what we will send to Arduino board and what we will want the arduino board to do for us. I guess the most easy task to check our skills is just passing random integers to arduino board, using one diode, which will flash one or two times depending on the parity of number passed.

Ok, let’s build up some Arduino code:

int ledPin = 13;
int usbnumber = 0;
void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    if (Serial.available() > 0) {
        usbnumber = Serial.read();
    }

    if (usbnumber > 0) {
        if (usbnumber % 2 == 0){
            digitalWrite(ledPin, HIGH);
            delay(300);
            digitalWrite(ledPin, LOW);
            delay(300);
        }else{
            digitalWrite(ledPin, HIGH);
            delay(300);
            digitalWrite(ledPin, LOW);
            delay(300);
            digitalWrite(ledPin, HIGH);
            delay(300);
            digitalWrite(ledPin, LOW);
            delay(300);
        }
        usbnumber = 0;
    }
}

Ok, let’s get through this step by step. Just before the setup function we define that we will use the 13th pin for output, besides that we initialize the variable that will hold the number read from USB. In the setup function we define that the ledPin will be used for output and we start up the USB connection. In the main loop we check whether there is any data available on the USB connection. If there is any data, we just read the data to our usbnumber variable. Later on the loop we check if the number read is greater than zero. If it is, we know that some data has been read. We check if the number can be divided by two. If the remainder is zero, we flash the LED one time. If the reminder is 1 (the number we have read can not be divided by two), we flash the led two times.

Ok, so far with the arduino code. Let’s build some more PHP code:

$fp =fopen("com3", "w");
while (true){
    $i = ($i + 1) % 10;
    echo "Wrote $i - the LED should flash (" . ($i % 2 == 0 ? ' 1 time ' : '2 times ') . ")\r\n";
    fwrite($fp, chr($i));
    sleep(3);
}
fclose($fp);

There’s not that much of new things to talk about. Just like in the previous PHP code exmaple, this one is also opening a COM3 connection. The new part is the infinite loop, which contains the number writing to COM3 port. The code is simple - just increase the variable $i by one and take the modulus of the number. Afterwards just log some debug information to console and write the data to USB. After writing the data, just sleep for 3 seconds and repeat the loop.

Ok, the last bits of this long writeup:

  1. we need to upload the arduino code to our board
  2. we need to run the PHP code

The first one should be straightforward for everyone, just hit the appropriate button on the arduino development environment toolbar. The second one could be tricky for some people. But I’ll try to explain how I do it. Let’s pretend I’ve downloaded the Windows binary installation of PHP 5.2 and unzipped it to c:/php/. I enter the windows command line, change the directory to c:/php and type php c:/path/to/usb/php/script.php. Done! Watch the LED on the Arduino board and track the debug info on the commandline window.

Summary

I’ve learned some new things:

  • Basic controlling of Arduino board from PHP
  • The only pin that you can use without resistors is the 13th pin. To use leds directly with other pins you should use resistors. As you might imagine I don’t have any at the moment, so I’m just sticking to using just the 13th pin. I guess I’ll need to get more into the electronics stuff to achieve something more.

Well, that’s it for now. If there are any questions/comments - the comment form is below. I guess I’ll try to check out the Serial interface a bit deeper to find out what exactly you can do with the USB port. And one of the next things to find out will be the option to write functions to do common things. The arduino part of this example is begging for some refactoring.

Hold on and wait for the next posts. By the way, you can use the RSS feed to read the latest posts of this blog automatically.

Getting started with Arduino

Posted on April 18th, 2008 in programming | No Comments »

Ok, let’s get started with Arduino. You’ve decided that you want to learn some electronics and don’t have any clue on where to start. I was exactly in the same situation a while ago. I had bought the “electronics for dummies” book, red some paragraphs of it about resistors and some other components, but I had no idea on how to connect them and make them do things I need. The arduino is exactly what a beginner needs - it has very simple programming language, it can be connected directly to your computer via USB cable.

The first step obviously is getting a arduino board. The interesting thing is you can choose - you can build your own board or buy a ready made. I don’t think it’s wise for beginners to build the board themselves. As I live in Latvia, where there are no arduino board resellers, I chose to order one from CoolComponents. It cost me a total of GBP 25, which is quite few if we compare to other development board programmers and software packages needed. The best part is that the arduino development environment (the code editor) is free.

Ok, we’ve got the programming board, what next? I need to connect it to my computer and get some electronic components to do the testing of the board. You can buy a USB cable, but I chose to use one from my printer. As about the components, I had no clue about what I need, so I took a look at the arduino website getting started guide and saw that the only thing you need to get started with programming is a single diode, which you can get for a dime in the local electronics store.

Despite the fact that arduino website tells you that you need to install drivers for Windows, my Windows XP Pro downloaded all the drivers for arduino automatically right after connecting it to my PC. If you use other operating system, probably you’ll need to follow the guide in the arduino website.

So far so good, I decided I’m ready for the first tutorial from the arduino website. The tutorial shows you how to blink a LED. Nothing special, but quite useful for beginners. I put the LED in the digital output 13 and GND in the arduino board and just did a copy and paste from the tutorial page. The first upload to the arduino board .. and a couple of seconds later my circuit is running! The LED is blinking. WOW!

int ledPin = 13; // LED connected to digital pin 13

void setup()
{
	pinMode(ledPin, OUTPUT); // sets the digital pin as output
}

void loop()
{
	digitalWrite(ledPin, HIGH);   // sets the LED on
	delay(1000);                  // waits for a second
	digitalWrite(ledPin, LOW);    // sets the LED off
	delay(1000);                  // waits for a second
}

Basically this is a very simple program. Each of the arduino programs consist of two parts. The setup and loop functions. The setup function is executed once upon the startup of the circuit, while the loop function is executed over and over while the circuit is running. Before the setup function we can define some variables. In this case we define the ledPin variable which will contain the number of pin we use for the LED. As we can see the setup function just defines that the 13th pin will be used for output. The loop function ouputs the current to 13th pin, then waits for 1000ms (which is 1 second) and then turns off the current and waits for another 1000ms. After the delay of 1000ms averything starts from the beginning - the led is turned on again. You can play around with the delay values and re-upload the program to the board. The satisfaction is guaranteed.

If you have done any C/C++ or PHP programming, the syntax should be straightforward to you. As I’ve been doing PHP programming for some 5 years now and I have some basic C/C++ and other programming language background I didn’t have any problems with this.

Ok, that’s for the very basics, get ready for the next things!

Intro about me and my aims

Posted on April 17th, 2008 in General | No Comments »

I’m a beginner in electronics and this blog is intended to help me share the things I will learn. At the moment I’ve started to study Arduino programming and I enjoy it so far. Just to be sure where things are going, there are a couple of aims for me:

  1. Learn to use those small 8×2, 16×2 LCD screens to display some data my arduino calculates.
  2. Learn to use motors to move around the arduino powered robots.
  3. Create a line-follower robot (a machine that can read a line on the ground and follow it without any human interaction)

These are just the first three of my closest aims. At the moment I have no experience in electronics and that’s the most interesting part I guess. If you are ready to start learning the electronics step by step with me, then just hold on.

As about myself - I have some programming background and propper education to do it. I have a masters degree in computer science, however I have studied no electronics in my life before. I’ve been programming PHP and creating web applications for 5 years now. It’s time for something new. As you might imagine, PHP is a rather simple language and that’s the way I take things. If I need to do some simple programming, PHP is my language of choice. The last but not least - my mother language is not English, so please excuse me for the language mistakes.

Ok, just hold on and follow the news!