What Happens When I Press a Key? - Computerphile
ฝัง
- เผยแพร่เมื่อ 10 ก.พ. 2025
- Just what happens when you hit a key on a computer's keyboard? Dr Steve Bagley takes us on the keypress' journey....
Watch Part 2 Now: • How Software Deals wit...
Building the BBC Micro: • Building the BBC Micro...
Choosing a Password: • How to Choose a Passwo...
/ computerphile
/ computer_phile
This video was filmed and edited by Sean Riley.
Computer Science at the University of Nottingham: bit.ly/nottsco...
Computerphile is a sister project to Brady Haran's Numberphile. More at www.bradyharan.com
Always nice to see a seemingly simple system explained properly to uncover a hidden complexity I've never given much thought to before. Fascinating video.
"I like my keyboards soft and mushy" quote of the day :D
"I like my keyboards soft and mushy" *laughs in mechanical*
BHURGVFDI SHOUIE UIEFSL BEVI BUSIOEV VSBUYEOI HUEVSJKD
Your laugh in mechanical.
@Red Dunkey ygudhhbiuhvjkfkyuhrgnkvhjbikrtuhjgesguhyurhgbjvhgfbvsuyehbnxeruyvhbsiyurghbnvuihsgbxbenuyrghubdfiyugshb
@Red Dunkey uygjvj
I find the clickety-clacking to be highly therapeutic.
This is just superb, I have been researching "which keys are which notes on a piano?" for a while now, and I think this has helped. You ever tried - Penaycer Rudimentary Preponderance - (just google it ) ? It is an awesome one off guide for discovering how to play the piano easily minus the normal expense. Ive heard some unbelievable things about it and my colleague got amazing results with it.
10:02 And one nice thing about scan codes is they don’t distinguish between modifier and non-modifier keys; it’s just “key «n» has been pressed” and “key «n» has been released”, it’s up to the software to decide if key «n» is a modifier key or not. And you can distinguish between e.g. left-shift and right-shift (they have different scan codes), and implement other fun custom behaviours.
At least for USB: yes, they do. The state of the modifier keys is encoded in a single byte (which indeed allows a distinction between left-shift and right-shift), then other keys are transmitted individually. Sure, the software can decide what to do with that information, but the modifier keys do play a special role from the hardware perspective.
@@floxbr9350yeah i learnt that in ben eater's video about usb
it goes through tons of layers of abstractions until it reaches some bad electron based application
This is the real story.
Or when I'm testing my program, a poorly written SDL application
🤮
??
One thing not mentioned is the "de-bouncing" circuit. As switches, the keyboard switches tend to "bounce" or "ring". One keypress produced not just one, but multiple key-down and key-up events. The "de-bouncer" ensures that these are picked up by the machine as a single press.
noferblatz you can also fix this with many many diodes (one for each key) , no ghosting then :)
Andrew Joy you can use diodes to debounce? I've used caps, but never heard of diodes.
Diodes can't be used for debouncing, usually. I think Andrew is mistaken. Ghosting and debouncing are independent of each other.
bvbk007 I agree with you. Might be worth mentioning software debouncing, that I've used on arduino projects. No extra components, the software does a very crude simulation of an RC network response. Maybe called a boxcar filter?
bvbk007 ok, just making sure I didn't fall asleep in Electronics or something.
Back in the days of windows 95/98 and XP I used ports 0x60 and 0x64 to communicate with the keyboard controller directly and insert characters into the keyboards output buffer which were then read by windows as normal key presses. This let me get past several games anti cheat / botting software.
why would you want to cheat?
It depends on the interface, XT, AT and PS/2 (PS/2 and AT are the same with just a new connector ) are interrupts , USB uses polling.
PS/2 AT etc The computer does nothing , the keyboard controller polls the matrix and sends hardware interrupts to the CPU
For USB the same thing happens but the keyboard does not send an interrupt, it holds the keys in a buffer till the computer polls it for key presses.
Language does not change the scan code set ! AT PS/2 USB ect are ALL scan code set 2 , XT is scan code set 1 ( for some reason) and most terminals and pre PC computers mainframes , serial terminals etc use scancode set 3
USB standards specifies a scan code for USB keyboards, it does not use set 2 (AT). Or if does it is non-compliant with the USB standard for keyboards.
Yes your correct. But they use the same codes in the background so 2c is Z in USB and in Set 2 so its short hand.
\[T]/
USB is most certainly not using set 2 - for the reason why, look up what the scancode is for the arrow keys, which have a prefix for set 1 compatibility, or the Pause key which is 7 bytes long. USB keycodes are in alphabetic order and Z in particular is 1D (see HID usage tables, section 10 keyboard). Your firmware might be translating it for legacy OS support, however. Set 3 was more logical in that it used a single bit for press/release and one byte for each event. Also, the polling in USB is performed by the host controller, not the CPU, so we still have an interrupt for when things have changed. There are also buffers in both keyboards and port controllers for PS/2, AT etc, but the CPU typically has to handle them byte by byte.
I agree. This video is quite oversimplified and erroneous at times.
The M is the epitome of keyboard perfection. There's a reason it is so remembered: It saw satisfying, comfortable, accurate, and near-indestructible. Very few keyboards achieve that level of quality, and those that do achieve it today are designed specifically in imitation of the M's design and always compared to it.
No way , model F any day !
The earlier IBM beamspring is probably the best keyboard mechanism ever made. Unfortunately it comes with some real drawbacks like its huge size and complexity of the capacitive sensing circuitry used.
Yeh but they are amazing! I love mine. F uses capacitive sensing too but the controller is less fussy about dust etc. Thats why beamsprings come with contamination shields . Or did, they have all rotten away now.
Not sure about epitome, but certainly a classic. Have 3 model M keyboards that I used for many years, but now use WASD Code V2 keyboards, with Cherry MX blue switches at home and clears at the office. I like them all better than my M keyboards for layout and feel.
It would be really cool and suit your channel if you made a video about Docker and the differences on how Docker and a full virtual machine realize the virtualization!
Love your channel!
Newton’s Third Law, action = reaction; contemplate the Zen of physics: when you a press a key, the key presses back.
I dig how the game Steve thinks up off the top of his head is Quake. Right on mate
Years ago I used to program on a desktop system that used Hall Effect keys. The keyboard was specifically designed for data entry. It was made in Utica, NY and was originally called a Cogar System 4. Later Singer bought the company and called it a Singer 1501. When Singer was bought by ICL it became the ICL 1501.
A VERY nifty system for its day.
Has someone already roasted this guy?
Video comes up just as I'm doing an assignment that uses interrupts, instruction pointers and a like. On one hand, it's neat timing. On the other, it's the last thing I wanna see xD
As an r/MechanicalKeyboards member I am offended by his taste in keyboards....
Hey its dome over PCB is basically a realforce in all but name !
Myself i prefer a good beamspring, or some nice complicated alps.
DT > Reddit :P
He said "I like my keyboard soft and mushy" and I was like no no no no NO NO NO
quangluu96 I mean their videos are mostly software related so I get why he didn't go into too much detail.
I presume he does actual work on his machines. Mechanical keyboards are usually frowned upon by coders due to their disturbing nature :) Sit in a cubicle etc with ten other people around you having those things and you'll understand why they're so hated
You can get quiet mechanical keyswitches that are a decent compromise.
Dr. Bagley's shirt needs some texture filtering.
Some ray tracing
PS/2 interrupts, USB and Bluetooth do not. With the newer ones, the controllers have a buffer which the OS polls. Also, insulting the IBM model M is a bold strategy Cotton.
What I want to know is what happens when I press the key?
This explains why when accessing button presses there are the methods GetKeyDown(Key), GetKeyUp(Key), and GetKey(Key). Thank you. And also if anybody knows about Scratch by MIT, their language was not great with those functions. It was very frustrating.
Also I prefer quieter keyboards because I typically make videos about what typing and the noise in the video is annoying. But if I'm playing League or something I do like to hear that I have indeed pressed a key.
"And this is basically the brains of the keyboard..."
That's just some PCB track with gaps in, you've already looks at "the brains of the keyboard" on the other side.
Yep, those were the feelers.
At 1:20, he’s trying to begin explaining to us how the circuitry of the keyboard receives a signal, only to be interrupted and asked how many keys are possible to be pressed. Still laughing.
I liked at the end how his example of a computer game was something from 25 years ago. I bet half the viewers are younger than that game.
he could have been refering to quake champions - or at least heard about it which is why quake was at the forefront of his mind :)
How can a computer expert not like the model M? It's perfect!
I guess he's not a touch typist. I'm typing this on a Model M.
@@RaymondHng me too
Somewhere out there when a key is pressed.... a paradise
Press F to Pay Respects
You should make a series out of these, from the keyboard, through the usb/ps2 bus, to the driver, then the os, display driver, monitor, etc. The whole stack from input to output. - or maybe just talk about each piece of the stack for an episode. It's very computerphile centric.
I was expecting something like this when I first saw the title, I'm really disappointed :(
The only thing missing from this video is Dr. Bagley literally dropping a microphone and walking off set.
If I heard him correctly, 2 to the 100 keyboard combinations is a number greater than the number of atoms in the universe.
This helped me decipher the difference between having a pathological or spiritual entity controlling the other end of the conversation when taking to an Artificially intellegent source and having the genuine thing. Thank you. I'm a little paranoid.
How dare you saying that about the beloved, eternal, all clacky Model M. Heresy!
Nice paper man, very nice touch!
I rather enjoy this episode. I like the basic breakdowns of computers into their electronic components.
After the model m comment
*audible gasp*
what a baller! got 2 imacs instead of two monitors and a mac
I lol'ed!!! :D
Maybe he's particularly decadent and uses one of them in target display mode for the other…
dangit now i cant type how helpful this is
I love it. He was all ready to rock on until ... that wonderfully cryptic question. Spent the rest of the video talking about the hardware / software interface.
Yes, I am a firmware engineer.
but everytime if you mention interrupts - it's nice to explain that modern PCs just have four to eight CPUs in - quickly explaining that multicore is just an array of actual CPUs (cores) in one part of the PC.
I pushed "H" on keyboard, but nothing happened..... :(
Does computer have to be turned on?
No, computer doesn't need to be on. It sounds like your keyboard is not working. Have you tried restarting your keyboard?
Jeremy Elliot
Yes, i tried, with torch, as always. Did not help.
Maybe it needs new oil and spark plugs?
We'll it does need the voltage to apply to the rows somehow. Try plugging it into a battery
This is normal. You have a French keyboard, and the "H" is silent in French. HTH. HAND.
No, you need to have common sense.
Great video! I remember opening up my PSP and wondering how the circuit board worked and how it could tell which button was being pushed when they were both connected
11:00 onwards was a bit lacking in detail. HOW does the hardware interrupt the CPU? What happens - memory registers? Special pins on the CPU...what EXACTLY?
Grundibular the implementation varies a bit depending on the cpu itself, but generally speaking, the CPU will have an interrupt controller. When the controller itself receives an interrupt from a device, such as a key press, it will force the processor to save its state and jump to a special part of memory called an interrupt vector table. This table will then tell the cpu where to jump next, into what is called an interrupt service routine, which actually handles the new data. Once this is done, the cpu resumes its previous work.
if its a USB keyboard it doesn't interrupt the CPU, PS/2 keyboards do but USB ones rely once again on polling. USB devices communicate by sending 1 frame of data every 1/1000th of a second, this is why many gaming keyboards; in search of a gimmick to make themselves appear advantageous over normal ones... claim an update rate of 1000hz, simply they just send data out on every USB frame, most keyboards update at 125hz because 125 is 1/8th of 1000 so they only need to update on every 8th frame.
@@RWoody1995 technically speaking, your software does receive USB interrupts. They just aren't generated by the keyboard.
To get the load off the CPU, dedicated hardware polls the keyboard at regular intervals, and sends an interrupt to the system when a change occurs
I remember I was asked this in a interview. I got to the interrupt handler in three sentences or less .
So is the key value delivered to the current application? What’s the api for it to read ? It’s reading it using an api like a file ?
Most new motherboards that I'm aware of don't have a true PS/2 port. It has a built-in adapter. USB I believe.
Microsoft Word is essentially a printing press simulator with lots of bells and whistles...
"I like my keyboards like I like my peas: soft and mushy."
Based on that fly shirt, I suppose the stereotype of computer scientist's being fashionably obtuse is only an American thing
I really appreciated the graphic diagrams.. very well done. Thanks.
Do touch sensors next!!!
This guy offended an entire group of pc users at once by saying he likes keys soft and mushy
Can you please make a video about the history of focus stealing (foreground window and keyboard cursor) in operating systems and web browsers? It's quite an annoying issue in computing and still hasn't been addressed after decades!
i will look for a link that shows you. thankyou
Never would have known that cpu scans keyboard electronically like it scans monitor
Cool
Learns new things everytime
Excellent videos Steve!!
Your are doing a great job! One recommendation, English subtitles please..couldn't get the accent right!
A letter appears on the screen. Next question.
Lauren Hahn end of story, video length = 2 seconds. 12 minutes and 26 seconds saved :) genius
Appropriate quake reference is appropriate😀
I like how the subtitles just give up at around 2:20.
Whoever invented the fn-key needs to get fired. Unlike the other control keys, "fn+A" doesn't actually register as a modification on 'A', meaning that you can't bind things to "fn+A" programmatically. Add to that the fact that there is no standard for fn-lock or no, and that the key itself is always on the opposite side of the keyboard from whatever you want to push it with...
Top 3 horrible keyboard "features":
1. fn
2. right-click key
3. insert
i wanna make a mouse keyboard now
In other words, there are *one nonillion, two hundred sixty-seven octillion, six hundred fifty septillion, six hundred sextillion, two hundred twenty-eight quintillion, two hundred twenty-nine quadrillion, four hundred one trillion, four hundred ninety-six billion, seven hundred three million, two hundred five thousand, three hundred seventy-six* different key combinations on a standard keyboard.
I was expecting to see jokes in the comments about pressing the ANY key or "Keyboard not found, press F1 to continue"
I don’t know why that “keyboard not found, press a key to continue” thing is considered such a joke. It makes sense, after all, that if the hardware requires a keyboard to continue, it should wait for you to connect one.
Now I understand why in javascript you can't just ask if "W" is pressed, but instead check if the keyboard tells if a key is pressed and if that key is coincidentally keyCode 87 and then ask if a key is released and if that was coincidentally also keyCode 87.
You guys make awesome knowledge videos
I also can't stand the loud mechanical keyboards, I'm on your side with this one.
Lineprinter paper! Reminds me of computer science A level in the seventies...cool!
This is part 1, right? Did not even mention interrupts yet.
"An A press is an A press"
Cherry MX blue keyswitches for life! If your officemate doesn't think you are under machine gun attack its not a real keyboard!
Plus It sets you up for a quick move, either to an office so no one is bothered by your keeb, or out the door, so no one is bothered by your keeb.
Otherwise, the company is liable for the PTSD your office mates suffer, from being under attack all day!
3:33 haha, I'm getting stressed just thinking about how much trouble it's going to be to put the keyboard back together after the video
Now that's out of the way let's hear Dr. Steve Bagley explain 0.5x A button presses.
I like my keys soft and mushy? Pah, no taste at all.
D I SG R AC EF UL !
did you even talk about debouncing the button signal? i might have missed it
I would have liked to see more on the software side.
3:45 shots fired! XD
When euro was introduced they actually sold new keyboards for people by saying that it has the euro character.
Hmm one question remains for me: Back in the days, why was I able to boost and steer right at the same time in Need for Speed but not able to boost and steer left (shift + arrow keys)? And why was my friend able to do it on his computer with his keyboard?
By pressing down a special key, It plays a little melody, 🎵
Dose this guy not know about the modern mechanical keyboard market? Like come on
of course he does. that's why he said he just started a flame war when He mentioned the Model M.
Model M isn't a modern mechanical keyboard though, so it's not really proof that he's aware of the modern mechanical keyboard movement/fad.
I paused the video and counted the number of keys...
.
.
.
.
.
.
.
My keyboard's got 103 keys.
A key press is a key press. You can't say it's only an electrical signal.
2:06 Or there would be, if your hardware implemented “n-key rollover”, which means it can distinguish every possible combination of keys being pressed at once. Not sure if current keyboard hardware actually supports that.
Spend as much time explaining the harder to grasp concepts as you did on this.
An ally in the war against annoying mechanical keyboards
"I love my keyboards soft and mushy"
You should be ashamed of yourself!!!
what if I handbuilt a custom membrane keyboard? im already doing 90% of what the mechkeys community wants, is that enough to leave me alone? XD
I do actually want to build a custom keyboard with some nice soft tactile switches, but they don't exist in the same form factor as cherrys or kaihls
make a second video explaining the software sides of it
Anyone remember the times where you could push (at most) three keys simultaneously? :) My first computer would at that point freeze for the duration of beep (from the speaker at the bottom of the computer case) repeatedly until some keys were released.
I had forgotten all about this. . . then you mentioned the beep.
This is something Vsauce asks in the beginning of their video and then ends up talking about totally different things like communism or dinosaurs.
you don't need a microcontroller though, you can scan using a 555 timer and counter IC, then run the result of the matrix through various logic gates to create a binary code output, I guess this could get quite complex when dealing with a computer keyboard, I have only done it with a numeric keypad. Anyway I guess then what happens is the result updates a register, and whenever a key press is detected to have occurred, an interrupt is sent to the CPU periodically, the CPU then reads your keyboard register when it wants to.
On the Apple ][, if you press 1, 2, and 3 at the same time, it would also get an S, or something like that.
I'm curious about why there is a swedish keyboard there. Seems a bit random, but being swedish myself I like it. What's the story?
The Swedish keyboard layout has keys to generate the letters å, ä, and ö. Norwegian and Danish keyboard layouts generate å, ø, and æ.
@@RaymondHng well, yes. But why does British computer science guys need that?
Maybe he knows Swedish.
Det är möjligt
Mechanical keyboards are the tactile equivalent of atomic operations!
Off topic, but can you create a video about the SWARM robots project from Rolls Royce, the Universities of Nottingham and Harvard for car engine inspections?
Questions about the fanfold greenbar paper used in so many of these videos.
Why/how do they have so much of it?
Are they using up leftover/surplus inventory from a bygone era?
Are there still dot matrix printers in use at the university?
I'm dying to know.
I'm not actually certain but I think the modern rubber dome keyboard probably owes a fair bit to the design of the Sinclair keyboard.
TheTurnipKing - The first computer with a chiclet keyboard was the Interact Model One (1978). Virtually everything that came out in '82 and '83 had one, so singling out the Spectrum is a little unfair.
@@Tevildo the Sinclair machines are neat though because you can see the evolution from bare membrane in the ZX80, to the rubber mat over membrane to the plastic key over rubber mat over membrane that characterises modern keyboard design
damn this is fascinating, wish i was intelligent enough to comprehend it
As a human being I am offended by your taste in keyboards.
8:45 Are you telling that having the keyboard check itself for keypresses and telling the computer to check what was pressed only if the keyboard noticed that keypress beforehand, sent a signal to the computer, the computer checked back what was pressed is faster than constantly polling the keyboard. That makes no sense.
Győri Sándor it makes perfect sense. The CPU is not constantly polling the keyboard, it is the keyboard that does the dirty polling work and tells the CPU when something happens (which is almost never from a CPU cycles point of view).
Imagine you are waiting for an amazon package to come, would you go to the street every 2 minutes to check if the postman is there? Or rather do your usual stuff at home and just pay attention when somebody rings the bell?
The message from the keyboard to the computer doesn't tell the computer to check what was pressed, typically. The message sent already holds that information. From the CPU's perspective, keypresses are very rare, and spending time looking for them there would make little sense, particularly as switching tasks is quite costly. The interrupt allows it to jump to the keyboard handling routine only when the keyboard has sent new information.
No, purely from the perspective of speed, me checking the door every second while I'm standing there is faster than sitting on the couch and only getting up when the bell rings. Because getting to the door takes time too, and the delivery guy has to press the doorbell too. It's not efficient in any way. But certainly is faster.
Yep, this tradeoff between polling and interrupts does exist! Interrupts cause a context switch, which involves saving some state and jumping to another routine, possibly waking up a CPU that was sleeping entirely. Spinning the CPU on a single task can achieve faster reaction times on many, but not all, processors (the exceptions tend to have hardware contexts, like SPARC register windows, ARM fast interrupts or XMOS threads). The point I was making is that the CPU receives the interrupt when the message has arrived; it is not involved while the keyboard is transferring, and does not need a round trip to interrogate the keyboard. It's more like the mail man leaves the note at the desk you're already working than you answering the bell. (On PS/2, there's a high risk the CPU is fast enough to switch back and forth for each byte, which can get costly as many messages are several bytes long.)
On modern computers, USB driver stacks and USB controller chips connected via PCI to the rest of the chipset handle that type of packet- and event-driven communication. It’s a whole other level of complexity (for example, I have a keyboard with USB hub where a USB wireless mouse and thumbdrives are connected). Then there’s all kinds of graphics drivers, font-rendering algorithms, window-management software modules and other complications to traverse for the key press (or key release) to do something useful. The more you dig into these kind of things, the more the mind boggles!
3:26 A poppy memorial day keyboard
There are different codes called make and break codes for when a key is pressed vs released.
huh, The video was cut short. I assume there is a part 2.
If we discuss on keyboard types here: Microsoft Modern Keyboard (or Surface Keyboard) and for mobile devices ideally their Surface type covers... your preference may be different, but nothing is better than a Surface Keyboard or the Apple Keyboard (but I hate Apple for not giving the Apple keyboard a numpad - a numpad is a must and it has to be default on - with every OS you run it with... I do not use the numpad functions on the keys when the numpad is off - ever...)
Yeah subtitles!!
Considering that a usb bus is still very definitely 5V, it’s probably still 5V not 3.3.
Please do a video about why it is that these days, I'm CONSTANTLY having to click on something twice to make it respond. This never used to happen, I swear it didn't. And it's everywhere now: web site buttons, dialogue boxes, phone screen controls that I tap, keyboard input, SO many places. Trigger once... nothing. Trigger again... aha! It worked. WHY?!!?!?!
User of Microsoft KlunkyOS?