# 19. Архитектура I2C(TWI) Two-wire serial interface
в даташите страница 172
## Объяснение на русском
этот ролик не по конкретно avr, но смысл объясняет верно, тем более, что это интерфейс, а интерфейсы на то и интерфейсы, чтобы быть реализованными схожим образом https://www.youtube.com/watch?v=_4KD29qnhNM
Интерфейс/шина для связи с другими устройствами, например, для записи данных в ROM

Этот интерфейс передает данные по проводам. По SDA идут данные, по SCL- импульсы тактирования
R1, R2 - подтягивающие регистры
Максимум устройств (slave) может быть 127. У каждого устройства есть свой адрес от 1 до 127 (на адрес выделяется 7 бит) . 0 использовать нельзя
Одновременно может быть только 1 коннект ведущий-ведомый (если к ведомому попытается подключиться ещё 1 мастер и подключение не остановлено, то последнему мастеру придётся ждать) при завершении подключения первого мастера второй сразу начнёт общение со вторым
Общение это любой обмен данными (приём или получение)
I2c разработана Филипс, но возможно дабы избежать траблов решили переименовать
Схема подключения состоит из 2 проводов (не считая земли)
Sda - линия данных
Scl - линия тактовых импульсов
По шине данных импульсы ходят в обе стороны
Slave принимают и отдают данные по приходу тактовых импульсов (подробнее в spi). Это позволяет мастеру работать с устройствами разной скоростт
Скорость шины 10/100 килобит в секунду.
Работает при напряжении 5, 3.3 вольта
Общая ёмкость устройств должна быть меньше 400 пФ. (Складывается из всех слейвов) Поэтому реально подключить 127 устройств вряд ли выйдет.
Установлены правила
1 - sda изменяет данные только при scl = 0
2 - мастер может изменить импульс на sda с 1 на 0 при scl = 1. Это называется импульс start. Он переводит все slave в режим ожидания данных. Такое же изменение с 0 на 1 означает stop (slave могут подключиться к другим мастерам)
Передача ведётся байтами побитно (последовательно) начиная со старшего бита
На каждый байт приёмник должен выставить 0 или 1. 0 - принято успешно, 1 - провально (бит acknowledge)
Передача начинается с выставления мастером адресного байта (так он показывает с каким конкретно устройством общается) (7 бит) + 1 бита направления (1 если мастер хочет принимать, 0 если отдавать
Передача;
Сначала на сда стоит 1. мастер подаёт бит старт, и переводио сда в 0. Слейвы начинают слушать. Потом мастер подаёт адресный байт и напопаление. Распознавший свой адрес слейв выставляет бит acknowledge и начинается передача данных. Байт - бит acknowledge т так пока не закончится. Мастер выставляет бит стоп
Приём: бит подтверждения выставляет мастер (кроме того, что идёт после адресного байта) , байты данных отправляет slave. Когда master отказывается принимать данные он выставляет бит N = 1 (вместо acknowledgeacknowledge. После этого мастер выставляет стоп
## на английском языке

Twbr - устанавливает скорость на ведущем устройстве
Объяснение страшных слов:
spike filter - устраняет помехи
## на русском языке

The first step in a TWI transmission is to transmit a START condition. This is done by writing a specific value into TWCR, instructing the TWI hardware to transmit a START condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the START condition.
2. When the START condition has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the START condition has successfully been sent.
3. The application software should now examine the value of TWSR, to make sure that the START condition was successfully transmitted. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load SLA+W into TWDR. Remember that TWDR is used both for address and data. After TWDR has been loaded with the desired SLA+W, a specific value must be written to TWCR, instructing the TWI hardware to transmit the SLA+W present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the address packet.
4. When the address packet has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the address packet has successfully been sent. The status code will also reflect whether a Slave acknowledged the packet or not.
5. The application software should now examine the value of TWSR, to make sure that the address packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load a data packet into TWDR. Subsequently, a specific value must be written to TWCR, instructing the TWI hardware to transmit the data packet present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet.
6. When the data packet has been transmitted, the TWINT Flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a Slave acknowledged the packet or not.
7. The application software should now examine the value of TWSR, to make sure that the data packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must write a specific value to TWCR, instructing the TWI hardware to transmit a STOP condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the STOP condition. Note that TWINT is NOT set after a STOP condition has been sent.