---
title: "Parsing laser distance meter serial output"
date: 2013-08-16
---

UPDATE: Serial commands and timing information are now available
[here][1].

This is a follow-up on my previous article about an [arduino-compatible laser
distance meter with serial output][2]. I've received several emails asking for
example code to parse the serial output.

image:photo-16-580x435.jpg

```
int strstart_P(const char *s1, const char * PROGMEM s2)
{
    return strncmp_P(s1, s2, strlen_P(s2)) == 0;
}
 
int getdist(void)
{
    char buf[64];
    char *comma;
    int dist;
    int rc;
 
    for (;;) {
        rc = Serial.readBytesUntil('\n', buf, sizeof(buf));
        buf[rc] = '\0';
 
        if (!strstart_P(buf, PSTR("Dist: ")))
            continue;
 
        comma = strchr(buf, ',');
        if (comma == NULL)
            continue;
 
        *comma = '\0';
 
        dist = atoi(buf + strlen_P(PSTR("Dist: ")));
        return dist;
    }
}
 
void setup(void)
{
    Serial.begin(115200);
}
 
void loop(void)
{
    int dist_mm;
    int dist_m;
    char buf[128];
 
    dist_mm = getdist();
    dist_m = dist_mm / 1000;
 
    snprintf_P(buf, sizeof(buf),
        PSTR("Laser distance: %d.%dm"),
        dist_m, dist_mm % 1000);
 
    Serial.println(buf);
}
```

image:Screen-Shot-2013-08-16-at-3.44.37-AM-580x323.png

[1]: /laser-distance-meter-update-serial-commands-timing-measurements/
[2]: /arduino-laser-distance-meter/