Русские Блоги
Разница между SPI, I2C и UART тремя протоколами последовательной шины
Концепция шины I2C (Inter-Integrated Circuit):
Связь I2C Нужно всего 2 двунаправленных шины —— Одна линия данных SDA (последовательные данные: линия последовательных данных), одна линия синхронизации SCL (последовательные часы: линия последовательных часов). Линия SDA используется для передачи данных, а линия SCL используется для синхронизации передачи и приема данных. Данные, передаваемые по линии SDA, представляют собой прямую передачу (старший байт байта передается первым), и каждая передача составляет 8 бит, то есть 1 байт. Поддержка мульти-мастеринга в любой момент времени Мастер может быть только один . Каждое устройство, подключенное к шине, имеет один Независимый адресный адрес , Всего 7 бит, хост использует этот адрес для доступа к устройству. Шины SDA и SCL необходимо соединить подтягивающими резисторами.Когда шина свободна, обе линии имеют высокий уровень. Любое устройство, подключенное к шине, будет понижать уровень сигнала шины, когда оно выдает низкий уровень, то есть SDA и SCL каждого устройства находятся в линейной связи. Когда несколько хостов используют шину одновременно, необходим арбитраж, чтобы определить, какое устройство занимает шину, в противном случае данные будут конфликтовать.

Универсальный асинхронный приемник / передатчик, обычно называемый UART, представляет собой асинхронный приемник / передатчик, который является частью компьютерного оборудования. Он будет передавать данные вПоследовательная связьпротивПараллельное общениеЧтобы преобразовать между. Как микросхема, преобразующая параллельные входные сигналы в последовательные выходные сигналы, UART обычно интегрируется в соединение с другими интерфейсами связи.
Последовательный порт во встроенной системе обычно относится к порту UART, но мы часто не знаем разницы между ним и COM-портом, а также отношения между RS232, TTL и т. Д. Фактически, UART, COM относятся к форме физического интерфейса (аппаратного), а TTL, RS-232 относится к стандарту уровня (электрический сигнал).
UART имеет 4 контакта (VCC, GND, RX, TX), используя уровень TTL, низкий уровень — 0 (0 В), высокий уровень — 1 (3,3 В или выше).
Особенности UART: Как правило, контроллеры uart создаются вместе с процессорами во встроенных системах.Как и микросхема Freescale IMX6, существует несколько контроллеров uart.
Введение в интерфейс SPI
В последние несколько дней я наткнулся на флэш-память, использующую интерфейс SPI, и знаю, что флэш-память также может быть последовательной. Кажется, что это действительно была лягушка на дне колодца. Я нашел некоторую информацию об интерфейсе SPI. Позже я нашел информацию на английском языке, перевел ее и добавил Мое личное понимание было собрано в статью, надеюсь, она будет полезна новичкам.
Полное название интерфейса SPI — «Serial Peripheral Interface», что означает последовательный периферийный интерфейс. Впервые он был определен компанией Motorola для процессоров серии MC68HCXX. Интерфейс SPI в основном используется между EEPROM, FLASH, часами реального времени, аналого-цифровым преобразователем, процессором цифрового сигнала и декодером цифрового сигнала.
Интерфейс SPI — это синхронная последовательная передача данных между ЦП и периферийными низкоскоростными устройствами. Под импульсом сдвига ведущего устройства данные передаются в битах, старший бит находится спереди, а положение — сзади. Это полнодуплексная связь, и скорость передачи данных общая. Он быстрее шины I2C, а скорость может достигать нескольких Мбит / с.
Интерфейс SPI работает в режиме ведущий-ведомый. В этом режиме обычно есть ведущее устройство и одно или несколько ведомых устройств. Интерфейс включает следующие четыре сигнала:
(1) Вывод данных MOSI-ведущего устройства, ввод данных ведомого устройства
(2) Ввод данных MISO-ведущего устройства, вывод данных ведомого устройства
(3) Сигнал SCLK-clock, генерируемый ведущим устройством.
(4) / SS — сигнал включения ведомого устройства, управляемый ведущим устройством
В двухточечной связи интерфейс SPI не требует операций адресации и является полнодуплексным, что является простым и эффективным.
В системе с несколькими подчиненными устройствами каждое подчиненное устройство нуждается в независимом разрешающем сигнале, который немного сложнее аппаратно, чем система I2C.
Интерфейс SPI на самом деле представляет собой два простых регистра сдвига во внутреннем оборудовании.Передаваемые данные составляют 8 бит.Под сигналом включения ведомого и импульсом сдвига, генерируемым ведущим устройством, он передается бит за битом, причем старший бит находится спереди, а младший бит — сзади. . Как показано на рисунке ниже, данные изменяются по заднему фронту SCLK, и в то же время в регистре сдвига сохраняется один бит данных.
Схема внутреннего оборудования интерфейса SPI:
Наконец, один недостаток интерфейса SPI: нет назначенного управления потоком и нет механизма ответа, подтверждающего, получены ли данные.
Разница между SPI, I2C и UART тремя протоколами последовательной шины:
Первый, разница, конечно же, в названии:
SPI (последовательный периферийный интерфейс: последовательный периферийный интерфейс);
I2C(INTER IC BUS)
UART (универсальный асинхронный приемный передатчик: универсальный асинхронный приемный передатчик)
Во-вторых, разница заключается в линии электрического сигнала:
Шина SPI состоит из трех сигнальных линий Состав: последовательные часы (SCLK), последовательный вывод данных (SDO), последовательный ввод данных (SDI). Шина SPI может соединять несколько устройств SPI друг с другом. Устройство SPI, которое обеспечивает последовательные часы SPI, является ведущим или ведущим SPI, а другие устройства являются ведомыми или ведомыми (ведомыми) SPI. Полнодуплексная связь может быть реализована между ведущими и ведомыми устройствами.При наличии нескольких ведомых устройств может быть добавлена строка выбора ведомого устройства.
Если вы используете универсальный порт ввода-вывода для имитации шины SPI, у вас должен быть выходной порт (SDO), входной порт (SDI), а другой порт зависит от типа реализованного устройства.Если вы хотите реализовать устройство ведущее-ведомое, вам понадобится порт ввода и вывода. , Если реализовано только ведущее устройство, порта вывода достаточно; если реализовано только ведомое устройство, требуется только порт ввода.
Шина I2C — это стандарт двустороннего, двухпроводного (SCL, SDA), последовательного интерфейса и интерфейса с несколькими ведущими устройствами.Он имеет механизм арбитража шины и очень подходит для передачи данных между устройствами на короткие расстояния и нечасто. В его системе протокола адрес устройства-получателя всегда переносится при передаче данных, поэтому может быть реализована сеть устройств.
Если порт ввода-вывода общего назначения используется для имитации шины I2C и достижения двунаправленной передачи, требуется порт ввода-вывода (SDA), а также порт вывода (SCL). (Примечание: данные I2C относительно плохо изучены, описание здесь может быть очень неполным)
Шина UART — это асинхронный последовательный порт Следовательно, он, как правило, намного сложнее, чем структура первых двух синхронных последовательных портов. Он обычно состоит из генератора скорости передачи (генерируемая скорость передачи в 16 раз больше скорости передачи), приемника UART и передатчика UART. На оборудовании есть два провода: один для отправки, а другой для приема.
Очевидно, что если универсальный порт ввода-вывода используется для моделирования шины UART, требуются один входной порт и один выходной порт.
В-третьих, из второго пункта очевидно, что SPI и UART могут обеспечить полный дуплекс, а I2C — нет;
В-четвертых, посмотрите на мнение быдла!
Wudanyu: Количество линий I2C меньше. Я думаю, что он более мощный, чем UART и SPI, но технически более проблематичный, потому что I2C требует поддержки двунаправленного ввода-вывода и Используйте подтягивающий резистор , Я думаю, что способность к помехам слабая, обычно используется для связи между чипами на одной плате и меньше используется для междугородной связи. Реализация SPI проще. UART требует фиксированной скорости передачи данных, что означает, что интервал между двумя битами данных должен быть одинаковым. SPI не имеет значения, потому что это синхронизированный протокол.
Quickmouse: скорость I2C немного ниже, чем у SPI, и протокол немного сложнее, чем SPI, но соединение меньше, чем у стандартного SPI.
Выбор между I2C и SPI для вашего проекта
Выбор между I2C и SPI двумя основными параметрами последовательной связи может быть довольно сложной задачей и существенно повлиять на дизайн проекта, особенно если используется неверный протокол связи. И SPI, и I2C приносят свои преимущества и ограничения в качестве протоколов связи, которые делают их подходящими для конкретных приложений.
SPI или Serial to Peripheral Interface, представляет собой очень маломощный четырехпроводный интерфейс последовательной связи, предназначенный для IC-контроллеров и периферийных устройств для связи друг с другом. Шина SPI представляет собой полнодуплексную шину, которая позволяет передавать сообщения одновременно и с ведущего устройства со скоростью до 10 Мбит / с. Высокоскоростная работа SPI, как правило, ограничивает ее использование для связи между компонентами на отдельных печатных платах из-за увеличения емкости, которая добавляет к сигнальным линиям связь более длинного расстояния. Емкость печатной платы также может ограничивать длину линий связи SPI.
Хотя SPI является установленным протоколом, он не является официальным стандартом, который приводит к нескольким вариантам и настройкам SPI, которые могут привести к проблемам совместимости. Реализации SPI всегда должны проверяться между главными контроллерами и подчиненными периферийными устройствами, чтобы гарантировать, что комбинация не будет иметь никаких неожиданных коммуникационных проблем, которые повлияют на разработку продукта.
I2C является официальным стандартным протоколом последовательной связи, который требует только двух сигнальных линий, предназначенных для связи между микросхемами на печатной плате. Первоначально I2C был разработан для связи 100 кбит / с, но более быстрые режимы передачи данных были разработаны на протяжении многих лет для достижения скорости до 3,4 Мбит / с. Протокол I2C был установлен в качестве официального стандарта, который обеспечивает хорошую совместимость между реализациями I2C и хорошую обратную совместимость.
Выбор между I2C и SPI
Выбор между I2c и SPI, двумя основными протоколами последовательной связи, требует хорошего понимания преимуществ и ограничений I2C, SPI и вашего приложения. Каждый протокол связи будет иметь определенные преимущества, которые будут отличаться, как это применимо к вашей заявке. Ключевыми отличиями между I2C и SPI являются:
- I2C требует только два провода, в то время как SPI требует три или четыре
- SPI поддерживает высокоскоростную полнодуплексную связь, в то время как I2C работает медленнее
- I2C потребляет больше энергии, чем SPI
- I2C поддерживает несколько устройств на одной и той же шине без дополнительных линий сигнала выбора через адресацию устройства связи, в то время как SPI требует дополнительных сигнальных линий для управления несколькими устройствами на одной и той же шине
- I2C гарантирует, что переданные данные принимаются ведомым устройством, в то время как SPI не проверяет правильность приема данных
- I2C может быть заблокирован одним устройством, которое не освобождает коммуникационную шину
- SPI не может передавать с печатной платы, хотя I2C может, хотя и при низких скоростях передачи данных
- I2C дешевле реализовать, чем протокол связи SPI
- SPI поддерживает только одно ведущее устройство на шине, в то время как I2C поддерживает несколько мастер-устройств
- I2C менее восприимчив к шуму, чем SPI
- SPI может перемещаться только на короткие расстояния и редко покидать печатную плату, в то время как I2C может передавать данные на гораздо большие расстояния, хотя при низких скоростях передачи данных
- Отсутствие формального стандарта привело к нескольким изменениям протокола SPI, которые в значительной степени избегались протоколом I2C
Эти различия между SPI и I2C должны сделать выбор лучшего варианта связи для вашего приложения более простым. И SPI, и I2C являются хорошими коммуникационными возможностями, но у каждого есть несколько отличительных преимуществ и предпочтительных приложений. В целом, SPI лучше подходит для приложений с высокой скоростью и низкой мощностью, в то время как I2C лучше подходит для связи с большим количеством периферийных устройств и динамического изменения роли главного устройства среди периферийных устройств на шине I2C. И SPI, и I2C — надежные, стабильные протоколы связи для встроенных приложений, которые хорошо подходят для встроенного мира.
Как найти финансирование для вашего проекта приложения

Разработка мобильного приложения — сложный процесс, а также дорогостоящий. Эти полезные советы помогут вам найти источник для финансирования проекта разработки приложений.
Выбор веб-сайта для вашего видео-блога

При выборе веб-сайта видео-блога рассмотрите стоимость и функции в дополнение к теме и платформе. Проверьте эти видео-сайты блога для своего блога.
Выбор правильного веб-сервера для вашего бизнеса

Веб-сервер является основой всего, что происходит с вашей веб-страницей, и все же часто люди об этом ничего не знают.
I2c или spi что лучше
SPI vs. I2C: How to Choose the Best Protocol for Your Memory Chips

SPI and I2C are probably the most commonly used digital protocols to connect integrated circuits in a diverse array of products. SPI and I2C are both easy-to-use, hard-to-break serial digital protocols that are quite easy to route from a signal integrity perspective. Unlike impedance-controlled high-speed differential serial protocols, these two protocols do not have an impedance specification and will often be considered electrically short. This means that, on the PCB, the design requirements are relatively simple and there is still some freedom within the standard to tune the performance as you would like.
One of the common implementations of SPI and I2C in a PCB layout is as a protocol for reading and writing to an external Flash memory. Flash chips are a very common component in embedded systems and can offer high capacities of non-volatile memory up to Gb values. When choosing a memory chip, you’ll want to match the application requirements and functionality with the bus speed you need for read and write operations in your memory chip. There is also the matter of the type of Flash memory you’ll need to access (NOR vs. NAND).
SPI and I2C Comparison
The Serial Peripheral Interface (SPI) and Inter-Integrated Circuit (I2C) protocols are both simple serial digital protocols that run at low to moderate speeds. These two interfaces have some common characteristics:
- They use more than one wire for sending/receiving data
- The clock is source-synchronous, meaning there is a single trace that carries the clock line
- Other chips on the bus are addressable or toggle-able
- Most microcontrollers will have one or both of these interfaces integrated
- The signal level can be set by the core voltage given to the chip
- Neither of these interfaces has an impedance requirement
Clearly, these interfaces are very similar. They do have some important differences as summarized in the table below.
— Serial data (SDA)
— Serial clock (SCL, sometimes named SCK)
— Master-in, slave out (MISO)
— Master-out, slave in (MOSI)
— Serial clock (SCK or SCLK)
— Chip select (CS, optional)
— Broadcast bus topology
— Star for CS pins
— Standard mode: up to 100 kbps
— Fast mode: up to 400 kbps
— Fast mode plus: up to 1 Mbps
— High-speed mode: up to 3.4 Mpbs
— Fixed by clock window time, reaches up to 60 Mbps
— Depends on bus capacitance and pull-up resistor values (use RC time constant)
— Specified for a given load impedance
— Address pins fixed on each component
— CS pins used in the main controller to toggle chips (can be toggled with GPIOs or dedicated CS pins)
The SPI standard offers higher data rates and can run with much faster edge rates compared to I2C. Due to the use of pullups on I2C, the typically high bus capacitance, and the fact that the driving method is open-drain, I2C buses can have rise times reaching 100’s of nanoseconds. SPI buses can have rise times as low as 1 ns for advanced components driving low load capacitances, which means they may exhibit transient ringing during switching. SPI lines are also much more likely to produce crosstalk because their switching speed is so fast. To learn more about these two protocols and signal integrity in SPI buses, read the following resources.
- Learn more about SPI impedance and signal integrity
- Learn more about SPI, I2C, and UART
Important Considerations When Choosing Between SPI and I2C for Memory Chips
Accessing NAND vs. NOR Flash Memories
In this section I don’t want to get into the particulars of NAND vs. NOR Flash memories, instead I want to focus on how each is accessed with a serial protocol. Both types of Flash chips can be accessed with an SPI or I2C bus if you can procure the right memory component:
- NOR Flash — This is overwhelmingly accessed using SPI, even on smaller and slower Flash chips. Slower chips are available that can be accessed with I2C.
- NAND Flash — This is overwhelmingly accessed using a parallel bus, but chips with I2C and SPI buses are available in approximately equal number.
If you look on Octopart and use the filter features, you’ll be able to locate some high-capacity memories that use either interface.
I2C to SPI Interface Bridging For Memories
If you need to convert between an I2C and SPI interface, you can use an interface bridge. These components convert the data format between these interfaces, thus a component that might only have an SPI bus can then access peripheral components that only have an I2C bus. This includes memory chips, although if the controller is only using I2C and the memory is using SPI then the speed might be limited and the receiving component might not work due to long rise times.
To overcome this limitation with I2C, it’s best to use a controller with SPI, and then use the interface bridge to access a peripheral that only has I2C. Note that the SPI side will have to be clocked lower to ensure it can be used at I2C speeds. This would be done in the following topology:

Another common requirement in open-drain and push-pull serial protocols (where the signal level is set by the core voltage) is level shifting. The simplest way to build a PCB is with a single power source that is regulated down to the desired core voltage, such as with an LDO. In reality, you might have some peripherals that run at a higher voltage (say, 3.3 V) while the main controller runs at lower voltage with multiple rails (2.5 V, 1.8 V, etc.). If your MCU runs at 3V3 but your memory runs at 1V8 (this is a common situation), then you will need to route your SPI or I2C signals through a level shifter. Note that some interface bridges will include a level shifter that connects to two power rails; the topology is shown below.

Once you’ve located components for your design, how do you decide between an SPI vs. I2C interface? Here are some points that will drive your decision:
Speed: When you’re transferring data in bulk or have a tight window to verify user input against the data stored in a memory chip, every single microsecond counts. If repeated read and write capability is needed in real time with the rest of your system, then use SPI. If the controller only needs to occasionally read or write from memory, then use I2C.
Controller: If you’re using a very small MCU or peripheral and you have very few pins to spare, then you should go with I2C. In fact, you probably won’t have a choice with some microcontrollers. For example, the classic ATTiny MCUs only have I2C, so if they need data from an external memory then you will have to find a memory chip that supports I2C.
Power: If you’re designing a battery-operated device that needs to repeatedly access data, you might opt for SPI as the interface will use less average power than an I2C interface.
SPI and I2C routing are much easier when you use the complete set of PCB design and routing features in Altium Designer ® . When you’ve finished your design, and you want to release files to your manufacturer, the Altium 365 ™ platform makes it easy to collaborate and share your projects.
We have only scratched the surface of what’s possible with Altium Designer on Altium 365. Start your free trial of Altium Designer + Altium 365 today.
Difference between I2C and SPI (I2C VS SPI)
A communication protocol is a system that allows two or more entities to talk to each other in a communications system. Communication protocols describe communication rules, syntax and how the device can recover from errors. Like human beings, communication protocols allow data transmission between hardware, software or a combination of the two with different languages.
In this post, I will discuss the differences between I2C and SPI (I2C vs SPI), although there are many serial communications protocols the I2C and SPI are very well-known. I2C and SPI are both bus protocols that enable the user to transfer serial, short-distance data.
What is I2C Protocol?
I2C stands for “inter-Integrated Circuit bus”. It is also called as I2C. I2C is a two-wire serial protocol for connecting low-speed devices such as microcontrollers, EEPROMs, Analog to Digital (A/D) and Digital to Analog (D/A) converters, Input/Output (I/O) interfaces and other similar peripherals in an embedded system.
The I2C bus is famous because it is easy to use, it can have more than one master and multiple slaves, only upper bus speed is defined and only two wires with pull-up resistors are needed to connect a nearly unlimited number of I2C devices. I2C can use even slower microcontrollers with general-purpose I/O pins because they only need to create appropriate Start and Stop conditions, in addition, to read and write byte functions.
I2C requires just 2 wires to transfer data between devices:
- SCL (Serial Clock)-The clock signal line.
- SDA (Serial Data)-The line for sending and receiving data between master and slave.
I2C is a serial communication protocol and the SDA line is used to transmit the data bit by bit.
History of I2C protocol:
The I2C bus protocol was invented by Philips Semiconductors in the early 1980s. Its primary purpose was to provide a convenient way to connect a CPU to peripheral chips on a TV set. Today, however, I2C is used in a wide range of communication applications, from LCD to Factory Automation.
It was originally developed for Philips chips. The original standard permitted only 100kHz transmissions and afforded only 7-bit addresses and limits the number of devices on the bus only 112. The first public specification was published in 1992, adding a fast-mode of 400kHz as well as an expanded address space of 10-bits. Three additional modes were also added later: fast mode plus-1MHz; high-speed mode, 3.4MHz; and ultra-fast mode, 5MHz.
How I2C work?
Now you might be thinking how two wires can be used to send data from a master to multiple slaves. Well, for that each device is provided preset ID or a unique device address so that the master can select which devices to use. Serial Clock (or SCL) and Serial Data (or SDA) are the two wires or lines. The SCL line is used to transmit the clock signal that synchronizes the transfer of data between the devices on the I2C bus, and the master generates the clock signal. The other line is the SDA line that is used to send the data.
There is no constant connection between master and slave, transmitting and receiving on the bus. It only depends on the direction of the data at the time. If the master decides to transmit the data to the slave then before sending any data, the master must first address the slave. Additionally, the power supply must be connected via a pull-up resistor. When the bus is idle, both the lines should be on high power.
Steps to transfer data between master and slave device:
- The master sends a transmission signal to each connected slave by replacing the SDA channel from high voltage to low voltage and the SCL channel from high to low after replacing the SDA channel.
- The master sends the target slave address, which is compared with the addresses of all the slave devices connected to the SCL and SDL lines. Then all slaves compare the address with their own address. If the address matches any device, that device is selected and all the other devices are removed from the SCL and SDL lines and that slave(device) reverts an ACK bit that switches the SDA line low to one bit. If the address does not match its address, the Slave will leave the SDA line high.
- After that master sends the data frame or receives it. After the transmission of each data frame, the slave returns another ACK bit to the master to acknowledge the successful data transfer.
- To end the transmission of data the master sends the slave a stop signal by changing SCL high before shifting SDA high.
How Clock(SCL) works in I2C data transmission:
- All masters generate their own clocks on the SCL line to send messages to the I2C bus.
- Data is only acceptable throughout the clock’s high time cycle.
- Synchronization of the clock is carried out by connecting the I2C interface to the SCL wire, where the transition shifts from high to low.
- Once the clock of the device goes low it will keep the SCL line in low state until it reaches the clock’s high level.
- The low-to-high transition does not change the state of the SCL line if another clock is still in a low time cycle. The device with the longest low period often holds the SCL line low.
Transmission modes in I2C communication:
- Standard mode: 100Kbps
- Fast mode: 400Kbps
- High-Speed mode: 3.5Mbps
- Ultra-fast mode: 5Mbps
Synchronous or Asynchronous: Synchronous
Serial or Parallel: Serial
Advantages of I2C Communication:
- Efficient, because it allows multiple master multiple slave communication.
- Allows communication using two wires only.
- Uses ACK / NACK bit that confirms every data frame is successfully transmitted.
Disadvantages:
- I2C has a half-duplexinterface.
- May become complex as the number of devices increases.
- It may become complex with increasing numbers of devices.
What is SPI Protocol?
SPI or Serial Peripheral Interface is a full-duplex synchronous serial communication protocol that is used for short-distance communications. The unique advantage of SPI is that the data can be transferred without interruption. A number of bits can be sent or received in a continuous stream.
Serial Peripheral Interface (SPI) is a master-slave style protocol that has a single master and multiple slave architecture. SPI is used to send data between the microcontroller(master) and peripheral devices(slaves) such as shift registers, sensors, etc. It uses a separate clock, data wires, and select lines to select the device which it wants to send data.
SPI Protocol consist of 4 wires:
- MOSI (Master-Out Slave-In) — Master line to send the slave data.MISO
- (Master-In Slave-Out)– Slave line to send the master data.
- SCLK (Serial Clock) — Line to send clock signal.
- SS/CS(Slave Select/Chip Select) — Master’s line to choose the slave.
SPI is also a serial communication and in this data can be sent in a continuous stream.
History of SPI protocol:
Motorola developed the SPI interface in the mid-1980s and it has become a de-facto standard. Ideally suited for use of data stream applications. Secure Digital cards and liquid crystal displays (LCDs) are common applications.
How SPI works?
1. The communication is started by the master always. Next, the master arranges the clock using a frequency that is less than or equal to the maximum frequency allowed by the slave. Now, the master manages the transfer of data by producing the clock signal (SCLK).
2. The master then selects the desired slave for communication by switching the slave peripheral (SS) selection chip to a “low” state and activating the specific slave whom the master wants to communicate by using the slave selection (SS).
3. The master sends data bit by bit to the MOSI slave by sending the MSB bit first. Slaves read bits when received.
4. If an appropriate response is required then the slave gives the master data one bit at a time along the MISO line by sending LSB bit first. As received the master reads the bits.
Operating Modes of SPI:
The master and slave really have to decide on certain protocols for synchronization. For those two clock characteristics, the Clock Polarity (CPOL or CKP) and the Clock Phase (CPHA) required.
The polarity of the clock determines the state of the clock. If CPOL is LOW, then master generates the clock, e.g. when Idle SCK is low state and switches to HIgh state during data transfer. Likewise, when CPOL is Up, SCK is HIGH in idle state and LOW in the active state.
The phase of the clock determines the clock transition, i.e. switching (LOW to HIGH) or switching (HIGH to LOW), when data is sent. If CPHA is 0, data is transferred to the rising clock edge. Data is transferred to the falling edge when CPHA is 1.
Depending on the values for clock polarity (CPOL) and clock phase (CPHA), there are 4 SPI modes: modes 0 to 4.
- Mode 0(CPOL = 0 and CPHA = 0):
Mode 0 occurs when the clock polarity is LOW and the clock phase is 0. In mode 0, data transmission takes place on the rising edge of the clock. - Mode 1(CPOL = 0 and CPHA = 1):
Mode 1 occurs when the clock polarity is low and the clock phase is 1. In mode 1, data is transmitted with the falling end of the clock. - Mode 2(CPOL = 1 and CPHA = 0):
Mode 2 occurs when the clock polarity is HIGH and the clock phase is 0. In mode 2, data is transmitted as the clock edge increases. - Mode 3(CPOL = 1 and CPHA = 1):
Mode 3 occurs when the clock polarity is HIGH and the clock phase is 1. In mode 3, data is transmitted as the clock edge increases.
Synchronous or Asynchronous: Synchronous
Serial or Parallel: Serial
Advantages of SPI Communication:
- There is no start and stop bit, so data can be transferred continuously without interruption.
- SPI is a full-duplex communication protocol.
- It has high-speed data bus 10 MHz.
- Different MISO and MOSI lines, so that data can be sent and received simultaneously.
Disadvantages of SPI Communication:
- SPI uses four wires for communication.
- It supports only one master.
- An additional dedicated master pin for CS or SS is needed for each additional slave.
- No protocol is set for error detection.
- No acknowledgment mechanism is established and therefore data receipt is not confirmed.
How to choose between I2C and SPI?
I think you’ve got to learn some information from this post, but let me tell you a little difference that’s going to help you determine which one you need.