我尝试使用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中看到的情况来看,Stream_Element
是一种模块化类型,并且应该已经被投射到Integer
type。
就像是
Int_value := Integer(Buffer(Buffer'First));
应该直接工作,但我没有测试任何东西;)
类型GNAT.Serial_Communications.Serial_Port
是Ada.Streams.Root_Stream_Type
的扩展:
type Serial_Port is new Ada.Streams.Root_Stream_Type with private;
这意味着您可以将其用作流,因此使用Read
属性(有关详细信息,请参阅ARM 13.13)。此外,我建议使用Interfaces
包中的整数类型而不是Ada Integer
类型,因为所有Ada整数类型都由要支持的最小范围定义,并且没有强制存储大小(有关详细信息,请参阅ARM 3.5.4 (21)和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;