B4J Tutorial B4J Arduino Demo

Here's a really simple demonstration of connecting an Arduino Uno to an app written in B4J.

You will need to modify the code around line 25 to reflect the correct COM Port that your Arduino is connected to. You can test the Arduino code using the Arduino IDE Serial Monitor - by entering the commands "HIGH" or "LOW" (sans quotes) to cycle your Arduino LED on. Set the Serial Monitor to NEWLINE and 9600 Baud.

After you get a successfull test, you should close the Arduino IDE as it may try to maintain the connection with your Arduino - which ties up your COM port and will prevent the B4J app from connecting. It's also possible that without running the Arduino IDE Serial Monitor prior to using the B4J app you will have problems connecting to the Arduino and may have to specify the serial port connection properties in your B4J Project.

Update (02/13/2014):
I added the SetParams function to the AppStart Subroutine below - this will enable the connection from the Java App to the Arduino without requiring the initial connection by the Arduino IDE / Serial Monitor. Contents of the Zip File were updated to reflect the change also.

B4J Program:
B4X:
#Region  Project Attributes

    #MainFormWidth: 330
    #MainFormHeight: 200

#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private txtFromArduino As TextField
    Private btnLEDOn As Button
    Private btnLEDOff As Button
    Private sp As Serial
    Private astream As AsyncStreams
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    sp.Initialize("")
    MainForm.RootPane.LoadLayout("test1") 'Load the layout file.
    MainForm.Show
    MainForm.Title = "B4J Arduino Demo"
    ' SET TO YOUR COM PORT VALUE
    sp.Open("COM3")
    ' CONFIGURE PORT (ADDED 2/13/2014)  
    Dim BaudRate As Int = 9600
    Dim DataBits As Int = 8
    Dim StopBits As Int = 1
    Dim Parity As Int = 0
    sp.SetParams (BaudRate , DataBits , StopBits , Parity )
    astream.Initialize(sp.GetInputStream, sp.GetOutputStream, "astream")
    txtFromArduino.Text = "Awaiting Selection"
End Sub

Sub AStream_NewData (Buffer() As Byte)
    Dim s As String = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Log(s)
    If s = "0" Then
    txtFromArduino.Text = "Arduino Replied with a 0 (zero) LED=OFF"
    Else If s = "1" Then
    txtFromArduino.Text = "Arduino Replied with a 1 (one) LED=ON"
    End If
End Sub

Sub Send_To_Arduino(cmd As String)
    Dim bytes() As Byte = (cmd & CRLF).GetBytes("UTF8")
    astream.Write(bytes)
End Sub

Sub btnLEDOff_Action
    Send_To_Arduino("LOW")
End Sub
Sub btnLEDOn_Action
    Send_To_Arduino("HIGH")
End Sub

Sub MainForm_Closed
    sp.Close
    astream.Close
End Sub
Sub AStream_Error
    Log("Error: " & LastException)
    astream.Close
End Sub

Arduino Program:
B4X:
int LED = 13;                  // define pin 13 as led;

void setup()                    // run once, when the sketch starts
{
  Serial.begin(9600);          // set up Serial library at 9600 bps
  pinMode(LED,OUTPUT);          // define pin 13 as output (led);
  Serial.print("Awaiting Input... \n");  // display initial message in Serial Monitor;
}

String txtMsg = "";
char s;

void loop() {
    while (Serial.available() > 0) {
        s=(char)Serial.read();
    
        if (s == '\n') {
            if(txtMsg=="HIGH") {  digitalWrite(LED, HIGH);
              Serial.write("1");          
            }
            if(txtMsg=="LOW")  {  digitalWrite(LED, LOW);
              Serial.write("0");          
            }
        
            txtMsg = "";
        } else {
            txtMsg +=s;
        
        }
    }
}

There's a simple JavaFX Form included in the attached zip file that is used to send the instruction(s) to the Arduino and display the response received from the Arduino.

Here's a link to a short video of the program turning an LED on.

Gaver
 

Attachments

  • B4J_Arduino_V2.zip
    1.5 KB · Views: 876
Last edited:

GMan

Well-Known Member
Licensed User
Longtime User
When i start the serial communication with an ARDUINO, it resets when connecting (as the original ARDUINO IDE does).
How can i disable that - it depends AFAIK on the RTS / CTS parameters.
 

Gaver Powers

Member
Licensed User
Longtime User
GMan,

When you say it resets, what are you referring to?
Meaning - what is changing on the Arduino - is a pin going low or high on connection?

Also, I noticed that if I did not begin with a connection between the Arduino IDE/Serial Monitor and then launch the Java App - the java app would not be able to communicate with the Arduino. I believe the Arduino IDE establishes the connection protocol thru the COM Port (8;N;1) and that after making that connection - it becomes available to the Java App. I was able to work around this problem in a different program by using the SetParams function of the JSerial Library:
Ref: http://www.b4x.com/b4j/help/jserial.html There's also functions exposed for manipulating the RTS / CTS bits in the Library.

The code above and the Attached B4J file was updated with the changes today (2/13/2014).
 
Last edited:

GMan

Well-Known Member
Licensed User
Longtime User
Dont know if High or Low - the ARDUINO resets :rolleyes:
When i connect through a "normal" terminalproggi like HTerm or so it did not restart.

So i will have a look on the RTS DTS parameters....

btw: i am using own code , here is some output from one of my MEGAs:
B4X:
14:45 Uhr
Zeitschaltuhr Check

5 s Input Chance !
--- Sequenz wird gestartet! ---
Free RAM vorher : 2296

13.2.2014 14:45:19
Messung Nummer  : 154
Humidity-1 (%)  : 51.00
Humidity-2 (%)  : 47.00
Temperature1(oC): 14.00
Temperature2(oC): 16.00
Heizung AN      :
eC-Sensor #1    : 1017
eC-Sensor #2    : 1021
eC-Sensor #3    : 1023
eC-Sensor #4    : 1023
eC-Sensor #5    : 968
Methan-Sensor   : 2.56
PIR-Sensor      : 0

14:46 Uhr
Zeitschaltuhr Check

GBox OVL        :
DS18x20-1  (oC): 13.69
GBox OHL        :
DS18x20-2  (oC): 13.75
GBox OHR        :
DS18x20-3  (oC): 14.56
GBox OVR        :
DS18x20-4  (oC): 13.75
GBox MVL        :
DS18x20-5  (oC): 15.06
GBox UHL        :
DS18x20-6  (oC): 13.75
Strom  [V=]    : 1.51
Last  [mA]    : 0.00

NICHT Gespeichert !
RAM frei: 2296
 
Last edited:

Gaver Powers

Member
Licensed User
Longtime User
GMan,

If your Arduino is doing a reset when you connect all your sensors - but is NOT doing a reset when you connect with a Terminal Emulator - then my guess would be something is wrong with the schematic and how the instruments are wired to the arduino - meaning one (or more) of them may be sending more voltage / current or drawing more than the board can handle. Or... one of the leads could be connected to a reset pin on the mega. Not sure without a schematic and clone of your instrument array.

I would suggest trying the connection to the sensors one at a time and see if one of them is causing the reset.

G
 

GMan

Well-Known Member
Licensed User
Longtime User
No, that doesnt make sense...as written, if i connect through other terminal proggis there is no reset, except the Terminal unter the ARDUINO IDE which resets the board also every time when connecting.
I have also self coded software for Windows (done with VB) which works also without a reset.
 

Gaver Powers

Member
Licensed User
Longtime User
GMan,

I tried connecting using the Arduino IDE / Serial Monitor and it does not appear to be resetting the Arduino during the connection process (Arduino Uno).

Using the Arduino code above - immediately on connection - the Arduino writes to the Serial Port :
B4X:
Serial.print("Awaiting Input... \n");
which flashes the LED's (Rx/Tx) on the Arduino and displays the message "Awaiting Input..." in the serial monitor.

As far as I can tell - it it not resetting the arduino.

If I press the "reset" button on the Arduino Uno - the LED on pin 13 flashes 3 times (rapidly), followed with a single Tx LED flash - which I believe is caused by the bootloader writing the application to the CPU again, followed by the Serial.print function to the Serial Monitor (Tx operation).

What does your Mega do when you run the program above in the Arduino IDE / Serial Monitor?
Are you seeing the same results I am?

G
 

GMan

Well-Known Member
Licensed User
Longtime User
Do you have UNO Rev.3 ?
And maybe a MEGA for trying that ?

As i can say on UNO and MEGA the chips reset in the same moment the ide connects - and there is no paramter or option to disable that.
 

Gaver Powers

Member
Licensed User
Longtime User

GMan

Well-Known Member
Licensed User
Longtime User
Hoi,
This discussion on the Arduino.cc forum appears to be dealing with the same subject - and is suggesting you can prevent the reset by attaching a Capacitor to the board.
Yo, found it - but since i start the IDE Serial Monitor only after compiling it doesnt matter.
Normally i use (as written) self coded or other (HTerm i.e.) Win-Software or Apps for that, and with that the effect doesnt take effect :cool:
 

GMan

Well-Known Member
Licensed User
Longtime User
to communicate directly with these ports not usb, any ideas
What do you mean with that ?

You can connect through Bluetooth or LAN or WLAN to your Arduino and read/write datas from that busses.
 

salim safran

Member
Licensed User
Longtime User
Gman, some i/o extenders for example analoge, digital, RTC, LCD TFT do have either i2c or spi. i want to communicate with them through b4a directly not through Arduino. there intresting boards like pcduino, beaglebone, olmix, cubie and many others can run android and do have also i2c and spi ports, I have seen the pi-b4j library but still want to stay with boards that support android.
 
Last edited:

GMan

Well-Known Member
Licensed User
Longtime User
some i/o extenders for example analoge, digital, RTC, LCD TFT do have either i2c or spi.
i want to communicate with them through b4a directly not through Arduino.
Can you gimme a link to such a device ?

there intresting boards like pcduino, beaglebone, olmix, cubie and many others can run android and do have also i2c and spi ports
Yo, but still dont understand why do you want to install Android on a µc only for accessing the ports. This works also with native Arduino (or others) code.

I have seen the pi-b4j library but still want to stay with boards that support android.
Looking forward to see the results....
 

pepelillo

New Member
Hi all.

Newbe with B4J, I'm trying to deal with my arduino project. Arduino part is finished and working properly but I want to get some serial info via arduino serial port. This is working and I can see data via serialmonitor within arduino ide, and works very well.

This is a very simple program to get this serial data to the B4J log console (as a very starting point):

B4X:
#Region  Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 400
#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private sp As Serial
    Private astream As AsyncStreams

End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    'MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
    MainForm.Show
    sp.Initialize("")
    sp.Open("COM20")
    Dim BaudRate As Int = 38400
    Dim DataBits As Int = 8
    Dim StopBits As Int = 1
    Dim Parity As Int = 0
    sp.SetParams (BaudRate , DataBits , StopBits , Parity )
    astream.Initialize(sp.GetInputStream, sp.GetOutputStream, "astream")
   

End Sub
Sub AStream_NewData (Buffer() As Byte)
    Dim s As String = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Log(s)
End Sub


After that I'll start with parsing, checking and showing data, but first i't neccesary to check that communication is reliable.

And the I get the first issue, arduino sends data with a LF (only a LF) at the end of every seria data packet (AFAIK serial can deal with LF, CR or LF/CR), but randomly some data packets are splited (as if there were a LF or CR within) and I'm checked that it's not true.

Any idea will be great.

Thanks
 

asmag

Member
Licensed User
Longtime User
Hi!

I did some test with this project. I put 2 ImageViews to simulate the action of leds : ON/OFF but the ImageView works fine only I run on debug mode. If I run on release mode, the ImageView Control disapear. What was my wrong ?
 

pivar

Member
Licensed User
Longtime User
Late , but thanks to Gaver Powers ; so I make softs for machines et to pilot steppers motors, relay and read switch , arduino is good ; for UI data calcutation , B4j is my best ; so B4j and megaAT2560 are exchanging data :
B4j send commands (strings were the firsts char are command and following are parameters) , Arduino send datas ;
I tested it in parallel with Wemos (mini pro) at 921600 bauds :
send 1000 times string of a dozen of char (ard to B4J) takes 280ms (180ms with Wemos) ;
make 100000 for next with two lines calcul integer takes 119ms (9ms with Wemos) ;
make 100000 for next with two lines of float takes 119ms (174ms with Wemos)
To find automatically the microcontroller , I use try (sp.Open(COMX)) catch and when find open , send string and wait if answer is good
But Wemos is also with Wifi ; I have no Idea how to find Wemos with Wifi ; do someone has tracks ?
 

pivar

Member
Licensed User
Longtime User
Achh, new thread , I'm not very bright , but I hav'nt find how to start a question in forum
, but with astream events I have find with arduino mega and Wemos some unexpected situations :if mega (or wemos) send by serial two messages , I see in the buffer B4j only one string (ex:Serial.print("123") and Serial.print("456") and the B4j buffer has 123456 , or sometimes first event "12345" and second event "6"
(with println on mega or Wemos byte 13 and 10 are added , but problem is the same)
I saw kind of same remark on astream somewhere in the forum
But I would have one event per Serial.print and so I tested with variations of time between two Serial.print
With 150ms between two Serial.print , B4j read two events at any baud speed
 
Top