Skip to content

Your first query on Arduino

In this tutorial you'll program an Arduino Uno to log in to SQL Server, create a table, and print its rows to the Serial Monitor.

You need:

  • An Arduino Uno, Mega or Nano, with a W5100 or W5500 Ethernet shield, plugged into the same network as your computer
  • The Arduino IDE 2.x
  • A SQL Server: see Before you start

1. Install tdslite

  1. In the Arduino IDE, open Tools → Manage Libraries...
  2. Search for tdslite and click Install.

The Ethernet library comes with the IDE, so there's nothing else to install.

2. Create the sketch

Open File → New Sketch and save it as first-query. Replace its contents step by step with the code below.

Start with the two libraries the sketch uses:

#include <Ethernet.h>
#include <tdslite.h>

tdslite needs a buffer to send and receive data through. You give it one when you create the driver, so you decide how much RAM it uses:

// The buffer that tdslite uses to send and receive data
tdsl::uint8_t net_buf [768] = {};

// The driver, talking over the Ethernet shield
tdsl::arduino_driver<EthernetClient> driver{net_buf};

When a query returns rows, tdslite calls a function of yours once for each row. This one prints the two columns of the table you'll create:

// Called once for each row of a result set
static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) {
    const auto name = row [1].as<tdsl::char_view>();
    Serial.print(row [0].as<tdsl::int32_t>());
    Serial.print(F(": "));
    Serial.write(name.data(), name.size());
    Serial.println();
}

Add a small helper that stops the sketch when something goes wrong:

static void halt(const __FlashStringHelper * why) {
    Serial.println(why);
    while (true) {
        delay(1000);
    }
}

3. Connect to SQL Server

Now write setup(). First bring up the Ethernet shield. Pick an IP address that is free in your network:

void setup() {
    Serial.begin(115200);
    while (!Serial) {
    }

    // Change the IP address to a free one in your network
    byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    Ethernet.begin(mac, IPAddress(192, 168, 1, 50));
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        halt(F("No Ethernet shield found"));
    }

Then tell tdslite where the server is and log in. Put your computer's IP address in server_name:

    // TDSL_PMEMSTR keeps the strings in flash, which saves RAM
    decltype(driver)::progmem_connection_parameters params;
    params.server_name = TDSL_PMEMSTR("192.168.1.10"); // your computer's IP address
    params.port        = 1433;
    params.user_name   = TDSL_PMEMSTR("sa");
    params.password    = TDSL_PMEMSTR("Tutorial-Passw0rd");
    params.packet_size = 512;

    Serial.println(F("Connecting..."));
    if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) {
        halt(F("Could not connect to SQL Server"));
    }
    Serial.println(F("Connected"));

4. Create a table

Still in setup(), create a table and put three rows in it, then close the function:

    // A table whose name starts with # is temporary: SQL Server drops it
    // when the connection closes
    driver.execute_query(TDSL_PMEMSTR("CREATE TABLE #fruits(id INT, name VARCHAR(16))"));
    driver.execute_query(
        TDSL_PMEMSTR("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')"));
}

5. Read the rows

Finally, select the rows every ten seconds in loop():

void loop() {
    const auto result =
        driver.execute_query(TDSL_PMEMSTR("SELECT id, name FROM #fruits"), print_row);
    Serial.print(result.affected_rows);
    Serial.println(F(" row(s)"));
    delay(10000);
}

6. Run it

  1. Select your board and port in the IDE, and click Upload.
  2. Open Tools → Serial Monitor and set it to 115200 baud.

After a few seconds you'll see:

Connecting...
Connected
1: apple
2: banana
3: cherry
3 row(s)

and the last four lines again every ten seconds.

If you see Could not connect to SQL Server instead, check the server's IP address and that your computer's firewall lets port 1433 in. Troubleshoot has more.

What you've done

You've connected an Arduino to SQL Server, created a table, and read rows from it through a callback, all within the 2 kB of RAM of an Uno. When you compile the sketch, the IDE prints how much RAM it uses: the 768-byte network buffer is most of it.

The complete sketch
#include <Ethernet.h>
#include <tdslite.h>

// The buffer that tdslite uses to send and receive data
tdsl::uint8_t net_buf [768] = {};

// The driver, talking over the Ethernet shield
tdsl::arduino_driver<EthernetClient> driver{net_buf};

// Called once for each row of a result set
static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) {
    const auto name = row [1].as<tdsl::char_view>();
    Serial.print(row [0].as<tdsl::int32_t>());
    Serial.print(F(": "));
    Serial.write(name.data(), name.size());
    Serial.println();
}

static void halt(const __FlashStringHelper * why) {
    Serial.println(why);
    while (true) {
        delay(1000);
    }
}

void setup() {
    Serial.begin(115200);
    while (!Serial) {
    }

    // Change the IP address to a free one in your network
    byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    Ethernet.begin(mac, IPAddress(192, 168, 1, 50));
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        halt(F("No Ethernet shield found"));
    }

    // TDSL_PMEMSTR keeps the strings in flash, which saves RAM
    decltype(driver)::progmem_connection_parameters params;
    params.server_name = TDSL_PMEMSTR("192.168.1.10"); // your computer's IP address
    params.port        = 1433;
    params.user_name   = TDSL_PMEMSTR("sa");
    params.password    = TDSL_PMEMSTR("Tutorial-Passw0rd");
    params.packet_size = 512;

    Serial.println(F("Connecting..."));
    if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) {
        halt(F("Could not connect to SQL Server"));
    }
    Serial.println(F("Connected"));

    // A table whose name starts with # is temporary: SQL Server drops it
    // when the connection closes
    driver.execute_query(TDSL_PMEMSTR("CREATE TABLE #fruits(id INT, name VARCHAR(16))"));
    driver.execute_query(
        TDSL_PMEMSTR("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')"));
}

void loop() {
    const auto result =
        driver.execute_query(TDSL_PMEMSTR("SELECT id, name FROM #fruits"), print_row);
    Serial.print(result.affected_rows);
    Serial.println(F(" row(s)"));
    delay(10000);
}

Next steps