Контроллер интерфейса ps/2

Краткое описание

  • Pin 4 — Питание, +5 В. Используется для подачи питания на подключаемое устройство.
  • Pin 3 — Земля/Корпус. Общий вывод для питания.
  • Pin 5 — CLK — синхронизация (Clock). Включается при передаче данных мышью.
  • Pin 1 — Data, передаваемые данные.

Изначально PS/2 реализовывался со стороны компьютера микросхемой контроллера 8048, затем был заменен на микросхему микроконтроллера 8042, затем его функции перешли в Super I/O или LPC чип, либо в южный мост чипсета.
Перед подачей питания на устройство контроллер порта на материнской плате «слушает» CLK. При передаче от устройства (PS/2 клавиатуры или PS/2 мыши) к компьютеру используется следующий протокол. Устройство не начинает передачу, если Clock не находился в «1» по крайней мере 50 микросекунд. Устройство передаёт последовательно:

  1. старт бит — всегда ноль;
  2. 8 бит данных;
  3. бит чётности;
  4. стоп бит — всегда единица.

Устройство устанавливает/меняет сигнал Data, когда Clock находится в логической единице. Контроллер на материнской плате читает данные, когда Clock находится в логическом нуле.

При передаче в обратную сторону команд от контроллера на материнской плате компьютера к клавиатуре или мыши протокол отличается от описанного выше.

Последовательность передаваемых бит здесь сложнее:

  1. контроллер опускает сигнал Clock в ноль на время примерно 100 микросекунд;
  2. контроллер опускает сигнал Data в ноль, формируя старт бит;
  3. контроллер отпускает сигнал Clock в логическую единицу, клавиатура фиксирует старт бит;
  4. далее клавиатура генерирует сигнал Clock, а контроллер подает передаваемые биты;
  5. после того, как контролёр передал все свои биты, включая бит чётности и стоп бит, клавиатура посылает последний бит «ноль», который является подтверждением приёма.

История

Клавиатура к первым ПК (IBM PC и IBM PC/XT, 1981 год) подключалась по однонаправленному (передача данных только в одну сторону — от клавиатуры к компьютеру) интерфейсу, программное взаимодействие с которым осуществлялось с помощью двух портов микросхемы параллельного интерфейса 8255: порт A (он был доступен по адресу 60h) использовался как регистр принятых от клавиатуры данных, а порт B (61h) содержал биты, управляющие как клавиатурой, так и другими устройствами. Нажатие и отпускание клавиш кодировалось способом, ныне известным как таблица скан-кодов № 1.

В компьютерах IBM PC/AT (первые из них появились в 1984 году) от применения микросхемы 8255 отказались. Для обеспечения взаимодействия с клавиатурой был применён микроконтроллер 8042. Изменился и сам физический интерфейс: он стал двунаправленным. Хотя клавиатура по-прежнему подключалась через 5-контактный DIN-коннектор, она была несовместимой с клавиатурами IBM PC и IBM PC/XT (хотя в переходный период выпускалось большое число клавиатур, пригодных для использования с обоими типами интерфейсов; выбор нужного интерфейса осуществлялся специальным переключателем). В клавиатурах IBM PC/AT была использована новая таблица скан-кодов, получившая № 2.

В 1987 году IBM начала выпуск семейства ПК IBM PS/2. В этих компьютерах использовалась та же самая микросхема 8042, однако её функции были расширены: она обеспечивала подключение не только клавиатуры, но и мыши, для которой был добавлен второй коннектор. Электрически интерфейс остался тем же самым, что на IBM PC/AT, однако коннекторы поменялись: вместо 5-контактных DINов стали использовать 6-контактные MiniDINы. С помощью переходника клавиатура IBM PC/AT могла быть подключена к PS/2, и наоборот. IBM разработала и новую таблицу скан-кодов — № 3, но клавиатуры, пригодные для использования с разными типами ПК, обеспечивали программное переключение используемой таблицы.

Помимо подключения клавиатуры и мыши, контроллер интерфейса PS/2 обеспечивает выполнение ещё ряда функций; например, он управляет вентилем линии A20 или позволяет выполнить сброс процессора ПК. Достоверно неизвестно, когда именно эти функции были на него возложены, однако современные контроллеры их поддерживают.

Следует заметить, что контроллер интерфейса PS/2, описываемый в этой статье, часто ошибочно именуют контроллером клавиатуры. Это абсолютно неверно. Последний находится внутри самой клавиатуры, отслеживает нажатия и отпускания клавиш и посылает по интерфейсу PS/2 соответствующие скан-коды, а также принимает по этому интерфейсу команды и выполняет их (например, переключает светодиоды или меняет скорость автоповтора нажатия клавиш). Контроллер интерфейса PS/2 никакого отношения к клавиатуре или мыши как таковой не имеет и располагается на системной плате компьютера; к нему можно подключить абсолютно любое устройство, использующее интерфейс PS/2

Задача этого контроллера — принимать данные от устройства (клавиатуры, мыши, ещё чего-нибудь — неважно) и позволять процессору их считывать, а также принимать данные от процессора и передавать их устройству.

Некорректно называть контроллер PS/2 и контроллером 8042. Во-первых, 8042 — это микроконтроллер, который мог быть запрограммирован на решение самых разных задач, и его применение для управления интерфейсом PS/2 в составе персонального компьютера — лишь одно из многих возможных. Во-вторых, уже давным-давно функции контроллера PS/2 выполняет другая микросхема. Наконец, современные контроллеры зачастую выполняют массу других функций, например, связанных с поддержкой ACPI. По всем этим причинам корректно говорить лишь о контроллере PS/2, совместимом с точки зрения пользователя с контроллером, реализованным в IBM PC/AT на микросхеме 8042.

Hardware issues

Hotplugging

PS/2 ports are designed to connect the digital I/O lines of the microcontroller in the external device directly to the digital lines of the microcontroller on the motherboard. They are not designed to be hot swappable. Hot swapping PS/2 devices usually does not cause damage because more modern microcontrollers tend to have more robust I/O lines built into them which are harder to damage than those of older controllers; however, hot swapping can still potentially cause damage on older machines, or machines with less robust port implementations.

If they are hot swapped, the devices must be similar enough that the driver running on the host system recognizes and can be used with the new device. Otherwise, the new device will not function properly. While this is seldom an issue with standard keyboard devices, the host system rarely recognizes the new device attached to the PS/2 mouse port. In practice most keyboards can be hot swapped but this should be avoided.

Durability

Bus powered PS/2-to-USB adapter

PS/2 connectors are not designed to be plugged in and out very often, which can lead to bent or broken pins. Additionally, PS/2 connectors only insert in one direction and must be rotated correctly before attempting connection. (If a user attempts to insert the connector in the wrong orientation and then tries to rotate it to the correct orientation without first pulling it out, then bent pins could result.)

Most but not all connectors include an arrow or flat section which is usually aligned to the right or top of the jack before being plugged in. The exact direction may vary on older or non-ATX computers and care should be taken to avoid damaged or bent pins when connecting devices. This issue is slightly alleviated in modern times with the advent of the PS/2-to-USB adapter: users can just leave a PS/2 connector plugged into the PS/2-to-USB adapter at all times and not risk damaging the pins this way. A USB-to-PS/2 adapter does not have this problem.

Fault isolation

In a standard implementation both PS/2 ports are usually controlled by a single microcontroller on the motherboard. This makes design and manufacturing extremely simple and cheap. However, a rare side effect of this design is that a malfunctioning device can cause the controller to become confused, resulting in both devices acting erratically. (A well designed and programmed controller will not behave in this way.) The resulting problems can be difficult to troubleshoot (e.g., a bad mouse can cause problems that appear to be the fault of the keyboard and vice versa).

Is There Any Use for PS/2 Anymore?

For the most part, no, PS/2 really is gone. There aren’t piles of PS/2 devices sitting around with nowhere to go. Computers and their peripherals migrated to USB at roughly the same time.

There was a time during the transition, however, when you might have bought a new computer that only had USB ports but you wanted to use your trusty, PS/2-based keyboard and mouse. In those situations, a PS/2-to-USB converter might come in handy (more on that below) and might be a reason you’ll still find the occasional PS/2 device at home.

PS/2 does tend to work better than USB in a «switching» environment, where one keyboard, mouse, and monitor operates a number of different computers. This sort of setup is common in data centers, albeit older ones.

Remote access software is now more commonly used in the business and enterprise environments, allowing anyone with access to connect to an unlimited number of other computers remotely, negating the need for PS/2 switching devices altogether.

However, PS/2 might be preferred in some situations where security is critically important. If the computer runs on PS/2 only, then all USB connection types can be disabled to prevent removable devices from transferring viruses to the computer or copying files off of it.

Another use for PS/2 is if entering the BIOS setup utility proves difficult with a USB device. Problems with USB drivers could prevent the keyboard from interacting with the utility, something that PS/2 usually doesn’t have an issue with.

PS/2 might also be used if there’s a limited number of USB ports. PS/2 can be used for the keyboard and mouse to free up USB ports for other devices like external hard drives.

Communication protocol

Each port implements a bidirectional serial channel. The channel is slightly asymmetrical: it favors transmission from the input device to the computer, which is the majority case. The bidirectional IBM AT and PS/2 keyboard interface is a development of the unidirectional IBM PC keyboard interface, using the same signal lines but adding capability to send data back to the keyboard from the computer; this explains the asymmetry.

The interface has two main signal lines, Data and Clock. These are single-ended (common mode) signals driven by open-collector drivers at each end. Normally, the transmission is from the device to the computer; then, the attached peripheral device generates the Clock signal. To transmit a byte, the device simply outputs a serial frame of data (including 8 bits of data and a parity bit) on the Data line serially as it toggles the Clock line once for each bit. The host controls the direction of communication using the Clock line; when the host pulls it low, communication from the attached device is inhibited. The host can interrupt the device by pulling Clock low while the device is transmitting; the device can detect this by Clock staying low when the device releases it to go high as the device-generated clock signal toggles. When the host pulls Clock low, the device must immediately stop transmitting and release Clock and Data to both float high. (So far, all of this is the same as the unidirectional communication protocol of the IBM PC keyboard port, though the serial frame formats differ.) The computer can use this state of the interface simply to inhibit the device from transmitting when the computer is not ready to receive. (For the IBM PC keyboard port, this was the only normal use of signalling from the computer to the keyboard. The keyboard could not be commanded to retransmit a keyboard scan code after it had been sent, since there was no reverse data channel to carry commands to the keyboard, so the only way to avoid losing scan codes when the computer was too busy to receive them was to inhibit the keyboard from sending them until the computer was ready. This mode of operation is still an option on the IBM AT and PS/2 keyboard port.)

To send a byte of data back to the keyboard, the computer pulls Clock low, waits briefly, then toggles it with a clock signal generated by the computer, while outputting a frame of bits on the Data line, one bit per Clock pulse, just as the attached device would do to transmit in the other direction. The device defers to the control of the computer over the Clock line and receives the data byte. (A keyboard normally interprets this byte as a command or a parameter byte for a preceding command.) The computer releases the Clock line when it is done. The device will not attempt to transmit to the computer until both Clock and Data have been high for a minimum period of time.

Transmission from the device to the computer is favored because from the normal idle state, the device does not have to seize the channel before it can transmit—the device just begins transmitting immediately. In contrast, the computer must seize the channel by pulling the Clock line low and waiting for the device to have time to release the channel and prepare to receive; only then can the computer begin to transmit data.

Color code

Original PS/2 connectors were black or had the same color as the connecting cable (mainly white). Later the PC 97 standard introduced a color code: the keyboard port, and the plugs on compliant keyboards, were purple; mouse ports and plugs were green. (Some vendors initially used a different color code; Logitech used the color orange for the keyboard connector for a short period, but soon switched to purple.) Today this code is still used on most PCs. The pinouts of the connectors are the same, but most computers will not recognize devices connected to the wrong port.

Color Description
  Purple Keyboard
  Green Mouse

Цвета разъёмов

Спецификация PC97 определяет для разъёмов порта PS/2 в системном блоке и на кабелях подключаемых устройств:

Цвет устройство
сиреневый клавиатура
зелёный мышь

До внедрения этого стандарта цвета разъёмов не оговаривались, поэтому на практике обычно использовались разъёмы чёрного цвета, а наружный корпус разъёмов на кабелях совпадал с цветом оболочки кабеля (как правило, белый или серый).

Некоторые производители изначально использовали свою систему цветового кодирования: например, клавиатуры «Logitech» имели корпус разъёма оранжевого цвета, но в дальнейшем перешли на использование стандартных цветов.

What Do You Do When a PS/2 Keyboard or Mouse Locks Up?

There are lots of reasons why a computer might lock up, sometimes called freezing, but when you know it’s just the keyboard or mouse, and they’re PS/2-based devices, the solution is usually pretty simple.

Typically this happens when a PS/2-based mouse or keyboard comes loose just enough to lose connection with your computer. Unfortunately, just pushing the PS/2 port into the receptacle again isn’t enough.

Unlike the newer USB standard, PS/2 is not hot-swappable, meaning you cannot unplug and plug-back-in a PS/2 device and expect it to work. Your computer must be restarted once a firm connection is reestablished.

Add this to the long list of reasons why USB is an improvement on PS/2.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector