PIC 18 SPI — Intro to SPI Protocol

Allows 8 bits of data to be Synchronously Transmitted & Received Simultaneously — SPI — PIC Episode #01

J3
Jungletronics
12 min readDec 29, 2019

--

This project is about using the SD card filing system in its SPI mode and PIC18F.

Fig 1. SanDisk 1TB Extreme MicroSDXC UHS-I Memory Card with Adapter — A2, U3, V30, 4K UHD, Micro SD — SDSQXA1–1T00-GN6MA

The SPI bus is one of the most commonly used protocols for serial communication between a microcontroller and a peripheral device. The SPI bus is a master-slave type bus protocol.

Fig 5. For each clock cycle, send 1 bit on the MOSI line, and receive 1 bit on the MISO line; SPI bus is synchronous

In this protocol, one device (usually the microcontroller) is designated the master, and one or more other devices (usually sensors, converters, etc.) are designated, slaves. In a minimum configuration, only one master and one slave are used. The master communicates with the slaves and controls all the activities on the bus.

SPI Uses four wires (I2C and UARTs use two); No acknowledgment that the data has been successfully received (I2C has this); No form of error checking like the parity bit in UART; Only allows for a single master.

Project Description

This project is about using the SD card filing system. In this project, a file called MYFILE55.TXT is created on an SD card. Text This is MYFILE.TXT is written to the file initially; The text This is the added data is appended to the file. The file can be opened on a PC and its contents can be verified.

The SD card is inserted into a cardholder, and the holder is connected to PORTC of the microcontroller. The interface between the SD card and the microcontroller ports is as follows:

Project PDL

According to the SD card specifications, when the card is operating with a supply voltage of VDD ¼ 3.3 V, the input and output pin voltage levels are as follows:

Although the output produced by the card (2.475 V) is sufficient to drive the input port of a PIC microcontroller, the logic HIGH output of the microcontroller (about 4.3 V) is too high for the SD card inputs (maximum 3.6 V).

As a result of this, a potential divider is set up at the three inputs of the SD card using 2.2 and 3.3 K resistors.

Thus, the maximum voltage at the inputs of the SD card is limited to about 2.5 V: SD card input voltage ¼ 4.3 V, 3.3 K/(2.2 K þ 3.3 K) ¼ 2.48 V; The microcontroller is powered from a 5-V supply, which is obtained using a 7805 type 5-V regulator with a 9-V input; The 2.7- to e3.6-V supply required by the SD card is obtained using an MC33269DT-3.3 type regulator with a 3.3-V output and is driven from the 5-V input voltage.

Project Program mikroC Pro for PIC - mikroC Pro for PIC language provides an extensive set of library functions to read and write data to; Here is the code:

Let’s begin with the code!

SD cards (and also MultiMedia Cards, MMC)

Data can be written or read from a given sector of the card, or the file system on the card can be used for more sophisticated applications. mikroC Pro for PIC compiler supports an SD card library (called the Mmc library) with many functions. Some commonly used functions for file handling are listed below:

The SPI module has to be initialized through the SPIx_Init_Advanced routine with the following parameters. Once the MMC/SD card is initialized, the SPI module can be operated at higher speeds:

In this project, a new file is created, the text is written inside the file, and then the file is closed. At the beginning of the program, the program creates file MYFILE55.TXT by calling library function Mmc_Fat_Open with the arguments as the filename and the creation flag 0x80, which tells the function to create a new file if the file does not exist. The filename should be in filename.extension format, although it is also possible to specify an eight-digit filename and a three-digit extension with no ‘.’ in-between as the ‘.’ will be inserted by the function. Other allowed values of the creation flag are given below. The Mmc_Fat_Open function returns a filehandle. In multiple file operations, we can select the file we wish to operate on by specifying this handle in the Mmc_Fat_Activate function call. Note that the SD card must have been formatted in FAT16 before we can read or write to the card. Most new cards are already formatted, but we can also use the Mmc_Fat_QuickFormat function to format a card. Function Mmc_Fat_Rewrite is called to clear the file and position the cursor to the beginning, ready for writing. Initial text is written to the file using function Mmc_Fat_Open File Creation Fags.

If the file does not exist and 0x80 is set, a new file with the specified name will be created. Then, function Mmc_Fat_Append is called to append the second text to the file. Finally, function Mmc_Fat_Close is called to close the file and release the handle.

Before one of these arguments can be used the following definitions must be made at the beginning of the program. Note that one of the arguments to the Mmc_Fat_Open function is the file mode (FILE_READ, FILE_WRITE, or FILE_APPEND).

More About SPI

SD Card

Please take a look at the basic principles and operation of SD card memory devices. SD cards are commonly used in many electronic devices where a large amount of non-volatile data storage is required. Some application areas are as follows:

Fig 13. SD card specifications are maintained by the SD Card Association, which has >600 members.

The SD card is a flash memory storage device designed to provide a high capacity, nonvolatile, and rewritable storage in small size. The memory capacity of the SD cards is increasing all the time. Currently, they are available in capacities from several gigabytes to >128 GB. SD cards are available in three sizes: standard SD card, miniSD card, and the microSD card.

MiniSD and microSD cards are electrically compatible with the standard SD cards, and they can be inserted in special adapters and used as standard SD cards in standard card slots. SD card speeds are measured in three different ways: in kilobytes per second (kB/s), in megabytes per second (MB/s), or in an “x” rating similar to that of CD-ROMS where “x” is the speed corresponding to 150 kB/s. Thus, the various “x” based speeds are as follows:

As far as the memory capacity is concerned, we can divide SD cards into three families: Standard-Capacity (SDSC), High-Capacity (SDHC), and eXtended-Capacity (SDXC). SDSC is the older cards with capacities 1e2 GB. SDHC have capacities 4e32 GB, and SDXC cards have capacities >32e128 GB. The SD and SDHC families are available in all three sizes, but the SDXC family is not available in the mini size. In the projects in this book, we shall be using the standard SD cards only. The use of the smaller size SD cards is virtually the same and is not described here any further. SD cards can be interfaced to microcontrollers using two different protocols: SD card protocol and the SPI protocol. The SPI protocol is the most commonly used protocol and is the one used in the projects in this book. SPI bus is currently used by microcontroller interface circuits to talk to a variety of devices such as

The advantages of the SPI bus are as follows:

In addition, the disadvantages of the SPI bus are

It is important to realize that there are no SPI standards governed by any international committee. As a result of this, there are several versions of the SPI bus implementation. In some applications, the MOSI and MISO lines are combined into a single data line, thus reducing the line requirements into three. Some implementations have two clocks, one to capture (or display) data and another to clock it into the device. Also, in some implementations, the chip select line may be active-high rather than active low. The standard SD card has nine pins with the pin layout shown in Figure 7.71. Depending on the interface protocol used, pins have different functions. Table 7.6 gives the function of each pin in both the SD mode and the SPI mode of operation. 1 2 3 4 5 6 7 8 9 Figure 7.71: Standard SD Card Pin Layout. Operation of the SD Card in the SPI Mode When the SD card is operated in the SPI mode only seven pins are used:

Three pins are used for the power supply, leaving four pins for the SPI mode of operation:

At power-up, the SD card defaults to the SD bus protocol. The card is switched to the SPI mode if the CS signal is asserted during the reception of the reset command. When the card is in the SPI mode, it only responds to SPI commands. The host may reset a card by switching the power supply off and on again. Most high-level language compilers normally provide a library of commands for initializing, reading, and writing to SD cards. In general, it is not necessary to know the internal structure of an SD card before it can be used since the available library functions can easily be used. It is, however, important to have some knowledge about the internal structure of an SD card so that it can be used efficiently. In this section, we shall be looking briefly at the internal architecture and the operation of SD cards.

An SD card has a set of registers that provide information about the status of the card. When the card is operated in the SPI mode, these registers are as follows:

The CID consists of 16 bytes, and it contains the manufacturer ID, product name, product revision, card serial number, manufacturer date code, and a checksum byte. The CSD consists of 16 bytes, and it contains card-specific data such as the card data transfer rate, read/write block lengths, read/write currents, erase sector size, file format, write protection flags, and checksum. The SCR is 8 bytes long, and it contains information about the SD card’s special features capabilities such as security support, and data bus widths supported. The OCR is only 4 bytes long, and it stores the VDD voltage profile of the card. The OCR shows the voltage range in which the card data can be accessed. All SD card SPI commands are 6 bytes long with the MSB transmitted first. The first byte is known as the “command” byte, and the remaining 5 bytes are “command arguments”. Bit 6 of the command byte is set to “1” and the MSB bit is always “0”. With the remaining 6 bits, we have 64 possible commands, named CMD0 to CMD63. Some of the important commands are

In response to a command, the card sends a status byte known as R1. The MSB bit of this byte is always “0” and the other bits indicate various error conditions.

Reading Data The SD card in the SPI mode supports a single block and multiple blocks read operations. The host should set the block length, and after a valid read command, the card responds with a response token, followed by a data block and a CRC check. The block length can be between 1 and 512 bytes. The starting address can be any valid address range of the card. In multiple block read operations, the card sends data blocks with each block having its own CRC check attached to the end of the block. Writing Data The SD card in the SPI mode supports single or multiple blocks write operations. After receiving a valid write command from the host, the card will respond with a response token and will wait to receive a data block. A 1-byte “start block” token is added to the beginning of every data block. After receiving the data block, the card responds with a “data response” token and the card will be programmed as long as the data block has been received with no errors. In multiple write operations, the host sends the data blocks one after the other, each preceded with a “start block” token. The card sends a response byte after receiving each data block. A card can be inserted and removed from the bus without any damage. This is because all data transfer operations are protected by CRC codes, and any bit changes as a result of inserting or removing a card can easily be detected. SD cards operate with a typical supply voltage of 2.7 V. The maximum allowed power supply voltage is 3.6 V. If the card is to be operated from a standard 5.0-V supply, a voltage regulator should be used to drop the voltage to 2.7 V. The use of an SD card requires the card to be inserted into a special cardholder with external contacts (Figure 7.72). Connections can then be made easily to the required card pins. Figure 7.72: SD Card Holder.

Smart Card

As an example of serial data communications, consider the smart cards in your wallet. Each card has an embedded microcontroller, typically 8-bit, giving it its intelligence. Cost constraints are severe to give a manufacturing price of under $1, and a large component of this is accounted for by the non-corrosive gold-plated contacts, via which the microcontroller is powered and clocked when in contact with the card reader. In order to keep the mechanical precision of the reader low and hence reliability high, the number of contacts must be minimized and the pad size maximized.

Here only two port pins are used. One labeled SDO (Serial Data Output) outputs the data bit by bit, with the most significant bit first. The other, labeled SCK (Serial ClocK), is used to clock the three shift registers at the same time, and hence shift the data left one bit at a time.

Credits & References

Book: PIC Microcontroller Projects in C Basic to Advanced by Dogan Ibrahim

--

--

J3
Jungletronics

😎 Gilberto Oliveira Jr | 🖥️ Computer Engineer | 🐍 Python | 🧩 C | 💎 Rails | 🤖 AI & IoT | ✍️