Periodic Sampling and a PC Dashboard
Data acquisition is the most common real-time job: measure something at a fixed rate, process each sample before the next one arrives, and pass the results on. In this experiment the LaunchPad samples a signal 500 times a second, filters it inside the ADC interrupt, and streams both traces to a live plot on the PC. Then you break it on purpose: sample too slowly and watch a signal turn into a different one, send too much and watch the link drop data.
This builds on two things you know: the ADC from ENCS4110, and the profiler from Experiment 1, which now measures the filter.
Objectives
- Start ADC conversions from a timer, so samples are evenly spaced without the CPU's help.
- Predict and observe aliasing when a signal is sampled below twice its frequency.
- Write a moving-average filter that costs the same time however long it is, and measure that time.
- Pass samples from an interrupt to
mainthrough a buffer, and stream them to a PC plot within the UART's budget.
Background
Sampling at a fixed rate
A sampled signal is only meaningful if the samples are evenly spaced: every calculation that follows (filters, frequencies, controllers) assumes the time between samples is exactly 1 / fs. Starting each conversion from software inside a loop gives uneven spacing, because the loop's time varies. Instead, a timer starts every conversion in hardware:
- Timer0A runs in periodic mode with
TAILR = SystemCoreClock / FS_HZ - 1, and itsTAOTEbit makes every time-out a trigger for the ADC. No timer interrupt is needed. - The ADC's
EMUXregister selects that trigger for sample sequencer 3 (value0x5: timer). - When the conversion is done, the sequencer raises an interrupt, and the handler reads the result.
The jitter of the sampling instants is now the jitter of a hardware timer: effectively zero. The handler's own latency (Experiment 1) only decides how soon the sample is processed, not when it was taken.
| Register | Field | Value | Meaning |
|---|---|---|---|
TIMER0->CTL | TAOTE (bit 5) | 1 | Each Timer A time-out triggers the ADC |
ADC0->EMUX | EM3 (bits 15:12) | 0x5 | Sequencer 3 starts on a timer trigger |
ADC0->SSMUX3 | MUX0 | 0 | Sample AIN0 (PE3) |
ADC0->SSCTL3 | END0, IE0 | 1, 1 | One sample, then interrupt |
Aliasing
The sampling theorem says a signal can be rebuilt from its samples only if the sampling rate is more than twice its highest frequency: fs > 2 fmax. Half the sampling rate, fs / 2, is the Nyquist frequency.
A frequency above the Nyquist frequency does not disappear: it folds back and shows up as a lower one, an alias. A sine of frequency f, sampled at fs, looks exactly like a sine of
falias = | f - k · fs |, for the whole number k that makes it smallest.
At fs = 500 Hz, a 450 Hz input gives the same samples as a 50 Hz one. Once sampled, no software can tell them apart. That is why real systems put an analog low-pass filter before the ADC.
A moving average in constant time
A moving average of the last N samples smooths noise:
y[n] = (x[n] + x[n-1] + … + x[n-N+1]) / N
Adding N numbers every sample costs time that grows with N. A running sum does it in constant time: add the new sample, subtract the one that just left the window, and keep the window in a circular array.
sum += x - window[idx]; // new sample in, oldest out
window[idx] = x;
idx = (idx + 1) & (N - 1); // wrap around (N is a power of 2)
y = sum >> SHIFT; // divide by N = 2^SHIFT with a shiftWith N a power of 2, the division is a shift and the wrap-around is a mask. A moving average also has a quirk worth seeing: it cancels a sine whose period fits exactly into the window, at fs / N and its multiples.
From the interrupt to main: a circular buffer
The UART is slow: one character takes 87 µs at 115200 baud. Sending from inside the ADC handler would make the handler longer than the sampling period (the lesson of Experiment 1). So the work is split:
- The handler (the producer) puts each result into a circular buffer and moves
head. main(the consumer) takes results out attailand sends them, as fast as the UART allows.
Only the handler writes head, and only main writes tail, so no locking is needed. If the buffer fills, the handler counts the sample in dropped instead of overwriting one main hasn't sent.
The UART's budget
At 115200 baud with 8 data bits, a start bit and a stop bit, the link carries 11,520 characters a second. Each line here, like 2051,2047\n, is up to 10 characters:
| Sampling rate | Characters per second | Share of the link |
|---|---|---|
| 500 Hz | about 5,000 | about 43% |
| 1000 Hz | about 10,000 | about 87% |
| 2000 Hz | about 20,000 | more than the link can carry |
Every real-time link has a budget like this. The ADC can sample far faster than the UART can report.
Activity
The LaunchPad samples a signal-generator sine at 500 Hz, computes an 8-sample moving average in the ADC interrupt, and streams both to a live plot on the PC.
Setting up
Use a new Keil project as in Experiment 1. On the PC, install Python 3, then the two libraries the plotter needs: pip install pyserial matplotlib. To use LabVIEW instead, see Using LabVIEW instead below.
Keep the input between 0 and 3.3 V
The ADC pins are not 5 V tolerant, and a negative voltage can damage them. Set the signal generator to a sine, 3 Vpp, 1.65 V offset and check it on the oscilloscope before connecting it.
Step 1: Wire it and add the definitions
| From | To | Note |
|---|---|---|
| Signal generator output | PE3 (AIN0) | Sine, 3 Vpp, 1.65 V offset, 50 Hz to start |
| Signal generator ground | LaunchPad GND | |
| Logic analyzer CH0 | PE1 (D0) | High while the ADC handler runs |
| Logic analyzer GND | LaunchPad GND |
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOA (1U << 0) // RCGCGPIO bit for Port A (UART0)
#define RCGC_GPIOE (1U << 4) // RCGCGPIO bit for Port E (analog input, debug pin)
#define RCGC_ADC0 (1U << 0) // RCGCADC bit for ADC0
#define RCGC_TIMER0 (1U << 0) // RCGCTIMER bit for Timer0
#define RCGC_UART0 (1U << 0) // RCGCUART bit for UART0
// Pins
#define AIN0 (1U << 3) // PE3: analog input 0, the signal we sample
#define D0 (1U << 1) // PE1: debug pin, high while the ADC handler runs
#define U0RX (1U << 0) // PA0, to the LaunchPad's USB serial port
#define U0TX (1U << 1) // PA1
#define PCTL_PA01_MASK (0xFFU << 0) // PA0's and PA1's fields in GPIOA->PCTL
#define PCTL_PA01_UART (0x11U << 0) // 1 selects U0RX and U0TX
#define PORTE_BITS(p) (*((volatile uint32_t *)(GPIOE_BASE + ((p) << 2))))
#define PIN_HIGH(p) (PORTE_BITS(p) = (p))
#define PIN_LOW(p) (PORTE_BITS(p) = 0)
// ADC0, sample sequencer 3 (one sample per trigger)
#define SS3 (1U << 3) // ACTSS, IM, ISC: sequencer 3's bit
#define EMUX_SS3 (0xFU << 12) // EMUX: sequencer 3's trigger field
#define EMUX_SS3_TIMER (0x5U << 12) // 0x5 in that field: started by a timer
#define SSCTL_END0 (1U << 1) // SSCTL3: the first sample is the last
#define SSCTL_IE0 (1U << 2) // SSCTL3: interrupt when it's done
// Timer0: no interrupt of its own, it only starts the ADC
#define CFG_32BIT 0x0
#define TAMR_PERIODIC 0x2
#define CTL_TAEN (1U << 0) // CTL: Timer A enable
#define CTL_TAOTE (1U << 5) // CTL: Timer A output trigger: each time-out starts the ADC
// UART0: 115200 baud, 8 data bits, FIFOs on (as in ENCS4110 Experiment 10)
#define CTL_UARTEN (1U << 0)
#define CTL_TXE (1U << 8)
#define CTL_RXE (1U << 9)
#define LCRH_WLEN_8 (0x3U << 5)
#define LCRH_FEN (1U << 4)
#define FR_TXFF (1U << 5) // FR: transmit FIFO full
#define BAUD_IBRD 27 // 50,000,000 / (16 * 115200) = 27.1267
#define BAUD_FBRD 8 // 0.1267 * 64 + 0.5 = 8
// Sampling
#define FS_HZ 500 // Sampling rate. Nyquist frequency: FS_HZ / 2 = 250 Hz
#define FS_LOAD (SystemCoreClock / FS_HZ - 1)
#define AVG_N 8 // Moving-average length: a power of 2
#define AVG_SHIFT 3 // log2(AVG_N): divide by shifting
#define BUF_SIZE 128 // Samples waiting for the UART: a power of 2
// The profiler from Experiment 1
typedef struct { uint32_t start, last, min, max, count; } profile_t;
volatile profile_t p_isr = { .min = 0xFFFFFFFF }; // The ADC handler, filter included
// Samples on their way from the ADC handler to main()
volatile uint16_t buf_raw[BUF_SIZE];
volatile uint16_t buf_avg[BUF_SIZE];
volatile uint32_t head; // Written only by the handler
volatile uint32_t tail; // Written only by main()
volatile uint32_t dropped; // Samples lost because the buffer was full
volatile uint32_t samples; // Samples taken so farEMUX_SS3_TIMERandCTL_TAOTEare the two settings that let the timer start conversions on its own.FS_HZis the sampling rate;FS_LOADturns it into the timer's reload value.AVG_NandAVG_SHIFTset the moving average: 8 samples, divided by shifting right 3.buf_raw,buf_avg,headandtailare the circular buffer between the handler andmain.droppedcounts samples lost when it is full.
Step 2: Add the profiler and the setup functions
The profiler is the one you wrote in Experiment 1's Task:
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++;
}// PE3 as analog input 0, PE1 as the debug pin
void pins_init(void)
{
SYSCTL->RCGCGPIO |= RCGC_GPIOE;
while ((SYSCTL->PRGPIO & RCGC_GPIOE) == 0) {}
GPIOE->AFSEL |= AIN0; // Not plain GPIO
GPIOE->DEN &= ~AIN0; // Digital input off
GPIOE->AMSEL |= AIN0; // Analog on
GPIOE->DIR |= D0;
GPIOE->DEN |= D0;
}
// ADC0 sequencer 3: one sample of AIN0 each time Timer0 times out
void adc_init(void)
{
SYSCTL->RCGCADC |= RCGC_ADC0;
while ((SYSCTL->PRADC & RCGC_ADC0) == 0) {}
ADC0->ACTSS &= ~SS3; // Off while we set it up
ADC0->EMUX = (ADC0->EMUX & ~EMUX_SS3) | EMUX_SS3_TIMER; // Trigger: a timer
ADC0->SSMUX3 = 0; // Input: AIN0
ADC0->SSCTL3 = SSCTL_END0 | SSCTL_IE0;
ADC0->ISC = SS3;
ADC0->IM |= SS3; // Interrupt to the NVIC
ADC0->ACTSS |= SS3;
NVIC_EnableIRQ(ADC0SS3_IRQn);
}
// Timer0A times out FS_HZ times a second; each time-out starts one conversion
void sample_timer_init(void)
{
SYSCTL->RCGCTIMER |= RCGC_TIMER0;
while ((SYSCTL->PRTIMER & RCGC_TIMER0) == 0) {}
TIMER0->CTL = 0;
TIMER0->CFG = CFG_32BIT;
TIMER0->TAMR = TAMR_PERIODIC;
TIMER0->TAILR = FS_LOAD;
TIMER0->CTL = CTL_TAEN | CTL_TAOTE; // Start, and trigger the ADC
}
void uart_init(void)
{
SYSCTL->RCGCUART |= RCGC_UART0;
SYSCTL->RCGCGPIO |= RCGC_GPIOA;
while ((SYSCTL->PRUART & RCGC_UART0) == 0) {}
while ((SYSCTL->PRGPIO & RCGC_GPIOA) == 0) {}
GPIOA->AFSEL |= U0RX | U0TX;
GPIOA->PCTL = (GPIOA->PCTL & ~PCTL_PA01_MASK) | PCTL_PA01_UART;
GPIOA->DEN |= U0RX | U0TX;
UART0->CTL = 0;
UART0->IBRD = BAUD_IBRD;
UART0->FBRD = BAUD_FBRD;
UART0->LCRH = LCRH_WLEN_8 | LCRH_FEN;
UART0->CC = 0; // Clocked from the system clock
UART0->CTL = CTL_UARTEN | CTL_TXE | CTL_RXE;
}pins_init()turns PE3 into an analog input: alternate function on, digital off, analog on.adc_init()sets sequencer 3 to one sample of AIN0, started by a timer, with an interrupt when done. The sequencer is disabled while it is set up.sample_timer_init()starts Timer0A withTAOTEset and no interrupt: its only job is to start conversions.uart_init()is ENCS4110's 115200-baud UART0 setup, on the LaunchPad's USB serial port.
Step 3: Add the UART output and the ADC handler
void uart_putc(char c)
{
while (UART0->FR & FR_TXFF) {} // Wait for room in the transmit FIFO
UART0->DR = (uint32_t)c;
}
// A number in decimal, without printf: printf is large and slow
void uart_dec(uint32_t n)
{
char digits[10];
int i = 0;
do { digits[i++] = (char)('0' + n % 10); n /= 10; } while (n);
while (i) uart_putc(digits[--i]);
}uart_dec()prints a number in decimal withoutprintf, which is large and slow.
// Runs FS_HZ times a second, right after each conversion: read, filter, queue
void ADC0SS3_Handler(void)
{
static uint16_t window[AVG_N]; // The last AVG_N samples
static uint32_t sum; // Their sum
static uint32_t idx; // Where the oldest one is
PIN_HIGH(D0);
prof_start(&p_isr);
uint32_t x = ADC0->SSFIFO3 & 0xFFF; // 12-bit result, 0 to 4095
ADC0->ISC = SS3;
// Moving average with a running sum: two additions however long the window is
sum += x - window[idx];
window[idx] = (uint16_t)x;
idx = (idx + 1) & (AVG_N - 1);
uint32_t avg = sum >> AVG_SHIFT;
// Queue both for main() to send. If the buffer is full, count the loss.
uint32_t next = (head + 1) & (BUF_SIZE - 1);
if (next == tail)
dropped++;
else
{
buf_raw[head] = (uint16_t)x;
buf_avg[head] = (uint16_t)avg;
head = next;
}
samples++;
prof_stop(&p_isr);
PIN_LOW(D0);
}- The handler reads the result and clears the flag first, then filters with the running sum.
next == tailmeans the buffer is full: the sample is counted as dropped, never overwritten.p_isrmeasures the whole handler. D0 shows it on the analyzer.
Step 4: Write main
int main(void)
{
cycles_init();
pins_init();
uart_init();
adc_init();
sample_timer_init(); // Last: sampling starts now
while (1)
{
// Send every queued sample as one text line: "raw,average\n"
while (tail != head)
{
uart_dec(buf_raw[tail]);
uart_putc(',');
uart_dec(buf_avg[tail]);
uart_putc('\n');
tail = (tail + 1) & (BUF_SIZE - 1);
}
}
}sample_timer_init()comes last, so no conversion starts before the UART and the ADC are ready.- The loop empties the buffer as fast as the UART takes characters. Each line is
raw,average.
Build, flash, and run. Then start the plotter on the PC, with the LaunchPad's serial port (Device Manager on Windows; ls /dev/tty.usbmodem* on macOS). Close Keil's or PuTTY's serial window first: only one program can open the port.
#!/usr/bin/env python3
"""Experiment 2 dashboard: a live plot of the "raw,average" lines the LaunchPad sends.
Install once: pip install pyserial matplotlib
Run: python plot.py COM5 (Windows; see Device Manager for the number)
python plot.py /dev/tty.usbmodem0E2... (macOS)
Options: --fs 500 the sampling rate in the firmware (FS_HZ)
--seconds 1 how much history to show
"""
import argparse
from collections import deque
def parse_line(line):
"""'1234,1200' -> (1234, 1200). Anything else (a half line, noise) -> None."""
parts = line.strip().split(",")
if len(parts) != 2 or not all(p.isdigit() for p in parts):
return None
return int(parts[0]), int(parts[1])
def frequency(values, fs):
"""Estimate the main frequency from upward crossings of the mean, in Hz."""
if len(values) < 3:
return 0.0
mean = sum(values) / len(values)
crossings = [i for i in range(1, len(values))
if values[i - 1] < mean <= values[i]]
if len(crossings) < 2:
return 0.0
periods = (crossings[-1] - crossings[0]) / (len(crossings) - 1) # in samples
return fs / periods
def peak_to_peak(values):
return max(values) - min(values) if values else 0
def main():
import serial # pyserial
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("port")
ap.add_argument("--fs", type=float, default=500)
ap.add_argument("--seconds", type=float, default=1)
args = ap.parse_args()
n = int(args.fs * args.seconds)
raw, avg = deque(maxlen=n), deque(maxlen=n)
link = serial.Serial(args.port, 115200, timeout=0)
pending = ""
fig, ax = plt.subplots(figsize=(10, 5))
raw_line, = ax.plot([], [], label="raw", linewidth=1)
avg_line, = ax.plot([], [], label="moving average", linewidth=2)
ax.set_xlim(0, args.seconds * 1000)
ax.set_ylim(0, 4095)
ax.set_xlabel("time (ms)")
ax.set_ylabel("ADC reading (0 to 4095)")
ax.legend(loc="upper right")
readout = ax.text(0.01, 0.97, "", transform=ax.transAxes, va="top", family="monospace")
def update(_frame):
nonlocal pending
pending += link.read(link.in_waiting or 1).decode("ascii", errors="ignore")
*lines, pending = pending.split("\n") # keep the unfinished last line
for line in lines:
sample = parse_line(line)
if sample:
raw.append(sample[0])
avg.append(sample[1])
t = [i * 1000 / args.fs for i in range(len(raw))]
raw_line.set_data(t, list(raw))
avg_line.set_data(t, list(avg))
readout.set_text(f"f ~ {frequency(list(raw), args.fs):6.1f} Hz "
f"p-p raw {peak_to_peak(raw):4d} p-p avg {peak_to_peak(avg):4d}")
return raw_line, avg_line, readout
_anim = FuncAnimation(fig, update, interval=50, blit=False, cache_frame_data=False)
plt.show()
if __name__ == "__main__":
main()python plot.py COM5 --fs 500Check: the plot shows the 50 Hz sine as two traces, raw and smoothed, and the readout says about 50 Hz. In the Watch window, samples climbs by 500 a second and dropped stays 0. On the analyzer, D0 pulses are exactly 2 ms apart.
Then try: sweep the generator from 50 Hz up to 550 Hz and back, watching the readout. Below 250 Hz it follows the generator; above 250 Hz the frequency on the plot goes down while the generator's goes up.
| Generator frequency | Predicted alias at fs = 500 Hz | Frequency on the plot |
|---|---|---|
| 50 Hz | 50 Hz | |
| 200 Hz | 200 Hz | |
| 300 Hz | 200 Hz | |
| 450 Hz | 50 Hz | |
| 520 Hz | 20 Hz |
| Measurement | Value |
|---|---|
p_isr.max, the handler's worst case (cycles and µs) | |
| D0 pulse width on the analyzer | |
| Share of the 2 ms sampling period the handler uses |
- Does the plot show both traces, with the right frequency at 50 Hz?
- Did the frequency on the plot fold back above 250 Hz, as predicted?
- Does
droppedstay at 0 at 500 Hz? - Can you say why the UART is not used inside the handler?
More to try (optional)
| Try this | What you'll see |
|---|---|
| Set the generator to 62.5 Hz | The average trace goes nearly flat: 62.5 Hz is fs / 8, and its period fits exactly into the 8-sample window. |
Set AVG_N to 32 and AVG_SHIFT to 5 | Smoother, but the average lags behind the raw trace. p_isr barely changes: the running sum costs the same for any N. |
Set FS_HZ to 2000 (and run the plotter with --fs 2000) | The UART can't keep up: dropped climbs and the plot has gaps. |
Set FS_HZ to 1000 | About 87% of the link: still no drops, but little margin. |
The complete program
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOA (1U << 0) // RCGCGPIO bit for Port A (UART0)
#define RCGC_GPIOE (1U << 4) // RCGCGPIO bit for Port E (analog input, debug pin)
#define RCGC_ADC0 (1U << 0) // RCGCADC bit for ADC0
#define RCGC_TIMER0 (1U << 0) // RCGCTIMER bit for Timer0
#define RCGC_UART0 (1U << 0) // RCGCUART bit for UART0
// Pins
#define AIN0 (1U << 3) // PE3: analog input 0, the signal we sample
#define D0 (1U << 1) // PE1: debug pin, high while the ADC handler runs
#define U0RX (1U << 0) // PA0, to the LaunchPad's USB serial port
#define U0TX (1U << 1) // PA1
#define PCTL_PA01_MASK (0xFFU << 0) // PA0's and PA1's fields in GPIOA->PCTL
#define PCTL_PA01_UART (0x11U << 0) // 1 selects U0RX and U0TX
#define PORTE_BITS(p) (*((volatile uint32_t *)(GPIOE_BASE + ((p) << 2))))
#define PIN_HIGH(p) (PORTE_BITS(p) = (p))
#define PIN_LOW(p) (PORTE_BITS(p) = 0)
// ADC0, sample sequencer 3 (one sample per trigger)
#define SS3 (1U << 3) // ACTSS, IM, ISC: sequencer 3's bit
#define EMUX_SS3 (0xFU << 12) // EMUX: sequencer 3's trigger field
#define EMUX_SS3_TIMER (0x5U << 12) // 0x5 in that field: started by a timer
#define SSCTL_END0 (1U << 1) // SSCTL3: the first sample is the last
#define SSCTL_IE0 (1U << 2) // SSCTL3: interrupt when it's done
// Timer0: no interrupt of its own, it only starts the ADC
#define CFG_32BIT 0x0
#define TAMR_PERIODIC 0x2
#define CTL_TAEN (1U << 0) // CTL: Timer A enable
#define CTL_TAOTE (1U << 5) // CTL: Timer A output trigger: each time-out starts the ADC
// UART0: 115200 baud, 8 data bits, FIFOs on (as in ENCS4110 Experiment 10)
#define CTL_UARTEN (1U << 0)
#define CTL_TXE (1U << 8)
#define CTL_RXE (1U << 9)
#define LCRH_WLEN_8 (0x3U << 5)
#define LCRH_FEN (1U << 4)
#define FR_TXFF (1U << 5) // FR: transmit FIFO full
#define BAUD_IBRD 27 // 50,000,000 / (16 * 115200) = 27.1267
#define BAUD_FBRD 8 // 0.1267 * 64 + 0.5 = 8
// Sampling
#define FS_HZ 500 // Sampling rate. Nyquist frequency: FS_HZ / 2 = 250 Hz
#define FS_LOAD (SystemCoreClock / FS_HZ - 1)
#define AVG_N 8 // Moving-average length: a power of 2
#define AVG_SHIFT 3 // log2(AVG_N): divide by shifting
#define BUF_SIZE 128 // Samples waiting for the UART: a power of 2
// The profiler from Experiment 1
typedef struct { uint32_t start, last, min, max, count; } profile_t;
volatile profile_t p_isr = { .min = 0xFFFFFFFF }; // The ADC handler, filter included
// Samples on their way from the ADC handler to main()
volatile uint16_t buf_raw[BUF_SIZE];
volatile uint16_t buf_avg[BUF_SIZE];
volatile uint32_t head; // Written only by the handler
volatile uint32_t tail; // Written only by main()
volatile uint32_t dropped; // Samples lost because the buffer was full
volatile uint32_t samples; // Samples taken so far
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++;
}
// PE3 as analog input 0, PE1 as the debug pin
void pins_init(void)
{
SYSCTL->RCGCGPIO |= RCGC_GPIOE;
while ((SYSCTL->PRGPIO & RCGC_GPIOE) == 0) {}
GPIOE->AFSEL |= AIN0; // Not plain GPIO
GPIOE->DEN &= ~AIN0; // Digital input off
GPIOE->AMSEL |= AIN0; // Analog on
GPIOE->DIR |= D0;
GPIOE->DEN |= D0;
}
// ADC0 sequencer 3: one sample of AIN0 each time Timer0 times out
void adc_init(void)
{
SYSCTL->RCGCADC |= RCGC_ADC0;
while ((SYSCTL->PRADC & RCGC_ADC0) == 0) {}
ADC0->ACTSS &= ~SS3; // Off while we set it up
ADC0->EMUX = (ADC0->EMUX & ~EMUX_SS3) | EMUX_SS3_TIMER; // Trigger: a timer
ADC0->SSMUX3 = 0; // Input: AIN0
ADC0->SSCTL3 = SSCTL_END0 | SSCTL_IE0;
ADC0->ISC = SS3;
ADC0->IM |= SS3; // Interrupt to the NVIC
ADC0->ACTSS |= SS3;
NVIC_EnableIRQ(ADC0SS3_IRQn);
}
// Timer0A times out FS_HZ times a second; each time-out starts one conversion
void sample_timer_init(void)
{
SYSCTL->RCGCTIMER |= RCGC_TIMER0;
while ((SYSCTL->PRTIMER & RCGC_TIMER0) == 0) {}
TIMER0->CTL = 0;
TIMER0->CFG = CFG_32BIT;
TIMER0->TAMR = TAMR_PERIODIC;
TIMER0->TAILR = FS_LOAD;
TIMER0->CTL = CTL_TAEN | CTL_TAOTE; // Start, and trigger the ADC
}
void uart_init(void)
{
SYSCTL->RCGCUART |= RCGC_UART0;
SYSCTL->RCGCGPIO |= RCGC_GPIOA;
while ((SYSCTL->PRUART & RCGC_UART0) == 0) {}
while ((SYSCTL->PRGPIO & RCGC_GPIOA) == 0) {}
GPIOA->AFSEL |= U0RX | U0TX;
GPIOA->PCTL = (GPIOA->PCTL & ~PCTL_PA01_MASK) | PCTL_PA01_UART;
GPIOA->DEN |= U0RX | U0TX;
UART0->CTL = 0;
UART0->IBRD = BAUD_IBRD;
UART0->FBRD = BAUD_FBRD;
UART0->LCRH = LCRH_WLEN_8 | LCRH_FEN;
UART0->CC = 0; // Clocked from the system clock
UART0->CTL = CTL_UARTEN | CTL_TXE | CTL_RXE;
}
void uart_putc(char c)
{
while (UART0->FR & FR_TXFF) {} // Wait for room in the transmit FIFO
UART0->DR = (uint32_t)c;
}
// A number in decimal, without printf: printf is large and slow
void uart_dec(uint32_t n)
{
char digits[10];
int i = 0;
do { digits[i++] = (char)('0' + n % 10); n /= 10; } while (n);
while (i) uart_putc(digits[--i]);
}
// Runs FS_HZ times a second, right after each conversion: read, filter, queue
void ADC0SS3_Handler(void)
{
static uint16_t window[AVG_N]; // The last AVG_N samples
static uint32_t sum; // Their sum
static uint32_t idx; // Where the oldest one is
PIN_HIGH(D0);
prof_start(&p_isr);
uint32_t x = ADC0->SSFIFO3 & 0xFFF; // 12-bit result, 0 to 4095
ADC0->ISC = SS3;
// Moving average with a running sum: two additions however long the window is
sum += x - window[idx];
window[idx] = (uint16_t)x;
idx = (idx + 1) & (AVG_N - 1);
uint32_t avg = sum >> AVG_SHIFT;
// Queue both for main() to send. If the buffer is full, count the loss.
uint32_t next = (head + 1) & (BUF_SIZE - 1);
if (next == tail)
dropped++;
else
{
buf_raw[head] = (uint16_t)x;
buf_avg[head] = (uint16_t)avg;
head = next;
}
samples++;
prof_stop(&p_isr);
PIN_LOW(D0);
}
int main(void)
{
cycles_init();
pins_init();
uart_init();
adc_init();
sample_timer_init(); // Last: sampling starts now
while (1)
{
// Send every queued sample as one text line: "raw,average\n"
while (tail != head)
{
uart_dec(buf_raw[tail]);
uart_putc(',');
uart_dec(buf_avg[tail]);
uart_putc('\n');
tail = (tail + 1) & (BUF_SIZE - 1);
}
}
}Common problems
| Symptom | Cause and fix |
|---|---|
samples stays 0 | The timer isn't triggering: check CTL_TAOTE in TIMER0->CTL and EMUX_SS3_TIMER in ADC0->EMUX, and that the handler is named ADC0SS3_Handler. |
| The readings sit at 0 or 4095 | The input is outside 0 to 3.3 V, or the generator's ground isn't connected to the LaunchPad's. |
| The plotter says the port is busy | Another program (Keil's serial window, PuTTY) has it open. Close it. |
The plot is empty but samples climbs | Wrong port name, or the plotter started before the board: restart it. |
| The frequency readout jumps around | The input is very small or noisy: raise the amplitude, keeping within 0 to 3.3 V. |
Using LabVIEW instead
The board doesn't care what reads the serial port. In LabVIEW, the same dashboard is a single loop:
- VISA Configure Serial Port: the LaunchPad's port, 115200 baud, termination character enabled (line feed).
- In a While Loop: VISA Read, then Scan From String with the format
%d,%dto split the two numbers. - Wire both numbers to a Waveform Chart, with history length 500, and add a Stop button.
- After the loop, VISA Close.
Task
Smooth a potentiometer: the knob that will set the motor's speed in later experiments. Sample it at 1 kHz, filter it with a first-order IIR filter, and send only 50 readings a second to the PC. Then choose the filter strength by measuring the trade-off between noise and delay.
The IIR filter
A first-order IIR (infinite impulse response) filter needs no window at all, just its last output:
y[n] = y[n-1] + (x[n] - y[n-1]) / 2K
Each new sample moves the output a fraction 1 / 2K of the way toward it. In integers, keep the output scaled up by 2K in a variable y_q so no precision is lost:
y_q = y_q + x - (y_q >> K) and y = y_q >> K
A larger K means smoother output, but slower to follow a change: after a sudden step, y reaches 63% of the way in 2K samples and 95% in about 3 · 2K.
Wire the potentiometer's ends to 3.3 V and GND, and its wiper to PE3, instead of the signal generator.
The starter program
Start from this program. It compiles and runs, but sends the raw value as the filtered one, 1000 times a second: the three TODOs are yours.
// Experiment 2 Task: a smooth potentiometer reading, streamed to the PC 50 times a second.
// Write the three TODOs (highlighted). The rest is the Activity program, adapted: don't change it.
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOA (1U << 0) // RCGCGPIO bit for Port A (UART0)
#define RCGC_GPIOE (1U << 4) // RCGCGPIO bit for Port E (analog input, debug pin)
#define RCGC_ADC0 (1U << 0) // RCGCADC bit for ADC0
#define RCGC_TIMER0 (1U << 0) // RCGCTIMER bit for Timer0
#define RCGC_UART0 (1U << 0) // RCGCUART bit for UART0
// Pins
#define AIN0 (1U << 3) // PE3: analog input 0, the potentiometer's wiper
#define U0RX (1U << 0) // PA0, to the LaunchPad's USB serial port
#define U0TX (1U << 1) // PA1
#define PCTL_PA01_MASK (0xFFU << 0) // PA0's and PA1's fields in GPIOA->PCTL
#define PCTL_PA01_UART (0x11U << 0) // 1 selects U0RX and U0TX
// ADC0, sample sequencer 3 (one sample per trigger)
#define SS3 (1U << 3) // ACTSS, IM, ISC: sequencer 3's bit
#define EMUX_SS3 (0xFU << 12) // EMUX: sequencer 3's trigger field
#define EMUX_SS3_TIMER (0x5U << 12) // 0x5 in that field: started by a timer
#define SSCTL_END0 (1U << 1) // SSCTL3: the first sample is the last
#define SSCTL_IE0 (1U << 2) // SSCTL3: interrupt when it's done
// Timer0: no interrupt of its own, it only starts the ADC
#define CFG_32BIT 0x0
#define TAMR_PERIODIC 0x2
#define CTL_TAEN (1U << 0) // CTL: Timer A enable
#define CTL_TAOTE (1U << 5) // CTL: Timer A output trigger: each time-out starts the ADC
// UART0: 115200 baud, 8 data bits, FIFOs on (as in ENCS4110 Experiment 10)
#define CTL_UARTEN (1U << 0)
#define CTL_TXE (1U << 8)
#define CTL_RXE (1U << 9)
#define LCRH_WLEN_8 (0x3U << 5)
#define LCRH_FEN (1U << 4)
#define FR_TXFF (1U << 5) // FR: transmit FIFO full
#define BAUD_IBRD 27 // 50,000,000 / (16 * 115200) = 27.1267
#define BAUD_FBRD 8 // 0.1267 * 64 + 0.5 = 8
// Sampling
#define FS_HZ 1000 // Sampling rate: 1 kHz
#define FS_LOAD (SystemCoreClock / FS_HZ - 1)
#define FILTER_K 4 // IIR filter strength: each new sample counts 1/2^K
#define SEND_EVERY 1 // TODO 3: send 50 lines a second, not FS_HZ
#define BUF_SIZE 128 // Samples waiting for the UART: a power of 2
// The profiler from Experiment 1
typedef struct { uint32_t start, last, min, max, count; } profile_t;
volatile profile_t p_isr = { .min = 0xFFFFFFFF }; // The ADC handler, filter included
volatile uint32_t y_q; // The filter's state: the output times 2^FILTER_K
uint32_t send_count; // Samples since the last one queued
// Samples on their way from the ADC handler to main()
volatile uint16_t buf_raw[BUF_SIZE];
volatile uint16_t buf_avg[BUF_SIZE];
volatile uint32_t head; // Written only by the handler
volatile uint32_t tail; // Written only by main()
volatile uint32_t dropped; // Samples lost because the buffer was full
volatile uint32_t samples; // Samples taken so far
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++;
}
// PE3 as analog input 0
void pins_init(void)
{
SYSCTL->RCGCGPIO |= RCGC_GPIOE;
while ((SYSCTL->PRGPIO & RCGC_GPIOE) == 0) {}
GPIOE->AFSEL |= AIN0; // Not plain GPIO
GPIOE->DEN &= ~AIN0; // Digital input off
GPIOE->AMSEL |= AIN0; // Analog on
}
// ADC0 sequencer 3: one sample of AIN0 each time Timer0 times out
void adc_init(void)
{
SYSCTL->RCGCADC |= RCGC_ADC0;
while ((SYSCTL->PRADC & RCGC_ADC0) == 0) {}
ADC0->ACTSS &= ~SS3; // Off while we set it up
ADC0->EMUX = (ADC0->EMUX & ~EMUX_SS3) | EMUX_SS3_TIMER; // Trigger: a timer
ADC0->SSMUX3 = 0; // Input: AIN0
ADC0->SSCTL3 = SSCTL_END0 | SSCTL_IE0;
ADC0->ISC = SS3;
ADC0->IM |= SS3; // Interrupt to the NVIC
ADC0->ACTSS |= SS3;
NVIC_EnableIRQ(ADC0SS3_IRQn);
}
// Timer0A times out FS_HZ times a second; each time-out starts one conversion
void sample_timer_init(void)
{
SYSCTL->RCGCTIMER |= RCGC_TIMER0;
while ((SYSCTL->PRTIMER & RCGC_TIMER0) == 0) {}
TIMER0->CTL = 0;
TIMER0->CFG = CFG_32BIT;
TIMER0->TAMR = TAMR_PERIODIC;
TIMER0->TAILR = FS_LOAD;
TIMER0->CTL = CTL_TAEN | CTL_TAOTE; // Start, and trigger the ADC
}
void uart_init(void)
{
SYSCTL->RCGCUART |= RCGC_UART0;
SYSCTL->RCGCGPIO |= RCGC_GPIOA;
while ((SYSCTL->PRUART & RCGC_UART0) == 0) {}
while ((SYSCTL->PRGPIO & RCGC_GPIOA) == 0) {}
GPIOA->AFSEL |= U0RX | U0TX;
GPIOA->PCTL = (GPIOA->PCTL & ~PCTL_PA01_MASK) | PCTL_PA01_UART;
GPIOA->DEN |= U0RX | U0TX;
UART0->CTL = 0;
UART0->IBRD = BAUD_IBRD;
UART0->FBRD = BAUD_FBRD;
UART0->LCRH = LCRH_WLEN_8 | LCRH_FEN;
UART0->CC = 0; // Clocked from the system clock
UART0->CTL = CTL_UARTEN | CTL_TXE | CTL_RXE;
}
void uart_putc(char c)
{
while (UART0->FR & FR_TXFF) {} // Wait for room in the transmit FIFO
UART0->DR = (uint32_t)c;
}
// A number in decimal, without printf: printf is large and slow
void uart_dec(uint32_t n)
{
char digits[10];
int i = 0;
do { digits[i++] = (char)('0' + n % 10); n /= 10; } while (n);
while (i) uart_putc(digits[--i]);
}
// Runs FS_HZ times a second, right after each conversion: read, filter, queue
void ADC0SS3_Handler(void)
{
prof_start(&p_isr);
uint32_t x = ADC0->SSFIFO3 & 0xFFF; // 12-bit result, 0 to 4095
ADC0->ISC = SS3;
uint32_t y = x; // The filtered value. Until TODO 1 it is just the raw sample.
// TODO 1: the IIR filter. Add x to y_q and take away y_q >> FILTER_K,
// then make y the new y_q >> FILTER_K
samples++;
// TODO 2: add 1 to send_count. While it is below SEND_EVERY, stop the profile
// and return without queuing. Otherwise reset it to 0 and carry on.
uint32_t next = (head + 1) & (BUF_SIZE - 1);
if (next == tail)
dropped++;
else
{
buf_raw[head] = (uint16_t)x;
buf_avg[head] = (uint16_t)y;
head = next;
}
prof_stop(&p_isr);
}
int main(void)
{
cycles_init();
pins_init();
uart_init();
adc_init();
sample_timer_init(); // Last: sampling starts now
while (1)
{
// Send every queued sample as one text line: "raw,filtered\n"
while (tail != head)
{
uart_dec(buf_raw[tail]);
uart_putc(',');
uart_dec(buf_avg[tail]);
uart_putc('\n');
tail = (tail + 1) & (BUF_SIZE - 1);
}
}
}How the provided part works
- It is the Activity program at 1 kHz, without the debug pin. The handler now ends in your filter and a decimation step instead of the moving average.
y_qis the filter's state, kept between calls.send_countcounts samples since the last one queued.p_isrstill times the whole handler, so you can see what your filter costs.
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: the filter (the handler)
- Two lines, straight from the formula above: update
y_q, then setyfrom it.
TODO 2: send fewer samples (the handler)
- Add 1 to
send_count. If it is still belowSEND_EVERY, callprof_stop(&p_isr)andreturn. - Otherwise set
send_countback to 0 and let the queuing below run.
TODO 3: how many (SEND_EVERY)
- 1000 samples a second, 50 lines a second: write
SEND_EVERYin terms ofFS_HZ, so it stays right if the rate changes.
Build, flash, and run the plotter with --fs 50: that is now the rate lines arrive at, not the sampling rate.
Fill this in for K = 2, 4 and 6, changing FILTER_K and rebuilding each time.
FILTER_K | Peak-to-peak at rest: raw | Peak-to-peak at rest: filtered | Time to follow a quick turn of the knob (ms) |
|---|---|---|---|
| 2 | |||
| 4 | |||
| 6 |
- Does the filtered trace follow the knob, smoothly?
- Do 50 lines a second arrive (the plotter's x-axis spans 1 s with
--fs 50)? - Which K would you pick for a motor speed knob, and why?
- How many cycles does the handler take with your filter, compared with the moving average?