Simvik

Receive from a GPS module, from its interface description

Set the baud rate divider and frame format the module's datasheet gives, with only the receiver enabled, and read one NMEA sentence. A medium embedded C…

medium · Reading datasheets and schematics · datasheets · driver · uart

A GPS module sends position sentences to UART1. Working from the Datasheet excerpt below, write:

  • gps_uart_init(), which sets the baud rate divider and frame format the module needs and enables the UART with only the receiver on.
  • gps_read_line(buf, max), which waits for the next sentence and copies it into buf without its CR LF, as a string. It skips anything before the $, stores at most max − 1 characters, and returns the sentence's length.

Datasheet excerpt

Serial interface (GPS module datasheet)

ParameterValue
Baud rate9600 (default)
Frame8 data bits, no parity, 1 stop bit, least significant bit first
OutputNMEA 0183 sentences, each starting with $ and ending with CR LF (\r\n), at most 82 characters

USART1 (microcontroller reference manual)

USART1's kernel clock on this board is 16 MHz.

OffsetRegisterDescription
0x00SRbit 5 RXNE: DR holds a received byte. bit 3 ORE: overrun
0x04DRthe received byte; reading it clears RXNE
0x08BRRbaud rate divider: f_CK / baud, rounded to the nearest integer
0x0CCR1bit 13 UE: enable. bit 12 M: 0 = 8 data bits, 1 = 9. bit 10 PCE: parity. bit 3 TE: transmitter. bit 2 RE: receiver

The module's RX pin is not connected, so the microcontroller's transmitter stays off.

Starter code

void gps_uart_init(void) {
  UART1->BRR = UART_CLOCK / GPS_BAUD;
  UART1->CR1 = UART_CR1_UE | UART_CR1_TE | UART_CR1_RE;
}

int gps_read_line(char *buf, int max) {
  int n = 0;
  for (;;) {
    while (!(UART1->SR & UART_SR_RXNE)) {
    }
    char c = (char)UART1->DR;
    if (c == '\n') break;
    if (n < max - 1) buf[n++] = c;
  }
  buf[n] = '\0';
  return n;
}

Example tests

One sentence

gps_uart_init();
char line[83];
int n = gps_read_line(line, sizeof line);
printf("BRR %u CR1 0x%04X\n%d [%s]\n", (unsigned)UART1->BRR, (unsigned)UART1->CR1, n, line);

Expected output:

BRR 1667 CR1 0x2004
70 [$GPGGA,092750.000,5321.6802,N,00630.3372,W,1,8,1.03,61.7,M,55.2,M,,*76]

Learn it first

More Reading datasheets and schematics problems