Serial Talk- Sending data from ESP32 (and Arduino Uno) to Java in cmd

Nickson Joram
Nov 1 · 5 min read

Communication is an important thing that is widely being used to share the information. We, human are communicating with each other using various mediums. Not only us, everything in the universe have a way to communicate and transmit data from one place to another.

The most of the people who are in love with ESP32 or Arduino things are just preferring Processing to create GUI. There, you can handle almost all the things with out editing your Arduino sketch.

What for Java people? Even though Java people use various IDE to create various magnificent things, should they get defeated by this communication issue?

Hey wait, are you kidding me? Processing and Java, are they different? When you are using Processing, at your right top corner, you can see mode selection and the most probably you can see Java. Then your face will probably shine and start coding public class bla bla and so on….!

Yes?

Hell no.

Just look at this example.

void setup(){
size(500, 500);
}

void draw(){
background(64);
ellipse(mouseX, mouseY, 20, 20);
}

This is a sketch to have an ellipse shape at your mouse tip in your desired sized frame. If you run this in an ordinary Java platform, will it work? But actually, Processing is a liar right? When we run the above mentioned code, Processing is secretly turning those lines into Java code that looks exactly like this.

import processing.core.PApplet;

public class MySketch extends PApplet {

public void settings() {
size(500, 500);
}

public void draw(){
background(64);
ellipse(mouseX, mouseY, 20, 20);
}

public static void main(String[] passedArgs) {
String[] appletArgs = new String[] { "MySketch" };
PApplet.main(appletArgs);
}
}

Those who can manage this liar, no need to worry. But those who are in Java fully, without knowing Processing, have to have some way of doing communication right?

So how can we communicate with an ESP32 or with an Arduino Uno? Since we are focusing on receiving the data from ESP32, we have to set the sketch for the ESP32. That means, we have to make sketch for ESP32 to emit some data.

So initially we have to define the special symbol used in Serial Data Stream from ESP32.

char start_char = ‘@’;
char end_char = ‘#’;
char sep_char = ‘:’;

After that we have to define the data variables that has to be sent along with a temporary String holder.

char name[] = “ESP32”;
String data1=”Hi Hello”;
String data2=”Good Morning”;
//Temporary String holder
String temp;

Then we have to define the setup() and loop() which is clearly explained here.

void setup(){
//Start Serial Port
Serial.begin(9600);
}

void loop() {
//Data Export Loop
startStream();
writeStream(name);
writeStream(data1);
writeStream(data2);
endStream();
}

Here, you can see, there are three new methods. Obviously we are going to use OOP concept. I hope if your are watching carefully, the variable types of name is different than that of data1 and data2. Right? So, we are having overloading methods having the method name writeStream. So we need to write two separate methods so that we can run this program.

I’ve defined the methods as follows.

void startStream(){
Serial.write(start_char);
Serial.flush();
}

void endStream(){
Serial.write(end_char);
Serial.flush();
}

void sepStream(){
Serial.write(sep_char);
Serial.flush();
}
void writeStream(String data){
temp = String(data);
byte charBuf[temp.length()];
temp.getBytes(charBuf,temp.length()+1);
Serial.write(charBuf,temp.length());
Serial.flush();
sepStream();
}
void writeStream(char string[]){
Serial.write(string);
Serial.flush();
sepStream();
}

So now we have set the sketch for our ESP32. What should we, the noble Java Programmers do now?

To engage in serial communication, we need to add a library called jSSC (Java Simple Serial Connector). Let the class name be SerialCommunication.

/**
*
* @author A Nickson Joram
*/
import jssc.SerialPort;
import jssc.SerialPortList;
import jssc.SerialPortException; //these things have to imported

public class SerialCommunication{
//Declare Special Symbol Used in Serial Data Stream from ESP32, we did the same in Arduino IDE sketch too. It should be same
final static String start_char = "@";
final static String end_char = "#";
final static String sep_char = ":";

public static void main(String[] args) throws InterruptedException {

Then to know the available hardware ports in your machine,

        //Display Available Ports -- ideas: let user choose?
System.out.println("Available ports");
String[] portList = SerialPortList.getPortNames();
for(int i = 0; i < portList.length; i++)
System.out.println(portList[i]); //this will print the active hardware ports in your machine

Now we will be having the active hardware ports. We can either omit this step by straightly referring the port in our code or just make instant input when we have multiple boards connected at once.

        //Define Serial Port # -- can be found in Device Manager or Arduino IDE
SerialPort serialPort = new SerialPort("COM5");

In my machine, the ESP32 was connected to COM5, so I used it. Note that, it may vary from machine to machine. Deciding the ports and things shall be refereed here.

After that we have to get the data form the ESP32 and have to print it on our cmd.

        try {
//Open Serial Port
serialPort.openPort();
//Define Parameter -- can be found in Device Manager
// baudRate, iataBits, stopBits, parity
serialPort.setParams(9600,8,1,0);
byte[] buffer; //Filter out bad data from Arduino initialization
buffer = serialPort.readBytes(200);
//Retrieve data from Arduino -- read 100 bytes
buffer = serialPort.readBytes(100);
//Convert bytes into String
String dataStream = new String(buffer);
//Isolate Data Stream using symbols defined earlier
dataStream = dataStream.substring(dataStream.indexOf(start_char)+1);
dataStream = dataStream.substring(0,dataStream.indexOf(end_char)-1);
//Retrieve data sent by Arduino in form of Strings
String[] data = dataStream.split(sep_char);
//Display obtained data
for(int i = 0; i < data.length; i++)
System.out.println(data[i]);
}catch (SerialPortException ex) {
//Display Errors
System.out.println(ex);
}

When we run this class what would be the output?

Available ports
COM1
COM5
ESP32
Hi Hello
Good Morning

This communication shall be done continuously (try for that way of communication). We can even plot real-time graph from the sensors we connect with ESP32 or even more.

Java programmers now may have the smile which is unique for us. Hell yeah, we are immortal. Aren’t we?

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade