Well, have you ever heard of the Universal Serial Bus (USB) cable? It’s that cable that takes three tries putting it in before you finally get it right every single time. Well, computers typically have a lot of ports for these kinds of cables, so basically everything used with a computer except for headphones which use a jack, are connected with a USB cable.
But connecting peripherals to the computer is not exactly all about just putting the end of the cable into the port. The computer has to actually install the device that has been plugged into the USB port. Modern operating systems typically support USB cables since their use is so widespread, so sometimes when you plug in a USB you don’t even realize that it had to be installed because the process was so quick. Essentially, what happens during the installation process is the exact same as when installing software. Code from the installer is being given to the local system (your computer) to be copied and placed in different sections of the computer. This is done so that the local system can then execute the code in its own way and the device can become usable on the system. So, the code installed when a new keyboard is plugged into a computer specifies what occurs when each button is pressed. Other programs on the system can then manipulate that code so that when a button is pressed, something else happens that what initially is supposed to. That is how we can use “w” when playing games to move the character “up”.
But, as stated before, USB cables are not the only way to connect a device to a computer. A jack can also be used to establish connection. A jack is typically used for headphones instead of a USB because of how they each process data, which can affect the sound. With modern computers, jacks are usually only used for audio output as they can be specialized to only transfer audio signals out of the jack and to the device (your headphones or speakers). Whereas, USB ports are typically used to transfer data from the device (like a mouse) and possibly even back to the device.
That is pretty much how it all works. A device that has some kind of cable attached to it gets plugged into the computer, then the device attempts to install itself onto the local system. After this, the computer can allow the execution of the code that was installed onto it, which allows the external device to actually manipulate what is done on the computer. It is all quite fascinating as there truly is a lot that is going on, but all we have to worry about is plugging the cable into the right port...which can amazingly be the most difficult part of the process.