Last week’s post we talked about how Alexa can be used to talk to an Arduino micro controller using the code from an earlier project. This week, we’ll continue exploring this project by creating an Arduino Server that will listen for commands, and execute commands based on this task.

Recap: Using Alexa to Control an Arduino Device

If you remember,  I start with an Arduino, attach an ethernet shield to it and connect it to the network. I program a server on the Arduino to listen for commands and do something when it gets them, and then in the pyHarmony App, I put in a string to talk to the Arduino, issuing recognizable commands, then push that off to the website, and have it tell the Arduino what to do.

Creating an Arduino Server is relatively easy. Using the Ethernet Libraries from Arduino, its just a few lines of code to build our server. Set the Mac Address, the IPAddress and Gateway, then create a server listening on a port with one line of code:  EthernetServer server(23); This line starts a server on port 23, listening for incoming connections. Below is the server setup block:

// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 233);
IPAddress myDns(192,168,1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 0, 0);


// telnet defaults to port 23
EthernetServer server(23);

Once we’ve created our server, we can set up a connection and start listening for data. This too is easy, and done with just a few lines of code.

void setup() {
  // initialize the ethernet device
  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  // start listening for clients
  server.begin();

Line 17 through 19 setup the server listener and allows the connection. A telnet connection is made to the Arduino, and the connection is then established.

Next, we need to have the code start listening for the data coming in. The Loop function is where this all takes place. EthernetClient client = server.available(); starts the listening; a connection is made, and then we determine if we are establishing a new connection or if we are just looking at data coming in from an existing connection. If the connection is new, we send the word “Hello” to let the client know that they are connected and can start sending data. If we’ve already done that, we simply enter a loop and grab and store each character coming in a variable called incoming.

Incoming is an array of 8 characters long, but Arduino requires that strings end with NULL, so the 8th position is reserved for that. This means our commands can be strings of seven characters long. For each character we receive, we add it to the incoming array, (to build the command) and echo the string back to the client to tell them we got it. So; Client sends “S”, we capture “S” and put it in incoming in position 1, and send “S” back to the client to tell them we got it. Next the client sends “t”, and as before, we store “t” in incoming at position 2, and sent “t” back to the client. We continue doing this for 7 characters building something like “S”,”t”,”a”,”r”,”t”,”I”,”t”, and we have a command!

Once we reach our 7 character limit, we process the command, reset incoming to empty, and start over for the next command.

Examine the Results

Then all we need to do is examine the string we got. If “StartIt” is a command we want to recognize, we simply parse, and process on a match.

In the following code sample, I’m recognizing 2 commands; “StartIt” and “StopIt “, and anything else is treated as an unrecognized command. It’s trivial to add more commands; simply put in an “if” clause for each command you want. These commands don’t do much, actually, I’ll leave it to you to figure out what you want your Arduino to do, but it could be lots of things.

You could read a sensor and return the value of it. You could start/stop a motor. You could talk to another Arduino and tell it to do something (a technique I’ll be Using to get Jeeves to rumble into the room). There’s lots of possibilities here; just add your imagination and stir!

Test the code

To test this code, download it to your Arduino; take care to set the IP settings right for your network. Plug in an Ethernet Shield and connect your network cable. On your computer, start telnet and connect to the Arduino on the IP you specified in code. Press enter a couple of times until you get “Hello!” and then press a couple more times till you get “Unknown Command”. Then type in “StartIt” or “StopIt ” and the Arduino should send you back a confirmation.

In the next chapter, we’ll build out the client (the bits that go between Alexa and the Arduino), and start talking about how to get Alexa to do her bit. See you then!

/*
 Arduino Server

 A simple server listens for specific commands, and then executes specific cod
 based on those commands.

 created 31 March 2016
 by Jerry Parker

 */

#include <SPI.h>
#include <Ethernet.h>

char incoming[8]; // incoming string
int commandIndex = 0; // index into incoming command array
String command;  // the recieved command

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 233);
IPAddress myDns(192,168,1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 0, 0);


// telnet defaults to port 23
EthernetServer server(23);
boolean alreadyConnected = false; // whether or not the client was connected previously

void setup() {
  // initialize the ethernet device
  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  // start listening for clients
  server.begin();
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


  Serial.print("Server Address:");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // wait for a new client:
  EthernetClient client = server.available();

  // when the client sends the first byte, say hello:
  if (client) {
    if (!alreadyConnected) {
      // clear out the input buffer:
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello!");
      alreadyConnected = true;
    }

    if (client.available() > 0) {
      // read the data incoming from the client:
      char thisChar = client.read();
      //store the data into the incoming array
      // incoming[] contains a string of 7 recieved characters
      // to build a command. all commands are 7 characters, padded by space
      //
      incoming[commandIndex] = thisChar;
      // echo the data back to the client:
      server.write(thisChar);
      // echo the bytes to the server as well:
      Serial.write(thisChar);
      commandIndex ++;
      // build the command into incoming[]
      if (commandIndex == 7){
        // when we reach 7 characters, parse the command
        //and reset the index to 0
        commandIndex = doAction(client);

      }
    }
  }
}
  int doAction(EthernetClient client) {
    int processCommand =0;
    incoming[8]='\0'; //add the null value to the end of the array
    command = incoming;
    if (command == "StartIt") {
      // execute command Startit
      Serial.println(" Doing StartIt");
      // Start Doing Some Stuff
      client.println("Got StartIt");
      processCommand=1;
    }
    if (command == "StopIt ") {
      // execute command StopIt
      Serial.println(" Doing StopIt");
      // STOP doing some Stuff
      client.println("Got StopIt");
      processCommand=1;
    }
    //add commands as needed
    //
    //
    // catch unknown commands
    if (processCommand==0){
      // execute "command Unknown"
      Serial.println(" UnknownCommand");
      Serial.println(command);
      // do some stuff
      client.println(" Unknown Command");
    }
    return 0;
  }

Shopping cart

Subtotal
Shipping and discount codes are added at checkout.
Checkout