How to resolve "Error 200: Division by zero"? - turbo-pascal

I've FreeDos OS installed on VirtualBox on a windows xp, dual core, host machine. I installed FreeDos because I wanted to run a Pascal code using Turbo Pascal. When I run the code, it throws error 'Error 200: Division by zero.'. How can I solve this?
-Turbo Pascal 7.0, Free DOS 1.1, Virtual Box 4.3.6, Windows XP Service Pack 3 Host machine
-This error is unfortunately caused by fast Pentium CPUs and I found a patch on the internet that will resolve the error. (www.filewatcher.com/m/bp7patch.zip.62550-0.html) Now the other problem is, when i was tracing the code, it hangs at 'RxWait procedure when trying to execute while not odd(port[RXTX + 5]) do;'
uses crt;
const
{ COM1: RS232 port address }
RXTX = $3F8; { $2F8 if COM2: is used }
ACK = 6;
NAK = 21;
ESC = 27;
var
dummy,
checkSum : integer;
key : char;
protocol : integer;
procedure InitComm;
{ Set baudrate to 9600, 8 bits, no parity, 1 stop bit }
var i : integer;
begin
i := 1843200 div 9600 div 16;
port[RXTX + 3] := $80;
port[RXTX + 1] := hi(i);
port[RXTX]:= lo(i);
port[RXTX + 3] := 3;
port[RXTX + 4] := $A;
while odd(port[RXTX + 5]) do
begin
dummy := port[RXTX];
delay(10);
end;
end; { InitComm }
procedure Tx(data : integer);
{ Transmit a character on serial channel }
begin
while port[RXTX + 5] and $20 = 0 do;
port[RXTX] := data and $FF;
end; { Tx }
function RxWait : integer;
{ Waits for a character from serial channel }
begin
while not odd(port[RXTX + 5]) do;
RxWait := port[RXTX];
end; { RxWait }
procedure Tx2(data : integer);
{ Transmit a char on serial channel + Calculate check sum }
begin
Tx(data);
checkSum := (checkSum + data) and $FF;
end; { Tx2 }
procedure TxCommand(c1, c2 : char;
sendCheckSum : boolean);
{ Transmit command (no data) on serial channel }
begin
Tx(ESC);
checkSum := 0;
Tx2(ord(c1));
Tx2(ord(c2));
if sendCheckSum then
begin
Tx2(checkSum);
dummy := RxWait;
end;
end; { TxCommand }
function ReadNumber(n : integer) : real;
{ Read n bytes from serial channel }
var
number: real;
i : integer;
begin
number := 0;
checkSum := 0;
for i := 1 to n do
number := number * 256 + RxWait;
dummy := RxWait;
ReadNumber := number;
end; { ReadNumber }
procedure Revisions;
var
tmp : integer;
sw,
prot : real;
begin
TxCommand('P', 'R', FALSE);
checkSum := 0;
tmp := RxWait;
sw := tmp + RxWait / 100.0;
protocol := RxWait;
prot := protocol + RxWait / 100.0;
dummy := RxWait;
tmp := RxWait;
writeln('Software revision: ', sw:4:2);
writeln('Protocol revision: ', prot:4:2);
end; { Revisions }
procedure ReadCountReg;
begin
TxCommand('R', 'C', FALSE);
writeln(ReadNumber(4):11:0, ' coins counted.');
dummy := RxWait;
end; { ReadCountReg }
procedure ReadAccReg;
begin
TxCommand('R', 'A', FALSE);
writeln(ReadNumber(4):11:0, ' coins in accumulator.');
dummy := RxWait;
end; { ReadAccReg }
procedure Setbatch(limit : longint);
begin
TxCommand('W', 'L', FALSE);
case protocol of
1 : begin
Tx2(limit div 256);
Tx2(limit mod 256);
end;
2 : begin
Tx2( limit div 16777216);
Tx2((limit div 65536) mod 256);
Tx2((limit div 256) mod 256);
Tx2( limit mod 256);
end;
end; { case protocol }
Tx2(checkSum);
dummy := RxWait;
end; { Setbatch }

As far as I remember (more than 12 years ago), CRT unit had problems about Pentium CPUs and giving that division by zero error. I was using Turbo Pascal 7 those days. What I mean is that it may not be your coding error, but just CRT unit itself.

Old question I know, but there is another way to write Turbo Pascal code without incurring the wrath of the infamous RTE 200 bug. FreePascal (www.freepascal.org) is fully TP7 compatible and runs under a number of OSes including DOS, Windows and Linux.
Hope this helps!

I solved it setting the Execution Cap to 20%. So the processor is probably as slower as expected in those days. You can play with percentages until the error disappear
Regards

Related

Ada - accessibility check raised

I have downloaded this program from Github: https://github.com/raph-amiard/ada-synth-lib
I have attemted the first example and I am presented with an exception. If anybody would be able to give me an insight into why this is, it would be massively appreciated. I've been stumped on this for a long time and I'm really keen to get this working.
The error I recieve is: raised PROGRAM_ERROR : waves.adb:110 accessibility check failed
Here is the main file:
with Waves; use Waves;
with Write_To_Stdout;
procedure Main is
Sine_Gen : constant access Sine_Generator := Create_Sine (Fixed (440.0));
begin
Write_To_Stdout (Sine_Gen);
end Main;
Here is the waves.adb file
with Effects; use Effects;
with Interfaces; use Interfaces;
package body Waves is
function Mod_To_Int (A : Unsigned_32) return Integer_32;
-------------------
-- Update_Period --
-------------------
procedure Update_Period
(Self : in out Wave_Generator'Class; Buffer : in out Period_Buffer)
is
begin
Self.Frequency_Provider.Next_Samples (Buffer);
for I in Buffer'Range loop
Buffer (I) :=
Utils.Period_In_Samples
(Frequency (Buffer (I)));
end loop;
end Update_Period;
------------
-- Create --
------------
function Create_Saw
(Freq_Provider : Generator_Access) return access Saw_Generator
is
begin
return new Saw_Generator'(Frequency_Provider => Freq_Provider,
Current => -1.0, others => <>);
end Create_Saw;
-----------------
-- Next_Sample --
-----------------
overriding procedure Next_Samples
(Self : in out Saw_Generator; Buffer : in out Generator_Buffer)
is
P_Buffer : Period_Buffer;
begin
Update_Period (Self, P_Buffer);
for I in Buffer'Range loop
Self.Step := 2.0 / Float (P_Buffer (I));
Self.Current := Self.Current + Sample (Self.Step);
if Self.Current > 1.0 then
Self.Current := Self.Current - 2.0;
end if;
Buffer (I) := Self.Current;
end loop;
end Next_Samples;
------------
-- Create --
------------
function Create_Square
(Freq_Provider : access Generator'Class) return access Square_Generator is
begin
return new Square_Generator'(Frequency_Provider =>
Generator_Access (Freq_Provider),
Is_High => True,
Current_Sample => 0,
others => <>);
end Create_Square;
-----------------
-- Next_Sample --
-----------------
overriding procedure Next_Samples
(Self : in out Square_Generator; Buffer : in out Generator_Buffer)
is
P_Buffer : Period_Buffer;
begin
Update_Period (Self, P_Buffer);
for I in Buffer'Range loop
Self.Current_Sample := Self.Current_Sample + 1;
declare
A : constant Period := Period (Self.Current_Sample)
/ P_Buffer (I);
begin
if A >= 1.0 then
Self.Current_Sample := 0;
Buffer (I) := 1.0;
end if;
Buffer (I) := (if A >= 0.5 then 1.0 else -1.0);
end;
end loop;
end Next_Samples;
------------
-- Create --
------------
function Create_Sine
(Freq_Provider : access Generator'Class) return access Sine_Generator
is
Ret : constant access Sine_Generator :=
new Sine_Generator'(Frequency_Provider =>
Generator_Access (Freq_Provider),
Current_Sample => 0,
Current_P => 0.0,
others => <>);
begin
Ret.Current_P := 0.0;
return Ret;
end Create_Sine;
-----------------
-- Next_Sample --
-----------------
overriding procedure Next_Samples
(Self : in out Sine_Generator; Buffer : in out Generator_Buffer)
is
P_Buffer : Period_Buffer;
begin
Update_Period (Self, P_Buffer);
for I in Buffer'Range loop
Self.Current_Sample := Self.Current_Sample + 1;
if Period (Self.Current_Sample) >= Self.Current_P then
Self.Current_P := P_Buffer (I) * 2.0;
Self.Current_Sample := 0;
end if;
Buffer (I) :=
Sample
(Sin
(Float (Self.Current_Sample)
/ Float (Self.Current_P) * Pi * 2.0));
end loop;
end Next_Samples;
------------
-- Create --
------------
function Create_Chain
(Gen : access Generator'Class;
Sig_Procs : Signal_Processors
:= No_Signal_Processors) return access Chain
is
Ret : constant access Chain :=
new Chain'(Gen => Generator_Access (Gen), others => <>);
begin
for P of Sig_Procs loop
Ret.Add_Processor (P);
end loop;
return Ret;
end Create_Chain;
-------------------
-- Add_Processor --
-------------------
procedure Add_Processor
(Self : in out Chain; P : Signal_Processor_Access) is
begin
Self.Processors (Self.Nb_Processors) := P;
Self.Nb_Processors := Self.Nb_Processors + 1;
end Add_Processor;
-----------------
-- Next_Sample --
-----------------
overriding procedure Next_Samples
(Self : in out Chain; Buffer : in out Generator_Buffer)
is
S : Sample;
begin
Self.Gen.Next_Samples (Buffer);
for J in Buffer'Range loop
S := Buffer (J);
for I in 0 .. Self.Nb_Processors - 1 loop
S := Self.Processors (I).Process (S);
end loop;
Buffer (J) := S;
end loop;
end Next_Samples;
---------
-- LFO --
---------
function LFO (Freq : Frequency; Amplitude : Float) return Generator_Access
is
Sin : constant Generator_Access := Create_Sine (Fixed (Freq));
begin
return new Attenuator'
(Level => Amplitude,
Source => new Transposer'(Source => Sin, others => <>), others => <>);
end LFO;
------------
-- Create --
------------
function Create_ADSR
(Attack, Decay, Release : Millisecond; Sustain : Scale;
Source : access Note_Generator'Class := null) return access ADSR
is
begin
return new ADSR'
(State => Off,
Source => Source,
Attack => Msec_To_Period (Attack),
Decay => Msec_To_Period (Decay),
Release => Msec_To_Period (Release),
Sustain => Sustain,
Current_P => 0, others => <>);
end Create_ADSR;
-----------------
-- Next_Sample --
-----------------
overriding procedure Next_Samples
(Self : in out ADSR; Buffer : in out Generator_Buffer)
is
Ret : Sample;
begin
for I in Buffer'Range loop
case Self.Source.Buffer (I).Kind is
when On =>
Self.Current_P := 0;
Self.State := Running;
when Off =>
Self.State := Release;
Self.Cur_Sustain := Scale (Self.Memo_Sample);
Self.Current_P := 0;
when No_Signal => null;
end case;
Self.Current_P := Self.Current_P + 1;
case Self.State is
when Running =>
if Self.Current_P in 0 .. Self.Attack then
Ret := Exp8_Transfer
(Sample (Self.Current_P) / Sample (Self.Attack));
elsif
Self.Current_P in Self.Attack + 1 .. Self.Attack + Self.Decay
then
Ret :=
Exp8_Transfer
(Float (Self.Decay + Self.Attack - Self.Current_P)
/ Float (Self.Decay));
Ret := Ret
* Sample (1.0 - Self.Sustain)
+ Sample (Self.Sustain);
else
Ret := Sample (Self.Sustain);
end if;
Self.Memo_Sample := Ret;
when Release =>
if Self.Current_P in 0 .. Self.Release then
Ret :=
Exp8_Transfer
(Sample (Self.Release - Self.Current_P)
/ Sample (Self.Release))
* Sample (Self.Cur_Sustain);
else
Self.State := Off;
Ret := 0.0;
end if;
when Off => Ret := 0.0;
end case;
Buffer (I) := Ret;
end loop;
end Next_Samples;
----------------------
-- Next_Sample --
----------------------
overriding procedure Next_Samples
(Self : in out Pitch_Gen; Buffer : in out Generator_Buffer)
is
Ret : Sample;
begin
if Self.Proc /= null then
Self.Proc.Next_Samples (Buffer);
end if;
for I in Buffer'Range loop
case Self.Source.Buffer (I).Kind is
when On =>
Self.Current_Note := Self.Source.Buffer (I).Note;
Self.Current_Freq :=
Note_To_Freq (Self.Current_Note, Self.Relative_Pitch);
when others => null;
end case;
Ret := Sample (Self.Current_Freq);
if Self.Proc /= null then
Ret := Ret + Buffer (I);
end if;
Buffer (I) := Ret;
end loop;
end Next_Samples;
------------------
-- Create_Noise --
------------------
function Create_Noise return access Noise_Generator
is
N : constant access Noise_Generator := new Noise_Generator;
begin
return N;
end Create_Noise;
F_Level : constant Sample := 2.0 / Sample (16#FFFFFFFF#);
G_X1 : Unsigned_32 := 16#67452301#;
G_X2 : Unsigned_32 := 16#EFCDAB89#;
Z : constant := 2 ** 31;
----------------
-- Mod_To_Int --
----------------
function Mod_To_Int (A : Unsigned_32) return Integer_32 is
Res : Integer_32;
begin
if A < Z then
return Integer_32 (A);
else
Res := Integer_32 (A - Z);
Res := Res - (Z - 1) - 1;
return Res;
end if;
end Mod_To_Int;
------------------
-- Next_Samples --
------------------
overriding procedure Next_Samples
(Self : in out Noise_Generator; Buffer : in out Generator_Buffer)
is
pragma Unreferenced (Self);
begin
for I in Buffer'Range loop
G_X1 := G_X1 xor G_X2;
Buffer (I) := Sample (Mod_To_Int (G_X2)) * F_Level;
G_X2 := G_X2 + G_X1;
end loop;
end Next_Samples;
------------------
-- Next_Samples --
------------------
overriding procedure Next_Samples
(Self : in out Fixed_Gen; Buffer : in out Generator_Buffer) is
begin
if Self.Proc /= null then
Self.Proc.Next_Samples (Buffer);
for I in Buffer'Range loop
Buffer (I) := Self.Val + Buffer (I);
end loop;
else
for I in Buffer'Range loop
Buffer (I) := Self.Val;
end loop;
end if;
end Next_Samples;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out ADSR) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Source);
Self.Memo_Sample := 0.0;
end Reset;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out Saw_Generator) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Frequency_Provider);
Self.Current := -1.0;
end Reset;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out Square_Generator) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Frequency_Provider);
Self.Current_Sample := 0;
Self.Is_High := True;
end Reset;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out Sine_Generator) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Frequency_Provider);
Self.Current_Sample := 0;
end Reset;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out Noise_Generator) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Frequency_Provider);
end Reset;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out Pitch_Gen) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Source);
Reset_Not_Null (Self.Proc);
end Reset;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out Fixed_Gen) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Proc);
end Reset;
-----------
-- Reset --
-----------
overriding procedure Reset (Self : in out Chain) is
begin
Base_Reset (Self);
Reset_Not_Null (Self.Gen);
end Reset;
-----------
-- Fixed --
-----------
function Fixed
(Freq : Frequency;
Modulator : Generator_Access := null;
Name : String := "";
Min : Float := 0.0;
Max : Float := 5_000.0;
Param_Scale : Param_Scale_T := Linear)
return access Fixed_Gen
is
begin
return new
Fixed_Gen'
(Val => Sample (Freq),
Proc => Modulator,
Name => To_Unbounded_String (Name),
Min => Min,
Max => Max,
Param_Scale => Param_Scale,
others => <>);
end Fixed;
---------------
-- Set_Value --
---------------
overriding procedure Set_Value
(Self : in out Fixed_Gen; I : Natural; Val : Float)
is
pragma Unreferenced (I);
begin
Self.Val := Sample (Val);
end Set_Value;
---------------
-- Set_Value --
---------------
overriding procedure Set_Value
(Self : in out ADSR; I : Natural; Val : Float)
is
begin
case I is
when 0 => Self.Attack := Sec_To_Period (Val);
when 1 => Self.Decay := Sec_To_Period (Val);
when 2 => Self.Sustain := Scale (Val);
when 3 => Self.Release := Sec_To_Period (Val);
when others => raise Constraint_Error;
end case;
end Set_Value;
end Waves;
And lastly, the write_to_stdout.adb file
with Utils; use Utils;
with GNAT.OS_Lib;
procedure Write_To_Stdout (G : access Generator'Class)
is
function Sample_To_Int16 is new Sample_To_Int (Short_Integer);
Int_Smp : Short_Integer := 0;
Ignore : Integer;
Buffer : Generator_Buffer;
begin
loop
Next_Steps;
G.Next_Samples (Buffer);
for I in Buffer'Range loop
Int_Smp := Sample_To_Int16 (Buffer (I));
Ignore := GNAT.OS_Lib.Write
(GNAT.OS_Lib.Standout, Int_Smp'Address, Int_Smp'Size / 8);
end loop;
exit when Sample_Nb > 10_000_000;
Sample_Nb := Sample_Nb + Generator_Buffer_Length;
end loop;
end Write_To_Stdout;
Thank you for reading, and any guidance into solving this would be most appreicated.
Cheers,
Lloyd
The function in question :
function Create_Sine
(Freq_Provider : access Generator'Class) return access Sine_Generator
is
Ret : constant access Sine_Generator :=
new Sine_Generator'(Frequency_Provider =>
Generator_Access (Freq_Provider),
Current_Sample => 0,
Current_P => 0.0,
others => <>);
begin
Ret.Current_P := 0.0;
return Ret;
end Create_Sine;
creates a new object, accessed by an access type in its local scope and returns a copy of the access. In this case it is probably OK but there is the possibility of similar cases where the object itself goes out of scope when the function returns, leaving a dangling access.
In this case it's probably overcautious since the only reference to the object is that returned, but the accessibility checks prohibit this whole class of potentially bug-ridden constructs. I say "probably" because the object could theoretically be allocated on the stack by some compilers, or in a locally owned storage pool rather than "the heap" for more reliable object lifetime management.
There is a solution : create the access in place in the returned object, rather than in an immediately discarded local object. Ada-2005 and later provide an "extended return" construct to allow this. It looks something like:
function Create_Sine
(Freq_Provider : access Generator'Class) return access Sine_Generator
is
begin
return Ret : constant access Sine_Generator :=
new Sine_Generator'( Frequency_Provider =>
Generator_Access (Freq_Provider),
Current_Sample => 0,
Current_P => 0.0,
others => <>)
do
-- initialisation actions here
Ret.Current_P := 0.0;
end return;
end Create_Sine;
not tested! but any of the usual sources should keep you straight now you know its name.
Here the caller owns the access type being initialised with the new object, so there is no danger of the access type out-living the accessed object.
There may be a better answer to this question overall. I have just addressed the immediate point, but the wider question is, do you need an access type here at all? In Ada the answer usually (but not always) is No. There are many cases where programmers coming from other languages just reach for the pointers, when there is a simpler or better way of doing things in Ada.

Ada - timing problem when using ttyUSB device (FTDI chip)

I have an odd problem with a simple Ada program that uses the "GNAT.Serial_Communications" package.
The program sends seven bytes (126, 1, 0, 0, 0, 0, 254) over the serial port device (8,N,1 # 115200 Baud), and I have verified that this is performed correctly using a logic analyser connected directly to the serial port pins.
The strange thing is that there are two large gaps (varies between 0.6 milliseconds and 2.4 ms) between the first three bytes sent. The rest of the bytes are sent at maximum speed as one would expect. Each individual byte is perfectly formed and sent at the correct rate. The idle time between bytes is the part that varies. In other words the timing looks like this...
[126]..........(big gap)..........[1]..........(big gap)..........[0][0][0][0][254]
I have a C version of this program that does not exhibit this behaviour, all bytes are sent in a single burst with no gaps.
Equally, catting the same data directly into the serial port from Bash also does not have these big gaps between the first three bytes.
So it appears that there is some aspect of the Ada libraries / runtimes that introduces this variable delay in the middle of my byte stream.
For my project, this is a tolerable problem but I would like to try to find out why this is happening.
There is apparently no problem with reading bytes from the serial port, it receives everything correctly.
with Interfaces; use Interfaces;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Streams; use Ada.Streams;
with GNAT.Serial_Communications;
procedure Main is
SP : GNAT.Serial_Communications.Serial_Port;
In_Data : String (1 .. 6) := "~ddddS"; -- this string literal is illustrative only
In_Buffer : Stream_Element_Array (1 .. 6);
Length : Stream_Element_Offset;
type PropIO_Octet is mod (2 ** 8);
type PropIO_Packet_Data is array (1 .. 4) of PropIO_Octet;
Packet_Start : constant PropIO_Octet := 16#7E#;
Packet_Escape_Marker : constant PropIO_Octet := 16#7D#;
Packet_Escape_XOR : constant PropIO_Octet := 16#20#;
Command_Hard_Reset : constant PropIO_Octet := 16#00#;
Command_Watchdog : constant PropIO_Octet := 16#01#;
procedure TX_Octet (Octet : in PropIO_Octet; Allow_Escape : in Boolean) is
Out_Buffer : Stream_Element_Array (1 .. 1);
Temp_Oct : PropIO_Octet := Octet;
begin
if Allow_Escape then
if (Temp_Oct = Packet_Start) or (Temp_Oct = Packet_Escape_Marker) then
Out_Buffer (Stream_Element_Offset (1)) := Character'Pos (Character'Val (Packet_Escape_Marker));
GNAT.Serial_Communications.Write (SP, Out_Buffer);
Temp_Oct := Temp_Oct xor Packet_Escape_XOR;
end if;
end if;
Out_Buffer (Stream_Element_Offset (1))
:= Character'Pos (Character'Val (Temp_Oct));
GNAT.Serial_Communications.Write (SP, Out_Buffer);
end TX_Octet;
procedure TX_Packet (
Command : in PropIO_Octet;
Data : in PropIO_Packet_Data
) is
CS : PropIO_Octet := 16#00#;
begin
TX_Octet (Packet_Start, False);
TX_Octet (Command, True);
CS := CS xor Command;
for D of Data loop
TX_Octet (D, True);
CS := CS xor D;
end loop;
CS := 16#FF# - CS;
TX_Octet (CS, True);
end TX_Packet;
begin
GNAT.Serial_Communications.Open(SP, "/dev/ttyUSB0");
GNAT.Serial_Communications.Set (
Port => SP,
Rate => GNAT.Serial_Communications.B115200,
Bits => GNAT.Serial_Communications.CS8,
Stop_Bits => GNAT.Serial_Communications.One,
Parity => GNAT.Serial_Communications.None
);
for i in 1 .. 10 loop
TX_Packet (Command_Watchdog, (0,0,0,0));
delay 1.0;
GNAT.Serial_Communications.Read (SP, In_Buffer, Length);
for i in 1 .. Length loop
In_Data (Integer (i)) := Character'Val (In_Buffer (i));
end loop;
Put_Line ("Response: " & In_Data (1 .. (Integer (Length))));
end loop;
GNAT.Serial_Communications.Close (SP);
end Main;
I'm running this code under Ubuntu 19.10 (latest updates) and Gnat 8.3.0. The serial device connected via USB is a legitimate FTDI device.
Any ideas what might cause this?
This is not the actual answer to the question (the answer is already in the comments I guess), but just a hint regarding the example code. As the type GNAT.Serial_Communications.Serial_Port derives from Ada.Streams.Root_Stream_Type, you can also use the stream-oriented attributes 'Read and 'Write to read and write to the serial port. As an example:
main.adb
with Ada.Text_IO;
with GNAT.Serial_Communications;
procedure Main is
package SC renames GNAT.Serial_Communications;
type Byte is mod 2**8;
type Byte_Array is array (Natural range <>) of Byte;
package Byte_IO is
new Ada.Text_IO.Modular_IO (Byte);
Port_1 : aliased SC.Serial_Port;
Port_2 : aliased SC.Serial_Port;
End_Token : constant := 16#FF#;
Buffer_Out : Byte_Array (0 .. 5) := (0, 1, 2, 3, 4, End_Token);
Buffer_In : Byte;
begin
-- Open the ports.
SC.Open (Port_1, "/dev/ttyS98");
SC.Open (Port_2, "/dev/ttyS99");
-- Write the byte array (packet) to port 1 in one go.
Byte_Array'Write (Port_1'Access, Buffer_Out);
-- Read the byte array (packet) back from port 2, byte-by-byte.
loop
Byte'Read (Port_2'Access, Buffer_In);
exit when Buffer_In = End_Token;
Byte_IO.Put (Buffer_In);
end loop;
Ada.Text_IO.New_Line;
-- Close the ports.
SC.Close (Port_1);
SC.Close (Port_2);
end Main;
The program can be tested by emulating two serial ports using socat (and pseudo-terminals, pty).
console 1 (create the emulated serial ports)
$ sudo socat -d -d pty,raw,echo=0,link=/dev/ttyS98 pty,raw,echo=0,link=/dev/ttyS99
2020/01/14 20:23:04 socat[2540] N PTY is /dev/pts/1
2020/01/14 20:23:04 socat[2540] N PTY is /dev/pts/2
2020/01/14 20:23:04 socat[2540] N starting data transfer loop with FDs [5,5] and [7,7]
console 2 (run the example program)
$ sudo ./main
0 1 2 3 4
Note: sudo is required to create and access the emulated devices.

Win10 <-> USB <-> Arduino - Problem to communicate with Autohotkey

My desire is to communicate with an Arduino Uno over an USB-port (COM3 - 9600,N,8,1).
I was going to manage the information with Autohotkey on a computer running Windows 10.
This test is only intended to read the information from the Arduino. But later I also want to be able to send information from the PC to the Arduino Uno.
The Arduino Uno has an extra card attached (Funduino JoyStick Shield V1.A) - only for the test.
This is the program I use on the Arduino .:
// Armuino --- Funduino Joystick Shield ---
// Playlist: https://www.youtube.com/playlist?list=PLRFnGJH1nJiKIpz_ZyaU-uAZOkMH8GAcw
//
// Part 1. Introduction - Basic Functions: https://www.youtube.com/watch?v=lZPZuBCFMH4
// Arduino digital pins associated with buttons
const byte PIN_BUTTON_A = 2;
const byte PIN_BUTTON_B = 3;
const byte PIN_BUTTON_C = 4;
const byte PIN_BUTTON_D = 5;
const byte PIN_BUTTON_E = 6;
const byte PIN_BUTTON_F = 7;
// Arduino analog pins associated with joystick
const byte PIN_ANALOG_X = 0;
const byte PIN_ANALOG_Y = 1;
void setup() {
Serial.begin(9600);
pinMode(PIN_BUTTON_B, INPUT);
digitalWrite(PIN_BUTTON_B, HIGH);
pinMode(PIN_BUTTON_E, INPUT);
digitalWrite(PIN_BUTTON_E, HIGH);
pinMode(PIN_BUTTON_C, INPUT);
digitalWrite(PIN_BUTTON_C, HIGH);
pinMode(PIN_BUTTON_D, INPUT);
digitalWrite(PIN_BUTTON_D, HIGH);
pinMode(PIN_BUTTON_A, INPUT);
digitalWrite(PIN_BUTTON_A, HIGH);
}
void loop() {
Serial.print("Buttons A:");
Serial.print(digitalRead(PIN_BUTTON_A));
Serial.print(" ");
Serial.print("B:");
Serial.print(digitalRead(PIN_BUTTON_B));
Serial.print(" ");
Serial.print("C:");
Serial.print(digitalRead(PIN_BUTTON_C));
Serial.print(" ");
Serial.print("D:");
Serial.print(digitalRead(PIN_BUTTON_D));
Serial.print(" ");
Serial.print("E:");
Serial.print(digitalRead(PIN_BUTTON_E));
Serial.print(" ");
Serial.print("F:");
Serial.print(digitalRead(PIN_BUTTON_F));
Serial.print(" -- ");
Serial.print("Position X:");
Serial.print(analogRead(PIN_ANALOG_X));
Serial.print(" ");
Serial.print("Y:");
Serial.print(analogRead(PIN_ANALOG_Y));
Serial.print(" ");
Serial.println();
delay(1000);
}
This program seems to work when I run the Arduino Serial Editor on the PC.
The values is coming row for row on the screen, like this .:
**00:58:44.434 -> Buttons A:1 B:1 C:1 D:1 E:1 F:1 -- Position X:334 Y:321**
(I can't see any wrong values in the Serial Editor. - maybe in higher speed)
But if I try to "do the same" with Autohotkey, characters may be missing - some times.
Like this .:
But:322
Buttons A:1 B:1 C:1 D:1 E:1 F:1 -- Position X:334 Y:322
334 Y:322
Buttons A:1 B:1 C:1 D:1 E:1 F:1 -- Position X:334 Y:322
I have no idea how the communication with USB should look like in Windows 10.
(I think it is not the same as eg. Windows XP)
I have looked on this solution .: Arduino + AutoHotKey > Serial Connection
- Not sure I found the right Arduino.ahk
- Maybe require Windows XP?
- It doesn't work for me!
This tip is better (but old) .: Arduino.ahk beta .01
The most of tests have been based on this link and I created the following AHK-program .:
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn ; Enable warnings to assist with detecting common errors.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
#Singleinstance force
COM = 3
Num_Bytes = 500
Mode =
; Initialize COM-port
COM_Port = COM%COM%
COM_Baud = 9600
COM_Parity = N
COM_Data = 8
COM_Stop = 1
COM_DTR = Off
FilNamn := A_ScriptDir "/Test.txt"
IfExist %FilNamn%
FileDelete %FilNamn%
COM_Settings = %COM_Port%:baud=%COM_Baud% parity=%COM_Parity% data=%COM_Data% stop=%COM_Stop% dtr=%COM_DTR%
COM_FileHandle := Serial_Initialize(COM_Settings)
Loop 100
{ ; ReadResult := Serial_Read(COM_FileHandle, Num_Bytes, Mode)
ReadResult := Serial_Read_Raw(COM_FileHandle, Num_Bytes, Mode)
asciiString := Hex2ASCII(ReadResult)
sleep 20
FileAppend %asciiString%, %FilNamn%, UTF-8
; SplashTextOn 800, 100, Arduino Read, %asciiString%
; Sleep 1000
; MsgBox ,, Rad %A_LineNumber% -> %A_ScriptName%, % COM_Settings "`n`n" ReadResult "`n`n- " StrLen(ReadResult) "`n`n- " Bytes_Received "`n`n- " asciiString, 1
}
Serial_Close(COM_FileHandle)
; MsgBox ,, Rad %A_LineNumber% -> %A_ScriptName%, % COM_Settings "`n`n" ReadResult "`n`n- " StrLen(ReadResult) "`n`n- " Bytes_Received
; asciiString := Hex2ASCII(ReadResult)
; MsgBox ,, Rad %A_LineNumber% -> %A_ScriptName%, % ReadResult "`n`n"asciiString
MsgBox ,, Rad %A_LineNumber% -> %A_ScriptName%, Klart!
ExitApp
ESC::
SplashTextOff
Serial_Close(COM_FileHandle)
MsgBox ,,, Programmet avslutas!, 1
ExitApp
Return
Hex2ASCII(fHexString)
{ Loop Parse, fHexString
NewHexString .= A_LoopField (Mod(A_Index,2) ? "" : ",")
Loop Parse, NewHexString, `,
ConvString .= Chr("0x" A_LoopField)
Return ConvString
} ;http://www.autohotkey.com/forum/post-211769.html#211769
;########################################################################
;###### Initialize COM Subroutine #######################################
;########################################################################
Serial_Initialize(SERIAL_Settings){
;Global SERIAL_FileHandle ;uncomment this if there is a problem
;###### Build COM DCB ######
;Creates the structure that contains the COM Port number, baud rate,...
VarSetCapacity(DCB, 28)
BCD_Result := DllCall("BuildCommDCB"
,"str" , SERIAL_Settings ;lpDef
,"UInt", &DCB) ;lpDCB
If (BCD_Result <> 1){
error := DllCall("GetLastError")
MsgBox, There is a problem with Serial Port communication. `nFailed Dll BuildCommDCB, BCD_Result=%BCD_Result% `nLasterror=%error%`nThe Script Will Now Exit.
ExitApp
}
;###### Extract/Format the COM Port Number ######
StringSplit, SERIAL_Port_Temp, SERIAL_Settings, `:
SERIAL_Port_Temp1_Len := StrLen(SERIAL_Port_Temp1) ;For COM Ports > 9 \\.\ needs to prepended to the COM Port name.
If (SERIAL_Port_Temp1_Len > 4) ;So the valid names are
SERIAL_Port = \\.\%SERIAL_Port_Temp1% ; ... COM8 COM9 \\.\COM10 \\.\COM11 \\.\COM12 and so on...
Else ;
SERIAL_Port = %SERIAL_Port_Temp1%
;MsgBox, SERIAL_Port=%SERIAL_Port%
;###### Create COM File ######
;Creates the COM Port File Handle
;StringLeft, SERIAL_Port, SERIAL_Settings, 4 ; 7/23/08 This line is replaced by the "Extract/Format the COM Port Number" section above.
SERIAL_FileHandle := DllCall("CreateFile"
,"Str" , SERIAL_Port ;File Name
,"UInt", 0xC0000000 ;Desired Access
,"UInt", 3 ;Safe Mode
,"UInt", 0 ;Security Attributes
,"UInt", 3 ;Creation Disposition
,"UInt", 0 ;Flags And Attributes
,"UInt", 0 ;Template File
,"Cdecl Int")
If (SERIAL_FileHandle < 1){
error := DllCall("GetLastError")
MsgBox, There is a problem with Serial Port communication. `nFailed Dll CreateFile, SERIAL_FileHandle=%SERIAL_FileHandle% `nLasterror=%error%`nThe Script Will Now Exit.
ExitApp
}
;###### Set COM State ######
;Sets the COM Port number, baud rate,...
SCS_Result := DllCall("SetCommState"
,"UInt", SERIAL_FileHandle ;File Handle
,"UInt", &DCB) ;Pointer to DCB structure
If (SCS_Result <> 1){
error := DllCall("GetLastError")
MsgBox, There is a problem with Serial Port communication. `nFailed Dll SetCommState, SCS_Result=%SCS_Result% `nLasterror=%error%`nThe Script Will Now Exit.
Serial_Close(SERIAL_FileHandle)
ExitApp
}
;###### Create the SetCommTimeouts Structure ######
ReadIntervalTimeout = 0xffffffff
ReadTotalTimeoutMultiplier = 0x00000000
ReadTotalTimeoutConstant = 0x00000000
WriteTotalTimeoutMultiplier= 0x00000000
WriteTotalTimeoutConstant = 0x00000000
VarSetCapacity(Data, 20, 0) ; 5 * sizeof(DWORD)
NumPut(ReadIntervalTimeout, Data, 0, "UInt")
NumPut(ReadTotalTimeoutMultiplier, Data, 4, "UInt")
NumPut(ReadTotalTimeoutConstant, Data, 8, "UInt")
NumPut(WriteTotalTimeoutMultiplier, Data, 12, "UInt")
NumPut(WriteTotalTimeoutConstant, Data, 16, "UInt")
;###### Set the COM Timeouts ######
SCT_result := DllCall("SetCommTimeouts"
,"UInt", SERIAL_FileHandle ;File Handle
,"UInt", &Data) ;Pointer to the data structure
If (SCT_result <> 1){
error := DllCall("GetLastError")
MsgBox, There is a problem with Serial Port communication. `nFailed Dll SetCommState, SCT_result=%SCT_result% `nLasterror=%error%`nThe Script Will Now Exit.
Serial_Close(SERIAL_FileHandle)
ExitApp
}
Return SERIAL_FileHandle
}
;########################################################################
;###### Close COM Subroutine ############################################
;########################################################################
Serial_Close(SERIAL_FileHandle){
;###### Close the COM File ######
CH_result := DllCall("CloseHandle", "UInt", SERIAL_FileHandle)
If (CH_result <> 1)
MsgBox, Failed Dll CloseHandle CH_result=%CH_result%
Return
}
;########################################################################
;###### Write to COM Subroutines ########################################
;########################################################################
Serial_Write(SERIAL_FileHandle, Message){
;Global SERIAL_FileHandle
OldIntegerFormat := A_FormatInteger
SetFormat, Integer, DEC
;Parse the Message. Byte0 is the number of bytes in the array.
StringSplit, Byte, Message, `,
Data_Length := Byte0
;msgbox, Data_Length=%Data_Length% b1=%Byte1% b2=%Byte2% b3=%Byte3% b4=%Byte4%
;Set the Data buffer size, prefill with 0xFF.
VarSetCapacity(Data, Byte0, 0xFF)
;Write the Message into the Data buffer
i=1
Loop %Byte0% {
NumPut(Byte%i%, Data, (i-1) , "UChar")
;msgbox, %i%
i++
}
;msgbox, Data string=%Data%
;###### Write the data to the COM Port ######
WF_Result := DllCall("WriteFile"
,"UInt" , SERIAL_FileHandle ;File Handle
,"UInt" , &Data ;Pointer to string to send
,"UInt" , Data_Length ;Data Length
,"UInt*", Bytes_Sent ;Returns pointer to num bytes sent
,"Int" , "NULL")
If (WF_Result <> 1 or Bytes_Sent <> Data_Length)
MsgBox, Failed Dll WriteFile to COM Port, result=%WF_Result% `nData Length=%Data_Length% `nBytes_Sent=%Bytes_Sent%
SetFormat, Integer, %OldIntegerFormat%
Return Bytes_Sent
}
;########################################################################
;###### Read from COM Subroutines #######################################
;########################################################################
;########################################################################
;###### Read from COM Subroutines #######################################
;########################################################################
Serial_Read(COM_FileHandle, Num_Bytes, mode = "",byref Bytes_Received = "")
{
;Global COM_FileHandle
;Global COM_Port
;Global Bytes_Received
SetFormat, Integer, HEX
;Set the Data buffer size, prefill with 0x55 = ASCII character "U"
;VarSetCapacity won't assign anything less than 3 bytes. Meaning: If you
; tell it you want 1 or 2 byte size variable it will give you 3.
Data_Length := VarSetCapacity(Data, Num_Bytes, 0x55)
;msgbox, Data_Length=%Data_Length%
;###### Read the data from the COM Port ######
;msgbox, COM_FileHandle=%COM_FileHandle% `nNum_Bytes=%Num_Bytes%
Read_Result := DllCall("ReadFile"
,"UInt" , COM_FileHandle ; hFile
,"Str" , Data ; lpBuffer
,"Int" , Num_Bytes ; nNumberOfBytesToRead
,"UInt*", Bytes_Received ; lpNumberOfBytesReceived
,"Int" , 0) ; lpOverlapped
;MsgBox, Read_Result=%Read_Result% `nBR=%Bytes_Received% ,`nData=%Data%
If (Read_Result <> 1)
{
MsgBox, There is a problem with Serial Port communication. `nFailed Dll ReadFile on COM Port, result=%Read_Result% - The Script Will Now Exit.
Serial_Close(COM_FileHandle)
Exit
}
;if you know the data coming back will not contain any binary zeros (0x00), you can request the 'raw' response
If (mode = "raw")
Return Data
;###### Format the received data ######
;This loop is necessary because AHK doesn't handle NULL (0x00) characters very nicely.
;Quote from AHK documentation under DllCall:
; "Any binary zero stored in a variable by a function will hide all data to the right
; of the zero; that is, such data cannot be accessed or changed by most commands and
; functions. However, such data can be manipulated by the address and dereference operators
; (& and *), as well as DllCall itself."
i = 0
Data_HEX =
Loop %Bytes_Received%
{
;First byte into the Rx FIFO ends up at position 0
Data_HEX_Temp := NumGet(Data, i, "UChar") ;Convert to HEX byte-by-byte
StringTrimLeft, Data_HEX_Temp, Data_HEX_Temp, 2 ;Remove the 0x (added by the above line) from the front
;If there is only 1 character then add the leading "0'
Length := StrLen(Data_HEX_Temp)
If (Length =1)
Data_HEX_Temp = 0%Data_HEX_Temp%
i++
;Put it all together
Data_HEX .= Data_HEX_Temp
}
;MsgBox, Read_Result=%Read_Result% `nBR=%Bytes_Received% ,`nData_HEX=%Data_HEX%
SetFormat, Integer, DEC
Data := Data_HEX
Return Data
}
;########################################################################
;###### Read from COM Subroutines #######################################
;########################################################################
Serial_Read_Raw(SERIAL_FileHandle, Num_Bytes, mode = "",byref Bytes_Received = ""){
;Global SERIAL_FileHandle
;Global SERIAL_Port
;Global Bytes_Received
OldIntegerFormat := A_FormatInteger
SetFormat, Integer, HEX
;Set the Data buffer size, prefill with 0x55 = ASCII character "U"
;VarSetCapacity won't assign anything less than 3 bytes. Meaning: If you
; tell it you want 1 or 2 byte size variable it will give you 3.
Data_Length := VarSetCapacity(Data, Num_Bytes, 0)
;msgbox, Data_Length=%Data_Length%
;###### Read the data from the COM Port ######
;msgbox, SERIAL_FileHandle=%SERIAL_FileHandle% `nNum_Bytes=%Num_Bytes%
Read_Result := DllCall("ReadFile"
,"UInt" , SERIAL_FileHandle ; hFile
,"Str" , Data ; lpBuffer
,"Int" , Num_Bytes ; nNumberOfBytesToRead
,"UInt*", Bytes_Received ; lpNumberOfBytesReceived
,"Int" , 0) ; lpOverlapped
;MsgBox, Read_Result=%Read_Result% `nBR=%Bytes_Received% ,`nData=%Data%
If (Read_Result <> 1){
MsgBox, There is a problem with Serial Port communication. `nFailed Dll ReadFile on COM Port, result=%Read_Result% - The Script Will Now Exit.
Serial_Close(SERIAL_FileHandle)
Exit
}
;if you know the data coming back will not contain any binary zeros (0x00), you can request the 'raw' response
If (mode = "raw")
Return Data
;###### Format the received data ######
;This loop is necessary because AHK doesn't handle NULL (0x00) characters very nicely.
;Quote from AHK documentation under DllCall:
; "Any binary zero stored in a variable by a function will hide all data to the right
; of the zero; that is, such data cannot be accessed or changed by most commands and
; functions. However, such data can be manipulated by the address and dereference operators
; (& and *), as well as DllCall itself."
i = 0
Data_HEX =
Loop %Bytes_Received%
{
;First byte into the Rx FIFO ends up at position 0
Data_HEX_Temp := NumGet(Data, i, "UChar") ;Convert to HEX byte-by-byte
StringTrimLeft, Data_HEX_Temp, Data_HEX_Temp, 2 ;Remove the 0x (added by the above line) from the front
;If there is only 1 character then add the leading "0'
Length := StrLen(Data_HEX_Temp)
If (Length =1)
Data_HEX_Temp = 0%Data_HEX_Temp%
i++
;Put it all together
Data_HEX .= Data_HEX_Temp
}
;MsgBox, Read_Result=%Read_Result% `nBR=%Bytes_Received% ,`nData_HEX=%Data_HEX%
SetFormat, Integer, DEC
Data := Data_HEX
SetFormat, Integer, %OldIntegerFormat%
Return Data
}
Thanks for your time!
Has managed to get better communication between Windows and the Arduino. (with a different configuration).Made two windows in a GUI
One where I can enter characters.
Arduinon echoes back what is typed and returns that character to the PC
The other show the returned characters..
It works (in 9600bps), but first I send a headline and if the baud rate increases, "strange" characters always appear at the beginning of the test.
Don't know if the serial buffer in the Arduino / PC needs to be cleared before the characters start to read in sharp mode? (how to do that?)
In the Arduino SerialMonitor I got not readable information with higher baudrate (from another test program)
My ECHO-program in the Arduino
int incomingByte;
void setup() {
Serial.begin(9600);
}
void loop(){
if (Serial.available() > 0) {
incomingByte = Serial.read();
//Serial.print(incomingByte);
Serial.write(incomingByte);
}
}

VHDL RS-232 Receiver

I have been trying to design an RS-232 receiver taking an FSM approach. I will admit that I do not have a very well-rounded understanding of VHDL, so I have been working on the code on the fly and learning as I go. However, I believe I've hit a brick wall at this point.
My issue is that I have two processes in my code, one to trigger the next state and the other to perform the combinational logic. My code is as follows:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity ASyncReceiverV4 is
Port ( DataIn : in STD_LOGIC;
Enable : in STD_LOGIC;
CLK : in STD_LOGIC;
BadData : out STD_LOGIC;
DataOut : out STD_LOGIC_VECTOR (7 downto 0));
end ASyncReceiverV4;
architecture Behavioral of ASyncReceiverV4 is
type states is (StartBitCheck, ReadData, StopBitCheck);
signal currentState, nextState : states;
begin
process(CLK)
begin
if rising_edge(CLK) then
currentState <= nextState;
end if;
end process;
process(CLK)
variable counter : integer := 0;
variable dataIndex : integer := 0;
begin
case currentState is
when StartBitCheck =>
if Enable = '1' then
if (DataIn = '0' and counter < 8) then
counter := counter + 1;
elsif (DataIn = '0' and counter = 8) then
BadData <= '0';
nextState <= ReadData;
counter := 0;
else
nextState <= StartBitCheck;
end if;
end if;
when ReadData =>
if Enable = '1' then
if counter < 16 then
counter := counter + 1;
elsif (counter = 16 and dataIndex < 8) then
DataOut(dataIndex) <= DataIn;
counter := 0;
dataIndex := dataIndex + 1;
elsif dataIndex = 8 then
dataIndex := 0;
nextState <= StopBitCheck;
else
nextState <= ReadData;
end if;
end if;
when StopBitCheck =>
if Enable = '1' then
if DataIn = '1' then
if counter < 16 then
counter := counter + 1;
nextState <= StopBitCheck;
elsif counter = 16 then
counter := 0;
nextState <= StartBitCheck;
end if;
else
DataOut <= "11111111";
BadData <= '1';
nextState <= StartBitCheck;
end if;
end if;
end case;
end process;
end Behavioral;
For whatever reason, based on my simulations, it seems that my processes are out of sync. Although things are only supposed to occur at the rising edge of the clock, I have transitions occurring at the falling edge. Furthermore, it seems like things are not changing according to the value of counter.
The Enable input is high in all of my simulations. However, this is just to keep it simple for now, it will eventually be fed the output of a 153,600 Baud generator (the Baud generator will be connected to the Enable input). Hence, I only want things to change when my Baud generator is high. Otherwise, do nothing. Am I taking the right approach for that with my code?
I can supply a screenshot of my simulation if that would be helpful. I am also not sure if I am including the correct variables in my process sensitivity list. Also, am I taking the right approach with my counter and dataIndex variables? What if I made them signals as part of my architecture before any of my processes?
Any help on this would be very much so appreciated!
The easiest way to fix this, while also producing the easiest to read code, would be to move to a 1-process state machine like so (warning: not complied may contain syntax errors):
entity ASyncReceiverV4 is
Port ( DataIn : in STD_LOGIC;
Enable : in STD_LOGIC;
CLK : in STD_LOGIC;
BadData : out STD_LOGIC;
DataOut : out STD_LOGIC_VECTOR (7 downto 0));
end ASyncReceiverV4;
architecture Behavioral of ASyncReceiverV4 is
type states is (StartBitCheck, ReadData, StopBitCheck);
signal state : states := StartBitCheck;
signal counter : integer := 0;
signal dataIndex : integer := 0;
begin
process(CLK)
begin
if rising_edge(CLK) then
case state is
when StartBitCheck =>
if Enable = '1' then
if (DataIn = '0' and counter < 8) then
counter <= counter + 1;
elsif (DataIn = '0' and counter = 8) then
BadData <= '0';
state <= ReadData;
counter <= 0;
end if;
end if;
when ReadData =>
if Enable = '1' then
if counter < 16 then
counter <= counter + 1;
elsif (counter = 16 and dataIndex < 8) then
DataOut(dataIndex) <= DataIn;
counter <= 0;
dataIndex <= dataIndex + 1;
elsif dataIndex = 8 then
dataIndex <= 0;
state <= StopBitCheck;
end if;
end if;
when StopBitCheck =>
if Enable = '1' then
if DataIn = '1' then
if counter < 16 then
counter <= counter + 1;
elsif counter = 16 then
counter <= 0;
state <= StartBitCheck;
end if;
else
DataOut <= "11111111";
BadData <= '1';
state <= StartBitCheck;
end if;
end if;
end case;
end if;
end process;
end Behavioral;
Note that while this no longer contains language issues, there are still odd things in the logic.
You cannot enter the state StopBitCheck until counter is 16 because the state transition is in an elsif of counter < 16. Therefore, the if counter < 16 in StopBitCheck is unreachable.
Also note that the state transition to StopBitCheck happens on the same cycle that you would normally sample data, so the sampling of DataIn within StopBitCheck will be a cycle late. Worse, were you ever to get bad data (DataIn/='1' in StopBitCheck), counter would still be at 16, StartBitCheck would always go to the else clause, and the state machine would lock up.
Some more explanation on what was wrong before:
Your simulation has things changing on the negative clock edge because your combinatorial process only has the clock on the sensitivity list. The correct sensitivity list for the combinatorial process would include only DataIn, Enable, currentState, and your two variables, counter and dataIndex. Variables can't be a part of your sensitivity list because they are out of scope for the sensitivity list (also you do not want to trigger your process off of itself, more on that in a moment).
The sensitivity list is, however, mostly just a crutch for simulators. When translated to real hardware, processes are implemented in LUTs and Flip Flops. Your current implementation will never synthesize because you incorporate feedback (signals or variables that get assigned a new value as a function of their old value) in unclocked logic, producing a combinatorial loop.
counter and dataIndex are part of your state data. The state machine is simpler to understand because they are split off from the explicit state, but they are still part of the state data. When you make a two process state machine (again, I recommend 1 process state machines, not 2) you must split all state data into Flip Flops used to store it (such as currentState) and the output of the LUT that generates the next value (such as nextState). This means that for your two process machine, the variables counter and dataIndex must instead become currentCounter, nextCounter, currentDataIndex, and nextDataIndex and treated like your state assignment. Note that if you choose to implement changes to keep a 2-process state machine, the logic errors mentioned above the line will still apply.
EDIT:
Yes, resetting the counter back to 0 before moving into StopBitCheck might be a good idea, but you also need to consider that you are waiting the full 16 counts after sampling the last data bit before you even transition into StopBitCheck. It is only because counter is not reset that the sample is only off by one clock instead of 16. You may want to modify your ReadData action to transition to StopBitCheck as you sample the last bit when dataIndex=7 (as well as reset counter to 0) like so:
elsif (counter = 16) then
DataOut(dataIndex) <= DataIn;
counter <= 0;
if (dataIndex < 7) then
dataIndex <= dataIndex + 1;
else
dataIndex <= 0;
state <= StopBitCheck;
end if;
end if;
A pure state machine only stores a state. It generates its output purely from the state, or from a combination of the state and the inputs. Because counter and dataIndex are stored, they are part of the state. If you wanted to enumerate every single state you would have something like:
type states is (StartBitCheck_Counter0, StartBitCheck_counter1...
and you would end up with 8*16*3 = 384 states (actually somewhat less because only ReadData uses dataIndex, so some of the 384 are wholly redundant states). As you can no doubt see, it is much simpler to just declare 3 separate signals since the different parts of the state data are used differently. In a two process state machine, people often forget that the signal actually named state isn't the only state data that needs to be stored in the clocked process.
In a 1-process machine, of course, this isn't an issue because everything that is assigned is by necessity stored in flip flops (the intermediary combinational logic isn't enumerated in signals). Also, do note that 1-process state machines and 2-process state machines will synthesize to the same thing (assuming they were both implemented correctly), although I'm of the opinion that is comparatively easier to read and more difficult to mess up a 1-process machine.
I also removed the else clauses that maintained the current state assignment in the 1-process example I provided; they are important when assigning a combinational nextState, but the clocked signal state will keep its old value whenever it isn't given a new assignment without inferring a latch.
First Process runs just on CLK rising edge, while the second one runs on both CLK edge (because runs on every CLK change).
You use 2 process, “memory-state” and “next-state builder”, the first must be synchronous (as you done) and the second, normally, is combinatorial to be able to produce next-state in time for next CLK active edge.
But in your case the second process needs also to run on every CLK pulse (because of variable counter and index), so the solution can be to run the first on rising-edge and the second on falling-edge (if your hardware support this).
Here is your code a little bit revisited, I hope can be useful.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity ASyncReceiverV4 is
Port ( DataIn : in STD_LOGIC;
Enable : in STD_LOGIC;
CLK : in STD_LOGIC;
BadData : out STD_LOGIC := '0';
DataOut : out STD_LOGIC_VECTOR (7 downto 0) := "00000000");
end ASyncReceiverV4;
architecture Behavioral of ASyncReceiverV4 is
type states is (StartBitCheck, ReadData, StopBitCheck);
signal currentState : states := StartBitCheck;
signal nextState : states := StartBitCheck;
begin
process(CLK)
begin
if rising_edge(CLK) then
currentState <= nextState;
end if;
end process;
process(CLK)
variable counter : integer := 0;
variable dataIndex : integer := 0;
begin
if falling_edge(CLK) then
case currentState is
when StartBitCheck =>
if Enable = '1' then
if (DataIn = '0' and counter < 8) then
counter := counter + 1;
elsif (DataIn = '0' and counter = 8) then
BadData <= '0';
nextState <= ReadData;
counter := 0;
else
nextState <= StartBitCheck;
end if;
end if;
when ReadData =>
if Enable = '1' then
if counter < 15 then
counter := counter + 1;
elsif (counter = 15 and dataIndex < 8) then
DataOut(dataIndex) <= DataIn;
counter := 0;
dataIndex := dataIndex + 1;
elsif dataIndex = 8 then
dataIndex := 0;
nextState <= StopBitCheck;
else
nextState <= ReadData;
end if;
end if;
when StopBitCheck =>
if Enable = '1' then
if DataIn = '1' then
if counter < 15 then
counter := counter + 1;
nextState <= StopBitCheck;
elsif counter = 15 then
counter := 0;
nextState <= StartBitCheck;
end if;
else
DataOut <= "11111111";
BadData <= '1';
nextState <= StartBitCheck;
end if;
end if;
end case;
end if;
end process;
end Behavioral;
This is a 0x55 with wrong stop bit receive data simulation

Inno Setup Windows DLL function call with pointer to structure

I am trying to set a service's failure actions using Inno Setup's Pascal scripting language. I receive the classic "access violation at address..." error. Seems that it is impossible because the language don't have any support to pointers. Any ideas? Here is the code snippet:
type
TScAction = record
aType1 : Longword;
Delay1 : Longword;
aType2 : Longword;
Delay2 : Longword;
aType3 : Longword;
Delay3 : Longword;
end;
type
TServiceFailureActionsA = record
dwResetPeriod : DWORD;
pRebootMsg : String;
pCommand : String;
cActions : DWORD;
saActions : TScAction;
end;
function ChangeServiceConfig2(hService: Longword; dwInfoLevel: Longword; lpInfo: TServiceFailureActionsA): BOOL;
external 'ChangeServiceConfig2A#advapi32.dll stdcall';
procedure SimpleChangeServiceConfig(AService: string);
var
SCMHandle: Longword;
ServiceHandle: Longword;
sfActions: TServiceFailureActionsA;
sActions: TScAction;
begin
try
SCMHandle := OpenSCManager('', '', SC_MANAGER_ALL_ACCESS);
if SCMHandle = 0 then
RaiseException('SimpleChangeServiceConfig#OpenSCManager: ' + AService + ' ' +
SysErrorMessage(DLLGetLastError));
try
ServiceHandle := OpenService(SCMHandle, AService, SERVICE_ALL_ACCESS);
if ServiceHandle = 0 then
RaiseException('SimpleChangeServiceConfig#OpenService: ' + AService + ' ' +
SysErrorMessage(DLLGetLastError));
try
sActions.aType1 := SC_ACTION_RESTART;
sActions.Delay1 := 60000; // First.nDelay: in milliseconds, MMC displayed in minutes
sActions.aType2 := SC_ACTION_RESTART;
sActions.Delay2 := 60000;
sActions.aType3 := SC_ACTION_RESTART;
sActions.Delay3 := 60000;
sfActions.dwResetPeriod := 1; // in seconds, MMC displayes in days
//sfActions.pRebootMsg := null; // reboot message unchanged
//sfActions.pCommand := null; // command line unchanged
sfActions.cActions := 3; // first, second and subsequent failures
sfActions.saActions := sActions;
if not ChangeServiceConfig2(
ServiceHandle, // handle to service
SERVICE_CONFIG_FAILURE_ACTIONS, // change: description
sfActions) // new description
then
RaiseException('SimpleChangeServiceConfig#ChangeServiceConfig2: ' + AService + ' ' +
SysErrorMessage(DLLGetLastError));
finally
if ServiceHandle <> 0 then
CloseServiceHandle(ServiceHandle);
end;
finally
if SCMHandle <> 0 then
CloseServiceHandle(SCMHandle);
end;
except
ShowExceptionMessage;
end;
end;
You have two problems in your script. Like Deanna suggested you have to use the var keyword in the declaration of the lpInfo parameter.
Also you need to change the TScAction type to an array with two elements.
Here is my script that you can include in your Inno Setup script.
const
SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3; //The lpInfo parameter is a pointer to a SERVICE_DELAYED_AUTO_START_INFO structure.
//Windows Server 2003 and Windows XP: This value is not supported.
SERVICE_CONFIG_DESCRIPTION = 1; //The lpInfo parameter is a pointer to a SERVICE_DESCRIPTION structure.
SERVICE_CONFIG_FAILURE_ACTIONS = 2; //The lpInfo parameter is a pointer to a SERVICE_FAILURE_ACTIONS structure.
//If the service controller handles the SC_ACTION_REBOOT action, the caller must have
// the SE_SHUTDOWN_NAME privilege. For more information, see Running with Special Privileges.
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 4; //The lpInfo parameter is a pointer to a SERVICE_FAILURE_ACTIONS_FLAG structure.
//Windows Server 2003 and Windows XP: This value is not supported.
SERVICE_CONFIG_PREFERRED_NODE = 9; //The lpInfo parameter is a pointer to a SERVICE_PREFERRED_NODE_INFO structure.
//Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported.
SERVICE_CONFIG_PRESHUTDOWN_INFO = 7; //The lpInfo parameter is a pointer to a SERVICE_PRESHUTDOWN_INFO structure.
//Windows Server 2003 and Windows XP: This value is not supported.
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 6; //The lpInfo parameter is a pointer to a SERVICE_REQUIRED_PRIVILEGES_INFO structure.
//Windows Server 2003 and Windows XP: This value is not supported.
SERVICE_CONFIG_SERVICE_SID_INFO = 5; //The lpInfo parameter is a pointer to a SERVICE_SID_INFO structure.
SERVICE_CONFIG_TRIGGER_INFO = 8; //The lpInfo parameter is a pointer to a SERVICE_TRIGGER_INFO structure.
//This value is not supported by the ANSI version of ChangeServiceConfig2.
//Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2.
SC_ACTION_NONE = 0; // No action.
SC_ACTION_REBOOT = 2; // Reboot the computer.
SC_ACTION_RESTART = 1; // Restart the service.
SC_ACTION_RUN_COMMAND = 3; // Run a command.
type
TScAction = record
aType1 : Longword;
Delay1 : Longword;
end;
type
TServiceFailureActionsA = record
dwResetPeriod : DWORD;
pRebootMsg : String;
pCommand : String;
cActions : DWORD;
saActions : array of TScAction;
end;
function ChangeServiceConfig2(
hService: Longword;
dwInfoLevel: Longword;
var lpInfo: TServiceFailureActionsA): BOOL;
external 'ChangeServiceConfig2A#advapi32.dll stdcall';
procedure SimpleChangeServiceConfig(AService: string);
var
SCMHandle: Longword;
ServiceHandle: Longword;
sfActions: TServiceFailureActionsA;
sActions: array of TScAction;
begin
SetArrayLength(sActions ,3);
try
SCMHandle := OpenSCManager('', '', SC_MANAGER_ALL_ACCESS);
if SCMHandle = 0 then
RaiseException('SimpleChangeServiceConfig#OpenSCManager: ' + AService + ' ' +
SysErrorMessage(DLLGetLastError));
try
ServiceHandle := OpenService(SCMHandle, AService, SERVICE_ALL_ACCESS);
if ServiceHandle = 0 then
RaiseException('SimpleChangeServiceConfig#OpenService: ' + AService + ' ' +
SysErrorMessage(DLLGetLastError));
try
sActions[0].aType1 := SC_ACTION_RESTART;
sActions[0].Delay1 := 60000; // First.nDelay: in milliseconds, MMC displayed in minutes
sActions[1].aType1 := SC_ACTION_RESTART;
sActions[1].Delay1 := 60000;
sActions[2].aType1 := SC_ACTION_NONE;
sActions[2].Delay1 := 60000;
sfActions.dwResetPeriod := 1; // in seconds, MMC displayes in days
//sfActions.pRebootMsg := null; // reboot message unchanged
//sfActions.pCommand := null; // command line unchanged
sfActions.cActions := 3; // first, second and subsequent failures
sfActions.saActions := sActions;
if not ChangeServiceConfig2(
ServiceHandle, // handle to service
SERVICE_CONFIG_FAILURE_ACTIONS, // change: description
sfActions) // new description
then
RaiseException('SimpleChangeServiceConfig#ChangeServiceConfig2: ' + AService + ' ' +
SysErrorMessage(DLLGetLastError));
finally
if ServiceHandle <> 0 then
CloseServiceHandle(ServiceHandle);
end;
finally
if SCMHandle <> 0 then
CloseServiceHandle(SCMHandle);
end;
except
ShowExceptionMessage;
end;
end;
Try using the var keyword in the declaration for the lpInfo parameter to specify that it's to pass a pointer to the structure to the function.

Resources