Set up an interrupt (INT or IOC) and in the isr, set / clear a flag as approriate. In the main loop, process that flag.