How do I convert Java code into Arduino

Hi, I've got the code below which is in C++. How do I convert it to Arduino? I'm mainly troubled by the serial parts - converting byte[] command = new byte[5] etc..

Any help would be appreciated.

// This code snippit will get and convert all the data (Call continuously)
FlushPort();
ReadWriteRegister(128, _throttleOut, true);//_throttleOut is 0[0%] to 65535[100%]
_voltage = ReadWriteRegister(0, 0, false) / 2042.0 / 0.05;
_rippleVoltage = ReadWriteRegister(1, 0, false) / 2042 / 0.25;
_current = ReadWriteRegister(2, 0, false) / 2042.0 / 0.02;
_power = _voltage * _current;
if (!_lastReading.Equals(DateTime.MinValue))
	_ampHours += ((TimeSpan)(DateTime.Now - _lastReading)).TotalHours * _current;
_lastReading = DateTime.Now;
_throttle = (ReadWriteRegister(3, 0, false) / 2042.0 / 1.0);
_pwm = ReadWriteRegister(4, 0, false) / 2042.0 / 3.996735;
_rpm = ReadWriteRegister(5, 0, false) / 2042.0 / 4.89796E-5;
double poleCount = 4;//Motor pole count
_rpm = _rpm / (poleCount / 2);
_temp = ReadWriteRegister(6, 0, false) / 2042.0 * 30.0;
_becVoltage = ReadWriteRegister(7, 0, false) / 2042 / 0.25;
_safeState = ReadWriteRegister(26, 0, false);
_linkLiveEnabled = ReadWriteRegister(25, 0, false);
_estopStatus = ReadWriteRegister(27, 0, false) == 0 ? false : true;
_rawNTC = ReadWriteRegister(9, 0, false) / 2042.0 / 0.01567091;
_rawNTC = 1.0 / (Math.Log(_rawNTC * 10200.0 / (255.0 - _rawNTC) / 10000.0, Math.E) / 3455.0 + 1.0 / 298.0) - 273.0;

// Here is the flush port method
private void FlushPort()
{   
	// Flush out any existing data
	byte[] command = new byte[5];
	command[0] = command[1] = command[2] = command[3] = command[4] = 0;
	_port.Write(command, 0, 5);
	while (_port.BytesToRead > 0)
	{
		_port.ReadByte();
	}
}

// Here is the read write method
private double ReadWriteRegister(int reg, int value, bool writeMode)
        {
            // Send read command
            byte[] command = new byte[5];

            command[0] = (byte)(0x80 | _deviceId);
            command[1] = (byte)reg;x
            command[2] = (byte)((value >> 8) & 0xFF);
            command[3] = (byte)(value & 0xFF);
            command[4] = (byte)(0 - command[0] - command[1] - command[2] - command[3]);
            _port.Write(command, 0, 5);
            
            // Read response
            byte[] response = new byte[3];
            response[0] = (byte)_port.ReadByte();
            response[1] = (byte)_port.ReadByte();
            response[2] = (byte)_port.ReadByte();

            if ((byte)(response[0] + response[1] + response[2]) == 0)
            {
                return (double)((response[0] << 8) + (response[1]));
            }
            else
            {
                throw new Exception("Error communicating with device!");
            }
        }

The Arduino IDE uses C++
Where are you stuck ?

I'm using an Arduino Mega 2560 and I know that

byte[] command = new byte[5];

that code doesn't work in Arduino IDE.

Also this code here:

_port.Write(command, 0, 5);

Won't work either.

So I'm not sure how to convert that if that makes sense.

byte[] command = new byte[5];Which part of it won't work, bearing in mind that byte is s reserved word in the Arduino environment.

What are you expecting the _port.Write() function to do ?

byte[] command = new byte[5]

Looks more like Java than C++ to me.

Hi, you're right. I've changed the topic to Java code...Rookie mistake.

throw new Exception("Error communicating with device!");

That one is going to be fun.

Haha yes I got that one before when I tried. :slight_smile:

I suspect both 4th Order Ignorance and 2nd Order Ignorance. You are about to be gravely disappointed.

Structured exceptions do not exist in the Arduino world. That line of Java has no equivalent. You will not be able to perform a line-by-line conversion. (There are other troublesome lines in your snippet.)

If you want that code to run on an Arduino you will have to rewrite it.

Hmm... Do you know any Serial equivalent I can use on the arduino?

The small bit of "serial" in the code you posted is the smallest part of your effort.

Start with the biggest; post #6. How do you plan to handle run-time failures?

I just changed that to Serial.println("Error comm..."). Can you explain why a run-time error is a problem. I'm new to Java and in Arduino I haven't really handled run time errors..

hillp16:
Can you explain why a run-time error is a problem. I'm new to Java and in Arduino I haven't really handled run time errors..

Java is pretty much an interpreted language. The JVM is in charge and can can spot runtime errors and cause error events to happen which can be trapped within your Java code.

There is no equivalent to the JVM on an Arduino. If your code does something stupid there is nothing to warn you - you have to plan for problems yourself (such as division by zero).

...R

Ok.. So can anyone help me try convert this code? I don't know where to start..

Start with the stuff the compiler barfs on.

That code uses a whole lot of external methods. You'd be much better off starting from scratch rather than trying to "convert" this code.

Start with a small program and slowly add the functionality that you want. You could try to understand the Java code to help you implement an Arduino version, but most of the code above is calls to external functions, so it would all be different on the Arduino. Starting from scratch is a better option.

but, if you want to continue down your path (which I think is a bad idea), here's what will compile in C++.

//#define byte unsigned char

void someFunction();
void FlushPort();
double ReadWriteRegister(int reg, int value, bool writeMode);

void someFunction()
{
    double _throttleOut = 0;
    
    // This code snippit will get and convert all the data (Call continuously)
    FlushPort();
    ReadWriteRegister(128, _throttleOut, true);//_throttleOut is 0[0%] to 65535[100%]
    double _voltage = ReadWriteRegister(0, 0, false) / 2042.0 / 0.05;
    double _rippleVoltage = ReadWriteRegister(1, 0, false) / 2042 / 0.25;
    double _current = ReadWriteRegister(2, 0, false) / 2042.0 / 0.02;
    double _power = _voltage * _current;
    //if (!_lastReading.Equals(DateTime.MinValue))
    {
        //_ampHours += ((TimeSpan)(DateTime.Now - _lastReading)).TotalHours * _current;
    }
    //_lastReading = DateTime.Now;
    double _throttle = (ReadWriteRegister(3, 0, false) / 2042.0 / 1.0);
    double _pwm = ReadWriteRegister(4, 0, false) / 2042.0 / 3.996735;
    double _rpm = ReadWriteRegister(5, 0, false) / 2042.0 / 4.89796E-5;
    double poleCount = 4;//Motor pole count
    _rpm = _rpm / (poleCount / 2);
    double _temp = ReadWriteRegister(6, 0, false) / 2042.0 * 30.0;
    double _becVoltage = ReadWriteRegister(7, 0, false) / 2042 / 0.25;
    double _safeState = ReadWriteRegister(26, 0, false);
    double _linkLiveEnabled = ReadWriteRegister(25, 0, false);
    double _estopStatus = ReadWriteRegister(27, 0, false) == 0 ? false : true;
    double _rawNTC = ReadWriteRegister(9, 0, false) / 2042.0 / 0.01567091;
    //_rawNTC = 1.0 / (Math.Log(_rawNTC * 10200.0 / (255.0 - _rawNTC) / 10000.0, Math.E) / 3455.0 + 1.0 / 298.0) - 273.0;
}

// Here is the flush port method
void FlushPort()
{  
    // Flush out any existing data
    byte command[5];
    command[0] = command[1] = command[2] = command[3] = command[4] = 0;
    //_port.Write(command, 0, 5);
    //while (_port.BytesToRead > 0)
    {
        //_port.ReadByte();
    }
}

// Here is the read write method
double ReadWriteRegister(int reg, int value, bool writeMode)
{
    // Send read command
    byte command[5];

    //command[0] = (byte)(0x80 | _deviceId);
    //command[1] = (byte)reg;x
    command[2] = (byte)((value >> 8) & 0xFF);
    command[3] = (byte)(value & 0xFF);
    command[4] = (byte)(0 - command[0] - command[1] - command[2] - command[3]);
    //_port.Write(command, 0, 5);
    
    // Read response
    byte response[3];
    //response[0] = (byte)_port.ReadByte();
    //response[1] = (byte)_port.ReadByte();
    //response[2] = (byte)_port.ReadByte();

    if ((byte)(response[0] + response[1] + response[2]) == 0)
    {
        return (double)((response[0] << 8) + (response[1]));
    }
    else
    {
        //throw new Exception("Error communicating with device!");
    }
}

So far I have got the code below together. The values I am printing out give crazy, incorrect values (it thinks the voltage is 639V??), and they are mixed with the error message in the serial terminal.

Please pick out any errors - the code I have so far:

/* CONNECTIONS

CONTROLLER +5V     --> SERIAL LINK +5V
CONTROLLER SIGNAL  --> SERIAL LINK SIGNAL
CONTROLLER GND     --> SERIAL LINK GND

SERIAL LINK +BUS   --> ARDUINO +5V
SERIAL LINK TX     --> ARDUINO RX
SERIAL LINK RX     --> ARDUINO TX
SERIAL LINK GND    --> ARDUINO GND

*/

/* DEFINITIONS */

/* FLOATS */

byte command[5];
byte response[3];

/* INTEGERS */
int deviceId = 0x17;
int throttleOut = 0;
int voltage = 0;
int rippleVoltage = 0;
int current = 0;
int power = 0;
int throttle = 0;
int pwm = 0;
int rpm = 0;
int temp = 0;
int becVoltage = 0;
int safeState = 0;
int linkLiveEnabled = 0;
int eStopStatus = 0;
int rawNTC = 0;

/* SETUP */
void setup() {
  Serial1.begin(115200);
  Serial.begin(115200);

}
void loop() {
  flushPort();
  ReadWriteRegister(128, throttleOut, true);//_throttleOut is 0[0%] to 65535[100%]
  voltage = ReadWriteRegister(0, 0, false) / 2042.0 / 0.05;
  rippleVoltage = ReadWriteRegister(1, 0, false) / 2042 / 0.25;
  current = ReadWriteRegister(2, 0, false) / 2042.0 / 0.02;
  power = voltage * current;
  throttle = (ReadWriteRegister(3, 0, false) / 2042.0 / 1.0);
  pwm = ReadWriteRegister(4, 0, false) / 2042.0 / 3.996735;
  rpm = ReadWriteRegister(5, 0, false) / 2042.0 / 4.89796E-5;
  double poleCount = 4;//Motor pole count
  rpm = rpm / (poleCount / 2);
  temp = ReadWriteRegister(6, 0, false) / 2042.0 * 30.0;
  becVoltage = ReadWriteRegister(7, 0, false) / 2042 / 0.25;
  safeState = ReadWriteRegister(26, 0, false);
  linkLiveEnabled = ReadWriteRegister(25, 0, false);
  eStopStatus = ReadWriteRegister(27, 0, false) == 0 ? false : true;
  rawNTC = ReadWriteRegister(9, 0, false) / 2042.0 / 0.01567091;
  rawNTC = 1.0 / (log(rawNTC * 10200.0 / (255.0 - rawNTC) / 10000.0) / 3455.0 + 1.0 / 298.0) - 273.0;
  Serial.print("Voltage: ");
  Serial.println(voltage);
  Serial.print("Ripple Voltage: ");
  Serial.println(rippleVoltage);
  Serial.print("Current: ");
  Serial.println(current);
}
void flushPort() {

  command[0] = command[1] = command[2] = command[3] = command[4] = 0;
Serial1.write(command, 5);
  while (Serial1.available() > 0) {
    Serial1.read();
  }
}
uint16_t ReadWriteRegister(int reg, int value, bool writeMode) {
  // Send read command

  command[0] = (byte)(0x80 | deviceId);
  command[1] = (byte)reg;
  command[2] = (byte)((value >> 8) & 0xFF);
  command[3] = (byte)(value & 0xFF);
  command[4] = (byte)(0 - command[0] - command[1] - command[2] - command[3]);
  Serial1.write(command, 5);


  // Read response

  response[0] = (byte)Serial1.read();
  response[1] = (byte)Serial1.read();
  response[2] = (byte)Serial1.read();

  if ((byte)(response[0] + response[1] + response[2]) == 0)
  {
    return (double)((response[0] << 8) + (response[1]));
  }
  else
  {
    Serial.println("Error communicating with device!");
  }
}

The values I am printing out give crazy, incorrect values

So, print out the raw and intermediate values, and find where you went wrong.

Serial1.write(command, 5);


  // Read response

  response[0] = (byte)Serial1.read();

How long does the far-end take to turn around a command?

Never, ever read a serial line, unless you're sure there's something there to read.