Categories
Uncategorized

Communicate to Arduino from PC

Although the Arduinos are great little controllers, sometimes you need to connect them to a PC to transfer data or control. One of the simplest ways of using a PC to control your Arduino is with a menu.

Menus have been used on computers pretty much forever. Back in the 80’s the green screen (green text on a black background) text menu was very popular. They persist to this day in some specialized applications.

In a nutshell, your PC will run a simple terminal program. Putty.exe is a great choice. It’s free, works great and supports the popular VT100 terminal control characters we will need.

The Arduino serial parameters are set to 115,200 bits/second, 8N1. Make sure your terminal program is set up similarly.
The example program turns on and off two LEDs and displays the raw data read back from the Analog0 port

Here’s the program:

// Description:
// Simple menuing system for Arduino
// Demonstrates a menu with controls and
// data readback
//
// Communicates with PC at 115,200 bps 8N1
//
#define LED1 2
#define LED2 3

void setup()
{
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  Serial.begin(115200);
  menu();
}

void loop()
{
  int m = readMenu();
  switch (m)
  {
    case 1:
      // Turn on LED 1
      digitalWrite(LED1, HIGH);
      break;
    case 2:
      // Turn off LED 1
      digitalWrite(LED1, LOW);
      break;
    case 3:
      // Turn on LED 2
      digitalWrite(LED2, HIGH);
      break;
    case 4:
      // Turn off LED 2
      digitalWrite(LED2, LOW);
      break;
    case 5:
    {
      // VT100 reset cursor to end of menu (row 15, column 1)
      char resetCursor[] = {27,'[','1','6',';','1','H',0};
      Serial.print(resetCursor);
      Serial.print("A0: ");
      // Read Analog 0 input and display data
      Serial.print(analogRead(A0));
      break;
    }
    default:
      break;
   }
}

// Waits in a loop until key is pressed
// then returns digit selected
int readMenu()
{
  while (!Serial.available())
  {
    delay(100);
  }
  return Serial.read() - 48;
}

// Displays menu
void menu()
{
  // Clear screen
  char buf[] = {27,'[','2','J',0};
  Serial.print(buf);

  // Print menu
  Serial.println("\n\n\n\n\n");
  Serial.println("1....LED1 on");
  Serial.println("2....LED1 off");
  Serial.println("3....LED2 on");
  Serial.println("4....LED2 off");
  Serial.println("5....Read A0");
  Serial.println("\n\n Select 1..5");
}

 

When you run this, you will get a menu with 5 options. We demonstrate how to position the cursor on the screen using escape commands. Look at the code that prints the value of A0 on the screen for an example.

Menuing is a simple but effective way to get your PC and Arduino talking to each other.




If you'd like to subscribe to this blog, please click here.