Transmitting structures to the PLC
This sample shows the transfer of a structure to the PLC via ADS. The structure consists of elements of different data types:
Unpack the sample program 'Transmitting structures to the PLC': sample04.zip
- To execute the *.jar sample, the command 'java -classpath "Sample04.jar;[path to TcJavaToAds.jar] Main' must be executed in the console in the correct directory (example path: "C:TwinCAT\Ads Api\AdsToJava\*"). For this, java must be entered in the environment variables.
import de.beckhoff.jni.JNIByteBuffer;
import de.beckhoff.jni.tcads.AmsAddr;
import de.beckhoff.jni.tcads.AdsCallDllFunction;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Main
{
public static void main(String[] args)
{
long err;
AmsAddr addr = new AmsAddr();
TransferObject transfer = new TransferObject(); // See additional class
JNIByteBuffer dataBuff = new JNIByteBuffer(19);
// Open communication
AdsCallDllFunction.adsPortOpen();
err = AdsCallDllFunction.getLocalAddress(addr);
addr.setPort(AdsCallDllFunction.AMSPORT_R0_PLC_RTS1);
if (err != 0) {
System.out.println("Error: Open communication: 0x"
+ Long.toHexString(err));
} else {
System.out.println("Success: Open communication!");
}
// Use JNIByteBuffer as a backing array for ByteBuffer
ByteBuffer bb = ByteBuffer.wrap(dataBuff.getByteArray());
// Write elements to buffer. Litte Endian!
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putShort(transfer.getShortVal());
bb.putInt(transfer.getIntVal());
bb.put(transfer.getByteVal());
bb.putDouble(transfer.getDoubleVal());
bb.putFloat(transfer.getFloatVal());
// Write struct to PLC
err = AdsCallDllFunction.adsSyncWriteReq(addr,
0x4020, // Index Group
0x0, // Index Offset
19,
dataBuff);
if(err!=0) {
System.out.println("Error: Write request: 0x"
+ Long.toHexString(err));
} else {
System.out.println("Success: Write struct!");
}
// Close communication
err = AdsCallDllFunction.adsPortClose();
if(err!=0) {
System.out.println("Error: Close Communication: 0x"
+ Long.toHexString(err));
}
}
}
The object to be transferred:
public class TransferObject
{
private short shortVal;
private int intVal;
private byte byteVal;
private double doubleVal;
private float floatVal;
public TransferObject()
{
this.shortVal = Short.MAX_VALUE;
this.intVal = Integer.MIN_VALUE;
this.byteVal = 3;
this.doubleVal = 4.1234;
this.floatVal = 5.4321f;
}
public short getShortVal() {
return shortVal;
}
public int getIntVal() {
return intVal;
}
public byte getByteVal() {
return byteVal;
}
public double getDoubleVal() {
return doubleVal;
}
public float getFloatVal() {
return floatVal;
}
}