GNAT.Serial_Communications如何转换Stream_Element_Array

GNAT.Serial_Communications how to convert Stream_Element_Array

我尝试使用 GNAT.Serial_Communications 包编写一个与 Arduino 的小型通信程序。

与 Arduino 建立通信正常。 我正在使用 Serial_Communications.Read() 函数来获取信息。现在我想将 Stream_Element_Array 中存储的数据转换为 Integer

我尝试了 Integer'Value() 功能,但它不起作用,我收到错误消息:expected type "Standard.String"

使用 String'Value() 结果:prefix of value attribute must be scalar type.

我找不到任何关于 Stream_Element_Array 转换的信息。

  Serial_Communications.Open
  (Port => Port,
   Name => Port_Name);

  Serial_Communications.Set
  (Port      => Port,
   Rate      => Serial_Communications.B115200,
   Bits      => Serial_Communications.CS8,
   Stop_Bits => Serial_Communications.One,
   Parity    => Serial_Communications.Even);


  Serial_Communications.Read(Port  => Port,
                             Buffer => Buffer,
                             Last   => Last);

  Int_value := Integer'Value(String'Value(Buffer(1)));

  Serial_Communications.Close(Port => Port);

根据我在 the ARM, a Stream_Element is a modular type and should by the way already be cast to an Integer type 中看到的内容。

类似

Int_value := Integer(Buffer(Buffer'First));

应该可以直接工作,但我没有测试任何东西 ;)

类型 GNAT.Serial_Communications.Serial_PortAda.Streams.Root_Stream_Type 的扩展:

type Serial_Port is new Ada.Streams.Root_Stream_Type with private;

这意味着您可以将其用作流,因此可以使用 Read 属性(有关详细信息,请参阅 ARM 13.13 for details). Furthermore, I would recommend to use an integer type from the Interfaces package rather than the Ada Integer type as all Ada integer types are defined by a minimal range to be supported and have no mandated storage size (see ARM 3.5.4 (21) and ARM B.2)。

以下示例可能会有所帮助:

with Interfaces;
with GNAT.Serial_Communications;

procedure Main is

   package SC renames GNAT.Serial_Communications;

   Port_Name :         SC.Port_Name := "COM1";
   Port      : aliased SC.Serial_Port;

   Int_Value : Interfaces.Integer_8;

begin

   SC.Open
     (Port => Port,
      Name => Port_Name);

   SC.Set
     (Port      => Port,
      Rate      => SC.B115200,
      Bits      => SC.CS8,
      Stop_Bits => SC.One,
      Parity    => SC.Even); 

   --  Check Interfaces package for types other than "Integer_8".
   Interfaces.Integer_8'Read (Port'Access, Int_Value);

   SC.Close(Port => Port);

end Main;