Using an Arduino as a slave board

Arduino serial interfacing and basic function library (This article is a work in progress)
By Mike Molianri
Me.pngUsing an Arduino as a slave board | Home automation, Robots, Vending machines. What do they have in common? | The Arduino Code | The Liberty Basic Demo | Just the Library and function descriptions

Home automation, Robots, Vending machines. What do they have in common?

The answer is computers controlling hardware. Making lights go on and off. Controlling motors, relays and other electronic components.
Liberty Basic for windows makes programming simple but lacks the ability to directly control or interface with hardware (except the parallel port).

To make hardware interface coding simpler a set of functions is required to facilitate the communication with external hardware. Because the arduino is the most widely used hobby micro controller in the world and has so much support it is the obvious choice make a set of simple functions for LB users to take advantage of this great platform for there projects.


The things covered in this article are limited to simple port I/O (Input and output).
  • Test if pin is high or low
    • Get input from buttons and other sensors connected to the arduino
  • Set a pin high or low
    • Turn things on and off like lights, buzzers, motors, ect.
  • PWM (Pulse width modulation) output
    • Dim lights, Control servo motors, interface with variable speed motor controllers
  • PWM (Pulse width modulation) input
    • Get input from things like sliders and position information

The Arduino Code

To make liberty basic talk with an arduino they have to speak the same language.
In this case a string is used and send over to the device followed by a carriage return character CHR$(13)

The only thing you really have to understand about the arduino code is that it must be download to the arduino board using the arduino IDE.
This can be download from the following link.
http://arduino.cc/en/Main/Software

Note: This code is done in arduinos special form of c and is not basic code.
<span style="font-size: 1.1em;">// Buffer to store incoming commands from serial port
String inData;
 
void setup() {
    Serial.begin(9600);
    Serial.println("Serial conection started, waiting for instructions...");
}
 
void loop() {
    while (Serial.available() > 0)
    {
        char recieved = Serial.read();
        inData += recieved;
 
        // Process message when new line character is recieved
        if (recieved == '\n')
        {
        String Param0 = getValue(inData, ' ', 0);
        String Param1 = getValue(inData, ' ', 1);
        String Param2 = getValue(inData, ' ', 2);
        String Param3 = getValue(inData, ' ', 3);
        String Param4 = getValue(inData, ' ', 4);
        String Param5 = getValue(inData, ' ', 5);
 
            inData = "";
 
            int valParam0 = Param0.toInt();
            int valParam1 = Param1.toInt();
            int valParam2 = Param2.toInt();
            int valParam3 = Param3.toInt();
            int valParam4 = Param4.toInt();
            int valParam5 = Param5.toInt();
 
 
            //Serial.print(valParam0);
            //Serial.print(valParam1);
            //Serial.print(valParam2);
            //Serial.print(valParam3);
            //Serial.print(valParam4);
            //Serial.print(valParam5);
 
 
 
 
            if ( Param0 == "get")
              {
              pinMode(valParam1, INPUT);
              Serial.println(digitalRead(valParam1));
 
 
              }
 
            if ( Param0 == "set")
              {
              pinMode(valParam1, OUTPUT);
              digitalWrite(valParam1, valParam2);
              Serial.println("1");
 
 
              }
 
 
            if ( Param0 == "pwm.out")
              {
              analogWrite(valParam1, valParam2);
              Serial.println("1");
 
              }
 
 
 
            if ( Param0 == "pwm.in")
              {
              Serial.println(analogRead(valParam1));
              }
 
        }
    }
}
 
 
 
 
String getValue(String data, char separator, int index)
{
 int found = 0;
  int strIndex[] = {
0, -1  };
  int maxIndex = data.length()-1;
  for(int i=0; i<=maxIndex && found<=index; i++){
  if(data.charAt(i)==separator || i==maxIndex){
  found++;
  strIndex[0] = strIndex[1]+1;
  strIndex[1] = (i == maxIndex) ? i+1 : i;
  }
 }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}  </span>


The Liberty Basic Demo

The demo program shows off the basic functionality of the library.

The Com port that the arduino is on must be placed in the com port number text box.

A pin must be selected and a value to send must be entered.

The 4 buttons on the left are used to execute the functions.


The return value is populated by the what is returned by the arduino.
Screen shot.png

<span style="font-size: 1.1em;">dim  pins$(100)
 
 
 'Populate pin list
 for x = 0 to 13
    pins$(x) = str$(x)
 next x
 
 
    nomainwin
    WindowWidth = 360
    WindowHeight = 445
    UpperLeftX=int((DisplayWidth-WindowWidth)/2)
    UpperLeftY=int((DisplayHeight-WindowHeight)/2)
 
    listbox #main.PinSelector, pins$(, [listbox1DoubleClick],   10,  82, 130, 320
    statictext #main.statictext2, "Pin Selector",  10,  62, 130,  20
 
    textbox #main.ValToSend, 165,  32, 170,  25
    statictext #main.statictext4, "Value To Send", 165,  12, 170,  20
    statictext #main.statictext5, "Return Value", 165,  62, 175,  20
    textbox #main.ReturnValue, 165,  82, 170,  25
    button #main.button7,"Set Pin High/Low Status",[Set.Pin], UL, 165, 117, 170,  25
    button #main.button8,"Get Pin High/Low Status",[Get.Pin], UL, 165, 152, 170,  25
    button #main.button9,"PWM Output (Servos)",[PWM.Out], UL, 165, 187, 170,  25
    button #main.button10,"PWM Input",[PWM.In], UL, 165, 222, 170,  25
    statictext #main.statictext11, "Com Port Number",  10,  12, 145,  20
    textbox #main.ComPortNo,  10,  32, 130,  25
 
    open "LB Ultra Simple Arduino Demo" for dialog as #main
    print #main, "trapclose [quit.main]"
    wait
 
 
 
 
[Set.Pin]
    gosub [Get.The.Selctions.And.Textboxes.From.Main.Win]
    return.value = AD.Set(Com.port.Selection, Pin.Selection, Val.To.Send)
    print #main.ReturnValue, return.value
    wait
 
 
[Get.Pin]
    gosub [Get.The.Selctions.And.Textboxes.From.Main.Win]
    return.value = AD.Get(Com.port.Selection, Pin.Selection)
    print #main.ReturnValue, return.value
    wait
 
 
 
 
[PWM.Out]
    gosub [Get.The.Selctions.And.Textboxes.From.Main.Win]
    return.value = AD.PWM.Out(Com.port.Selection, Pin.Selection, Val.To.Send)
    print #main.ReturnValue, return.value
    wait
 
 
 
[PWM.In]
    gosub [Get.The.Selctions.And.Textboxes.From.Main.Win]
    return.value = AD.PWM.In(Com.port.Selection, Pin.Selection)
    print #main.ReturnValue, return.value
    wait
 
 
 
[quit.main]
    close #main
    end
 
 
 
 
 
[Get.The.Selctions.And.Textboxes.From.Main.Win]
    print #main.ValToSend, "!contents? Val.To.Send";
    print #main.ComPortNo, "!contents? Com.port.Selection";
    print #main.PinSelector, "selection? Pin.Selection"
    return
 
 
 
 
 
 
 
 
'Begin Arduino Code here -------------------------------------------------------
'These functions can be added to any program to provide arduini power input and output
'Descriptions for functions are in there comments
 
 
function AD.Set(com.port, PinNo, value)
'Set an Arduino pin high or low,
'Will return 1 one if successful, 0 if not
     AD.Set = val(AD.talk.to.device$(com.port,"set ";PinNo;" ";value))
end function
 
 
function AD.Get(com.port, PinNo)
'Will return the current state of the input pin
'1 for high, 0 for low
     AD.Get = val(AD.talk.to.device$(com.port,"get ";PinNo))
end function
 
 
function AD.PWM.Out(com.port, PinNo, value)
'Set the PWM output on the select pin to the value
'Will return a 1 for success and 0 for failure.
     AD.PWM.Out = val(AD.talk.to.device$(com.port,"pwm.out ";PinNo;" ";value))
end function
 
 
function AD.PWM.In(com.port, PinNo)
'Get the PWM input from the pin
'Will return a value of 0 to 1023
    AD.PWM.In = val(AD.talk.to.device$(com.port,"pwm.in ";PinNo))
end function
 
 
 
 
Function AD.talk.to.device$(port,msg$)
'Send a Message to the arduino and return the result sent back by the device
    if msg$ <> "" then
        'Open the com port
        open "COM" ; port ; ":9600,n,8,1" for random as #ArduinoCOMPort
 
        'Send message to device
        print #ArduinoCOMPort, msg$
 
        'Wait until there is a carriage return
        while foundLF = 0
            while lof(#ArduinoCOMPort) > 0
                temp$ = input$(#ArduinoCOMPort, 1)
                buffer$ = buffer$ + temp$
 
                if temp$ = chr$(13) then
                    foundLF = 1
                    exit while
                end if
            wend
        wend
 
        'Place the returned text in to AD.talk.to.device$
        AD.talk.to.device$ = buffer$
        close #ArduinoCOMPort
    else
        Notice "Improper Message Received, Must contain a command"
    end if
End function
 </span>


Just the Library and function descriptions

The bare naked functions are below with commented explanations for what they do.
<span style="font-size: 1.1em;">'Begin Arduino Code here -------------------------------------------------------
'These functions can be added to any program to provide arduini power input and output
'Descriptions for functions are in there comments
 
 
function AD.Set(com.port, PinNo, value)
'Set an Arduino pin high or low,
'Will return 1 one if successful, 0 if not
     AD.Set = val(AD.talk.to.device$(com.port,"set ";PinNo;" ";value))
end function
 
 
function AD.Get(com.port, PinNo)
'Will return the current state of the input pin
'1 for high, 0 for low
     AD.Get = val(AD.talk.to.device$(com.port,"get ";PinNo))
end function
 
 
function AD.PWM.Out(com.port, PinNo, value)
'Set the PWM output on the select pin to the value
'Will return a 1 for success and 0 for failure.
     AD.PWM.Out = val(AD.talk.to.device$(com.port,"pwm.out ";PinNo;" ";value))
end function
 
 
function AD.PWM.In(com.port, PinNo)
'Get the PWM input from the pin
'Will return a value of 0 to 1023
    AD.PWM.In = val(AD.talk.to.device$(com.port,"pwm.in ";PinNo))
end function
 
 
 
Function AD.talk.to.device$(port,msg$)
'Send a Message to the arduino and return the result sent back by the device
    if msg$ <> "" then
        'Open the com port
        open "COM" ; port ; ":9600,n,8,1" for random as #ArduinoCOMPort
 
        'Send message to device
        print #ArduinoCOMPort, msg$
 
        'Wait until there is a carriage return
        while foundLF = 0
            while lof(#ArduinoCOMPort) > 0
                temp$ = input$(#ArduinoCOMPort, 1)
                buffer$ = buffer$ + temp$
 
                if temp$ = chr$(13) then
                    foundLF = 1
                    exit while
                end if
            wend
        wend
 
        'Place the returned text in to AD.talk.to.device$
        AD.talk.to.device$ = buffer$
        close #ArduinoCOMPort
    else
        Notice "Improper Message Received, Must contain a command"
    end if
End function</span>

Using an Arduino as a slave board | Home automation, Robots, Vending machines. What do they have in common? | The Arduino Code | The Liberty Basic Demo | Just the Library and function descriptions