You have a millisecond sleep while polling for level changes which can have as little as 26 microseconds between them.
Whose quote was that?
I have a very vague recollection (and I might be wrong and too lazy to verify it myself) of SB's delay functions being highly platform dependent. Under Windows, delay precision is determined by the resolution of Windows system timer (Sleep() WinAPI), which is rather low at approx.
15.6 milliseconds (i.e. 0.0156 of a second) in most cases. OTOH under Linux, the resolution goes as high as the Linux system timer permits, which may be on the order of microseconds that is millionths of a second, e.g.
15.6 microseconds or 0.0000156 of a second.
I'm not sure which precision is applicable to, or supported on, the Raspberry Pi platform. At any rate, if RPi timing is as coarse as it is under Windows, then delay-based approaches to the events occurring as frequently as ca. 38,500 times per second (i.e. as short in their duration as only 26 µs/microseconds, or 0.000026 sec each) seem hardly reasonable and are bound to fail.