@@ -144,6 +144,14 @@ func Test(pkgName string, options *compileopts.Options) error {
144144
145145// Flash builds and flashes the built binary to the given serial port.
146146func Flash (pkgName , port string , options * compileopts.Options ) error {
147+ if port == "" {
148+ var err error
149+ port , err = getDefaultPort ()
150+ if err != nil {
151+ return err
152+ }
153+ }
154+
147155 config , err := builder .NewConfig (options )
148156 if err != nil {
149157 return err
@@ -255,6 +263,14 @@ func Flash(pkgName, port string, options *compileopts.Options) error {
255263// Note: this command is expected to execute just before exiting, as it
256264// modifies global state.
257265func FlashGDB (pkgName , port string , ocdOutput bool , options * compileopts.Options ) error {
266+ if port == "" {
267+ var err error
268+ port , err = getDefaultPort ()
269+ if err != nil {
270+ return err
271+ }
272+ }
273+
258274 config , err := builder .NewConfig (options )
259275 if err != nil {
260276 return err
@@ -480,6 +496,30 @@ func parseSize(s string) (int64, error) {
480496 return n , err
481497}
482498
499+ // getDefaultPort returns the default serial port depending on the operating system.
500+ // Currently only supports macOS and Linux.
501+ func getDefaultPort () (port string , err error ) {
502+ var portPath string
503+ switch runtime .GOOS {
504+ case "darwin" :
505+ portPath = "/dev/cu.usb*"
506+ case "linux" :
507+ portPath = "/dev/ttyACM*"
508+ default :
509+ return "" , errors .New ("unable to search for a default USB device to be flashed on this OS" )
510+ }
511+
512+ d , err := filepath .Glob (portPath )
513+ if err != nil {
514+ return "" , err
515+ }
516+ if d == nil {
517+ return "" , errors .New ("unable to locate a USB device to be flashed" )
518+ }
519+
520+ return d [0 ], nil
521+ }
522+
483523func usage () {
484524 fmt .Fprintln (os .Stderr , "TinyGo is a Go compiler for small places." )
485525 fmt .Fprintln (os .Stderr , "version:" , version )
@@ -547,7 +587,7 @@ func main() {
547587 printSize := flag .String ("size" , "" , "print sizes (none, short, full)" )
548588 nodebug := flag .Bool ("no-debug" , false , "disable DWARF debug symbol generation" )
549589 ocdOutput := flag .Bool ("ocd-output" , false , "print OCD daemon output during debug" )
550- port := flag .String ("port" , "/dev/ttyACM0 " , "flash port" )
590+ port := flag .String ("port" , "" , "flash port" )
551591 programmer := flag .String ("programmer" , "" , "which hardware programmer to use" )
552592 cFlags := flag .String ("cflags" , "" , "additional cflags for compiler" )
553593 ldFlags := flag .String ("ldflags" , "" , "additional ldflags for linker" )
0 commit comments