#!/usr/bin/perl ######################### # # debounce-sim.pl # # A quick simulation of a bouncing switch and the debounce routine from Jack Ganssel # # Copyright (C) 2008 Todd LaWall (aka bitreaper) # ######################### @bounceStates = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, # slience 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, # start the bouncing 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, # switch has settled 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, # do switches bounce on release? 0, 0, 0, 0, 0, 0, 0, 0, # this sim shows that it doesn't really matter 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, # start the bouncing again 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, # switche has settled 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, # noise 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, ); $State = 0x0; ################################################## # our two subroutines # # we need to pass in index, it's quick and dirty, so we know what tick we're on. # ################################################## sub RawKeyPressed{ my $index = shift; return $bounceStates[ $index ]; } ######################### # DebounceSwitch2() as it should look in the example, the only change being the index # being passed in. Obviously, that won't be in the final code. ######################### sub DebounceSwitch2{ my $index = shift; $State = ( $State << 1 ) | !RawKeyPressed( $index ) | 0xFE000000; if( $State == 0xFF000000 ){ return 1; } return 0; } ################################################## # Main loop, this would actually be your interrupt for the timer tick ################################################## print "status\t\tcycle\thex value\tkey state\n"; print "------\t\t-----\t---------\t---------\n"; for( my $i = 0; $i < 256; $i++ ){ if( DebounceSwitch2( $i )){ printf( "Debounced:\t%d\t%0X\t%d\n", $i, $State, $bounceStates[$i] ); }else{ printf( "Waiting\t\t%d\t%0X\t%d\n", $i, $State, $bounceStates[$i] ); } }