Wprowadzenie to I2C i SPI wigh PIC Microcontrollers

Mikrocontrollers from Microchip 's PIC family are widely used in embedded systems, from simpliche sensor nodes to complex industrial controllers. A key skill for any embedded developer im thee ability ty to interface distriverals using serial communication protoms. Two of thee most compatin are I ² C (Inter-Integrate Circuit) and SPI (Serial Peripheral Interface). Mastering these promeans allows you to controit sensors, memory chips, displays, ADC, and mand manyar devices tyour PIC digidate witail mitrail and.

This article provides a practilal, in-depth guidee to implementing I ² C and SPI on PIC microcontrollers. We will cover hardware setup, register configuration, typical code sequeres, and context debigging techniques. By thee end you will have thee knowndge te confidently add serial communication to your next PIC project.

Overview of I ² C andSPI

Both protores are syncuje serial buses, ale ich różnice architektur in architecture, speed, and application.

I ² C (Inter-Integrated Circuit)

I ² C wykorzystuje only two wires: indi1; FLT: 1; FLT: 0; FLT: 3; FLT: 1; FLT: 1; FLT: 1 X3; FLT: 1 XI3; FLT: 1 XI3; (Serial Data) andi1; FLT: 2 XI3; FLL XI3; FLT: 3 XI3; FLT: 3 XI3; FLT: 1 XI3; FLT: (Serial Data) anditi1; FLT: 2 XI3; FLT: SL X1; FLS; FLT: 3 X3; FLS; FLT: 3; FLV; FLT: 1 X3; FLC). EVE XE XP, FLS, FX, FX XP, FX, FX, EVE, EVE, EVE, EVE, EVE, EVE, EVE, EVE, EVE,

Ponieważ jeden z dwóch wires are needed, I ² C saves I / O pins, making it attractive for small PICs. However, the protocol is more complex than SPI because of addiressing, acke bits, and clock stretching.

SPI (Serial Peripheral Interface)

I I wykorzystuje linie four: vil 1; vil 1; fLT: 0 vil 3; vil 3; vil 1; fLT: 1 vil 3; ix 3; (Master Out Slave In), vil 1; flt: 2 vil 3; vil 3; vil 1; vil 1; vil 1; vil 3; vil 3; vil 3; vil 3; vil.

SPI is simpler to implement in hardware but requires more pins - one decreciated SS line per slave. Many PIC microcontrollers include a decretated Master Synchronous Serial Port (MSSP) module that can be configured for either I ² C or SPI.

Hardware Consignations for I ² C andSPI

Before diving into code, you mutt get thee hardware right.

Resistors: indiv1; FLT: 1; Xi1; FLT: 1; Xi1; FLT: 1 XI1; FLT: 1 XI1; FLT: 1 XI3; I ² C lines are open-drain; they require external pull-up resistors: typically 4.7 kВ to 10 kВ) to pull SDA andd SCL to V XI1; FLT: 2 XI3; DD XI1; FLT: 3 XI3; XI3. Thee value depended s on bus contabilitance ance andspeed. For long buses or fast mode, lower resistor values may bee ded tt time specifications.

Xi1; Xi1; FLT: 0 XI3; XI3; Voltage levels: XI1; XI1; FLT: 1 XI3; XI3; FLT: 1 XI3; Ensure yourr PIC and the perdirelerate operate at the te same logic voltage (e.g., 3.3 V or 5 V). If they different, use level shifters such the Antare 1; XIF: 2 X3; SparkFun BOB-12009 XI1; XI1; FLT: 3; OR a Simple MOSFET objet.

Refl1; FLT: 0 is 3; FLT: 0 is 3; Supports; Bus length and capacitiva loading: prefectude 1; FLT: 1 is 3; FLT: 0 longer wires (above a few inches), keep te bus capacitance below thee maximum umem specified in your PIC datasheet (prefectul 1; FLT: 2 giref; PIC16F1xxx daseet presence 1; present 1; export 1; FLT: 3; often states 400 pF for I ² C.

Reg.

Configuring I ² C on PIC Microcontrollers

Meczet modern PICs included thee environ1; Xi1; FLT: 0 XI3; Xi3; Master Synchronours Serial Port (MSSP) i1; Xi1; FLT: 1 XI3; Xi3; module that supports both I ² C and SPI. We 'll focus on the MSSP in I ² C master mode for a typical 8-bit PIC (e.g., PIC16F18877).

Key Registers for I ² C

  • (1); FLT: 0 (0); FLT: 0 (3); FLT: 1 (3); FLT: 1 (3); FLT: 1 (3); FLT: (3) C clock frequency is derived frem the system clock using a formula: F (1); FLT: (1); FLT: (1); FLT: (3) FLT: (4); FLT: (1); FLT: (1); FLT: 4 (3); FLT: (3); FLF (1); FLS (1); FLV (1) a (1)
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SSPxSTAT Xi1; Xi1; FLT: 1 Xi3; Xi3; - Status register. Bits indicate bus collision, write collision, and whether a start / stop condition has been condited.
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SSPxCON1 XI1; Xi1; FLT: 1 Xi3; Xi3; - XiL register 1. Selects I ² C mode (master, slave) and enables the module.
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SSPxCON2 Xi1; Xi1; FLT: 1 Xi3; Xi3; - Master mode control. Commands for sending Start, Restart, Stop, ande acking.
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SSPxBUF Xi1; Xi1; FLT: 1 Xi3; Xi3; - Data buffer. Write to send, read to receive.

I ² C Master Initialization Sequence

  1. Disable thee MSSP module by clearing the Kobieta: 1; Xi1; FLT: 0 Xi3; Xi3; SSPEN Xi1; Xi1; FLT: 1 Xi3; Xi3; bit (SSPxCON1 Ximp; lt; 5 Ximp; gt;).
  2. Set I ² C master mode (typically 0x08 in SSPxCON1 bits demmp; lt; 3: 0 demmp; gt;).
  3. Konfiguracja tych baud rate by loading SSPxADD with thee proper value.
  4. Set up SDA and SCL pins as inputs with swell pull-ups (or use external resistors).
  5. Enable the module by setting SSPEN.
  6. Opcjonalne wprowadzenie przerw for te MSSP.

Badanie: Reading from an LM75 Temperature Sensor

Te LM75 ma 7-bitowe adresatów (typically 0x48 for thee A0-A2 pins grounded). Tu read thee temperatur register (pointer 0x00), you mutt first write thee pointer, then generate a repeated start andd read.

Xi1; Xi1; FLT: 0 XI3; XI3; XI1; FLT: 1 XI3; XI3; FLT: 1 XI1; FLT: 2 XI3; XI3; Start → adresaci byte (0x90) → wyakt for ACK → pointer byte (0x00) → wyaid for ACK → Stop. XI1; FLT: 3 XI3; FLT: 3; FLT: 1; FLT: 4 XI3; FL3; FLT: 1; FLT: 5 XI3; FL3D; FRED temporature; FL3XIF: 1; FLT: 6 XI3T; PH; Star3T → addios byte (0x11111); FLT: FLT: 3D; FLT: FLT: FLS; FLS; FLP; FLP; FLP: FLP; FLP

Each byte exchange requires polling the SSPxSTAT register for te BF (Buffer Full) bit and the SSPxIF interrupt flag. A mean dimens is forminting to send thee ACK / NACK after rediving data. Usie thee predivine 1; British 1; FLT: 0 preditionate 3; ACCDT preditionate 3; ACCDT preditionate 1; IN: 1 pretionary 3; AND prediv1; FLT: 2 prediretional contribute; FLT: 2; ACCKEN pretionary 1; FLT: 3 prediuree 3; Bits in SSPxCON2 control assigame.

Common I ² C Pitfalls

  • Support: Support; Support: SSSP (set the messaged 1; Support 1; FLT: 2 message 3; FLT: 2 message 3; CKP message 1; FLT: 3 message 3; bit appropriatele).
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; Bus collision: Xi1; Xi1; FLT: 1 Xi3; Xi3; If anotherr master tries to drive the bus, the MSSP sets the BCLIF flag. Usie this to retry the transaction.
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; Stuck bus: Xi1; Xi1; FLT: 1 Xi3; Xi3; If a slave does not release SDA after a transmissionon, the bus may hang. Implement a timeout that sends nine clock pulses to recover.

Configuring SPI on PIC Microcontrollers

Te MSSP can also operate in SPI master or slave mode. We 'll cover master mode, which is most mocht moste.

Key Registers for SPI

  • (1) - (2 * (SPIxBRG + 1)).
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SPIxSTAT Xi1; Xi1; FLT: 1 Xi3; Xi3; - States register. Zawiera te BF bit, write collision, receive overflow flags.
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SPIxCON1 XI1; Xi1; FLT: 1 Xi3; Xi3; - XiL register 1. Selects master / slave, clock polarity (CKP), clock faxe (CKE), and sample point (SMP).
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SPIxCON2 Xi1; Xi1; FLT: 1 Xi3; Xi3; - Additional control (np., frame mode, SS2 enable).
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; SPIxBUF Xi1; Xi1; FLT: 1 Xi3; Xi3; - Data buffer for transmit and receive (buffered).

SPI Master Initialization Sequence

  1. Odłącz ten moduł SPI (clear SSPEN).
  2. Set thee desired clock polarity and faxe. Xi1; Xi1; FLT: 0 Xi3; Xi3; Mode 0 Xi1; Xi1; FLT: 1 Xi3; Xi3; (CKP = 0, CKE = 1) is thee mest Xin: data is sampled on the rising edge and shifted on thee falling edge.
  3. Konfiguracja thee baud rate in SPIxBRG. For 1 MHz with a 16 MHz clock, SPIxBRG = 7.
  4. Select master mode (SSPM bits = 0b0000 for SPI master, clock = FOSC / 4).
  5. Set the SS pin direction. On many PICs, thee SS pin is a decretated input in master mode. For slave selection, you mutt toggle a separate GPIO pin connectod to thee slave 's chip-select.
  6. - Zrobić modulację.

Badanie: Interfacing wigh an MCP3008 8-channel ADC

Te MCP3008 is a 10-bit ADC that communicates via SPI in mode 0. Tu read a channel (np., channel 0), thee master sends three bytes: a start bit, a single-ended / differental bit, and the e channel additions. The slave accordanously returns two data bytes.

1; FLT: 1; FLT: 0; FLT: 0; FL3; FLT: 1; FL3; FLT: 1; FLT: 1; FLT: 1; FLT: 2; FL3; FL3; FLT: 3; FL3; FL3; FL3; FL3; FLV: 1; FLT: 4; FLT: 3; FLT: 3; FLT: 3; FLT: 3; FLT: 3; FLV: 0; FLV: 0; FLF: 3; FLV: 3; FLV: 3; FLV (channel); 0; FLV: 0; FLS: FLS: 1; FLV: 1; FLV: 0; FLV: 0; FLV: 0; FLV: FLV: 0; FLV: 0; FLV: 0; FLV: 1; FLV: 1; FLV; FLV; FLV; F@@

Nie to wszystko jest napisane to SPIxBUF triggers a consignaanous receive. You mutt read thee buffer after each write to avoid overflow.

Managing Multiple SPI Slavs

Each slave wymaga unikalnego chip-select pin. Usie one GPIO per slave. Ensure there is a small delay between changing the SS pin andd startin the clock to meet setup time requiments of the slave. Many PIC allow you te use te hardware SS pin for automatic slave-select generation only in slave mode; in master mode you must do it manually.

Debugging I ² C and SPI Communication

When things don 't work, follow a metodical approach:

  • Reference 1; Reference 1; FLT: 0 Reference 3; Reference 3; Usie a logic analyzer or oscilloscope. Reference 1; Reference 1; FLT: 1 Reference 3; FLT: 0 Reference 3; FLT: 0 Reference 3; Usie a logic analyzer or oscilloscope. Reference 1; FLT: 1 Reference 3; FLT 3; FLT: 0 Reference 3; FLT: 0 Reference 3; FLT: 0 Reference Melt effective debugging tool. Check that thet thet clock is present, data transitions occur, and addirecorrect. For I ² C, verify start / stop conditions and assigge bits.
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; Check pull-up resistors. Xi1; FLT: 1 Xi3; Xi3; If SDA or SCL stay low, you may have a device holding the bus. Diconnect all slavs except one e andd try again.
  • Xi1; Xi1; FLT: 0 Xi3; Xi3; Verify baud rate. Xi1; FLT: 1 Xi3; Xi3; Measure the clock signal with a scope. For I ² C, thee clock frequency must with in thee slave 's specification.
  • Remember that thee adrets byte e (adresaci: lt1); 1) e.124; R / W bit goes in LSB).
  • Refl1; FLT: 0 presenti3; For SPI, check clock polarity andfaxe. Refl1; FLT: 1 presenti3; Efl3; Many slaves are sensitivie to the exact mode. Consult the slave 's datasheet. Also ensure that the chip-select line e active low and compatiingly.

If hardware debugging reveals correct waveforms, thee issie may be in your firmware. Usie debug LED or a serial console te print status registers. Many PIC development boards included an on-board programmer / debugger (e.g., MPLAB PICkit 4) that can help you step through the code.

Software Bit-Banging as a Backup

If thee hardware perdireleral is unavailable or if you must use a PIC that lacks an MSSP, you can implement I ² C or SPI in difficare using GPIO pins. For I ² C bit-banging, you toggle SDA and SCL directly, respecting timing delays. For SPI, you shift bits out distribut consumes CPU cycles and is slower. It is alsa good good gooy tte input pin. Bit-banging is emplible but consumes CPPPU cycles and is slower. It is alsa goua gooy taun thee protocol at.

Tematy zaawansowane

I ² C Multi-Master and Clock Speed Tuning

When multiple masters share the bus, you mutt handle arbitration cardifully. The MSSP in PIC supports multi-master mode; it monitors the bus andd will reminquish control if anotherr master sends data. Usie te te bus collision intermit (BCLIF) to o contact loss of distributionison and retry after a randem delay.

For faster I ² C (np., 400 kHz), enable slew-rate control on the output pins (if access) and use strogder pull-up resistors (np., 2.2 kzz). Some PICs have a dedicated eng1; Igl. 1; FLT: 0 exampli3; Igl.

SPI Daisy-Chaining andDMA

Some SPI devices support daisy-chaining, where the data output (MISO) of one device feed the input (MOSI) of thee next. This allows multiple slaves with a single chip-select line. The MSSP can handle-chaining if thee devices support it.

For high-speed SPI, consider using thee PIC 's Direct Memory Access (DMA) controller (aclicable on many newer PICs). DMA can transfer data to / frem the SPI buffer with out CPU intervention, freeing the core for contrar tasks. The DMA perdireteral is configured with source, destination, and count, then triggered by the SPI interrupt.

Konkluzja

I ² C and SPI are esential tools in y embedded designer 's kit. With the explicble MSSP module found in most PIC microcontrollers, implementing these procollas is expecforward once you understand the register setup and timing parameters. Always start with a simple tect - a dummy my write / read loop - to verify your hardware and diploare foundation.

Datasheets remain your best friend: Microchip 's besi1; Xi1; FLT: 0 + 3; Xi3; Official datasheets prepare 1; Xi1; FLT: 1 + 3; Xi3; FLT: 3 + 3; Xi3; Xips; (I ² C tips) and Xi1; Xi1; FLT: 4 + 3; XI3; XI1D; XI1D; XIF: 3 + 3D; XIF + 3D; (I) + L + L + L + L + L + 1; XIF + L + + L + + L + L + L + L + L + L + L + L + L + L + L + L + L + D + L + L + L + L + L + L + C + L + C + I + L + L + L + L + L + C + C + C + L + L + L + C + L + L + L + L + L + L + L + L + L +