Tested on 18F452, 8MHz, EasyPIC3 board.
Code: Select all
// Date 2005-08-16 ZR
program ReadString
var txt, delim: string[20];
// Reads chars from usart until delimiter sequence is detected.
// Read sequence is stored in output.
// Delimiter sequence is not stored in output.
// This is a blocking call, it is expected that the sequence arrives,
// otherwise the procedure exits after 20 received chars
procedure Usart_Read_Text(var output, delimiter: string[20]);
var i, j, data, data2: byte;
lasti: byte;
label exit;
begin
i := 0;
j := 0;
lasti := 0;
data2 := delimiter[0];
while true do
begin
if Usart_Data_Ready <> 0 then // something has arrived
begin
data := USART_Read; // read char
output[i] := data; // store char in data (delimiter is stored too)
if data = data2 then // does it match the sequence?
begin
lasti := i - j; // indicate where output should end
inc(j); // next letter in sequence
end
else
begin
j := 0; // sequences do not match, reset counters
lasti := 0;
end;
data2 := delimiter[j]; // get next delimiter
if data2 = 0 then // stop if the end of delimiter is reached
break;
inc(i);
if i > 20 then // too many chars received
begin
lasti := 19;
break;
end;
end;
end;
output[lasti] := 0; // place the end of string before delimiter
end;
// writes text to usart.
// text has to be zero terminated
procedure Usart_Write_Text(var uart_text: string[20]);
var i, data: byte;
begin
i := 0;
data := uart_text[0];
while data <> 0 do
begin
USART_Write(data);
inc(i);
data := uart_text[i];
end;
end;
// test program
begin
USART_init(9600);
delim := 'OK';
while true do
begin
if Usart_Data_Ready = 1 then
begin
Usart_Read_Text(txt, delim); // read text until "OK" is received
Usart_Write_Text(txt); // write back what has been read
end;
end;
end.