main.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "strconv"
  7. "time"
  8. "github.com/tarm/serial"
  9. )
  10. func main() {
  11. if len(os.Args) < 4 {
  12. log.Fatalf("Usage: %s <port> <baud> <data...>", os.Args[0])
  13. }
  14. portName := os.Args[1]
  15. baudRate, err := strconv.Atoi(os.Args[2])
  16. if err != nil {
  17. log.Fatalf("Invalid baud rate: %v", err)
  18. }
  19. config := &serial.Config{
  20. Name: portName,
  21. Baud: baudRate,
  22. Size: 8,
  23. Parity: serial.ParityNone,
  24. }
  25. port, err := serial.OpenPort(config)
  26. if err != nil {
  27. log.Fatalf("Failed to open port: %v", err)
  28. }
  29. defer port.Close()
  30. go func() {
  31. buf := make([]byte, 128)
  32. for {
  33. n, err := port.Read(buf)
  34. if err != nil {
  35. log.Printf("Failed to read from port: %v", err)
  36. return
  37. }
  38. if n > 0 {
  39. fmt.Print("Received bytes: ")
  40. for i := 0; i < n; i++ {
  41. fmt.Printf("0x%02X ", buf[i])
  42. }
  43. fmt.Println()
  44. }
  45. }
  46. }()
  47. for _, arg := range os.Args[3:] {
  48. data, err := strconv.ParseUint(arg, 0, 8)
  49. if err != nil {
  50. log.Fatalf("Invalid data byte: %v", err)
  51. }
  52. n, err := port.Write([]byte{byte(data)})
  53. if err != nil {
  54. log.Fatalf("Failed to write to port: %v", err)
  55. }
  56. fmt.Printf("Sent %d bytes to %s\n", n, portName)
  57. time.Sleep(10 * time.Millisecond)
  58. }
  59. }