首页 > 技术文章 > Ada 串口

santion 2021-06-01 17:47 原文

Ada 使用串口的一个例子。使用一个TX接RX的USB转RS232。

with Ada.Streams;
with GNAT.Serial_Communications;
with Ada.Text_IO;

procedure Serial is
	use Ada.Streams;
	use GNAT;
	use Ada.Text_IO;

	subtype Message is Stream_Element_Array (1 .. 20);

	Data   : constant String (1 .. 20)  := "ABCDEFGHIJLKMNOPQRST";
	Read_Data   :  String (1 .. 20)  ;
	Buffer : Message;
	Read_Buf : Message;

	S_Port : constant Natural := 1;
	--  Serial port number

begin
	--  Convert message (String -> Stream_Element_Array)

	for K in Data'Range loop
	   Buffer (Stream_Element_Offset (K)) := Character'Pos (Data (K));
	end loop;

	declare
	   --Port_Name : constant Serial_Communications.Port_Name :=
		--			 Serial_Communications.Name (Number => S_Port);
		Port_Name : constant Serial_Communications.Port_Name := "/dev/ttyUSB0";
	   Port      : Serial_Communications.Serial_Port;
	   
	   Offset : Stream_Element_Offset;
	   

	begin
		Put("Port  = ");
		Put_Line (String(Port_Name));
		
	   Serial_Communications.Open
		 (Port => Port,
		  Name => Port_Name);

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

	   Serial_Communications.Write
		 (Port   => Port,
		  Buffer => Buffer);
		  
		 Put ("Write = ");
		 Put_Line (Data);
		  
		 Serial_Communications.Read
		 (Port   => Port,
		  Buffer => Read_Buf,
		  Last => Offset);

	for K in Data'Range loop
	   Read_Data(K) := Character'Val(Read_Buf (Stream_Element_Offset (K)));
	end loop;
	Put("Read  = ");
	Put_Line (Read_Data);
	
	Serial_Communications.Close (Port => Port);
	end;
end Serial;

推荐阅读