Android Tutorial Arduino / B4A

Hi all. Interfacing B4A with Arduino is really very simple and you can create any kind of application.
This is a simple example:



Code B4A:

B4X:
#Region  Project Attributes
    #ApplicationLabel: Arduino Devil
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: portrait
    '#CanInstallToExternalStorage: false
    '#DebuggerForceStandardAssets: true
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    Dim usb As UsbSerial
    Private ast As AsyncStreamsText
End Sub

Sub Globals
    Private btn_accendi As Button
    Private btn_spegni As Button
    Private lbl_tipo As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    gira
End Sub

Sub gira

    If usb.UsbPresent(1) = usb.USB_NONE Then    ' Ver_2.4
        Log("No device USB NONE")
        Return
    End If
    If (usb.HasPermission(1)) Then    ' Ver_2.4
        Log("Device Information USB" & CRLF & usb.DeviceInfo(1))

        Dim dev As Int
        'IMPORTANT BAUD RATE AS ARDUINO
        dev = usb.Open(19200, 1)
        'dev = usb1.Open(4800, 1)
        'dev = usb1.Open(115200, 1)        ' Ver_2.4
        'dev = usb1.Open(9600, 1)        ' Ver_2.4
        If dev <> usb.USB_NONE Then
            Log( "CONNECTED SUCCESSFULLY!!!" & CRLF & "*****************")

        If ast.IsInitialized Then ast.Close
        ast.Initialize(Me, "ast", usb.GetInputStream, usb.GetOutputStream) 'initialize AsyncStreamsText with the socket streams.

        Else
            Log("Error opening USB port 1")
            Log("**************" & CRLF & "ERROR OPENING USB PORT 1 STEP 2" &CRLF& "**************")
        End If
    Else
        usb.RequestPermission(1)  ' Ver_2.4
        Log("GENERAL CHECK")
        gira
    End If
 

End Sub

Sub ast_NewText(Text As String)
    Log("****")
    Log("Valore: " & Text)
    'Log(Text.Length)
    If Text.Contains("ACCENDO") Then
        lbl_tipo.Visible = True
        lbl_tipo.Color = Colors.Green
        lbl_tipo.Text = "LED ON"
    else if Text.Contains("SPENGO") Then
        lbl_tipo.Visible = True
        lbl_tipo.Color = Colors.Red
        lbl_tipo.Text = "LED OFF"
    else if Text.Contains("Pronto") Then
        lbl_tipo.Visible = True
        lbl_tipo.Color = Colors.Black
        lbl_tipo.TextColor = Colors.White
        lbl_tipo.Text = "PUSH RESET"
    Else
        lbl_tipo.Visible = False
    End If
 
End Sub

Sub ast_Terminated
    Log("Connection terminated")
End Sub

Sub Activity_Click

 
End Sub


Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub


Sub btn_spegni_Click
    ast.Write("s")
End Sub

Sub btn_accendi_Click
    ast.Write("a")
End Sub


Code Arduino:
B4X:
#define LED 13

void setup() {
Serial.begin(19200); // apro la seriale
delay(1000); //attendo che l'utente faccia altrettanto
Serial.println(F("Pronto")); //sono pronto
pinMode(LED, OUTPUT);
}

//programma principale
void Loop() {


//controllo se c'è qualcosa in arrivo sulla seriale
If (Serial.available()) {
byte command = Serial.read(); //leggo il primo byte
switch (command) { //controllo che sia un comando valido
Case 'a': //ON LED
digitalWrite(LED, HIGH);
Serial.println(F("ACCENDO LED13"));
break;
Case 's': //OFF LED
digitalWrite(LED, LOW);
Serial.println(F("SPENGO LED13"));
break;
}
//svuoto il buffer da eventuali altri caratteri che non mi servono più
While (Serial.available()) {
byte a = Serial.read();
}
}
}

This is a little more complex application (all B4A).


Magic World B4X
Have a nice day
 
Last edited:

MarcoRome

Expert
Licensed User
Longtime User
Why not use B4R to develop the Arduino program? It will be simpler and work great with B4A.
Of course. Already think about this. The next developments will be made exclusively with B4R
 

xpectmore

Member
Licensed User
Longtime User
Marco : bel lavoro!
comprero anche io Arduino per iniziare a fare questo test ed la prima iniziativa con Arduino ed b4r!
grazie per iniziamento!
tantissimi anni fa ho studiato elettronica amatoriale da solo ed lo abbandonata a rispetto di informatica....
 

walterf25

Expert
Licensed User
Longtime User
Which library are you using to plot the signals on the graphs?

Walter
 

Beja

Expert
Licensed User
Longtime User
Thanks for this tutorial
If the arduino side is in B4R then it can be edited and modified to learn more and to fit other purposes.
I don't know Arduino Sketch.
 

Douglas Farias

Expert
Licensed User
Longtime User
@MarcoRome if you make the sample example on b4r post is here pls.
I'm thinking of starting a program on Arduino and B4R. I love watching videos and other programmers' results.
 

davidforexer

New Member

why i found " 'If' was not declared in this scope"... in

//controllo se c'è qualcosa in arrivo sulla seriale
If (Serial.available()) { ...
 

Erel

B4X founder
Staff member
Licensed User
Longtime User

MarcoRome

Expert
Licensed User
Longtime User
The Arduino code was written with the Arduino IDE ( long time ago ). You can translate the code in B4R in a very simple way.
See this example for the Led Blink.

B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

Sub Process_Globals
    Public Serial1 As Serial
    Private Timer1 As Timer
    Private pin As Pin
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")
    pin.Initialize(14, pin.MODE_OUTPUT)
    Timer1.Initialize("Timer1_Tick", 1000) '1000ms = 1 second
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick
    Dim currentState As Boolean = pin.DigitalRead
    Log("CurrentState: ", currentState)
    Dim NewState As Boolean = Not(currentState)
    Log("NewState: ", NewState)
    pin.DigitalWrite(NewState)
End Sub
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…