C Syntax Quick Start (QSG)

Standard Types & Pointers

#include <stdint.h>
uint8_t byte_val = 0xFF; // 8-bit unsigned
uint32_t reg_val = 0x4002;// 32-bit unsigned

// Pointer declaration & dereference
uint32_t *p_reg = &reg_val;
*p_reg = 0x0000;

Bitwise Masks

#define BIT_POS 5

REG |= (1 << BIT_POS); // SET bit
REG &= ~(1 << BIT_POS); // CLEAR bit
REG ^= (1 << BIT_POS); // TOGGLE bit

// CHECK if bit is 1
if (REG & (1 << BIT_POS)) { ... }

Hardware Protocols (Embedded Linux / Raspberry Pi)

I2C (SMBus) Read/Write

#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>

int fd = open("/dev/i2c-1", O_RDWR);
ioctl(fd, I2C_SLAVE, 0x68); // Set Slave Addr

// Write to register 0x00
char buf[2] = {0x00, 0xFF};
write(fd, buf, 2);

// Read 1 byte
char rx_buf[1];
read(fd, rx_buf, 1);

SPI Full-Duplex Transfer

#include <linux/spi/spidev.h>

int fd = open("/dev/spidev0.0", O_RDWR);

uint8_t tx[] = {0x01, 0x80, 0x00};
uint8_t rx[3] = {0};

struct spi_ioc_transfer tr = {
  .tx_buf = (unsigned long)tx,
  .rx_buf = (unsigned long)rx,
  .len = 3,
  .speed_hz = 1000000 // 1 MHz
};

ioctl(fd, SPI_IOC_MESSAGE(1), &tr);

Raspberry Pi (pigpio Library Reference)

While raw memory mapping is powerful, the pigpio library is the industry standard for C development on the Pi. It provides DMA-timed precision and handles the kernel-level safety checks for you.

1. The Standard Pi Template

#include <stdio.h>
#include <pigpio.h>

int main(int argc, char *argv[]) {
  // 1. Initialize the library
  if (gpioInitialise() < 0) {
    printf("pigpio initialization failed\n");
    return 1;
  }

  // Your hardware logic here...

  // 2. Release resources
  gpioTerminate();
  return 0;
}

Compilation Command

When compiling C code that uses this library, you must explicitly link it using the -lpigpio and -lrt flags.

gcc -Wall -o my_program my_program.c -lpigpio -lrt

Requires Sudo to run: sudo ./my_program

2. Writing to a GPIO (LED Blink)

#define LED_PIN 18 // Use Broadcom (BCM) pin numbering

// Inside main(), after gpioInitialise():

// Set the pin as an output
gpioSetMode(LED_PIN, PI_OUTPUT);

// Blink sequence
for (int i = 0; i < 5; i++) {
  gpioWrite(LED_PIN, 1); // Turn LED ON (3.3V)
  time_sleep(0.5); // Wait 500ms (pigpio native sleep function)

  gpioWrite(LED_PIN, 0); // Turn LED OFF (0V)
  time_sleep(0.5); // Wait 500ms
}

// Best practice: Turn off the LED before exiting
gpioWrite(LED_PIN, 0);
"In C, the QSG is your survival guide. Whether you're debugging a segfault on a Linux box or timing an SPI bus transaction on a Raspberry Pi, keeping the fundamental syntax locked in your head is what separates the technologists from the hobbyists."