├── .gitignore ├── LICENSE ├── README.md ├── analog_io.go ├── digital_io.go ├── firmata ├── constants.go └── firmata.go └── goduino.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # goduino 2 | Go's package for Arduino 3 | 4 | Goduino uses [Firmata](https://github.com/firmata/protocol) protocol for [Arduino](https://www.arduino.cc/) 5 | 6 | [![GoDoc](http://godoc.org/github.com/argandas/goduino?status.svg)](http://godoc.org/github.com/argandas/goduino) 7 | 8 | ## Prerequisites 9 | 10 | 1. Download and install the [Arduio IDE](http://www.arduino.cc/en/Main/Software) 11 | 2. Plug in your Arduino via USB 12 | 3. Open the Arduino IDE and open: `File > Examples > StandardFirmata` 13 | 4. Select Arduino´s board: `Tools > Board` 14 | 5. Select Arduino´s serial port: `Tools > Serial Port` 15 | 6. Click the Upload button 16 | 17 | ## Installation 18 | 19 | ```bash 20 | go get github.com/argandas/goduino 21 | ``` 22 | 23 | ## Usage 24 | 25 | ```go 26 | package main 27 | 28 | import ( 29 | "fmt" 30 | "github.com/argandas/goduino" 31 | "time" 32 | ) 33 | 34 | func main() { 35 | arduino := goduino.New("myArduino", "COM1") 36 | err := arduino.Connect() 37 | if err != nil { 38 | fmt.Println(err) 39 | return 40 | } 41 | defer arduino.Disconnect() 42 | 43 | arduino.PinMode(13, goduino.Output) 44 | for { 45 | arduino.DigitalWrite(13, 1) 46 | arduino.Delay(time.Millisecond * 500) 47 | arduino.DigitalWrite(13, 0) 48 | arduino.Delay(time.Millisecond * 500) 49 | } 50 | } 51 | ``` 52 | 53 | Note: For this example the selected serial port is `COM1`, be sure your Arduino is connected on this serial port. 54 | 55 | ## Stable versions 56 | 57 | This package has been tested on Go v1.4.2 & Firmata v2.4 58 | -------------------------------------------------------------------------------- /analog_io.go: -------------------------------------------------------------------------------- 1 | package goduino 2 | 3 | // AnalogRead retrieves value from analog pin. 4 | // Returns -1 if the response from the board has timed out 5 | func (ino *Goduino) AnalogRead(pin int) (value int, err error) { 6 | p := ino.digitalPin(pin) 7 | // Check if pin is configured as analog 8 | if ino.board.Pins()[p].Mode != Analog { 9 | if err = ino.PinMode(pin, Analog); err != nil { 10 | return 11 | } 12 | } 13 | value = ino.board.Pins()[p].Value 14 | ino.logger.Printf("analogRead(%d) -> %d\r\n", pin, value) 15 | return 16 | } 17 | -------------------------------------------------------------------------------- /digital_io.go: -------------------------------------------------------------------------------- 1 | package goduino 2 | 3 | // DigitalWrite write a HIGH or a LOW value to a digital pin. 4 | // 5 | // If the pin has been configured as an OUTPUT with pinMode(), 6 | // its voltage will be set to the corresponding value: 7 | // 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. 8 | func (ino *Goduino) DigitalWrite(pin, value int) error { 9 | // Check if pin is configured as analog 10 | if ino.board.Pins()[pin].Mode != Output { 11 | if err := ino.PinMode(pin, Output); err != nil { 12 | return err 13 | } 14 | } 15 | ino.logger.Printf("digitalWrite(%d, %d)\r\n", pin, value) 16 | return ino.board.DigitalWrite(pin, value) 17 | } 18 | 19 | // DigitalRead reads the value from a specified digital pin, either HIGH or LOW. 20 | func (ino *Goduino) DigitalRead(pin int) (value int, err error) { 21 | // Check if pin is configured as input 22 | if ino.board.Pins()[pin].Mode != Input { 23 | if err = ino.PinMode(pin, Input); err != nil { 24 | return 25 | } 26 | } 27 | value = ino.board.Pins()[pin].Value 28 | ino.logger.Printf("digitalRead(%d) -> %d\r\n", pin, value) 29 | return 30 | } 31 | -------------------------------------------------------------------------------- /firmata/constants.go: -------------------------------------------------------------------------------- 1 | package firmata 2 | 3 | import "fmt" 4 | 5 | type FirmataCommand byte 6 | type SysExCommand byte 7 | type SerialPort byte 8 | 9 | // Pin Modes 10 | const ( 11 | Input = 0x00 12 | Output = 0x01 13 | Analog = 0x02 14 | Pwm = 0x03 15 | Servo = 0x04 16 | 17 | // SPIConfig SPISubCommand = 0x10 18 | // SPIComm SPISubCommand = 0x20 19 | 20 | SPI_MODE0 = 0x00 21 | SPI_MODE1 = 0x04 22 | SPI_MODE2 = 0x08 23 | SPI_MODE3 = 0x0C 24 | 25 | SoftSerial SerialPort = 0x00 26 | HardSerial1 SerialPort = 0x01 27 | HardSerial2 SerialPort = 0x02 28 | HardSerial3 SerialPort = 0x03 29 | 30 | I2CModeWrite byte = 0x00 31 | I2CModeRead byte = 0x01 32 | I2CModeContinuousRead byte = 0x02 33 | I2CModeStopReading byte = 0x03 34 | 35 | // SerialConfig SerialSubCommand = 0x10 36 | // SerialComm SerialSubCommand = 0x20 37 | // SerialFlush SerialSubCommand = 0x30 38 | // SerialClose SerialSubCommand = 0x40 39 | ) 40 | 41 | // Firmata commands 42 | const ( 43 | DigitalMessage FirmataCommand = 0x90 44 | DigitalMessageRangeStart FirmataCommand = 0x90 45 | DigitalMessageRangeEnd FirmataCommand = 0x9F 46 | ReportAnalog FirmataCommand = 0xC0 47 | ReportDigital FirmataCommand = 0xD0 48 | AnalogMessage FirmataCommand = 0xE0 49 | AnalogMessageRangeStart FirmataCommand = 0xE0 50 | AnalogMessageRangeEnd FirmataCommand = 0xEF 51 | StartSysex FirmataCommand = 0xF0 52 | PinMode FirmataCommand = 0xF4 53 | EndSysex FirmataCommand = 0xF7 54 | ProtocolVersion FirmataCommand = 0xF9 55 | SystemReset FirmataCommand = 0xFF 56 | ) 57 | 58 | // SysEx Commands 59 | const ( 60 | Serial SysExCommand = 0x60 61 | AnalogMappingQuery SysExCommand = 0x69 62 | AnalogMappingResponse SysExCommand = 0x6A 63 | CapabilityQuery SysExCommand = 0x6B 64 | CapabilityResponse SysExCommand = 0x6C 65 | PinStateQuery SysExCommand = 0x6D 66 | PinStateResponse SysExCommand = 0x6E 67 | ServoConfig SysExCommand = 0x70 68 | StringData SysExCommand = 0x71 69 | ShiftData SysExCommand = 0x75 // a bitstream to/from a shift register 70 | I2CRequest SysExCommand = 0x76 71 | I2CReply SysExCommand = 0x77 72 | I2CConfig SysExCommand = 0x78 73 | FirmwareQuery SysExCommand = 0x79 74 | SamplingInterval SysExCommand = 0x7A // set the poll rate of the main loop 75 | SysExNonRealtime SysExCommand = 0x7E // MIDI Reserved for non-realtime messages 76 | SysExRealtime SysExCommand = 0x7F // MIDI Reserved for realtime messages 77 | SysExSPI SysExCommand = 0x80 78 | ) 79 | 80 | func (c FirmataCommand) String() string { 81 | switch { 82 | case (c & 0xF0) == DigitalMessage: 83 | return fmt.Sprintf("DigitalMessage (0x%x)", uint8(c)) 84 | case (c & 0xF0) == AnalogMessage: 85 | return fmt.Sprintf("AnalogMessage (0x%x)", uint8(c)) 86 | case c == ReportAnalog: 87 | return fmt.Sprintf("ReportAnalog (0x%x)", uint8(c)) 88 | case c == ReportDigital: 89 | return fmt.Sprintf("ReportDigital (0x%x)", uint8(c)) 90 | case c == PinMode: 91 | return fmt.Sprintf("PinMode (0x%x)", uint8(c)) 92 | case c == ProtocolVersion: 93 | return fmt.Sprintf("ProtocolVersion (0x%x)", uint8(c)) 94 | case c == SystemReset: 95 | return fmt.Sprintf("SystemReset (0x%x)", uint8(c)) 96 | case c == StartSysex: 97 | return fmt.Sprintf("StartSysex (0x%x)", uint8(c)) 98 | case c == EndSysex: 99 | return fmt.Sprintf("EndSysex (0x%x)", uint8(c)) 100 | } 101 | return fmt.Sprintf("Unexpected command (0x%x)", uint8(c)) 102 | } 103 | 104 | func (c SysExCommand) String() string { 105 | switch { 106 | case c == ServoConfig: 107 | return fmt.Sprintf("ServoConfig (0x%x)", uint8(c)) 108 | case c == StringData: 109 | return fmt.Sprintf("StringData (0x%x)", uint8(c)) 110 | case c == ShiftData: 111 | return fmt.Sprintf("ShiftData (0x%x)", uint8(c)) 112 | case c == I2CRequest: 113 | return fmt.Sprintf("I2CRequest (0x%x)", uint8(c)) 114 | case c == I2CReply: 115 | return fmt.Sprintf("I2CReply (0x%x)", uint8(c)) 116 | case c == I2CConfig: 117 | return fmt.Sprintf("I2CConfig (0x%x)", uint8(c)) 118 | // case c == ExtendedAnalog: 119 | // return fmt.Sprintf("ExtendedAnalog (0x%x)", uint8(c)) 120 | case c == PinStateQuery: 121 | return fmt.Sprintf("PinStateQuery (0x%x)", uint8(c)) 122 | case c == PinStateResponse: 123 | return fmt.Sprintf("PinStateResponse (0x%x)", uint8(c)) 124 | case c == CapabilityQuery: 125 | return fmt.Sprintf("CapabilityQuery (0x%x)", uint8(c)) 126 | case c == CapabilityResponse: 127 | return fmt.Sprintf("CapabilityResponse (0x%x)", uint8(c)) 128 | case c == AnalogMappingQuery: 129 | return fmt.Sprintf("AnalogMappingQuery (0x%x)", uint8(c)) 130 | case c == AnalogMappingResponse: 131 | return fmt.Sprintf("AnalogMappingResponse (0x%x)", uint8(c)) 132 | case c == FirmwareQuery: 133 | return fmt.Sprintf("FirmwareQuery (0x%x)", uint8(c)) 134 | case c == SamplingInterval: 135 | return fmt.Sprintf("SamplingInterval (0x%x)", uint8(c)) 136 | case c == SysExNonRealtime: 137 | return fmt.Sprintf("SysExNonRealtime (0x%x)", uint8(c)) 138 | case c == SysExRealtime: 139 | return fmt.Sprintf("SysExRealtime (0x%x)", uint8(c)) 140 | case c == Serial: 141 | return fmt.Sprintf("Serial (0x%x)", uint8(c)) 142 | case c == SysExSPI: 143 | return fmt.Sprintf("SPI (0x%x)", uint8(c)) 144 | } 145 | return fmt.Sprintf("Unexpected SysEx command (0x%x)", uint8(c)) 146 | } 147 | -------------------------------------------------------------------------------- /firmata/firmata.go: -------------------------------------------------------------------------------- 1 | package firmata 2 | 3 | import ( 4 | "bufio" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "log" 9 | "math" 10 | "os" 11 | "time" 12 | ) 13 | 14 | // Errors 15 | var ErrConnected = errors.New("client is already connected") 16 | 17 | // Firmata represents a client connection to a firmata board 18 | type Firmata struct { 19 | pins []Pin 20 | FirmwareName string 21 | ProtocolVersion string 22 | connected bool 23 | connection io.ReadWriteCloser 24 | analogPins []int 25 | ready bool 26 | analogMappingDone bool 27 | capabilityDone bool 28 | logger *log.Logger 29 | } 30 | 31 | // Pin represents a pin on the firmata board 32 | type Pin struct { 33 | SupportedModes []int 34 | Mode int 35 | Value int 36 | State int 37 | AnalogChannel int 38 | } 39 | 40 | // I2cReply represents the response from an I2cReply message 41 | type I2cReply struct { 42 | Address int 43 | Register int 44 | Data []byte 45 | } 46 | 47 | // New returns a new Firmata 48 | func New() *Firmata { 49 | c := &Firmata{ 50 | ProtocolVersion: "", 51 | FirmwareName: "", 52 | connection: nil, 53 | pins: []Pin{}, 54 | analogPins: []int{}, 55 | connected: false, 56 | logger: log.New(os.Stdout, "[firmata] ", log.Ltime), 57 | } 58 | 59 | return c 60 | } 61 | 62 | // Disconnect disconnects the Firmata 63 | func (f *Firmata) Disconnect() (err error) { 64 | f.connected = false 65 | return f.connection.Close() 66 | } 67 | 68 | // Connected returns the current connection state of the Firmata 69 | func (f *Firmata) Connected() bool { 70 | return f.connected 71 | } 72 | 73 | // Pins returns all available pins 74 | func (f *Firmata) Pins() []Pin { 75 | return f.pins 76 | } 77 | 78 | // Connect connects to the Firmata given conn. It first resets the firmata board 79 | // then continuously polls the firmata board for new information when it's 80 | // available. 81 | func (f *Firmata) Connect(conn io.ReadWriteCloser) (err error) { 82 | if f.connected { 83 | return ErrConnected 84 | } 85 | 86 | f.connection = conn 87 | 88 | // Start threads 89 | go f.process() 90 | 91 | // Reset device 92 | f.Reset() 93 | 94 | // Wait for device to response 95 | t := time.NewTicker(time.Second) 96 | for !f.connected { 97 | select { 98 | case <-t.C: 99 | // Do nothing 100 | case <-time.After(time.Second * 15): 101 | f.logger.Print("No response in 15 seconds. Resetting device") 102 | f.Reset() 103 | case <-time.After(time.Second * 30): 104 | // Close connections 105 | f.connection.Close() 106 | return errors.New("Unable to initialize connection") 107 | } 108 | } 109 | 110 | // Firmata creation successful 111 | f.logger.Print("Firmata ready to use") 112 | return nil 113 | } 114 | 115 | // Reset sends the SystemReset sysex code. 116 | func (f *Firmata) Reset() error { 117 | return f.write([]byte{byte(SystemReset)}) 118 | } 119 | 120 | // SetPinMode sets the pin to mode. 121 | func (f *Firmata) SetPinMode(pin int, mode int) error { 122 | f.pins[byte(pin)].Mode = mode 123 | return f.sendCommand([]byte{byte(PinMode), byte(pin), byte(mode)}) 124 | } 125 | 126 | // DigitalWrite writes value to pin. 127 | func (f *Firmata) DigitalWrite(pin int, value int) error { 128 | port := byte(math.Floor(float64(pin) / 8)) 129 | portValue := byte(0) 130 | f.pins[pin].Value = value 131 | // Build command 132 | for i := byte(0); i < 8; i++ { 133 | if f.pins[8*port+i].Value != 0 { 134 | portValue = portValue | (1 << i) 135 | } 136 | } 137 | return f.sendCommand([]byte{byte(DigitalMessage) | port, portValue & 0x7F, (portValue >> 7) & 0x7F}) 138 | } 139 | 140 | // ServoConfig sets the min and max pulse width for servo PWM range 141 | func (f *Firmata) ServoConfig(pin int, max int, min int) error { 142 | ret := []byte{ 143 | byte(ServoConfig), 144 | byte(pin), 145 | byte(max & 0x7F), 146 | byte((max >> 7) & 0x7F), 147 | byte(min & 0x7F), 148 | byte((min >> 7) & 0x7F), 149 | } 150 | return f.writeSysex(ret) 151 | } 152 | 153 | // AnalogWrite writes value to pin. 154 | func (f *Firmata) AnalogWrite(pin int, value int) error { 155 | f.pins[pin].Value = value 156 | return f.write([]byte{byte(AnalogMessage) | byte(pin), byte(value & 0x7F), byte((value >> 7) & 0x7F)}) 157 | } 158 | 159 | // FirmwareQuery sends the FirmwareQuery sysex code. 160 | func (f *Firmata) FirmwareQuery() error { 161 | return f.writeSysex([]byte{byte(FirmwareQuery)}) 162 | } 163 | 164 | // PinStateQuery sends a PinStateQuery for pin. 165 | func (f *Firmata) PinStateQuery(pin int) error { 166 | return f.writeSysex([]byte{byte(PinStateQuery), byte(pin)}) 167 | } 168 | 169 | // ProtocolVersionQuery sends the ProtocolVersion sysex code. 170 | func (f *Firmata) ProtocolVersionQuery() error { 171 | return f.write([]byte{byte(ProtocolVersion)}) 172 | } 173 | 174 | // CapabilitiesQuery sends the CapabilityQuery sysex code. 175 | func (f *Firmata) CapabilitiesQuery() error { 176 | return f.writeSysex([]byte{byte(CapabilityQuery)}) 177 | } 178 | 179 | // AnalogMappingQuery sends the AnalogMappingQuery sysex code. 180 | func (f *Firmata) AnalogMappingQuery() error { 181 | return f.writeSysex([]byte{byte(AnalogMappingQuery)}) 182 | } 183 | 184 | // ReportDigital enables or disables digital reporting for pin, a non zero 185 | // state enables reporting 186 | func (f *Firmata) ReportDigital(pin int, state int) error { 187 | return f.togglePinReporting(pin, state, byte(ReportDigital)) 188 | } 189 | 190 | // ReportAnalog enables or disables analog reporting for pin, a non zero 191 | // state enables reporting 192 | func (f *Firmata) ReportAnalog(pin int, state int) error { 193 | return f.togglePinReporting(pin, state, byte(ReportAnalog)) 194 | } 195 | 196 | // I2cRead reads numBytes from address once. 197 | func (f *Firmata) I2cRead(address int, numBytes int) error { 198 | return f.writeSysex([]byte{byte(I2CRequest), byte(address), (I2CModeRead << 3), 199 | byte(numBytes) & 0x7F, (byte(numBytes) >> 7) & 0x7F}) 200 | } 201 | 202 | // I2cWrite writes data to address. 203 | func (f *Firmata) I2cWrite(address int, data []byte) error { 204 | ret := []byte{byte(I2CRequest), byte(address), (I2CModeWrite << 3)} 205 | for _, val := range data { 206 | ret = append(ret, byte(val&0x7F)) 207 | ret = append(ret, byte((val>>7)&0x7F)) 208 | } 209 | return f.writeSysex(ret) 210 | } 211 | 212 | // I2cConfig configures the delay in which a register can be read from after it 213 | // has been written to. 214 | func (f *Firmata) I2cConfig(delay int) error { 215 | return f.writeSysex([]byte{byte(I2CConfig), byte(delay & 0xFF), byte((delay >> 8) & 0xFF)}) 216 | } 217 | 218 | func (f *Firmata) togglePinReporting(pin int, state int, mode byte) error { 219 | if state != 0 { 220 | state = 1 221 | } else { 222 | state = 0 223 | } 224 | 225 | if err := f.write([]byte{byte(mode) | byte(pin), byte(state)}); err != nil { 226 | return err 227 | } 228 | 229 | return nil 230 | 231 | } 232 | 233 | func (f *Firmata) writeSysex(data []byte) (err error) { 234 | frame := append([]byte{byte(StartSysex)}, append(data, byte(EndSysex))...) 235 | f.printSysExData("SysEx Tx", SysExCommand(frame[1]), frame) 236 | return f.write(frame) 237 | } 238 | 239 | func (f *Firmata) write(data []byte) (err error) { 240 | _, err = f.connection.Write(data[:]) 241 | return 242 | } 243 | 244 | func (f *Firmata) sendCommand(cmd []byte) error { 245 | f.printByteArray("Command send", cmd) 246 | _, err := f.connection.Write(cmd) 247 | return err 248 | } 249 | 250 | func (f *Firmata) read(length int) (buf []byte, err error) { 251 | i := 0 252 | for length > 0 { 253 | tmp := make([]byte, length) 254 | if i, err = f.connection.Read(tmp); err != nil { 255 | if err.Error() != "EOF" { 256 | return 257 | } 258 | <-time.After(5 * time.Millisecond) 259 | } 260 | if i > 0 { 261 | buf = append(buf, tmp...) 262 | length = length - i 263 | } 264 | } 265 | return 266 | } 267 | 268 | func (f *Firmata) process() { 269 | r := bufio.NewReader(f.connection) 270 | var init bool 271 | for { 272 | b, err := r.ReadByte() 273 | if err != nil { 274 | f.logger.Panic(err) 275 | return 276 | } 277 | cmd := FirmataCommand(b) 278 | f.logger.Printf("Incoming cmd %v", cmd) 279 | 280 | // First received byte must be ReportVersion command 281 | if !init { 282 | if cmd != ProtocolVersion { 283 | f.logger.Printf("Discarding unexpected command byte %0d (not initialized)\n", b) 284 | continue 285 | } else { 286 | init = true 287 | } 288 | } 289 | 290 | switch { 291 | case ProtocolVersion == cmd: 292 | buf, err := f.read(2) 293 | if err != nil { 294 | f.logger.Panic(err) 295 | return 296 | } 297 | f.ProtocolVersion = fmt.Sprintf("%v.%v", buf[0], buf[1]) 298 | f.logger.Printf("Protocol version: %s", f.ProtocolVersion) 299 | f.FirmwareQuery() 300 | case AnalogMessageRangeStart <= cmd && AnalogMessageRangeEnd >= cmd: 301 | buf, err := f.read(2) 302 | if err != nil { 303 | f.logger.Panic(err) 304 | return 305 | } 306 | 307 | value := uint(buf[0]) | uint(buf[1])<<7 308 | pin := int((cmd & 0x0F)) 309 | 310 | if len(f.analogPins) > pin { 311 | if len(f.pins) > f.analogPins[pin] { 312 | f.pins[f.analogPins[pin]].Value = int(value) 313 | f.logger.Printf("AnalogRead%v", pin) 314 | } 315 | } 316 | case DigitalMessageRangeStart <= cmd && DigitalMessageRangeEnd >= cmd: 317 | buf, err := f.read(2) 318 | if err != nil { 319 | f.logger.Panic(err) 320 | return 321 | } 322 | port := cmd & 0x0F 323 | portValue := buf[1] | (buf[2] << 7) 324 | for i := 0; i < 8; i++ { 325 | pinNumber := int((8*byte(port) + byte(i))) 326 | if len(f.pins) > pinNumber { 327 | if f.pins[pinNumber].Mode == Input { 328 | f.pins[pinNumber].Value = int((portValue >> (byte(i) & 0x07)) & 0x01) 329 | f.logger.Printf("DigitalRead%v", pinNumber) 330 | } 331 | } 332 | } 333 | case StartSysex == cmd: 334 | sysExData, err := r.ReadSlice(byte(EndSysex)) 335 | if err != nil { 336 | f.logger.Panic(err) 337 | break 338 | } 339 | // Remove EndSysEx byte 340 | f.parseSysEx(sysExData[:len(sysExData)-1]) 341 | } 342 | } 343 | } 344 | 345 | func (f *Firmata) parseSysEx(data []byte) { 346 | 347 | // ino.printSysExData("SysEx Rx", cmd, data) 348 | 349 | cmd := SysExCommand(data[0]) 350 | data = data[1:] 351 | f.printSysExData("SysEx Rx", cmd, data) 352 | 353 | switch cmd { 354 | case CapabilityResponse: 355 | f.pins = []Pin{} 356 | supportedModes := 0 357 | n := 0 358 | for _, val := range data[:(len(data) - 5)] { 359 | if val == 127 { 360 | modes := []int{} 361 | for _, mode := range []int{Input, Output, Analog, Pwm, Servo} { 362 | if (supportedModes & (1 << byte(mode))) != 0 { 363 | modes = append(modes, mode) 364 | } 365 | } 366 | 367 | f.pins = append(f.pins, Pin{SupportedModes: modes, Mode: Output}) 368 | supportedModes = 0 369 | n = 0 370 | continue 371 | } 372 | 373 | if n == 0 { 374 | supportedModes = supportedModes | (1 << val) 375 | } 376 | n ^= 1 377 | } 378 | f.logger.Printf("Total pins: %v\n", len(f.pins)) 379 | f.AnalogMappingQuery() 380 | case AnalogMappingResponse: 381 | f.analogPins = []int{} 382 | for index, val := range data[:len(f.pins)-1] { 383 | f.pins[index].AnalogChannel = int(val) 384 | if val != 127 { 385 | f.analogPins = append(f.analogPins, index) 386 | } 387 | // fmt.Println(index, ":", f.pins[index].AnalogChannel, ":", val) 388 | } 389 | f.logger.Printf("pin -> channel: %v\n", f.analogPins) 390 | f.connected = true 391 | case PinStateResponse: 392 | pin := data[0] 393 | f.pins[pin].Mode = int(data[1]) 394 | f.pins[pin].State = int(data[2]) 395 | 396 | if len(data) > 3 { 397 | f.pins[pin].State = int(uint(f.pins[pin].State) | uint(data[2])<<7) 398 | } 399 | if len(data) > 4 { 400 | f.pins[pin].State = int(uint(f.pins[pin].State) | uint(data[4])<<14) 401 | } 402 | f.logger.Printf("PinState%v", pin) 403 | case I2CReply: 404 | reply := I2cReply{ 405 | Address: int(byte(data[0]) | byte(data[1])<<7), 406 | Register: int(byte(data[2]) | byte(data[3])<<7), 407 | Data: []byte{byte(data[4]) | byte(data[5])<<7}, 408 | } 409 | for i := 8; i < len(data); i = i + 2 { 410 | if data[i] == byte(0xF7) { 411 | break 412 | } 413 | if i+2 > len(data) { 414 | break 415 | } 416 | reply.Data = append(reply.Data, 417 | byte(data[i])|byte(data[i+1])<<7, 418 | ) 419 | } 420 | f.logger.Printf("I2cReply%v", reply) 421 | case FirmwareQuery: 422 | name := []byte{} 423 | for _, val := range data[2:(len(data) - 1)] { 424 | if val != 0 { 425 | name = append(name, val) 426 | } 427 | } 428 | f.FirmwareName = string(name[:]) 429 | f.logger.Printf("Firmware: %s", f.FirmwareName) 430 | f.CapabilitiesQuery() 431 | case StringData: 432 | str := data[:] 433 | f.logger.Printf("StringData%v", string(str[:len(str)-1])) 434 | } 435 | } 436 | 437 | func (f *Firmata) printByteArray(title string, data []uint8) { 438 | fmt.Println() 439 | f.logger.Println(title) 440 | str := "" 441 | for index, b := range data { 442 | str += fmt.Sprintf("0x%02X ", b) 443 | if (index+1)%8 == 0 || index == len(data)-1 { 444 | f.logger.Println(str) 445 | str = "" 446 | } 447 | } 448 | fmt.Println() 449 | } 450 | 451 | func (f *Firmata) printSysExData(title string, cmd SysExCommand, data []uint8) { 452 | fmt.Println() 453 | f.logger.Println(title, "-", cmd) 454 | str := "" 455 | for index, b := range data { 456 | str += fmt.Sprintf("0x%02X ", b) 457 | if (index+1)%8 == 0 || index == len(data)-1 { 458 | f.logger.Println(str) 459 | str = "" 460 | } 461 | } 462 | fmt.Println() 463 | } 464 | -------------------------------------------------------------------------------- /goduino.go: -------------------------------------------------------------------------------- 1 | package goduino 2 | 3 | import ( 4 | "fmt" 5 | "github.com/argandas/goduino/firmata" 6 | "github.com/tarm/serial" 7 | "io" 8 | "log" 9 | "os" 10 | "time" 11 | ) 12 | 13 | const ( 14 | Input = firmata.Input 15 | Output = firmata.Output 16 | Analog = firmata.Analog 17 | Pwm = firmata.Pwm 18 | Servo = firmata.Servo 19 | ) 20 | 21 | type firmataBoard interface { 22 | Connect(io.ReadWriteCloser) error 23 | Disconnect() error 24 | Pins() []firmata.Pin 25 | AnalogWrite(int, int) error 26 | SetPinMode(int, int) error 27 | ReportAnalog(int, int) error 28 | ReportDigital(int, int) error 29 | DigitalWrite(int, int) error 30 | I2cRead(int, int) error 31 | I2cWrite(int, []byte) error 32 | I2cConfig(int) error 33 | } 34 | 35 | // Arduino Firmata client for golang 36 | type Goduino struct { 37 | name string 38 | port string 39 | board firmataBoard 40 | conn io.ReadWriteCloser 41 | openSP func(port string) (io.ReadWriteCloser, error) 42 | logger *log.Logger 43 | verbose bool 44 | } 45 | 46 | // Creates a new Goduino object and connects to the Arduino board 47 | // over specified serial port. This function blocks till a connection is 48 | // succesfullt established and pin mappings are retrieved. 49 | func New(name string, args ...interface{}) *Goduino { 50 | // Create new Goduino client 51 | goduino := &Goduino{ 52 | name: name, 53 | port: "", 54 | conn: nil, 55 | board: firmata.New(), 56 | openSP: func(port string) (io.ReadWriteCloser, error) { 57 | return serial.OpenPort(&serial.Config{Name: port, Baud: 57600}) 58 | }, 59 | logger: log.New(os.Stdout, fmt.Sprintf("[%s] ", name), log.Ltime), 60 | verbose: true, 61 | } 62 | // Parse variadic args 63 | for _, arg := range args { 64 | switch arg.(type) { 65 | case string: 66 | goduino.port = arg.(string) 67 | case io.ReadWriteCloser: 68 | goduino.conn = arg.(io.ReadWriteCloser) 69 | } 70 | } 71 | return goduino 72 | } 73 | 74 | // Connect starts a connection to the firmata board. 75 | func (ino *Goduino) Connect() error { 76 | if ino.conn == nil { 77 | // Try to connect to serial port 78 | sp, err := ino.openSP(ino.Port()) 79 | if err != nil { 80 | return err 81 | } 82 | // Serial connection was successful 83 | ino.conn = sp 84 | } 85 | // Firmata connection 86 | return ino.board.Connect(ino.conn) 87 | } 88 | 89 | // Disconnect closes the io connection to the firmata board 90 | func (ino *Goduino) Disconnect() (err error) { 91 | if ino.board != nil { 92 | // Disconnect firmata board 93 | return ino.board.Disconnect() 94 | } 95 | return nil 96 | } 97 | 98 | // Port returns the FirmataAdaptors port 99 | func (ino *Goduino) Port() string { return ino.port } 100 | 101 | // Name returns the FirmataAdaptors name 102 | func (ino *Goduino) Name() string { return ino.name } 103 | 104 | // PinMode configures the specified pin to behave either as an input or an output. 105 | func (ino *Goduino) PinMode(pin, mode int) error { 106 | // Check if pin is valid 107 | if uint8(pin) < 0 || pin > len(ino.board.Pins()) { 108 | return fmt.Errorf("Invalid pin number %v\n", pin) 109 | } 110 | switch mode { 111 | // If mode == Input 112 | case Input: 113 | // Set pin mode 114 | if err := ino.board.SetPinMode(pin, mode); err != nil { 115 | return err 116 | } 117 | if err := ino.board.ReportDigital(pin, 1); err != nil { 118 | return err 119 | } 120 | <-time.After(10 * time.Millisecond) 121 | // If mode == Analog 122 | case Analog: 123 | pin = ino.digitalPin(pin) 124 | // Set pin mode 125 | if err := ino.board.SetPinMode(pin, mode); err != nil { 126 | return err 127 | } 128 | if err := ino.board.ReportAnalog(pin, 1); err != nil { 129 | return err 130 | } 131 | <-time.After(10 * time.Millisecond) 132 | default: 133 | // Set pin mode 134 | if err := ino.board.SetPinMode(pin, mode); err != nil { 135 | return err 136 | } 137 | } 138 | // PinMode was successful 139 | ino.logger.Printf("pinMode(%d, %s)\r\n", pin, PinMode(mode)) 140 | return nil 141 | } 142 | 143 | // Close the serial connection to properly clean up after ourselves 144 | // Usage: defer client.Close() 145 | func (ino *Goduino) Delay(duration time.Duration) { 146 | time.Sleep(duration) 147 | } 148 | 149 | // digitalPin converts pin number to digital mapping 150 | func (ino *Goduino) digitalPin(pin int) int { 151 | return pin + 14 152 | } 153 | 154 | type PinMode uint8 155 | 156 | func (m PinMode) String() string { 157 | switch { 158 | case m == Input: 159 | return "INPUT" 160 | case m == Output: 161 | return "OUTPUT" 162 | case m == Analog: 163 | return "ANALOG" 164 | case m == Pwm: 165 | return "PWM" 166 | case m == Servo: 167 | return "SERVO" 168 | } 169 | return "UNKNOWN" 170 | } 171 | --------------------------------------------------------------------------------