Generated: Sat Oct 24 16:35:10 2020 from chk4key.pl 2019/10/22 2.7 KB. text copy
#!/usr/bin/perl -w # NAME: chk4key.pl # AIM: Find a way to POLL the keyboard # 2019-10-22 - Add more accurate timing... # 05/09/2010 - Added seconds waited, and cycles... # 14/12/2008 geoff mclane http://geoffair.net/mperl use strict; use warnings; use Term::ReadKey; use Time::HiRes qw(gettimeofday tv_interval); # provide more accurate timings #ReadMode('cbreak'); #ReadMode 1; # cooked mode sub show_hex { my ($i) = shift; print sprintf( "%03d ", $i ); if ($i == 0) { print "z "; } elsif ($i == 8 ) { print "d "; } elsif ($i == 9 ) { print "9 "; } elsif ($i == 7 ) { print "b "; } elsif ($i == 10 ) { print "c "; } elsif ($i == 13 ) { print "l "; } else { print sprintf( "%c ", $i ); } print sprintf( "%02X ", $i ); print sprintf( "%03o\n", $i ); } sub got_keyboard { my ($rc) = shift; if (defined (my $char = ReadKey(-1)) ) { # input was waiting and it was $char $$rc = $char; return 1; } return 0; } # You can effect a sleep of 250 milliseconds this way: # select(undef, undef, undef, 0.25); sub delay { my ($secs) = shift; select(undef, undef, undef, $secs); } sub delay_time($) { my ($secs) = shift; my $bgn = [gettimeofday]; select(undef, undef, undef, $secs); my $el = tv_interval( $bgn, [gettimeofday] ); return $el; } print "Show keyboard, until ESC to exit ...\n"; my $add_delay = 1; my $begin_time = time(); my $wait_secs = $begin_time; my $cycles = 0; my $tot_cycs = 0; my $del_time = 0; my ($i, $char, $ch, $len, $j, $dif1, $dif2); my $bgntm = [gettimeofday]; for ($i = 0; ; $i++) { $cycles++; if (got_keyboard(\$char)) { my $time_now = time(); $dif1 = $time_now - $begin_time; $dif2 = $time_now - $wait_secs; $len = length($char); print "Elapsed $dif1: Waited $dif2 seconds for key... $cycles cycles... Got $len: "; for ($j = 0; $j < $len; $j++) { $ch = substr($char,$j,1); show_hex( ord($ch) ); } if ($char eq "\033") { print "Got ESC char ...\n"; last; } $wait_secs = $time_now; $tot_cycs += $cycles; $cycles = 0; } # sleep(1); # delay(0.1) if ($add_delay); # $del_time += delay_time(0.1); $del_time += delay_time(0.02); } my $elap = tv_interval ( $bgntm, [gettimeofday]); my $elapd = $elap - $del_time; my $cycpersec = ($elapd > 0) ? $tot_cycs / $elapd : "Unknown"; print "Alive for $elap secs... but slept in 'select' for $del_time sec...\n"; print " just $elapd secs in the code short do-nothing loop...\n"; print " So Total Cycles $tot_cycs by in-code = $cycpersec cps...\n"; exit(0); # eof