| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package main |
| 9 |
|
| 10 |
|
| 11 |
import "C" |
| 12 |
|
| 13 |
import ( |
| 14 |
"bufio" |
| 15 |
"fmt" |
| 16 |
"os" |
| 17 |
"syscall" |
| 18 |
) |
| 19 |
|
| 20 |
const port = "COM4" |
| 21 |
|
| 22 |
func main() { |
| 23 |
handle, err := syscall.CreateFile(syscall.StringToUTF16Ptr(port), |
| 24 |
syscall.GENERIC_READ|syscall.GENERIC_WRITE, |
| 25 |
0, |
| 26 |
nil, |
| 27 |
syscall.OPEN_EXISTING, |
| 28 |
0, |
| 29 |
0) |
| 30 |
if err != nil { |
| 31 |
fmt.Print(err) |
| 32 |
return |
| 33 |
} |
| 34 |
fmt.Printf("handle created %d\n", handle) |
| 35 |
defer syscall.CloseHandle(handle) |
| 36 |
|
| 37 |
var dcb C.DCB |
| 38 |
dcb.BaudRate = 9600 |
| 39 |
dcb.ByteSize = 8 |
| 40 |
dcb.StopBits = C.ONESTOPBIT |
| 41 |
dcb.Parity = C.NOPARITY |
| 42 |
if C.SetCommState(C.HANDLE(handle), &dcb) == 0 { |
| 43 |
fmt.Printf("set comm state error %v\n", syscall.GetLastError()) |
| 44 |
return |
| 45 |
} |
| 46 |
fmt.Printf("set comm state succeed\n") |
| 47 |
|
| 48 |
var timeouts C.COMMTIMEOUTS |
| 49 |
|
| 50 |
timeouts.ReadIntervalTimeout = 1000 |
| 51 |
timeouts.ReadTotalTimeoutMultiplier = 0 |
| 52 |
timeouts.ReadTotalTimeoutConstant = 1000 |
| 53 |
timeouts.WriteTotalTimeoutMultiplier = 0 |
| 54 |
timeouts.WriteTotalTimeoutConstant = 1000 |
| 55 |
if C.SetCommTimeouts(C.HANDLE(handle), &timeouts) == 0 { |
| 56 |
fmt.Printf("set comm timeouts error %v\n", syscall.GetLastError()) |
| 57 |
return |
| 58 |
} |
| 59 |
fmt.Printf("set comm timeouts succeed\n") |
| 60 |
|
| 61 |
var n uint32 |
| 62 |
data := []byte("abc") |
| 63 |
err = syscall.WriteFile(handle, data, &n, nil) |
| 64 |
if err != nil { |
| 65 |
fmt.Println(err) |
| 66 |
return |
| 67 |
} |
| 68 |
fmt.Printf("write file succeed\n") |
| 69 |
fmt.Printf("Press Enter when ready for reading...") |
| 70 |
reader := bufio.NewReader(os.Stdin) |
| 71 |
_, _ = reader.ReadString('\n') |
| 72 |
|
| 73 |
data = make([]byte, 512) |
| 74 |
err = syscall.ReadFile(handle, data, &n, nil) |
| 75 |
if err != nil { |
| 76 |
fmt.Println(err) |
| 77 |
return |
| 78 |
} |
| 79 |
fmt.Printf("received data %v:\n", n) |
| 80 |
fmt.Printf("%x\n", data[:n]) |
| 81 |
fmt.Printf("closed\n") |
| 82 |
} |