Concatenate variable - twincat

I need to concatenate a string and an integer and a string into a variable - in this case an input.
The inputs are named as following:
DI_Section1_Valve AT %I*: BOOL;
DI_Section2_Valve AT %I*: BOOL;
DI_Section3_Valve AT %I*: BOOL;
Now, I want to loop through these (this is just a short example):
For i:= 1 TO 3 DO
Var[i] := NOT CONCAT(CONCAT('DI_Section', INT_TO_STRING(i)), '_Valve')
END_FOR
But by concatenating strings, I'll end up with a string, eg. 'DI_Section1_Valve', and not the boolean variable, eg. DI_Section1_Valve.
How do I end up with the variable instead of just the string?
Any help is appreciated, thanks in advance.
/Thoft99

That technique is called variable variables. Unfortunately this is not available in ST. There are few ways around it. As I understand Twincat 3 is based on Codesys 3.5. That means UNION is available. There is also a trick that references to BOOL does not work as expected and one reference take one byte. So you cannot place them in order, so you need to know BYTE address of input module.
TYPE DI_Bits : STRUCT
DI_Section1_Valve : BIT; (* Bit 1 *)
DI_Section2_Valve : BIT; (* Bit 2 *)
DI_Section3_Valve : BIT; (* Bit 3 *)
DI_Section4_Valve : BIT; (* Bit 4 *)
DI_Section5_Valve : BIT; (* Bit 5 *)
DI_Section6_Valve : BIT; (* Bit 6 *)
DI_Section7_Valve : BIT; (* Bit 7 *)
DI_Section8_Valve : BIT; (* Bit 8 *)
END_STRUCT
END_TYPE
TYPE DI_Sections : UNION
ByName : DI_Bits;
ByID : ARRAY[1..8] OF BOOL; (* Comment *)
ByMask: BYTE;
END_UNION
END_TYPE
PROGRAM PLC_PRG
VAR
DIS AT %IB0.0: DI_Sections; (* Our union *)
xOut : BOOL;
END_VAR
xOut := DIS.ByID[1];
xOut := DIS.ByName.DI_Section1_Valve;
DIS.ByID[5] := TRUE;
// Now DIS.ByName.DI_Section5_Valve also EQ TRUE
END_PROGRAM

You can't access a variables by using strings. What you can do instead is manually create an array of pointers to the values you want to index, for example:
DI_Section1_Valve AT %I*: BOOL;
DI_Section2_Valve AT %I*: BOOL;
DI_Section3_Valve AT %I*: BOOL;
DI_Section_Valves: ARRAY [1..3] OF POINTER TO BOOL
:= [ADR(DI_Section1_Valve), ADR(DI_Section2_Valve), ADR(DI_Section3_Valve)];
FOR i:= 1 TO 3 DO
out[i] := DI_Section_Valves[i]^;
END_FOR
EDIT: Alternatively, you could create a function that does this:
METHOD Get_DI_Selection_Valve : BOOL
VAR_INPUT
i: INT;
END_VAR
CASE i OF
1: Get_DI_Selection_Valve := DI_Section1_Valve;
2: Get_DI_Selection_Valve := DI_Section2_Valve;
3: Get_DI_Selection_Valve := DI_Section3_Valve;
END_CASE
FOR i:= 1 TO 3 DO
out[i] := Get_DI_Selection_Valve(i);
END_FOR
The idea is the same though

Related

TStringList.CustomSort: Compare() with variables

I am trying to custom sort a TStringList by a column in a .CSV file. My code below works (slowly, about 14 seconds for 200,000+ lines):
function Compare(List: TStringList; Index1, Index2: Integer): Integer;
function ColStr(const Ch: Char; const S: String; First, Last: Integer): String;
var
p1, p2: Integer;
function GetPos(const N: Integer; Start: Integer = 1): Integer;
var
I, Len, Count: Integer;
begin
Result := 0;
Len := Length(S);
if (Len = 0) or (Start > Len) or (N < 1) then Exit;
Count := 0;
for I := Start to Len do begin
if S[I] = Ch then begin
Inc(Count);
if Count = N then begin
Result := I;
Exit;
end;
end;
end;
end;
begin
p1 := GetPos(4, 1); // 4 should be a variable
p2 := GetPos(5, 1); // 5 should be a variable
if Last = 0 then Result := Copy(S, p1 + 1, length(S)) else Result := Copy(S, p1 + 1, p2 - p1 - 1);
end;
begin
Result := AnsiCompareStr(ColStr(',', List[Index1], 0, 1), ColStr(',', List[Index2], 0, 1));
end;
What I would want to do is not have this hard-coded but (where commented "should be a variable" depending on which column to sort). I know I can't use:
function Form1.Compare(List: TStringList; Index1, Index2: Integer): Integer;
for inserting variables, as I get the error:
Incompatible types: 'method pointer and regular procedure'.
I have searched through SO looking for instances of this error but cannot find one that fits my question. I would appreciate any pointers in the right direction.
This has to be done with Delphi 7 and Windows 11.
TStringList.CustomSort() does not let you pass in extra parameters, and it does not accept class methods or anonymous procedures. But, what it does do is pass the actual TStringList itself to the callback, so I would suggest deriving a new class from TStringList to add extra fields to it, and then you can access those fields inside the callback, eg:
type
TMyStringList = class(TStringList)
public
Count1: Integer;
Count2: Integer;
end;
function Compare(List: TStringList; Index1, Index2: Integer): Integer;
...
p1 := GetPos(TMyStringList(List).Count1, 1);
p2 := GetPos(TMyStringList(List).Count2, 1);
...
begin
...
end;
...
List := TMyStringList.Create;
// fill List ...
List.Count1 := ...;
List.Count2 := ...;
List.CustomSort(Compare);
So you are performing searching for k-th occurence of Ch and substring creation at every comparison.
You can optimize this process - before sorting make list/array of stringlists, created from every string, separated by needed character - use DelimitedText.
Inside compare function just work with this array and column numbers - sadly, you have to define them as global variables in current unit (for example, after Form1: TForm1)

How is a CRC32 checksum calculated with FreePascal(Lazarus)?

I have to make some project for my college, and I need to calculate CRC32. But I almost didn't work with shifts before, so even after I read theory it's still hard to me. I found some CRC32 basic algorithm for C (not mine) and I tried to rewrite it for Lazarus(Delphi). But it doesn't work. I can't understand, what's wrong. Please, help (*_ _)人
Here my code:
procedure TMyFrame.CRC32_Checksum();
var
P : Pointer;
Size, i : Integer;
CRC, j : LongWord;
B : ^Byte;
flag : Boolean;
begin
AssignFile (f, FileName);
Reset(f, 1);
Size := FileSize(f);
GetMem(P, Size);
BlockRead(f, P^, Size);
B := P;
//
//
CRC := $FFFFFFFF;
for i := 1 to Size do
begin
CRC := CRC XOR B^;
Inc(B);
for j := 0 to 7 do
begin
flag := (CRC AND 1) > 0;
if flag then
CRC := (CRC SHR 1) XOR $04C11DB7
else
CRC := CRC SHR 1;
end;
end;
LabeledEdit1.Text := IntToHEX(CRC, 8);
//
//
Freemem(P);
CloseFile(f);
end;
0xCBF43926 is the bit-wise inverse ("not") of 0x340BC6D9. You just need to use not on the result, or exclusive or with $FFFFFFFF.
Note that FPC comes with a CRC32 unit. (derived from crc32.c by Mark Adler, above )
This unit has a function to calculate the CRC for a block called crc32()
function crc32 (crc : cardinal; buf : Pbyte; len : cardinal): cardinal;
The XOR is included in this crc32.crc32() function.

Dynamic array in Turbo Pascal

I am working on my school project and I would like to use Dynamic (not static) array. I worked with ObjectPascal, so I am used to some syntax. But now I am programming in the old TurboPascal (I am using Turbo Pascal 7 for Windows).
It doesn't seem to know the ObjectPascal, so I thought, that you Turbo Pascal doesn't know dynamic arrays.
Could anyone tell me, if my theory is right or not? I tried to google, but I was not succesfull.
Basicly I am asking "how is it with dynamic arrays in Turbo Pascal 7" ?
Thank you for all reactions.
As MartynA says, there is no dynamic array type in Turbo Pascal. You need to manually allocate memory using pointers, and be careful if you use rangechecks.
Typically you define an array type
TYPE
TArrayT = array[0.. ((65535-spillbytes) div sizeof(T))-1] of T;
where spillbytes is a constant for a small deduction because you can't use the whole 64k, see what the compiler accepts. (Probably this deduction is for heapmanager structures inside the 64k block)
Then you define a pointer
PArrayT= ^TArrayT;
and a variable to it
var
P : PArrayT;
and you allocate nrelement elements using getmem;
getmem(P,SizeOf(T) * nrelements);
and optionally fill them with zero to initialize them:
fillchar(p^,SizeOf(T) * nrelements,#0);
You can access elements using
p^[index]
to free them, use freemem using the exact opposite of the getmem line.
freemem(P,Sizeof(T)*nrelements);
Which means you have to save the allocated number of elements somewhere. This was fixed/solved in Delphi and FPC.
Also keep in mind that you can't find bugs with rangechecking anymore.
If you want arrays larger than 64k, that is possible, but only with constraints, and it matters more which exact TP target (dos, dos-protected or Windows you use) I advise you to search for the online SWAG archive that has many examples. And of course I would recommend to go to FreePascal/Lazarus too where you can simply do:
var x : array of t;
begin
setlength(x,1000000);
and be done with it without additional lines and forget about all of this nonsense.
I'm using Turbo Pascal 5.5 and to create a dynamic array, perhaps the trick is to declare an array with zero dimension as follows:
dArray = array [0..0] of integer;
And then declare a pointer to that array:
pArray = ^dArray ;
And finally, create a pointer variable:
ArrayPtr : pArray;
You can now reference the pointer variable ArrayPtr as follows:
ArrayPtr^[i]; { The index 'i' is of type integer}
See the complete example below:
{
Title: dynarr.pas
A simple Pascal program demonstrating dynamic array.
Compiled and tested with Turbo Pascal 5.5.
}
program dynamic_array;
{Main Program starts here}
type
dArray = array [0..0] of integer;
pArray = ^dArray ;
var
i : integer;
ArrayPtr : pArray;
begin
for i := 0 to 9 do { In this case, array index starts at 0 instead of 1. }
ArrayPtr^[i] := i + 1;
writeln('The Dynamic Array now contains the following:');
writeln;
for i := 0 to 9 do
writeln(ArrayPtr^[i]);
end.
In this example, we have declared the array as:
array[0..0] of integer;
Therefore, the index starts at 0 and if we have n elements, the last element is at index n-1 which is similar to array indexing in C/C++.
Regular Pascal arrays start at 1 but for this case, it starts at 0.
unit Vector;
interface
const MaxVector = 8000;
// 64 k div SizeOf(float); number of float-values that fit in 64 K of stack
VectorError: boolean = False;
// toggle if error occurs. Calling routine can handle or abort
type
VectorStruc = record
Length: word;
Data: array [1..MaxVector] of float;
end;
VectorTyp = ^VectorStruc;
procedure CreateVector(var Vec: VectorTyp; Length: word; Value: float);
{ Generates a vector of length Length and sets all elements to Value }
procedure DestroyVector(var Vec: VectorTyp);
{ release memory occupied by vector }
procedure SetVectorElement(var Vec: VectorTyp; n: word; c: float);
function GetVectorElement(const Vec: VectorTyp; n: word): float;
implementation
var ch: char;
function WriteErrorMessage(Text: string): char;
begin
Write(Text);
Read(WriteErrorMessage);
VectorError := True; // toggle the error marker
end;
procedure CreateVector(var Vec: VectorTyp; Length: word; Value: float);
var
i: word;
begin
try
GetMem(Vec, Length * SizeOf(float) + SizeOf(word) + 6);
except
ch := WriteErrorMessage(' Not enough memory to create vector');
exit;
end;
Vec^.Length := Length;
for i := 1 to Length do
Vec^.Data[i] := Value;
end;
procedure DestroyVector(var Vec: VectorTyp);
var
x: word;
begin
x := Vec^.Length * SizeOf(float) + SizeOf(word) + 6;
FreeMem(Vec, x);
end;
function VectorLength(const Vec: VectorTyp): word;
begin
VectorLength := Vec^.Length;
end;
function GetVectorElement(const Vec: VectorTyp; n: word): float;
var
s1, s2: string;
begin
if (n <= VectorLength(Vec)) then
GetVectorElement := Vec^.Data[n]
else
begin
Str(n: 4, s1);
Str(VectorLength(Vec): 4, s2);
ch := WriteErrorMessage(' Attempt to read non-existent vector element No ' +
s1 + ' of ' + s2);
end;
end;
procedure SetVectorElement(var Vec: VectorTyp; n: word; C: float);
begin
if (n <= VectorLength(Vec)) then
Vec^.Data[n] := C
else
ch := WriteErrorMessage(' Attempt to write to non-existent vector element');
end;
end.
As long as your data fit on the stack, i.e., are smaller than 64 kB, the task is relatively simple. The only thing I don't know is where the 6 bit of extra size go, they are required, however.

How to use a variable in an array?

I'm using PASCAL for a course i'm doing and i'm having trouble with an assignment, in my program i'm using 2 arrays that uses a variable from a user's input but when i go to run the program it comes up with, Error: Can't evaluate constant expression. The code for the array is:
Var
x : integer;
s : array[1..x] of real;
n : array[1..x] of string[30];
Here x is the user's input, is there a way for an array to go from 1 to x?
If x is a variable, that won't work indeed. The range of a so called static array must be a constant expression, i.e. it must be known at compile time.
So what you want won't work, as is.
In FreePascal, you can use dynamic arrays, though. Their lengths can be set and changed at runtime.
var
x: Integer;
s: array of Real;
n: array of string[30]; // why not just string?
and later:
x := someUserInput(); // pseudo code!
SetLength(s, x);
SetLength(n, x);
You should be aware of the fact that dynamic arrays are 0-based, so your indexes run from 0 up to x - 1. But for the limits of the array, you should rather use Low() and High() instead:
for q := Low(s) to High(s) do
// access s[q];
(Low() and High() are not the topic, but just know they can also be used for static arrays, and that they return the actual array bounds -- I always use High and Low for this)
Here is not so simple as using managed types like dynamic arrays suggested by #RudyVelthuis but more funny solution providing some comprehension
about how it works internally :)
program dynarr;
{$mode objfpc}{$H+}
type
TArrayReal = array[1..High(Integer)] of Real;
TArrayString30 = array[1..High(Integer)] of string[30];
PArrayReal = ^TArrayReal;
PArrayString30 = ^TArrayString30;
var
i: Integer;
x: Integer;
s: PArrayReal;
n: PArrayString30;
begin
Write('Count: '); Readln(x);
// Allocate memory for the actual count of the elements
s := GetMem(SizeOf(Real) * x);
n := GetMem(SizeOf(string[30]) * x);
try
for i := 1 to x do
begin
Write('Row ', i:3, ': '); Readln(s^[i], n^[i]);
end;
Writeln('Your input was:');
for i := 1 to x do
Writeln('Row ', i:3, ': ', s^[i]:10:3, n^[i]: 20);
finally
// Do not forget to release allocated memory
FreeMem(s);
FreeMem(n);
end;
end.

Target (variable "") is not a signal error in VHDL

I have this piece of code
function func (k1, k2 : in bit_vector) return bit_vector is
variable result : bit_vector(1 to 32);
begin
for i in 0 to 31 loop
result(i) <= k1(i);
end loop;
return result;
end func;
I get this error :
target (variable "result") is not a signal
I know I need to change the type of result but I don't know what it should be.
Thanks.
When assigning to a variable use := as:
result(i) := k1(i);
Assign with <= is for assign to signal.
The range of result (1 to 32) does not match the range in the loop (0 to 31), so first assign in the loop (result(0) := k1(0)) will cause in a range error. Fix this by changing either result or loop range.

Resources