blib/lib/RPi/Serial.pm

filter: Statementstmt 13.5% 10 / 74 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 10.0% 2 / 20 Podpod 100% 13 / 13 totaltotal 17.0% 25 / 147 CC 16 SCAR 35.7
CC
16
Cov
9%
rx
110.0
_remote_crc
20.0
fd
6.0
CRAP 35.5
↑ Summary Serial.xs »
1 package RPi::Serial;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6  
7 1 our $VERSION = '3.02';
8  
9 1 require XSLoader;
10 1 XSLoader::load('RPi::Serial', $VERSION);
11  
12 0 ▶sub new {
Subroutine new: not called CC=1 SCAR=6.9
Pod documented
13 0 my ($class, $device, $baud) = @_;
14  
15 0 my $self = bless {
16 rx_data => '',
17 rx_started => 0,
18 rx_ended => 0,
19 }, $class;
20  
21 0 $self->fd(tty_open($device, $baud));
22  
23 0 return $self;
24 }
25 0 ▶sub close {
Subroutine close: not called CC=1 SCAR=6.9
Pod documented
26 0 tty_close($_[0]->fd);
27 }
28 0 ▶sub crc {
Subroutine crc: not called CC=1 SCAR=6.9
Pod documented
29 0 my ($self, $data) = @_;
30 0 return crc16($data, length($data));
31 }
32 0 ▶sub avail {
Subroutine avail: not called CC=1 SCAR=6.9
Pod documented
33 0 return tty_available($_[0]->fd);
34 }
35 0 ▶sub fd {
Subroutine fd: not called CC=2 SCAR=17.9
Pod documented
36 0 my $self = shift;
37 0 ▶ $self->{fd} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
38 0 return $self->{fd};
39 }
40 0 ▶sub flush {
Subroutine flush: not called CC=1 SCAR=6.9
Pod documented
41 0 tty_flush($_[0]->fd);
42 }
43 0 ▶sub putc {
Subroutine putc: not called CC=1 SCAR=6.9
Pod documented
44 0 tty_putc($_[0]->fd, $_[1]);
45 }
46 0 ▶sub puts {
Subroutine puts: not called CC=1 SCAR=6.9
Pod documented
47 0 tty_puts($_[0]->fd, $_[1]);
48 }
49 0 ▶sub getc {
Subroutine getc: not called CC=1 SCAR=6.9
Pod documented
50 0 return tty_getc($_[0]->fd);
51 }
52 0 ▶sub gets {
Subroutine gets: not called CC=1 SCAR=6.9
Pod documented
53 # Returns the exact bytes read (binary-safe); may be shorter than the
54 # requested count if the port's read timeout elapsed first.
55 0 return tty_gets($_[0]->fd, $_[1]);
56 }
57 0 ▶sub write {
Subroutine write: not called CC=2 SCAR=17.9
Pod documented
58 0 my ($self, $byte) = @_;
59 0 ▶ if (! defined $byte){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $byte) 0 0 0
60 0 die "write() requires a byte of data sent in\n";
61 }
62 0 $self->putc(pack("C", $byte));
63 }
64 0 ▶sub rx {
Subroutine rx: not called CC=10 SCAR=47.0
Pod documented
65 0 my ($self, $start, $end) = @_;
66  
67 0 my $c = chr $self->getc; # getc() returns the ord() val on a char* perl-wise
68  
69 0 ▶ if ($c ne $start && ! $self->{rx_started}){
Branch: 1 branch
BranchTrueFalseTotal
if ($c ne $start and not $self->{"rx_started"}) 0 0 0
Condition0%0/3
$c ne $start and not $self->{"rx_started"}
!ll&&!rl&&r
000
MC/DC0%0/2
$c ne $start and not $self->{"rx_started"}
$c ne $start not $self->{"rx_started"}
Truth table0%0/3
A and not(B)
A= $c ne $startB= not $self->{"rx_started"}
ABresult
0X0
100
111
70 0 $self->_rx_reset();
71 0 return;
72 }
73  
74 0 ▶ if ($c eq $start){
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq $start) 0 0 0
75 0 $self->{rx_started} = 1;
76 0 return;
77 }
78  
79 0 ▶ if ($c eq $end){
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq $end) 0 0 0
80 0 $self->{rx_ended} = 1;
81 }
82  
83 0 ▶ if ($self->{rx_started} && ! $self->{rx_ended}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"rx_started"} and not $self->{"rx_ended"}) 0 0 0
Condition0%0/3
$self->{"rx_started"} and not $self->{"rx_ended"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"rx_started"} and not $self->{"rx_ended"}
$self->{"rx_started"} not $self->{"rx_ended"}
Truth table0%0/3
A and not(B)
A= $self->{"rx_started"}B= not $self->{"rx_ended"}
ABresult
0X0
100
111
84 0 $self->{rx_data} .= $c;
85 }
86  
87 0 ▶ if ($self->{rx_started} && $self->{rx_ended}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"rx_started"} and $self->{"rx_ended"}) 0 0 0
Condition0%0/3
$self->{"rx_started"} and $self->{"rx_ended"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"rx_started"} and $self->{"rx_ended"}
$self->{"rx_started"} $self->{"rx_ended"}
Truth table0%0/3
A and B
A= $self->{"rx_started"}B= $self->{"rx_ended"}
ABresult
0X0
100
111
88  
89 0 my $l_crc = $self->_local_crc($self->{rx_data});
90 0 my $r_crc = $self->_remote_crc($self->{rx_data});
91  
92 0 ▶ if ($r_crc == $l_crc){
Branch: 1 branch
BranchTrueFalseTotal
if ($r_crc == $l_crc) { } 0 0 0
93 0 my $rx_data = $self->{rx_data};
94 0 $self->_rx_reset;
95 0 return $rx_data;
96 }
97 else {
98 0 warn "\ncompiled data '$self->{rx_data}' has mismatching CRC\n\n";
99 0 $self->_rx_reset;
100 0 return;
101 }
102 }
103 }
104 0 ▶sub tx {
Subroutine tx: not called CC=2 SCAR=17.9
Pod documented
105 0 my ($self, $data, $tx_start, $tx_end) = @_;
106  
107 0 my $crc = $self->crc($data);
108 0 my $crc_msb = $crc >> 8;
109 0 my $crc_lsb = $crc & 0xFF;
110  
111 0 my $tx = $tx_start . $data . $tx_end;
112  
113 0 for (split //, $tx){
114 0 $self->write($_);
115 }
116  
117 0 $self->write($crc_msb);
118 0 $self->write($crc_lsb);
119 }
120  
121 0 ▶sub DESTROY {
Subroutine DESTROY: not called CC=1 SCAR=6.9
122 0 tty_close($_[0]->fd);
123 }
124  
125 0 ▶sub _local_crc {
Subroutine _local_crc: not called CC=1 SCAR=6.9
126 0 return $_[0]->crc($_[1]);
127 }
128 0 ▶sub _remote_crc {
Subroutine _remote_crc: not called CC=4 SCAR=30.0
129 0 my ($self) = @_;
130  
131 0 ▶ while ($self->avail < 2){} # loop until we have two bytes to make up the CRC
Branch: 1 branch
BranchTrueFalseTotal
if ($self->avail < 2) 0 0 0
132  
133 0 my $crc_msb = $self->getc;
134 0 my $crc_lsb = $self->getc;
135  
136 0 my $crc = ($crc_msb << 8) | $crc_lsb;
137  
138 0 ▶ return if $crc_msb == -1 || $crc_lsb == -1;
Branch: 1 branch
BranchTrueFalseTotal
if $crc_msb == -1 or $crc_lsb == -1 0 0 0
Condition0%0/3
$crc_msb == -1 or $crc_lsb == -1
l!l&&r!l&&!r
000
MC/DC0%0/2
$crc_msb == -1 or $crc_lsb == -1
$crc_msb == -1 $crc_lsb == -1
Truth table0%0/3
A or B
A= $crc_msb == -1B= $crc_lsb == -1
ABresult
1X1
011
000
139 0 return $crc;
140 }
141 0 ▶sub _rx_reset {
Subroutine _rx_reset: not called CC=1 SCAR=6.9
142 0 my ($self) = @_;
143 0 $self->{rx_started} = 0;
144 0 $self->{rx_ended} = 0;
145 0 $self->{rx_data} = '';
146 }
147 0 ▶sub __placeholder {} # vim folds
Subroutine __placeholder: not called CC=1 SCAR=0.0
148 1 1;
149  
150 =head1 NAME
151  
152 RPi::Serial - Basic read/write interface to a serial port
153  
154 =head1 SYNOPSIS
155  
156 use RPi::Serial;
157  
158 my $dev = "/dev/ttyAMA0";
159 my $baud = 115200;
160
161 my $ser = RPi::Serial->new($dev, $baud);
162  
163 # Write a single char
164  
165 $ser->putc(5);
166  
167 # Write a string
168  
169 $ser->puts("hello, world!");
170  
171 # Write a single byte by its integer value (0-255)
172  
173 $ser->write(65);
174 my $char = $ser->getc;
175  
176 # Get a string
177  
178 my $num_bytes = 12;
179 my $str = $ser->gets($num_bytes);
180  
181 # Send a CRC-framed payload between start/end delimiters
182  
183 $ser->tx("payload", "<", ">");
184  
185 # Receive a CRC-framed payload (call in a loop until it returns the data)
186  
187 my $frame = $ser->rx("<", ">");
188  
189 my $crc = $ser->crc($str);
190  
191 $ser->flush;
192  
193 my $bytes_available = $ser->avail;
194  
195 $ser->close;
196  
197 =head1 DESCRIPTION
198  
199 Provides basic read and write functionality of a UART serial interface
200  
201 =head1 WARNING
202  
203 If using on a Raspberry Pi platform, the procedure to enable GPIO pins 14 (TXD)
204 and 15 (RXD) as a serial interface differs by board. On B<all> boards, first
205 free the port from the kernel console: in C<raspi-config>, under C<Interface
206 Options -E<gt> Serial Port>, answer B<no> to the login shell and B<yes> to the
207 serial hardware.
208  
209 =head2 Raspberry Pi 3 / 4 (and Zero W)
210  
211 The on-board Bluetooth modem is wired to the primary PL011 UART, leaving GPIO
212 14/15 on the inferior, baud-unstable mini-UART (C</dev/ttyS0>). To move the good
213 UART onto the header pins you must disable Bluetooth. Edit
214 C</boot/firmware/config.txt> (C</boot/config.txt> on releases before Bookworm)
215 and add:
216  
217 enable_uart=1
218 dtoverlay=disable-bt
219  
220 With that overlay the header serial port becomes C</dev/ttyAMA0>.
221  
222 =head2 Raspberry Pi 5
223  
224 Bluetooth has its B<own dedicated UART> and is B<not> shared with the GPIO 14/15
225 pins, so there is nothing to disable. Just enable the header UART in
226 C</boot/firmware/config.txt>:
227  
228 enable_uart=1
229  
230 The header serial port is C</dev/ttyAMA0>. (Note that on the Pi 5
231 C</dev/serial0> maps to the separate 3-pin debug-UART connector, B<not> the
232 header pins.)
233  
234 Save the file, then reboot the Pi.
235  
236 =head1 METHODS
237  
238 =head2 new($device, $baud);
239  
240 Opens the specified serial port at the specified baud rate, and returns a new
241 L<RPi::Serial> object.
242  
243 Parameters:
244  
245 $device
246  
247 Mandatory, String: The serial device to open (eg: C<"/dev/ttyAMA0">).
248  
249 $baud
250  
251 Mandatory, Integer: A valid baud rate to use.
252  
253 =head2 close
254  
255 Closes an already open serial device.
256  
257 =head2 avail
258  
259 Returns the number of bytes waiting to be read if any.
260  
261 =head2 flush
262  
263 Flush any data currently in the serial buffer.
264  
265 =head2 fd
266  
267 Returns the C<ioctl> file descriptor for the current serial object.
268  
269 =head2 getc
270  
271 Retrieve a single character from the serial port.
272  
273 =head2 gets($num_bytes)
274  
275 Read up to a specified number of bytes and return them as a string.
276  
277 The read blocks only until the port's configured read timeout (the C<VTIME>
278 value set when the port was opened) elapses, so the returned string may be
279 B<shorter> than C<$num_bytes> if fewer bytes arrived in time (or the device
280 closed). The result is binary-safe: embedded C<NUL> bytes and trailing
281 whitespace are preserved exactly as received.
282  
283 Parameters:
284  
285 $num_bytes
286  
287 Mandatory, Integer; The maximum number of bytes to read. If this number is
288 larger than what is available, the call returns the bytes received before the
289 read timeout elapsed (possibly an empty string).
290  
291 Returns: A string of the bytes actually read. Croaks on a read error.
292  
293 =head2 putc($char)
294  
295 Writes a single character to the serial device.
296  
297 Parameters:
298  
299 $char
300  
301 Mandatory, Unsigned Char: The character to write to the port.
302  
303 =head2 puts($string)
304  
305 Write a character string to the serial device.
306  
307 Parameters:
308  
309 $string
310  
311 Mandatory, String: Whatever you want to write to the serial line.
312  
313 =head2 crc($string)
314  
315 Calculate and return a CRC-16 checksum. Uses local B<crc16.c> application to
316 generate the CRC.
317  
318 Parameters:
319  
320 $string
321  
322 Mandatory, String: The string to perform the checksum on.
323  
324 =head2 write($byte)
325  
326 Writes a single byte to the serial device. The byte is packed into an unsigned
327 char before being sent, making this a convenience wrapper around L</putc($char)>
328 that accepts an integer value rather than a character.
329  
330 Parameters:
331  
332 $byte
333  
334 Mandatory, Unsigned Integer (0-255): The byte value to write to the port.
335 Croaks if not supplied.
336  
337 =head2 rx($start, $end)
338  
339 Reads a single character from the serial port and assembles framed data across
340 successive calls. A frame begins when the C<$start> delimiter is received and
341 ends when the C<$end> delimiter is received, at which point the two trailing
342 CRC-16 bytes are read and validated against the assembled payload.
343  
344 Call this repeatedly (eg: in a loop). Until a complete, CRC-valid frame has been
345 received it returns C<undef>; characters seen before the C<$start> delimiter are
346 discarded.
347  
348 Parameters:
349  
350 $start
351  
352 Mandatory, Char: The single character that marks the beginning of a frame.
353  
354 $end
355  
356 Mandatory, Char: The single character that marks the end of a frame.
357  
358 Returns: The assembled payload string once a full frame with a matching CRC has
359 been received, or C<undef> otherwise. Warns and discards the frame if the
360 received CRC does not match the locally computed one.
361  
362 =head2 tx($data, $tx_start, $tx_end)
363  
364 Transmits a frame of data. The C<$data> is wrapped between the C<$tx_start> and
365 C<$tx_end> delimiters and written to the port, followed by the two bytes (most
366 significant first) of the CRC-16 checksum calculated over C<$data>.
367  
368 Parameters:
369  
370 $data
371  
372 Mandatory, String: The payload to transmit.
373  
374 $tx_start
375  
376 Mandatory, Char: The single character to send before the payload.
377  
378 $tx_end
379  
380 Mandatory, Char: The single character to send after the payload.
381  
382 =head1 AUTHOR
383  
384 Steve Bertrand, C<< <steveb at cpan.org> >>
385  
386 =head1 LICENSE AND COPYRIGHT
387  
388 Copyright 2026 Steve Bertrand.
389  
390 This program is free software; you can redistribute it and/or modify it
391 under the terms of either: the GNU General Public License as published
392 by the Free Software Foundation; or the Artistic License.
393  
394 See L<http://dev.perl.org/licenses/> for more information.
↑ Summary Serial.xs »