Serial control of an Arduino


This is part of a series of posts on getting control of an Arduino via EPICS on a Raspberry Pi.  See here.  In this post, I’ll detail how the to prepare the Arduino.

Set up the circuit as in the following image.  All of the (very few) components can be found in the Arduino Starter Kit.

epics

Lay out the bread board in such a way that the photo-resistor points directly at the LED — not at the side of the LED, but at the top where most of the light is directed.  Also, note that the resistor values aren’t so important, but make sure the LED resistor sufficiently limits the current through it, and that the photo-resistor series resistor is high enough to provide sufficient gain.

Once the circuit has been laid out, upload the following sketch:

const int ledPin = 11;
 const int photoPin = A0;
int ledState = LOW;
 int oldState = LOW;
 String input = ""; // This will capture the serial input commands
void setup() {
 pinMode(ledPin, OUTPUT);
 pinMode(photoPin, INPUT);
 Serial.begin(115200); // Make sure the Serial commands match this baud rate
 }
void loop () {
 if (oldState != ledState) { // Only write to the LED when necessary
   analogWrite(ledPin, ledState);
   oldState = ledState;
 }
 while (Serial.available()>0){
   char lastRecvd = Serial.read();
   if (lastRecvd == '\n') { // The end of the command has arrived
     switch (input[0]) {
       case 'W': // A write command has come in
         input = input.substring(1,input.length());
         ledState = constrain(input.toInt(), 0, 255);
         input = "";
         break;
       case 'R': // A read command has come in
         Serial.print("R ");
         Serial.print(analogRead(photoPin)+'0');
         Serial.print("\n");
         input = "";
         break;
       default:
         break;
     }
   }
   else { // Input is still coming in
     input += lastRecvd;
   }
 }
}

One this has been uploaded, open the serial monitor from the Arduino IDE, set the baud rate, and make sure the line ending is set to “Both NL & CR”.  If everything has gone well, it should be possible to switch on the LED by sending “W255” via the serial monitor.  “W0” should switch it off, and intermediate values, 0<=N<=255, can be set with “WN”.

Sending “R” should give a return value in the monitor window.  Playing with the LED brightness should result in sensible changes in the values read back using this command.

Make sure this works.  Debugging EPICS without a good understanding of the system you are trying to control is very painful, so be sure that everything works as expected.