Created
July 15, 2020 06:14
-
-
Save lroman242/e38f1c4eda95b8a2b83abc43739c55ee to your computer and use it in GitHub Desktop.
Golang - Arduino communication via Serial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"github.com/tarm/serial" | |
"bufio" | |
"fmt" | |
) | |
func main() { | |
c := &serial.Config{Name: "COM3", Baud: 9600} | |
s, err := serial.OpenPort(c) | |
if err != nil { | |
log.Fatal("Cannot open port. ", err) | |
} | |
_, err = s.Write([]byte(`{"name":"someName","data":[null,false,1,"str",{"key1":"val"1}]}`)) | |
if err != nil { | |
log.Fatal("Cannot write bytes. ", err) | |
} | |
scanner := bufio.NewScanner(s) | |
for scanner.Scan() { | |
fmt.Println("======>", scanner.Text()) | |
} | |
if scanner.Err() != nil { | |
log.Fatal(err) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
char rx_byte; | |
String stringOne = String('\0'); | |
void setup() { | |
// initialize serial: | |
Serial.begin(9600); | |
} | |
void loop() { | |
// if there's any serial available, read it: | |
if (Serial.available() > 0) { | |
rx_byte = Serial.read(); | |
Serial.print("=====> "); | |
Serial.println((int)rx_byte); | |
if (rx_byte == EOF || rx_byte == '\r' || rx_byte == '\n') { | |
Serial.print("you typed: "); | |
Serial.println(stringOne); | |
Serial.print("len: "); | |
Serial.println(stringOne.length()); | |
stringOne = String('\0'); | |
} else { | |
stringOne.concat(rx_byte); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bufio.Scanner: token too long