Parse a modem signal report
Validate a +CSQ reply and convert it to dBm. A medium embedded C problem (UART), run and graded in the browser.
medium · UART · uart · parsing · at-commands
A cellular modem answers AT+CSQ with a line such as +CSQ: 23,99. The first number is the signal strength index rssi; the second (bit error rate) does not matter here.
Return the signal strength in dBm: -113 + 2 * rssi for rssi from 0 to 31. Return 0 if the strength is unknown (rssi is 99) or the line is malformed. A well-formed line is exactly +CSQ: , then one or two digits, then a comma.
Starter code
int csq_to_dbm(const char *line) {
int rssi = 0;
for (const char *p = line + 6; *p >= '0' && *p <= '9'; p++)
rssi = rssi * 10 + (*p - '0');
return -113 + 2 * rssi;
}Example tests
Normal reports
printf("%d %d\n", csq_to_dbm("+CSQ: 23,99"), csq_to_dbm("+CSQ: 0,0"));Expected output:
-67 -113Signal not known
printf("%d\n", csq_to_dbm("+CSQ: 99,99"));Expected output:
0Learn it first
- UART · Baud rate, framing, errors, flow control and DMA reception.
More UART problems
- Assemble command lines · Collect received characters into lines, with backspace and overflow handled.
- Detect the baud rate · Measure a 'U' character's bit times and snap to the nearest standard baud rate.
- Interrupt-driven transmit queue · Queue bytes for the UART and send them from the data-register-empty interrupt.
- Spot OK and ERROR in a modem stream · Feed received characters one at a time and report complete OK or ERROR lines.
- Driver: a polled UART transmitter · Configure a UART from its register map and send bytes without losing any.
- Driver: receive bytes and detect an overrun · Read the UART's receive register without blocking, and report lost bytes.
- Fix: lost bytes are never reported · A receive routine checks the data flag before the overrun flag, so overruns disappear.
- Command console · Split a command line into words, with quoted arguments, and dispatch it through a command table.
- Greenhouse: parse a console command · Parse a technician's command line, and refuse anything malformed or out of range.