I2C Sensors and Displays
I2C connects a microcontroller to many chips over just two wires: sensors, displays, memories, port expanders. It is convenient, and it is slow. In this experiment you drive the TM4C123's I2C module at register level (the bus transactions the Arduino library hid in the old lab), read a temperature sensor, show the result on an LCD, and measure how long each of those jobs takes. One of the numbers will surprise you, and it shapes how we schedule the motor station later.
Objectives
- Set up the TM4C123's I2C module as a bus master and choose the bus speed.
- Find every device on the bus with an address scan.
- Read a two-byte sensor register using a repeated start.
- Drive an HD44780 LCD through a PCF8574 I2C backpack.
- Measure the time of a sensor read and of an LCD update, at two bus speeds, and compare them with the bit count.
Background
The I2C bus
I2C uses two lines shared by every device: SCL, the clock, driven by the master, and SDA, the data. Both are open drain: a device can only pull a line low, and pull-up resistors bring it back high. That is what lets many devices share two wires safely. Most breakout boards, the LCD backpack included, carry their own pull-ups.
Every device has a 7-bit address. A transfer is a sequence of 9-bit slots: 8 bits from the sender, then one ACK bit from the receiver, who pulls SDA low to say "got it".
| Event | Who drives SDA | Meaning |
|---|---|---|
| START | Master | SDA falls while SCL is high: a transfer begins |
| Address + R/W | Master | 7 address bits, then 0 = write or 1 = read |
| ACK | The addressed device | Low: "I'm here". High (no ACK): nobody has that address |
| Data byte | Writer | 8 bits, most significant first |
| ACK | Reader | Low: "send more". The master leaves it high after the last byte it wants |
| Repeated START | Master | A new START without a STOP: change direction, keep the bus |
| STOP | Master | SDA rises while SCL is high: the bus is free |
Reading a register: the repeated start
Sensors keep their data in numbered registers. To read one, the master first writes the register number, then turns around and reads, without releasing the bus in between:
| Step | On the bus |
|---|---|
| 1 | START, address + W, ACK, register number, ACK |
| 2 | Repeated START, address + R, ACK |
| 3 | First data byte, master ACKs |
| 4 | Second data byte, master does not ACK, STOP |
The TM4C123 I2C master
The I2C module runs the bus for you, one byte at a time. You load the address and data, write a command to MCS, and wait until it reports the byte done.
| Register | What it holds |
|---|---|
MCR | MFE (bit 4) = 1: act as a master |
MTPR | The bus speed: SCL = 50 MHz / (2 × (6 + 4) × (TPR + 1)). TPR = 24 gives 100 kHz; TPR = 6 gives 357 kHz, the fastest standard-friendly setting below 400 kHz |
MSA | The device address in bits 7:1, and R/W in bit 0 |
MDR | The byte to send, or the byte received |
MCS, written | The command: RUN (bit 0), START (bit 1), STOP (bit 2), ACK (bit 3) |
MCS, read | The status: BUSY (bit 0), ERROR (bit 1, no ACK or lost bus) |
The commands this experiment uses:
MCS written | Does |
|---|---|
START | RUN | STOP | A whole one-byte transfer: send one byte, or (with R in MSA) receive one |
START | RUN | START, address, first byte, and keep the bus |
START | RUN | ACK | Repeated START in read direction, receive a byte and ACK it |
RUN | STOP | Receive the last byte without ACK, then STOP |
The LM75B temperature sensor
The LM75B keeps the temperature in register 0 as two bytes. The top 11 bits are a signed number in steps of 0.125 °C:
| Bytes read | Signed 16-bit value | Shifted right by 5 | Temperature |
|---|---|---|---|
0x19 0x00 | 6400 | 200 eighths | 25.0 °C |
0x19 0x20 | 6432 | 201 eighths | 25.125 °C |
0xFF 0xE0 | -32 | -1 eighth | -0.125 °C |
Shifting the signed value keeps the sign. Multiply by 10 and divide by 8 to get tenths of a degree, which we print as 25.1 without any floating point. Its address is 0x48 when its three address pins are tied low, as on most modules.
The LCD over I2C
An HD44780 character LCD needs at least six wires. A PCF8574 backpack reduces that to the two I2C lines: each byte you write to it sets its eight output pins, which drive the LCD.
| PCF8574 pin | LCD signal |
|---|---|
| P0 | RS: 0 = command, 1 = character |
| P2 | E: the LCD reads its data lines on E's falling edge |
| P3 | Backlight |
| P4 to P7 | D4 to D7: the LCD runs in 4-bit mode |
Sending one character takes two 4-bit halves, and each half needs three I2C bytes (data ready, E high, E low): six bus transfers per character.
Predicting the bus time
Count the bits, including the START, STOP and ACK slots, and divide by the bus speed:
| Job | Bits on the bus | At 100 kHz | At 357 kHz |
|---|---|---|---|
| One LM75B read | about 48 | about 0.5 ms | about 0.13 ms |
| One LCD character | about 120 | about 1.2 ms | about 0.34 ms |
| One LCD line (cursor + 16 characters) | about 2040 | about 20 ms | about 6 ms |
These are lower limits: the software between bytes adds time. You will measure the real numbers. Note the last row: updating one LCD line takes about 40 times as long as reading the sensor.
Activity
The program scans the bus and shows the addresses it finds, then reads the LM75B twice a second and shows the temperature on the LCD, timing both jobs.
Wiring the two modules
The LCD backpack needs 5 V: power it from the LaunchPad's VBUS pin. Its pull-ups then hold SDA and SCL at 5 V, which PB2 and PB3 tolerate as I2C inputs. Power the LM75B from 3.3 V. Both modules share SDA, SCL and GND.
Step 1: Wire the bus and add the definitions
| Signal | LaunchPad | LCD backpack | LM75B module | Logic analyzer |
|---|---|---|---|---|
| SCL | PB2 | SCL | SCL | CH0 |
| SDA | PB3 | SDA | SDA | CH1 |
| Power | VBUS (5 V), 3.3 V | VCC to VBUS | VCC to 3.3 V | |
| Ground | GND | GND | GND | GND |
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOB (1U << 1) // RCGCGPIO bit for Port B (I2C0 pins)
#define RCGC_I2C0 (1U << 0) // RCGCI2C bit for I2C0
// I2C0's pins
#define I2C0SCL (1U << 2) // PB2
#define I2C0SDA (1U << 3) // PB3
#define PCTL_PB23_MASK (0xFFU << 8) // PB2's and PB3's fields in GPIOB->PCTL: bits 15:8
#define PCTL_PB23_I2C0 (0x33U << 8) // 3 selects I2C0SCL and I2C0SDA
// I2C0 master registers
#define MCR_MFE (1U << 4) // MCR: master function enable
#define TPR_100KHZ 24 // MTPR: 50 MHz / (2 * (6 + 4) * (24 + 1)) = 100 kHz
#define TPR_FAST 6 // MTPR: 50 MHz / (2 * (6 + 4) * (6 + 1)) = 357 kHz
#define I2C_TPR TPR_100KHZ // The bus speed in use: change it in More to try
#define MCS_RUN (1U << 0) // MCS written: send or receive one byte
#define MCS_START (1U << 1) // MCS written: START (or repeated START) first
#define MCS_STOP (1U << 2) // MCS written: STOP after
#define MCS_ACK (1U << 3) // MCS written: ACK the byte received (more to come)
#define MCS_BUSY (1U << 0) // MCS read: transfer in progress
#define MCS_ERROR (1U << 1) // MCS read: no ACK, or lost the bus
// The devices on the bus (7-bit addresses)
#define LCD_ADDR 0x27 // PCF8574 LCD backpack: 0x27, or 0x3F on some boards
#define LM75_ADDR 0x48 // LM75B temperature sensor, address pins A2-A0 at GND
#define LM75_TEMP 0x00 // LM75B register 0: temperature
// The LCD backpack: what each bit of the PCF8574 drives
#define LCD_RS (1U << 0) // P0: 0 = command, 1 = character
#define LCD_EN (1U << 2) // P2: enable, the LCD latches on its falling edge
#define LCD_BL (1U << 3) // P3: backlight. P4 to P7: D4 to D7
// The profiler from Experiment 1
typedef struct { uint32_t start, last, min, max, count; } profile_t;
volatile profile_t p_read = { .min = 0xFFFFFFFF }; // One temperature read
volatile profile_t p_lcd = { .min = 0xFFFFFFFF }; // Writing one LCD line
// Results, for the Watch window
volatile uint8_t found[16]; // Addresses that answered the scan
volatile uint32_t found_count;
volatile int16_t temp_raw; // The LM75B's two bytes, as one signed number
volatile int32_t temp_tenths; // The temperature in tenths of a degree: 235 = 23.5 CI2C_TPRpicks the bus speed from the two values worked out from theMTPRformula.MCS_*name the command bits you write and the status bits you read: the same register, two meanings.LCD_ADDRis 0x27 on most backpacks and 0x3F on some. The scan in Step 4 tells you which you have.p_readandp_lcdare two profiles, one per job.
Step 2: Add the profiler and the I2C functions
void cycles_init(void)
{
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}
void prof_start(volatile profile_t *p) { p->start = DWT->CYCCNT; }
void prof_stop(volatile profile_t *p)
{
p->last = DWT->CYCCNT - p->start;
if (p->last < p->min) p->min = p->last;
if (p->last > p->max) p->max = p->last;
p->count++;
}void i2c_init(void)
{
SYSCTL->RCGCI2C |= RCGC_I2C0;
SYSCTL->RCGCGPIO |= RCGC_GPIOB;
while ((SYSCTL->PRGPIO & RCGC_GPIOB) == 0) {}
while ((SYSCTL->PRI2C & RCGC_I2C0) == 0) {}
GPIOB->AFSEL |= I2C0SCL | I2C0SDA; // Driven by a peripheral...
GPIOB->PCTL = (GPIOB->PCTL & ~PCTL_PB23_MASK) | PCTL_PB23_I2C0; // ...I2C0
GPIOB->ODR |= I2C0SDA; // SDA open drain (not SCL)
GPIOB->DEN |= I2C0SCL | I2C0SDA;
I2C0->MCR = MCR_MFE; // I2C0 is a master
I2C0->MTPR = I2C_TPR; // SCL speed
}
// Start one step of a transfer and wait for it. Returns 0 on ACK, -1 on no ACK.
int i2c_run(uint32_t command)
{
I2C0->MCS = command;
while ((I2C0->MCS & MCS_BUSY) == 0) {} // BUSY rises a few cycles after the write...
while (I2C0->MCS & MCS_BUSY) {} // ...and falls when the byte is done
return (I2C0->MCS & MCS_ERROR) ? -1 : 0;
}
// Write one byte to a device: START, address + W, data, STOP
int i2c_write(uint8_t addr, uint8_t data)
{
I2C0->MSA = (uint32_t)addr << 1; // Address in bits 7:1, bit 0 = 0: write
I2C0->MDR = data;
return i2c_run(MCS_START | MCS_RUN | MCS_STOP);
}
// Read a 2-byte register: START, address + W, register number,
// repeated START, address + R, byte (ACK), byte (no ACK), STOP
int i2c_read_reg16(uint8_t addr, uint8_t reg, uint16_t *value)
{
I2C0->MSA = (uint32_t)addr << 1; // Write: which register
I2C0->MDR = reg;
if (i2c_run(MCS_START | MCS_RUN) < 0)
{
I2C0->MCS = MCS_STOP; // Nobody answered: release the bus
return -1;
}
I2C0->MSA = ((uint32_t)addr << 1) | 1; // Read: bit 0 = 1
if (i2c_run(MCS_START | MCS_RUN | MCS_ACK) < 0) // Repeated START, first byte, ACK it
{
I2C0->MCS = MCS_STOP;
return -1;
}
uint32_t high = I2C0->MDR;
i2c_run(MCS_RUN | MCS_STOP); // Second byte, no ACK (the last one), STOP
*value = (uint16_t)((high << 8) | I2C0->MDR);
return 0;
}
// Is anyone at this address? A one-byte read: START, address + R, byte (no ACK), STOP.
// A read is harmless to any device; a write could change its settings.
int i2c_probe(uint8_t addr)
{
I2C0->MSA = ((uint32_t)addr << 1) | 1;
return i2c_run(MCS_START | MCS_RUN | MCS_STOP);
}i2c_init()gives PB2 and PB3 to I2C0 and makes only SDA open drain: the module drives SCL itself.i2c_run()writes a command and waits for it.BUSYtakes a few cycles to rise, so it waits for the rise first, then the fall.i2c_read_reg16()is the repeated-start sequence from the Background: write the register number, keep the bus, read two bytes, ACK the first, not the second.i2c_probe()is a one-byte read. Reading never changes a device's settings, so it is the safe way to knock on every address.
Step 3: Add the LCD functions
// A 1 ms clock from SysTick, for the LCD's delays
volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }
void delay_ms(uint32_t n)
{
uint32_t start = ms;
while (ms - start < n) {}
}
// One nibble on D7-D4 with an enable pulse: three bytes to the backpack
void lcd_nibble(uint8_t nibble, uint8_t rs)
{
uint8_t out = (uint8_t)((nibble << 4) | rs | LCD_BL);
i2c_write(LCD_ADDR, out); // Data and RS settle, E low
i2c_write(LCD_ADDR, out | LCD_EN); // E high
i2c_write(LCD_ADDR, out); // E low: the LCD latches the nibble
}
void lcd_command(uint8_t cmd)
{
lcd_nibble(cmd >> 4, 0);
lcd_nibble(cmd & 0x0F, 0);
if (cmd <= 0x02) delay_ms(2); // Clear and Home take 1.6 ms
}
void lcd_data(char ch)
{
lcd_nibble((uint8_t)ch >> 4, LCD_RS);
lcd_nibble((uint8_t)ch & 0x0F, LCD_RS);
}
void lcd_init(void)
{
delay_ms(50); // Power-up
lcd_nibble(0x03, 0); delay_ms(5); // The HD44780's 4-bit start-up sequence
lcd_nibble(0x03, 0); delay_ms(1);
lcd_nibble(0x03, 0); delay_ms(1);
lcd_nibble(0x02, 0); delay_ms(1);
lcd_command(0x28); // 4-bit, 2 lines, 5x8 dots
lcd_command(0x0C); // Display on, cursor off
lcd_command(0x06); // Cursor moves right
lcd_command(0x01); // Clear
}
void lcd_set_cursor(uint8_t row, uint8_t col)
{
lcd_command((uint8_t)((row == 0 ? 0x80 : 0xC0) + col));
}
void lcd_print(const char *s)
{
while (*s) lcd_data(*s++);
}
void lcd_hex2(uint8_t v) // Two hex digits, for addresses
{
const char *hex = "0123456789ABCDEF";
lcd_data(hex[v >> 4]);
lcd_data(hex[v & 0x0F]);
}
void lcd_tenths(int32_t t) // 235 -> "23.5", -45 -> "-4.5"
{
if (t < 0) { lcd_data('-'); t = -t; }
char digits[10];
int i = 0;
uint32_t whole = (uint32_t)t / 10;
do { digits[i++] = (char)('0' + whole % 10); whole /= 10; } while (whole);
while (i) lcd_data(digits[--i]);
lcd_data('.');
lcd_data((char)('0' + t % 10));
}- SysTick counts milliseconds for
delay_ms(), which the LCD's start-up sequence needs. lcd_nibble()sends one half-character as three I2C bytes, toggling E. Everything else builds on it.lcd_tenths()prints 235 as23.5: integer arithmetic only.
Step 4: Read the sensor and write main
// Try every address and remember the ones that answer
void i2c_scan(void)
{
found_count = 0;
for (uint8_t addr = 0x08; addr < 0x78; addr++) // 0x00-0x07 and 0x78-0x7F are reserved
if (i2c_probe(addr) == 0 && found_count < 16)
found[found_count++] = addr;
}
// The LM75B sends its temperature as 11 bits in the top of two bytes, in 0.125 C steps.
// Shifting the signed 16-bit value right by 5 keeps the sign: the result is in eighths of a degree.
int lm75_read_tenths(int32_t *tenths)
{
uint16_t value;
if (i2c_read_reg16(LM75_ADDR, LM75_TEMP, &value) < 0)
return -1;
temp_raw = (int16_t)value;
int32_t eighths = temp_raw >> 5;
*tenths = eighths * 10 / 8;
return 0;
}int main(void)
{
SysTick_Config(SystemCoreClock / 1000); // 1 ms ticks for delay_ms
cycles_init();
i2c_init();
lcd_init();
// Who is on the bus? Show the addresses on line 1 for two seconds.
i2c_scan();
lcd_set_cursor(0, 0);
lcd_print("I2C:");
for (uint32_t i = 0; i < found_count && i < 4; i++)
{
lcd_data(' ');
lcd_hex2(found[i]);
}
delay_ms(2000);
lcd_command(0x01);
while (1)
{
int32_t t;
prof_start(&p_read);
int ok = lm75_read_tenths(&t);
prof_stop(&p_read);
if (ok == 0) temp_tenths = t;
prof_start(&p_lcd); // How long does one LCD line take?
lcd_set_cursor(0, 0);
if (ok == 0)
{
lcd_print("Temp ");
lcd_tenths(temp_tenths);
lcd_print(" C ");
}
else
lcd_print("No LM75B ");
prof_stop(&p_lcd);
delay_ms(500);
}
}- The scan runs once at start-up and shows up to four addresses on the LCD for two seconds.
- In the loop,
p_readtimes only the sensor read, andp_lcdtimes only the LCD update. - The text ends with spaces so a shorter number fully replaces a longer one.
Build, flash, and run. In PulseView, add the I2C protocol decoder on CH0 (SCL) and CH1 (SDA): it labels every address, data byte, ACK and NACK.
Check: the LCD first shows I2C: 27 48 (or 3F 48), then Temp 24.5 C or similar. Hold the sensor between your fingers and the temperature rises within a few seconds. In PulseView, one read shows Write 0x48, 0x00, a repeated start, Read 0x48 and two data bytes, the last one with NACK.
Then try: set I2C_TPR to TPR_FAST, rebuild, and fill in the second column.
| Measurement | 100 kHz | 357 kHz |
|---|---|---|
p_read.min, one sensor read (µs) | ||
p_lcd.min, one LCD line (ms) | ||
| SCL period on the analyzer (µs) | ||
| Measured vs predicted read time |
- Did the scan find both devices, and do you know your LCD's address?
- Does the temperature change when you warm the sensor?
- Can you point to the repeated start and the final NACK in the PulseView decode?
- How many sensor reads could you do in the time of one LCD line update?
More to try (optional)
| Try this | What you'll see |
|---|---|
| Unplug the LM75B while it runs | The LCD shows No LM75B: the address byte gets no ACK and i2c_read_reg16() returns -1. On the analyzer, the transfer stops after the address. |
Change LM75_ADDR to 0x49 | The same: nobody answers at 0x49. |
Comment out lcd_command(0x01) after the scan and write a shorter line | Old characters stay on the screen: why every line is padded with spaces. |
Time lcd_command(0x01) with a profile | Clear is slower than writing a full line of spaces: it adds a 2 ms wait on top of its I2C bytes. |
The complete program
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOB (1U << 1) // RCGCGPIO bit for Port B (I2C0 pins)
#define RCGC_I2C0 (1U << 0) // RCGCI2C bit for I2C0
// I2C0's pins
#define I2C0SCL (1U << 2) // PB2
#define I2C0SDA (1U << 3) // PB3
#define PCTL_PB23_MASK (0xFFU << 8) // PB2's and PB3's fields in GPIOB->PCTL: bits 15:8
#define PCTL_PB23_I2C0 (0x33U << 8) // 3 selects I2C0SCL and I2C0SDA
// I2C0 master registers
#define MCR_MFE (1U << 4) // MCR: master function enable
#define TPR_100KHZ 24 // MTPR: 50 MHz / (2 * (6 + 4) * (24 + 1)) = 100 kHz
#define TPR_FAST 6 // MTPR: 50 MHz / (2 * (6 + 4) * (6 + 1)) = 357 kHz
#define I2C_TPR TPR_100KHZ // The bus speed in use: change it in More to try
#define MCS_RUN (1U << 0) // MCS written: send or receive one byte
#define MCS_START (1U << 1) // MCS written: START (or repeated START) first
#define MCS_STOP (1U << 2) // MCS written: STOP after
#define MCS_ACK (1U << 3) // MCS written: ACK the byte received (more to come)
#define MCS_BUSY (1U << 0) // MCS read: transfer in progress
#define MCS_ERROR (1U << 1) // MCS read: no ACK, or lost the bus
// The devices on the bus (7-bit addresses)
#define LCD_ADDR 0x27 // PCF8574 LCD backpack: 0x27, or 0x3F on some boards
#define LM75_ADDR 0x48 // LM75B temperature sensor, address pins A2-A0 at GND
#define LM75_TEMP 0x00 // LM75B register 0: temperature
// The LCD backpack: what each bit of the PCF8574 drives
#define LCD_RS (1U << 0) // P0: 0 = command, 1 = character
#define LCD_EN (1U << 2) // P2: enable, the LCD latches on its falling edge
#define LCD_BL (1U << 3) // P3: backlight. P4 to P7: D4 to D7
// The profiler from Experiment 1
typedef struct { uint32_t start, last, min, max, count; } profile_t;
volatile profile_t p_read = { .min = 0xFFFFFFFF }; // One temperature read
volatile profile_t p_lcd = { .min = 0xFFFFFFFF }; // Writing one LCD line
// Results, for the Watch window
volatile uint8_t found[16]; // Addresses that answered the scan
volatile uint32_t found_count;
volatile int16_t temp_raw; // The LM75B's two bytes, as one signed number
volatile int32_t temp_tenths; // The temperature in tenths of a degree: 235 = 23.5 C
void cycles_init(void)
{
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}
void prof_start(volatile profile_t *p) { p->start = DWT->CYCCNT; }
void prof_stop(volatile profile_t *p)
{
p->last = DWT->CYCCNT - p->start;
if (p->last < p->min) p->min = p->last;
if (p->last > p->max) p->max = p->last;
p->count++;
}
void i2c_init(void)
{
SYSCTL->RCGCI2C |= RCGC_I2C0;
SYSCTL->RCGCGPIO |= RCGC_GPIOB;
while ((SYSCTL->PRGPIO & RCGC_GPIOB) == 0) {}
while ((SYSCTL->PRI2C & RCGC_I2C0) == 0) {}
GPIOB->AFSEL |= I2C0SCL | I2C0SDA; // Driven by a peripheral...
GPIOB->PCTL = (GPIOB->PCTL & ~PCTL_PB23_MASK) | PCTL_PB23_I2C0; // ...I2C0
GPIOB->ODR |= I2C0SDA; // SDA open drain (not SCL)
GPIOB->DEN |= I2C0SCL | I2C0SDA;
I2C0->MCR = MCR_MFE; // I2C0 is a master
I2C0->MTPR = I2C_TPR; // SCL speed
}
// Start one step of a transfer and wait for it. Returns 0 on ACK, -1 on no ACK.
int i2c_run(uint32_t command)
{
I2C0->MCS = command;
while ((I2C0->MCS & MCS_BUSY) == 0) {} // BUSY rises a few cycles after the write...
while (I2C0->MCS & MCS_BUSY) {} // ...and falls when the byte is done
return (I2C0->MCS & MCS_ERROR) ? -1 : 0;
}
// Write one byte to a device: START, address + W, data, STOP
int i2c_write(uint8_t addr, uint8_t data)
{
I2C0->MSA = (uint32_t)addr << 1; // Address in bits 7:1, bit 0 = 0: write
I2C0->MDR = data;
return i2c_run(MCS_START | MCS_RUN | MCS_STOP);
}
// Read a 2-byte register: START, address + W, register number,
// repeated START, address + R, byte (ACK), byte (no ACK), STOP
int i2c_read_reg16(uint8_t addr, uint8_t reg, uint16_t *value)
{
I2C0->MSA = (uint32_t)addr << 1; // Write: which register
I2C0->MDR = reg;
if (i2c_run(MCS_START | MCS_RUN) < 0)
{
I2C0->MCS = MCS_STOP; // Nobody answered: release the bus
return -1;
}
I2C0->MSA = ((uint32_t)addr << 1) | 1; // Read: bit 0 = 1
if (i2c_run(MCS_START | MCS_RUN | MCS_ACK) < 0) // Repeated START, first byte, ACK it
{
I2C0->MCS = MCS_STOP;
return -1;
}
uint32_t high = I2C0->MDR;
i2c_run(MCS_RUN | MCS_STOP); // Second byte, no ACK (the last one), STOP
*value = (uint16_t)((high << 8) | I2C0->MDR);
return 0;
}
// Is anyone at this address? A one-byte read: START, address + R, byte (no ACK), STOP.
// A read is harmless to any device; a write could change its settings.
int i2c_probe(uint8_t addr)
{
I2C0->MSA = ((uint32_t)addr << 1) | 1;
return i2c_run(MCS_START | MCS_RUN | MCS_STOP);
}
// A 1 ms clock from SysTick, for the LCD's delays
volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }
void delay_ms(uint32_t n)
{
uint32_t start = ms;
while (ms - start < n) {}
}
// One nibble on D7-D4 with an enable pulse: three bytes to the backpack
void lcd_nibble(uint8_t nibble, uint8_t rs)
{
uint8_t out = (uint8_t)((nibble << 4) | rs | LCD_BL);
i2c_write(LCD_ADDR, out); // Data and RS settle, E low
i2c_write(LCD_ADDR, out | LCD_EN); // E high
i2c_write(LCD_ADDR, out); // E low: the LCD latches the nibble
}
void lcd_command(uint8_t cmd)
{
lcd_nibble(cmd >> 4, 0);
lcd_nibble(cmd & 0x0F, 0);
if (cmd <= 0x02) delay_ms(2); // Clear and Home take 1.6 ms
}
void lcd_data(char ch)
{
lcd_nibble((uint8_t)ch >> 4, LCD_RS);
lcd_nibble((uint8_t)ch & 0x0F, LCD_RS);
}
void lcd_init(void)
{
delay_ms(50); // Power-up
lcd_nibble(0x03, 0); delay_ms(5); // The HD44780's 4-bit start-up sequence
lcd_nibble(0x03, 0); delay_ms(1);
lcd_nibble(0x03, 0); delay_ms(1);
lcd_nibble(0x02, 0); delay_ms(1);
lcd_command(0x28); // 4-bit, 2 lines, 5x8 dots
lcd_command(0x0C); // Display on, cursor off
lcd_command(0x06); // Cursor moves right
lcd_command(0x01); // Clear
}
void lcd_set_cursor(uint8_t row, uint8_t col)
{
lcd_command((uint8_t)((row == 0 ? 0x80 : 0xC0) + col));
}
void lcd_print(const char *s)
{
while (*s) lcd_data(*s++);
}
void lcd_hex2(uint8_t v) // Two hex digits, for addresses
{
const char *hex = "0123456789ABCDEF";
lcd_data(hex[v >> 4]);
lcd_data(hex[v & 0x0F]);
}
void lcd_tenths(int32_t t) // 235 -> "23.5", -45 -> "-4.5"
{
if (t < 0) { lcd_data('-'); t = -t; }
char digits[10];
int i = 0;
uint32_t whole = (uint32_t)t / 10;
do { digits[i++] = (char)('0' + whole % 10); whole /= 10; } while (whole);
while (i) lcd_data(digits[--i]);
lcd_data('.');
lcd_data((char)('0' + t % 10));
}
// Try every address and remember the ones that answer
void i2c_scan(void)
{
found_count = 0;
for (uint8_t addr = 0x08; addr < 0x78; addr++) // 0x00-0x07 and 0x78-0x7F are reserved
if (i2c_probe(addr) == 0 && found_count < 16)
found[found_count++] = addr;
}
// The LM75B sends its temperature as 11 bits in the top of two bytes, in 0.125 C steps.
// Shifting the signed 16-bit value right by 5 keeps the sign: the result is in eighths of a degree.
int lm75_read_tenths(int32_t *tenths)
{
uint16_t value;
if (i2c_read_reg16(LM75_ADDR, LM75_TEMP, &value) < 0)
return -1;
temp_raw = (int16_t)value;
int32_t eighths = temp_raw >> 5;
*tenths = eighths * 10 / 8;
return 0;
}
int main(void)
{
SysTick_Config(SystemCoreClock / 1000); // 1 ms ticks for delay_ms
cycles_init();
i2c_init();
lcd_init();
// Who is on the bus? Show the addresses on line 1 for two seconds.
i2c_scan();
lcd_set_cursor(0, 0);
lcd_print("I2C:");
for (uint32_t i = 0; i < found_count && i < 4; i++)
{
lcd_data(' ');
lcd_hex2(found[i]);
}
delay_ms(2000);
lcd_command(0x01);
while (1)
{
int32_t t;
prof_start(&p_read);
int ok = lm75_read_tenths(&t);
prof_stop(&p_read);
if (ok == 0) temp_tenths = t;
prof_start(&p_lcd); // How long does one LCD line take?
lcd_set_cursor(0, 0);
if (ok == 0)
{
lcd_print("Temp ");
lcd_tenths(temp_tenths);
lcd_print(" C ");
}
else
lcd_print("No LM75B ");
prof_stop(&p_lcd);
delay_ms(500);
}
}Common problems
| Symptom | Cause and fix |
|---|---|
| The scan finds nothing | SDA and SCL swapped, no common ground, or no pull-ups (if neither module has them, add 4.7 kΩ from each line to 3.3 V). |
The program hangs in i2c_run() | The I2C module isn't clocked or the pins aren't set: check RCGCI2C, AFSEL and PCTL for PB2 and PB3. |
| The LCD lights but shows nothing, or only blocks | Turn the contrast potentiometer on the back of the backpack. |
| The LCD shows nothing at all, but the scan finds it | LCD_ADDR doesn't match the address the scan found. |
| The temperature reads 0.0 or -0.1 constantly | The two bytes are combined in the wrong order, or the shift is on an unsigned value. |
Task
Turn the program into a small temperature station: the temperature on line 1, the highest seen on line 2, and an alarm on the red LED with hysteresis. Along the way you write lcd_status(), a one-call line update the rest of the semester reuses for live values.
Hysteresis
An alarm that turns on above 30.0 °C and off below 30.0 °C chatters: sensor noise near the threshold flips it on and off every reading. Hysteresis uses two thresholds instead: the alarm turns on above ALARM_ON and turns off only below the lower ALARM_OFF. Small noise can no longer cross both.
| Alarm now | Temperature | Alarm next |
|---|---|---|
| Off | Above ALARM_ON | On |
| On | Below ALARM_OFF | Off |
| Either | Between the two | Unchanged |
The starter program
Start from this program. It compiles and runs and reads the sensor, but the LCD stays blank: the three TODOs are yours. Set ALARM_ON about 1.5 °C above your room's temperature first, so a finger on the sensor trips it.
// Experiment 3 Task: a temperature station with an alarm.
// Write the three TODOs (highlighted). The rest is the Activity program, adapted: don't change it.
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOB (1U << 1) // RCGCGPIO bit for Port B (I2C0 pins)
#define RCGC_I2C0 (1U << 0) // RCGCI2C bit for I2C0
#define RCGC_GPIOF (1U << 5) // RCGCGPIO bit for Port F (LED)
#define RED_LED (1U << 1) // PF1
// I2C0's pins
#define I2C0SCL (1U << 2) // PB2
#define I2C0SDA (1U << 3) // PB3
#define PCTL_PB23_MASK (0xFFU << 8) // PB2's and PB3's fields in GPIOB->PCTL: bits 15:8
#define PCTL_PB23_I2C0 (0x33U << 8) // 3 selects I2C0SCL and I2C0SDA
// I2C0 master registers
#define MCR_MFE (1U << 4) // MCR: master function enable
#define TPR_100KHZ 24 // MTPR: 50 MHz / (2 * (6 + 4) * (24 + 1)) = 100 kHz
#define TPR_FAST 6 // MTPR: 50 MHz / (2 * (6 + 4) * (6 + 1)) = 357 kHz
#define I2C_TPR TPR_100KHZ // The bus speed in use: change it in More to try
#define MCS_RUN (1U << 0) // MCS written: send or receive one byte
#define MCS_START (1U << 1) // MCS written: START (or repeated START) first
#define MCS_STOP (1U << 2) // MCS written: STOP after
#define MCS_ACK (1U << 3) // MCS written: ACK the byte received (more to come)
#define MCS_BUSY (1U << 0) // MCS read: transfer in progress
#define MCS_ERROR (1U << 1) // MCS read: no ACK, or lost the bus
// The devices on the bus (7-bit addresses)
#define LCD_ADDR 0x27 // PCF8574 LCD backpack: 0x27, or 0x3F on some boards
#define LM75_ADDR 0x48 // LM75B temperature sensor, address pins A2-A0 at GND
#define LM75_TEMP 0x00 // LM75B register 0: temperature
// The LCD backpack: what each bit of the PCF8574 drives
#define LCD_RS (1U << 0) // P0: 0 = command, 1 = character
#define LCD_EN (1U << 2) // P2: enable, the LCD latches on its falling edge
#define LCD_BL (1U << 3) // P3: backlight. P4 to P7: D4 to D7
// The alarm: on above ALARM_ON, off again only below ALARM_OFF (hysteresis).
// Set ALARM_ON about 1.5 C above your room temperature, so a finger on the sensor trips it.
#define ALARM_ON 300 // 30.0 C
#define ALARM_OFF 285 // 28.5 C
#define LCD_COLS 16
// The profiler from Experiment 1
typedef struct { uint32_t start, last, min, max, count; } profile_t;
volatile profile_t p_read = { .min = 0xFFFFFFFF }; // One temperature read
volatile profile_t p_lcd = { .min = 0xFFFFFFFF }; // Writing one LCD line
// Results, for the Watch window
volatile uint32_t alarm; // 1 while the alarm is on
volatile int32_t max_tenths = -1000; // The highest temperature seen
volatile int16_t temp_raw; // The LM75B's two bytes, as one signed number
volatile int32_t temp_tenths; // The temperature in tenths of a degree: 235 = 23.5 C
void cycles_init(void)
{
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}
void prof_start(volatile profile_t *p) { p->start = DWT->CYCCNT; }
void prof_stop(volatile profile_t *p)
{
p->last = DWT->CYCCNT - p->start;
if (p->last < p->min) p->min = p->last;
if (p->last > p->max) p->max = p->last;
p->count++;
}
void i2c_init(void)
{
SYSCTL->RCGCI2C |= RCGC_I2C0;
SYSCTL->RCGCGPIO |= RCGC_GPIOB;
while ((SYSCTL->PRGPIO & RCGC_GPIOB) == 0) {}
while ((SYSCTL->PRI2C & RCGC_I2C0) == 0) {}
GPIOB->AFSEL |= I2C0SCL | I2C0SDA; // Driven by a peripheral...
GPIOB->PCTL = (GPIOB->PCTL & ~PCTL_PB23_MASK) | PCTL_PB23_I2C0; // ...I2C0
GPIOB->ODR |= I2C0SDA; // SDA open drain (not SCL)
GPIOB->DEN |= I2C0SCL | I2C0SDA;
I2C0->MCR = MCR_MFE; // I2C0 is a master
I2C0->MTPR = I2C_TPR; // SCL speed
}
// Start one step of a transfer and wait for it. Returns 0 on ACK, -1 on no ACK.
int i2c_run(uint32_t command)
{
I2C0->MCS = command;
while ((I2C0->MCS & MCS_BUSY) == 0) {} // BUSY rises a few cycles after the write...
while (I2C0->MCS & MCS_BUSY) {} // ...and falls when the byte is done
return (I2C0->MCS & MCS_ERROR) ? -1 : 0;
}
// Write one byte to a device: START, address + W, data, STOP
int i2c_write(uint8_t addr, uint8_t data)
{
I2C0->MSA = (uint32_t)addr << 1; // Address in bits 7:1, bit 0 = 0: write
I2C0->MDR = data;
return i2c_run(MCS_START | MCS_RUN | MCS_STOP);
}
// Read a 2-byte register: START, address + W, register number,
// repeated START, address + R, byte (ACK), byte (no ACK), STOP
int i2c_read_reg16(uint8_t addr, uint8_t reg, uint16_t *value)
{
I2C0->MSA = (uint32_t)addr << 1; // Write: which register
I2C0->MDR = reg;
if (i2c_run(MCS_START | MCS_RUN) < 0)
{
I2C0->MCS = MCS_STOP; // Nobody answered: release the bus
return -1;
}
I2C0->MSA = ((uint32_t)addr << 1) | 1; // Read: bit 0 = 1
if (i2c_run(MCS_START | MCS_RUN | MCS_ACK) < 0) // Repeated START, first byte, ACK it
{
I2C0->MCS = MCS_STOP;
return -1;
}
uint32_t high = I2C0->MDR;
i2c_run(MCS_RUN | MCS_STOP); // Second byte, no ACK (the last one), STOP
*value = (uint16_t)((high << 8) | I2C0->MDR);
return 0;
}
// A 1 ms clock from SysTick, for the LCD's delays
volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }
void delay_ms(uint32_t n)
{
uint32_t start = ms;
while (ms - start < n) {}
}
// One nibble on D7-D4 with an enable pulse: three bytes to the backpack
void lcd_nibble(uint8_t nibble, uint8_t rs)
{
uint8_t out = (uint8_t)((nibble << 4) | rs | LCD_BL);
i2c_write(LCD_ADDR, out); // Data and RS settle, E low
i2c_write(LCD_ADDR, out | LCD_EN); // E high
i2c_write(LCD_ADDR, out); // E low: the LCD latches the nibble
}
void lcd_command(uint8_t cmd)
{
lcd_nibble(cmd >> 4, 0);
lcd_nibble(cmd & 0x0F, 0);
if (cmd <= 0x02) delay_ms(2); // Clear and Home take 1.6 ms
}
uint32_t lcd_col; // The column the next character goes to
void lcd_data(char ch)
{
lcd_col++;
lcd_nibble((uint8_t)ch >> 4, LCD_RS);
lcd_nibble((uint8_t)ch & 0x0F, LCD_RS);
}
void lcd_init(void)
{
delay_ms(50); // Power-up
lcd_nibble(0x03, 0); delay_ms(5); // The HD44780's 4-bit start-up sequence
lcd_nibble(0x03, 0); delay_ms(1);
lcd_nibble(0x03, 0); delay_ms(1);
lcd_nibble(0x02, 0); delay_ms(1);
lcd_command(0x28); // 4-bit, 2 lines, 5x8 dots
lcd_command(0x0C); // Display on, cursor off
lcd_command(0x06); // Cursor moves right
lcd_command(0x01); // Clear
}
void lcd_set_cursor(uint8_t row, uint8_t col)
{
lcd_col = col;
lcd_command((uint8_t)((row == 0 ? 0x80 : 0xC0) + col));
}
void lcd_print(const char *s)
{
while (*s) lcd_data(*s++);
}
void lcd_tenths(int32_t t) // 235 -> "23.5", -45 -> "-4.5"
{
if (t < 0) { lcd_data('-'); t = -t; }
char digits[10];
int i = 0;
uint32_t whole = (uint32_t)t / 10;
do { digits[i++] = (char)('0' + whole % 10); whole /= 10; } while (whole);
while (i) lcd_data(digits[--i]);
lcd_data('.');
lcd_data((char)('0' + t % 10));
}
// One whole LCD line: label, value, unit, then spaces to the end of the line.
// Writing over the old text, instead of clearing the screen, keeps the display from flickering.
// Example: lcd_status(0, "Temp ", 235, " C") shows "Temp 23.5 C " on line 1.
void lcd_status(uint8_t row, const char *label, int32_t tenths, const char *unit)
{
// TODO 1: cursor to the start of the row, print the label, the value (lcd_tenths)
// and the unit, then spaces until lcd_col reaches LCD_COLS
}
void led_init(void)
{
SYSCTL->RCGCGPIO |= RCGC_GPIOF;
while ((SYSCTL->PRGPIO & RCGC_GPIOF) == 0) {}
GPIOF->DIR |= RED_LED;
GPIOF->DEN |= RED_LED;
}
// The LM75B sends its temperature as 11 bits in the top of two bytes, in 0.125 C steps.
// Shifting the signed 16-bit value right by 5 keeps the sign: the result is in eighths of a degree.
int lm75_read_tenths(int32_t *tenths)
{
uint16_t value;
if (i2c_read_reg16(LM75_ADDR, LM75_TEMP, &value) < 0)
return -1;
temp_raw = (int16_t)value;
int32_t eighths = temp_raw >> 5;
*tenths = eighths * 10 / 8;
return 0;
}
int main(void)
{
SysTick_Config(SystemCoreClock / 1000);
cycles_init();
i2c_init();
lcd_init();
led_init();
while (1)
{
int32_t t;
prof_start(&p_read);
int ok = lm75_read_tenths(&t);
prof_stop(&p_read);
if (ok == 0)
{
temp_tenths = t;
if (t > max_tenths) max_tenths = t;
// TODO 2: the alarm with hysteresis: turn it on when temp_tenths rises above
// ALARM_ON, and off only when it falls below ALARM_OFF
prof_start(&p_lcd);
lcd_status(0, "Temp ", temp_tenths, " C");
// TODO 3: line 2 shows the highest temperature, labelled "HOT! " while the
// alarm is on and "Max " when it's off; the red LED is on with the alarm
prof_stop(&p_lcd);
}
delay_ms(250);
}
}How the provided part works
- It is the Activity program without the scan.
lcd_data()now counts columns inlcd_col, andlcd_set_cursor()sets it, solcd_status()knows how many spaces to add. max_tenthskeeps the highest temperature seen;alarmis the alarm state, read in the Watch window.p_lcdtimes both LCD lines together.
What to write: the three TODOs
Each TODO is highlighted in the starter, exactly where its code goes. Write them in order: 1, 2, 3.
TODO 1: one whole line (lcd_status())
lcd_set_cursor(row, 0), thenlcd_print(label),lcd_tenths(tenths)andlcd_print(unit).- Then a
whileloop that writes' 'untillcd_colreachesLCD_COLS.
TODO 2: the alarm (the main loop)
- Two
ifs, straight from the table above: off and aboveALARM_ONturns it on; on and belowALARM_OFFturns it off.
TODO 3: line 2 and the LED (the main loop)
- One
lcd_status()call on row 1: the label isalarm ? "HOT! " : "Max ", the value ismax_tenths. - Set or clear
RED_LEDinGPIOF->DATAto matchalarm, changing only that pin.
Build, flash, and run. Warm the sensor until the alarm trips, then let go and watch it clear.
| Measurement | Value |
|---|---|
p_lcd.min, both lines (ms) | |
| Temperature when the alarm turned on, and when it turned off | |
With ALARM_OFF set equal to ALARM_ON: does the LED flicker near the threshold? |
- Does line 1 show the temperature and line 2 the maximum, with no leftover characters?
- Does the alarm turn on above
ALARM_ONand stay on until the temperature falls belowALARM_OFF? - What did you see with no hysteresis?
p_lcdis the slowest job so far. What would happen to Experiment 2's 1 kHz sampling if the LCD update ran inside its interrupt?