---
# System prepended metadata

title: PMS5003T on Go
tags: [Go, PMS5003T, Raspberry Pi]

---

# PMS5003T on Go
###### tags: `Go`,`Raspberry Pi`, `PMS5003T`

 
```
PIN          GPIO
1 ->  VCC ->   2
2 ->  GND ->  14
4 ->  RX  ->   8
5 ->  TX  ->  10
```

``` go 
package aqi

import (
    "fmt"
    "strconv"
    "time"

    "github.com/goburrow/serial"
)

func GetAQIData() (int, int, int, float64, float64) {
    data := getData(5)

    pm1 := to_i(data, 10)
    pm25 := to_i(data, 12)
    pm10 := to_i(data, 14)
    temperature := float64(to_i(data, 24)) / 10.0
    humidity := float64(to_i(data, 26)) / 10.0

    return pm1, pm25, pm10, temperature, humidity
}

func getData(retry int) []byte {
    var data = make([]byte, 32)
    port := getPort()
    defer port.Close()
    _, err := port.Read(data)
    printError(err)
    dataStr := to_hex(data)

    // 檢查碼 若遇到錯誤 重試
    if dataStr[:2] != "42" || dataStr[2:4] != "4d"  {
        if retry > 0 {
            sleep(5000)
            getData(retry - 1)
        }
    }
    return data
}

func getPort() serial.Port {
    port, err := serial.Open(
        &serial.Config{
            Address:  "/dev/ttyS0",
            BaudRate: 9600,
            Timeout:  1 * time.Second,
        })
    printError(err)

    sleep(800)
    return port
}

func to_hex(data []byte) string {
    return fmt.Sprintf("%x", data)
}

func to_i(data []byte, idx int) int {
    data = data[idx : idx+2]
    n, _ := strconv.ParseUint(to_hex(data), 16, 10)
    return int(n)
}

func sleep(t int) {
    time.Sleep(time.Duration(t) * time.Millisecond)
}

func printError(err error) {
    if err != nil {
        fmt.Println(err)
    }
}
```