how to use Type Conversion _ TO _ operator in ST (TC3)

#PLC #TwinCAT3 #Beckhoff

Learn more at Part 4 - Data types & arrays (IEC 61131-3)

1) Example

PROGRAM MAIN
VAR
	// USINT is 1 byte
	nOne_Usint : USINT;

	// UINT is 2 bytes
	nOne_Uint : UINT := 259;	
END_VAR

-----------------------------------------------------------------------

//Ok, USINT is smaller than UINT
nOne_Uint := nOne_Usint + 5

//Convesion needed, UINT loses its left byte to fit USINT
nOne_Usint := UINT_TO_USINT(nOne_Uint) + 5

2) Documentation

There are type conversions from basically every primitive type in TwinCAT.

Every data type has type conversion operators, and they behave slightly different depending from which and to which data type you want to convert. Learn more here

The behavior is obviously different if you want to convert from one type of integer to another type of integer, compared to converting from an integer to string for example.

I will demonstrate with one example,

Let's assume we have declared two integers:

The USINT is 1 byte with an upper bound of 255,
250

and the UINT is 2 bytes with an upper bound of 65535
250

Lets now assume we assigned the UINT, that is the 2 bytes integer, the value of the USINT (that is the 1 byte integer) plus 5.
300

The compiler would have no problem with this simply because the UINT is bigger than the USINT and can easily fit the value of USINT plus 5.

If we would do it the other way around, we would get a compile error stating that we cannot convert the type UINT to the type USINT simply because the UINT is bigger than USINT and we can't fit the data in the UINT inside the USINT
500

What we need to do is to do a type conversion using UINT_TO_USINT of the UINT
500

that is we need to convert the value of the bigger data type to a value that can fit inside the smaller data type.

But, how does this work?

Let's assume the UINT has a value of 259, which is bigger than what we can fit inside the USINT which is 255.
500

If we represent the decimal value of 259 as a binary, this is what we will get.

Two bytes, each carrying eight bits.

What the type conversion will do is simply remove the left byte, and leave only the right byte
500

Because one byte is removed in the conversion, we are left with one byte which can fit inside an USINT

The right byte's value is 3 in base-10,
500

and we take that plus the five from before, which will give us the result 8.
500

A value of 8 can be stored in an USINT.