Tutorial: Serial Port Plugin AppGameKit > Arduino (2/4)
In the previous tutorial we build the Arduino circuit and add the Arduino sketch to test our wiring.
This tutorial we will do the code for AppGameKit to send a string to the Arduino, and change the Arduino code to receive the serial string and process as needed.
Let start our AppGameKit Classic or Studio and see what the process will be.
Create a New Project
The first thing to do, is to tell our AppGameKit App, that we will use the Serial Plugin.
#import_plugin SerialPlugin as serial
Next we will create variables for each LED.
LED1 as string = “0”
LED2 as string = “0”
LED3 as String = “0”
Then we will combine the LED1, Led2, Led3 strings to create a combined string to send to the Arduino.
We will add a EndofLine Character to the string to tell Arduino when the string ends, and then process.
Personaly I like to send a “#” character, But you can use any string to terminate (Last Character)
Some People use ‘\n’ as a terminate character. But for this tutorial I use the “#” hash as a Terminate character.
As we progress you will see why I’m doing this…
CurrentString as String
CurrentString = LED1+LED2+LED3+”#” // # tell Arduino to process string,
We will also create a LastString (as a Flag) , to only send the string once it change. This save Processing Power in AppGameKit as well as the Arduino.
Very Helpful when send long strings to Arduino… and prevent Arduino constantly process strings receive…
LastString = CurrentString
Then we need to scan the Serial Port and find available Ports.
If no Ports available the program exit. If there is ports available, use that Port
In The last Tutorial (Cleanup and Spice Up) we will add a CHECK to the Arduino and AppGameKit to monitor on Which comport the Arduino is connected, should there be more than one comport detected.
For now we assume it is only one comport and we use comport = 0
We will finish the AppGameKit Code and test with the PRINT function to see if the String to SEND to the Arduino is correct.
Once we know that is correct, we can add the code for sending in AppGameKit and then Arduino for receiving.
Code for previous Explanation.
Most comment in the code
// Project: arduino_agl_serial_plugin_Example1
#import_plugin SerialPlugin as serial
// show all errors
SetErrorMode(2)
// set window properties
SetWindowTitle( "arduino_agl_serial_plugin_Example1" )
SetWindowSize( 1024, 768, 0 )
SetWindowAllowResize( 1 ) // allow the user to resize the window
// set display properties
SetVirtualResolution( 1024, 768 ) // doesn't have to match the window
SetOrientationAllowed( 1, 1, 1, 1 ) // allow both portrait and landscape on mobile devices
SetSyncRate( 30, 0 ) // 30fps instead of 60 to save battery
SetScissor( 0,0,0,0 ) // use the maximum available screen space, no black borders
UseNewDefaultFonts( 1 ) // since version 2.0.22 we can use nicer default fonts
//Variables for our 3 Leds on the Arduino Board
Led1 as String = “0”
Led2 as String= “0”
Led3 as String=”0”
//Currentstring to be send to the arduino
CurrentString as String
//This is the last string send to the arduino
LastString as String
currentString = Led1+LEd2+Led3+"#"
lastString = CurrentString
//Check if there is any available Comports
//If no Comports found, the APP will Exit
num = serial.EnumerateSerialPorts()
if ( num > 0 )
portindex = 0
do
//Number of Comports detect on System
Print("Number of Ports Detected: "+str(num))
//Give Port name
Print("Port Name: "+serial.GetSerialPortName( portIndex ))
Sync()
Loop
else
// No Ports detected, EXIT Program
Message("No Serial Port detect")
do
Exit
Loop
endif
This code will tell if there is a comport available or Not, and display relevant information.
Next we want to add 3 Buttons, to Switch the 3 LEDs on the Arduino.
As you can see, the Variables led1, led2, led3 is = 0. This will tell Arduino the Led is Turned OFF
If we click the Button, we change the Variable to “1”, and this tell Arduino to switch it ON
If we press the button again, we change back to “0” to switch OFF.
This will be done for all 3 LED’s
Example Strings Arduino can receive
000#, all leds are OFF
100#, LED 1 ON, Led2 OFF, LED 3 OFF
111#, LED1 ON, LED 2 ON, LED3 ON etc…
To be able to do this, we will use the Buttons as Switches, and manipulate the CurrentString
Create 3 Virtual Buttons , and add the Text “OFF” to each button
Add the following below portindex = 0
AddVirtualButton(1,200,200,80) // button for LED1
AddVirtualButton(2,400,200,80) // Button for LED2
AddVirtualButton(3,600,200,80) // Button for LED3
SetVirtualButtonText(1,"OFF")
SetVirtualButtonText(2,"OFF")
SetVirtualButtonText(3,"OFF")
In the do loop, we will change the currentstring according to the button presses, for ON/OFF Switching
Add the following code in the DO Loop
if GetVirtualButtonPressed(1) // if button for LED1 is pressed
if led1 = "0"
led1 = "1"
SetVirtualButtonText(1,"ON") // change button to show ON
else
led1 = "0"
SetVirtualButtonText(1,"OFF") // change button to show ON
endif
elseif GetVirtualButtonPressed(2)
if led2 = "0"
led2 = "1"
SetVirtualButtonText(2,"ON") // change button to show ON
else
led2 = "0"
SetVirtualButtonText(2,"OFF") // change button to show ON
endif
elseif GetVirtualButtonPressed(3)
if led3 = "0"
led3 = "1"
SetVirtualButtonText(3,"ON") // change button to show ON
else
led3 = "0"
SetVirtualButtonText(3,"OFF") // change button to show ON
endif
endif
When you test this code in AppGameKit, your Buttons text will change according to the Led1, Led2, Led3 State.
We need to update the CurrentString and Compare with the LastString to know if we need to send New information to the Arduino
Before the Sync() in the Loop, add the following
currentString = Led1+LEd2+Led3+"#"
if lastString <> CurrentString
// Here we will process the string to send to the arduino
lastString = CurrentString
endif
Now that we know the string is working when press the buttons, we can add the code to communicate with the Arduino
First we need to Open the Port, to be able to read and write
We use the OpenSerialPort Function, specify the Baudrate (Which we can set in the Arduino) and portindex
Add the following code before the DO loop
iID = serial.OpenSerialPort( portIndex, 9600, 1, 0 )
if ( iID )
Sleep( 2 ) // just a small delay to get everything cleared and Initialized
And this code after the LOOP
Else
Message(“Cant connet to port”)
endif
Once everything OK and No connect errors, al we need to do is to add the Command to Send the Currentstring to the serial port
We will use
success = WriteSerialData( instanceID, String, length ) -- length can be -1 to use the string length
Add the BOLD lines to the If statement
if lastString <> CurrentString
// Here we will process the string to send to the arduino
// only if last string and current string differ
[b]serial.WriteSerialData( iID, CurrentString, -1 )
Sleep( 10 )[/b]
lastString = CurrentString
endif
Here is the complete AppGameKit code
// Project: arduino_agl_serial_plugin_Example1
#import_plugin SerialPlugin as serial
// show all errors
SetErrorMode(2)
// set window properties
SetWindowTitle( "arduino_agl_serial_plugin_Example1" )
SetWindowSize( 1024, 768, 0 )
SetWindowAllowResize( 1 ) // allow the user to resize the window
// set display properties
SetVirtualResolution( 1024, 768 ) // doesn't have to match the window
SetOrientationAllowed( 1, 1, 1, 1 ) // allow both portrait and landscape on mobile devices
SetSyncRate( 30, 0 ) // 30fps instead of 60 to save battery
SetScissor( 0,0,0,0 ) // use the maximum available screen space, no black borders
UseNewDefaultFonts( 1 ) // since version 2.0.22 we can use nicer default fonts
//Variables for our 3 Leds on the Arduino Board
Led1 as String = "0"
Led2 as String = "0"
Led3 as String = "0"
//Currentstring to be send to the arduino
CurrentString as String
//This is the last string send to the arduino
LastString as String
currentString = Led1+LEd2+Led3+"#"
lastString = CurrentString
//Check if there is any available Comports
//If no Comports found, the APP will Exit
num = serial.EnumerateSerialPorts()
if ( num > 0 )
portindex = 0
AddVirtualButton(1,200,200,80) // button for LED1
AddVirtualButton(2,400,200,80) // Button for LED2
AddVirtualButton(3,600,200,80) // Button for LED3
SetVirtualButtonText(1,"OFF")
SetVirtualButtonText(2,"OFF")
SetVirtualButtonText(3,"OFF")
iID = serial.OpenSerialPort( portIndex, 9600, 1, 0 )
if ( iID )
Sleep( 2 )
do
//Number of Comports detect on System
Print("Number of Ports Detected: "+str(num))
//Give Port name
Print("Port Name: "+serial.GetSerialPortName( portIndex ))
Print("Last String Send: "+LastString)
if GetVirtualButtonPressed(1) // if button for LED1 is pressed
if led1 = "0"
led1 = "1"
SetVirtualButtonText(1,"ON") // change button to show ON
else
led1 = "0"
SetVirtualButtonText(1,"OFF") // change button to show ON
endif
elseif GetVirtualButtonPressed(2)
if led2 = "0"
led2 = "1"
SetVirtualButtonText(2,"ON") // change button to show ON
else
led2 = "0"
SetVirtualButtonText(2,"OFF") // change button to show ON
endif
elseif GetVirtualButtonPressed(3)
if led3 = "0"
led3 = "1"
SetVirtualButtonText(3,"ON") // change button to show ON
else
led3 = "0"
SetVirtualButtonText(3,"OFF") // change button to show ON
endif
endif
currentString = Led1+LEd2+Led3+"#"
if lastString <> CurrentString
// Here we will process the string to send to the arduino
// only if last string and current string differ
serial.WriteSerialData( iID, CurrentString, -1 )
Sleep( 10 )
lastString = CurrentString
endif
Sync()
Loop
else
Print("Fail to connect")
sync()
endif
else
// No Ports detected, EXIT Program
Message("No Serial Port detect")
do
Exit
Loop
endif
When you compile the AppGameKit Project, It should work like the following Video
This is all we need for now in the AppGameKit APP. Next we will change our Arduino Sketch to Receive the String from our AppGameKit APP
Open the Arduino IDE, and load our previous Testing Connections example Sketch
Delete/comment the following Lines
delay(100); // delay a 10th of a second
digitalWrite(8,HIGH); //Make Pin HIGH (ON) and switch led on
delay (100);
digitalWrite(8,LOW); //Make Pin LOW (OFF) and switch led off
delay(100); // delay a 10th of a second
digitalWrite(9,HIGH); //Make Pin HIGH (ON) and switch led on
delay (100);
digitalWrite(9,LOW); //Make Pin LOW (OFF) and switch led off
delay(100); // delay a 10th of a second
digitalWrite(10,HIGH); //Make Pin HIGH (ON) and switch led on
delay (100);
digitalWrite(10,LOW); //Make Pin LOW (OFF) and switch led off
Your Arduino Sketch must look like this:
void setup() {
// put your setup code here, to run once:
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
}
First we need to tell Arduino to read the Serial port for any incoming data
More Comment in the Sketch/Code
Before Void Setup() add the following 2 lines
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
in the void setup() after pinMode(10,HIGH) add the following 2 lines
Serial.begin(9600); // open/initialize serial port
// reserve 200 bytes for the inputString:
inputString.reserve(200);
Now we need to create a Event to “listen” for any incoming serial data.
We will use a Function SerialEvent, to monitor any incoming data
Add the following after the Void Loop Function
void serialEvent() {
while (Serial.available()) { // while there is new data to read, read them byte by byte
char inChar = (char)Serial.read();
inputString += inChar; // While there is other characters and no “#” keep adding what you receive to the Inputstring
if (inChar == '#') { // In AGK we add the “#” hash as a terminate character
// We receive the # character. Stop reading and Change StringCompleteFlag to TRUE
// Now we can PARSE the string in the Main Loop and switch LED’s ON/OFF
stringComplete = true;
}
}
}
We have now a complete string, because we received the “#”|
NOTE. We havnt done any error checking code. This will come in a later tutorial
In the Main Loop add the following:
if (stringComplete) { // This will only run after we received the “#” and StringComplete = TRUE
//Serial.println(inputString);
//this we will change later with cleanup code.
// for now, lets set all LED’s state to LOW
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
Now we process the characters 1 by one to read the value and switch the led’s on accordingly
if (inputString.charAt(0) == '1'){
digitalWrite(8,HIGH);
}
if (inputString.charAt(1) == '1'){
digitalWrite(9,HIGH);
}
if (inputString.charAt(2) == '1'){
digitalWrite(10,HIGH);
}
inputString = ""; // finish process and clear Input string to receive new characters
stringComplete = false; // Set String to false to prevent running this routine again
}
Here is the complete arduino Sketch
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// put your setup code here, to run once:
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// put your main code here, to run repeatedly:
if (stringComplete) {
//Serial.println(inputString);
// clear the string:
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
if (inputString.charAt(0) == '1'){
digitalWrite(8,HIGH);
}
if (inputString.charAt(1) == '1'){
digitalWrite(9,HIGH);
}
if (inputString.charAt(2) == '1'){
digitalWrite(10,HIGH);
}
inputString = "";
stringComplete = false;
}
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
inputString += inChar;
if (inChar == '#') {
stringComplete = true;
}
}
}
Upload the sketch onto the arduino ,
If all goes according to plan, you AppGameKit app will be able to switch the Led;s ON/OFF