Arduino, Electronics, Tutorials

How to communicate with an Arduino via Serial using PHP code

Introduction

I recently got my hands on a 7-segment display module (always wanted to play with those!) for a little project and at first I wanted to use purely PHP on a Raspberry Pi Zero to control it. However, due to lack of time (and a touch of lazyness) I ended up using an Arduino with the default library associated with this module (TMI637.h), and while looking for ways in which I could send data to the display through PHP code I figured it was really easy to use serial communication for that! It’s fun because you can run your PHP code on your computer and send output to the Arduino via USB. You can create a lot of fun stuff with that – think about notifications, counters, and all sorts of things using Arduino for output coming from your computer via PHP.

This quick/simple tutorial will show how to control an RGB LED via serial with PHP code, from a computer connected to an Arduino board via USB.

Requirements

  • Arduino Micro or any other Arduino / Arduino-clone board with USB connection (the Micro uses micro USB as both power input and communication, so it’s quite easy)
  • 1x RGB LED
  • 3x 220ohm resistor
  • Breadboard
  • 1x Jumper wire (M/M)

The Circuit

It’s a very simple circuit, I connected the resistors directly to the RGB legs and the Arduino pins. I’m using a common anode RGB LED, so the common leg should be connected to 5v. If you are using a common cathode RGB LED, you should connect the common leg (which is the longer leg) to GND instead.

I used digital ports 3, 4 and 5 because they were easier to reach, but you can use other pins if you want.

Testing the Wiring

To test if the wiring is correct, load the following sketch – this is an example from Adafruit that you can find here:

/*
Adafruit Arduino - Lesson 3. RGB LED
*/

int redPin = 5;
int greenPin = 4;
int bluePin = 3;

//uncomment this line if using a Common Anode LED
#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);  
}

void loop()
{
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 255, 0);  // green
  delay(1000);
  setColor(0, 0, 255);  // blue
  delay(1000);
  setColor(255, 255, 0);  // yellow
  delay(1000);  
  setColor(80, 0, 80);  // purple
  delay(1000);
  setColor(0, 255, 255);  // aqua
  delay(1000);
}

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);  
}

You should see the LED blink in various colors. In my case, I wired the LED in such a way that the Red leg is on pin 5, the Green leg is on pin 4, and the Blue leg is on pin 3. If the colors don’t look right, you might change the numbers to identify which leg is which.

Controlling the RGB LED color via Serial on Arduino

Now let’s implement the serial communication in order to control the color of the LED. We are going to use the code provided by the Arduino examples, you can find it here (it’s a whole tutorial, so if there’s something you don’t quite understand you can check there for the full example).

Load this sketch to your board:

// pins for the LEDs:
const int redPin = 5;
const int greenPin = 4;
const int bluePin = 3;

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // make the pins outputs:
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

}

void loop() {
  // if there's any serial available, read it:
  while (Serial.available() > 0) {

    // look for the next valid integer in the incoming serial stream:
    int red = Serial.parseInt();
    // do it again:
    int green = Serial.parseInt();
    // do it again:
    int blue = Serial.parseInt();

    // look for the newline. That's the end of your sentence:
    if (Serial.read() == '\n') {
      // constrain the values to 0 - 255 and invert
      // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
      red = 255 - constrain(red, 0, 255);
      green = 255 - constrain(green, 0, 255);
      blue = 255 - constrain(blue, 0, 255);

      // fade the red, green, and blue legs of the LED:
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);

      // print the three numbers in one string as hexadecimal:
      Serial.print(red, HEX);
      Serial.print(green, HEX);
      Serial.println(blue, HEX);
    }
  }
}

After the code is loaded and running, open the Serial Monitor from the Arduino IDE (Tools -> Serial Monitor). Select 9600 baud (this is what we used in the code) and select “Newline” on the line ending select box (it’s the box to the left of the baud rate selection). This is important, because by default it won’t send newline terminations and we need this to identify the end of line.

Now type 255,0,0 and press enter to see the LED go RED! Go ahead and play with the values to see the LED change.

Controlling the LED via serial with PHP

Now that the serial communication is a go, we need to write a little PHP script to send commands via serial to the Arduino board. For that, we’ll use the Composer library hyperthese/serial .

Create a led.php file with the following contents:

<?php

require __DIR__ . '/vendor/autoload.php';

$serial = new PhpSerial();

//this is the port where my Arduino is. Check from the Arduino IDE to see yours!
$serial->deviceSet("/dev/ttyACM0");
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");

$serial->deviceOpen();

// we will send the colors as csv strings
$colors['red']   = '255, 0, 0';
$colors['green'] = '0, 255, 0';
$colors['blue']  = '0, 0, 255';

foreach ($colors as $color => $value) {
        echo "Now sending $color\n";
        $serial->sendMessage($value . "\n");
        sleep(1);
}

echo "DONE\n";

Please notice that it’s very important to use the same Baud Rate in both ends! Here we’re using 9600.

Now execute it with:

php led.php

And you should see the magic happenning. You get the gist of it, right? Think about the possibilities! App status, notifications, etc etc… <insert-heart-eyes-emoji-here>

This is a little demo I built using the Twitter API and an old LOLShield + Arduino I had here. I’m still tweaking things but I’m planning to share the project soon enough, so keep an eye on my Twitter for when I share the code. Enjoy:

Liked it? Take a second to support erikaheidi on Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *