From 7572125fcbe5588c2ba0110d59c796730c093933 Mon Sep 17 00:00:00 2001 From: Mirivlad Date: Sat, 12 Mar 2022 03:50:28 +0800 Subject: [PATCH] Add libraries dir --- libraries/Arduino_BuiltIn/LICENSE.txt | 121 ++ libraries/Arduino_BuiltIn/README.md | 8 + libraries/Arduino_BuiltIn/library.properties | 10 + .../Arduino_BuiltIn/src/Arduino_BuiltIn.h | 2 + libraries/EncButton/LICENSE | 21 + libraries/EncButton/README.md | 539 ++++++ libraries/EncButton/doc/diagram.png | Bin 0 -> 37800 bytes libraries/EncButton/doc/enc.png | Bin 0 -> 31272 bytes libraries/EncButton/doc/encAli.png | Bin 0 -> 79766 bytes .../examples/EncButton2/EncButton2.ino | 77 + .../EncButton2_array/EncButton2_array.ino | 20 + .../examples/callbackISR/callbackISR.ino | 29 + .../examples/callbackMode/callbackMode.ino | 91 + .../examples/optimisation/optimisation.ino | 41 + libraries/EncButton/examples/pcint/pcint.ino | 70 + .../examples/preClicks/preClicks.ino | 33 + .../EncButton/examples/stepMode/stepMode.ino | 47 + .../EncButton/examples/tickISR/tickISR.ino | 34 + .../EncButton/examples/tickMode/tickMode.ino | 78 + .../EncButton/examples/virtual/virtual.ino | 33 + .../virtual_AnalogKey/virtual_AnalogKey.ino | 35 + .../virtual_SimpleKeypad.ino | 44 + .../virtual_SimpleKeypad_array.ino | 44 + libraries/EncButton/keywords.txt | 102 ++ libraries/EncButton/library.properties | 9 + libraries/EncButton/src/EncButton.h | 488 ++++++ libraries/EncButton/src/EncButton2.h | 444 +++++ libraries/Ethernet/AUTHORS | 38 + libraries/Ethernet/README.adoc | 24 + .../AdvancedChatServer/AdvancedChatServer.ino | 119 ++ .../BarometricPressureWebServer.ino | 247 +++ .../examples/ChatServer/ChatServer.ino | 99 ++ .../DhcpAddressPrinter/DhcpAddressPrinter.ino | 95 + .../DhcpChatServer/DhcpChatServer.ino | 102 ++ .../examples/LinkStatus/LinkStatus.ino | 43 + .../examples/TelnetClient/TelnetClient.ino | 113 ++ .../UDPSendReceiveString.ino | 139 ++ .../examples/UdpNtpClient/UdpNtpClient.ino | 156 ++ .../Ethernet/examples/WebClient/WebClient.ino | 137 ++ .../WebClientRepeating/WebClientRepeating.ino | 130 ++ .../Ethernet/examples/WebServer/WebServer.ino | 123 ++ libraries/Ethernet/keywords.txt | 67 + libraries/Ethernet/library.properties | 10 + libraries/Ethernet/src/Dhcp.cpp | 433 +++++ libraries/Ethernet/src/Dhcp.h | 137 ++ libraries/Ethernet/src/Dns.cpp | 354 ++++ libraries/Ethernet/src/Dns.h | 40 + libraries/Ethernet/src/Ethernet.cpp | 242 +++ libraries/Ethernet/src/Ethernet.h | 322 ++++ libraries/Ethernet/src/EthernetClient.cpp | 215 +++ libraries/Ethernet/src/EthernetClient.h | 3 + libraries/Ethernet/src/EthernetServer.cpp | 179 ++ libraries/Ethernet/src/EthernetServer.h | 3 + libraries/Ethernet/src/EthernetUdp.cpp | 191 +++ libraries/Ethernet/src/EthernetUdp.h | 38 + libraries/Ethernet/src/socket.cpp | 539 ++++++ libraries/Ethernet/src/utility/w5100.cpp | 474 +++++ libraries/Ethernet/src/utility/w5100.h | 466 +++++ libraries/Firmata/Boards.h | 953 ++++++++++ libraries/Firmata/Firmata.cpp | 554 ++++++ libraries/Firmata/Firmata.h | 180 ++ libraries/Firmata/FirmataConstants.h | 97 ++ libraries/Firmata/FirmataDefines.h | 283 +++ libraries/Firmata/FirmataMarshaller.cpp | 431 +++++ libraries/Firmata/FirmataMarshaller.h | 75 + libraries/Firmata/FirmataParser.cpp | 480 ++++++ libraries/Firmata/FirmataParser.h | 105 ++ libraries/Firmata/LICENSE.txt | 458 +++++ .../AllInputsFirmata/AllInputsFirmata.ino | 90 + .../examples/AnalogFirmata/AnalogFirmata.ino | 94 + .../examples/EchoString/EchoString.ino | 44 + .../examples/OldStandardFirmata/LICENSE.txt | 458 +++++ .../OldStandardFirmata/OldStandardFirmata.ino | 239 +++ .../examples/ServoFirmata/ServoFirmata.ino | 65 + .../SimpleAnalogFirmata.ino | 46 + .../SimpleDigitalFirmata.ino | 72 + .../examples/StandardFirmata/LICENSE.txt | 458 +++++ .../StandardFirmata/StandardFirmata.ino | 823 +++++++++ .../examples/StandardFirmataBLE/LICENSE.txt | 458 +++++ .../StandardFirmataBLE/StandardFirmataBLE.ino | 835 +++++++++ .../examples/StandardFirmataBLE/bleConfig.h | 168 ++ .../StandardFirmataChipKIT/LICENSE.txt | 458 +++++ .../StandardFirmataChipKIT.ino | 802 +++++++++ .../StandardFirmataEthernet/LICENSE.txt | 458 +++++ .../StandardFirmataEthernet.ino | 969 +++++++++++ .../StandardFirmataEthernet/ethernetConfig.h | 94 + .../examples/StandardFirmataPlus/LICENSE.txt | 458 +++++ .../StandardFirmataPlus.ino | 851 +++++++++ .../examples/StandardFirmataWiFi/LICENSE.txt | 458 +++++ .../StandardFirmataWiFi.ino | 1048 +++++++++++ .../examples/StandardFirmataWiFi/wifiConfig.h | 240 +++ libraries/Firmata/extras/revisions.txt | 265 +++ libraries/Firmata/keywords.txt | 90 + libraries/Firmata/library.properties | 9 + libraries/Firmata/readme.md | 194 +++ libraries/Firmata/release.sh | 33 + .../test/firmata_test/firmata_test.ino | 172 ++ libraries/Firmata/test/readme.md | 13 + libraries/Firmata/utility/BLEStream.cpp | 3 + libraries/Firmata/utility/BLEStream.h | 243 +++ .../utility/BluefruitLE_SPI_Stream.cpp | 3 + .../Firmata/utility/BluefruitLE_SPI_Stream.h | 157 ++ .../Firmata/utility/EthernetClientStream.cpp | 3 + .../Firmata/utility/EthernetClientStream.h | 141 ++ .../Firmata/utility/EthernetServerStream.cpp | 3 + .../Firmata/utility/EthernetServerStream.h | 147 ++ libraries/Firmata/utility/FirmataFeature.h | 38 + libraries/Firmata/utility/SerialFirmata.cpp | 342 ++++ libraries/Firmata/utility/SerialFirmata.h | 208 +++ libraries/Firmata/utility/WiFiClientStream.h | 105 ++ libraries/Firmata/utility/WiFiServerStream.h | 107 ++ libraries/Firmata/utility/WiFiStream.cpp | 4 + libraries/Firmata/utility/WiFiStream.h | 226 +++ libraries/Firmata/utility/firmataDebug.h | 14 + libraries/GyverButton/LICENSE | 21 + libraries/GyverButton/README.md | 171 ++ .../examples/Gbutton_demo/Gbutton_demo.ino | 59 + .../Gbutton_example/Gbutton_example.ino | 50 + .../Gbutton_example_auto.ino | 54 + .../Gbutton_interrupt/Gbutton_interrupt.ino | 42 + .../Gbutton_timer_interrupt.ino | 44 + .../examples/_1-2-3-click/_1-2-3-click.ino | 18 + .../examples/_5_buttons/_5_buttons.ino | 36 + .../_5_buttons_auto/_5_buttons_auto.ino | 37 + .../examples/analogKeyboard/analogBtns.jpg | Bin 0 -> 94388 bytes .../analogKeyboard/analogKeyboard.ino | 45 + .../analogKeyboardG/analogKeyboardG.ino | 49 + .../btn_pinChangeInt/btn_pinChangeInt.ino | 57 + .../examples/clicks_step/clicks_step.ino | 27 + .../examples/increment/increment.ino | 41 + .../examples/many_clicks/many_clicks.ino | 19 + libraries/GyverButton/keywords.txt | 51 + libraries/GyverButton/library.properties | 9 + libraries/GyverButton/src/AnalogKey.h | 64 + libraries/GyverButton/src/GyverButton.cpp | 224 +++ libraries/GyverButton/src/GyverButton.h | 134 ++ libraries/Keyboard/LICENSE | 165 ++ libraries/Keyboard/README.adoc | 31 + libraries/Keyboard/examples/Serial/Serial.ino | 39 + libraries/Keyboard/keywords.txt | 24 + libraries/Keyboard/library.properties | 9 + libraries/Keyboard/src/Keyboard.cpp | 214 +++ libraries/Keyboard/src/Keyboard.h | 120 ++ libraries/Keyboard/src/KeyboardLayout.h | 65 + .../Keyboard/src/KeyboardLayout_de_DE.cpp | 138 ++ .../Keyboard/src/KeyboardLayout_en_US.cpp | 138 ++ .../Keyboard/src/KeyboardLayout_es_ES.cpp | 138 ++ .../Keyboard/src/KeyboardLayout_fr_FR.cpp | 138 ++ .../Keyboard/src/KeyboardLayout_it_IT.cpp | 138 ++ .../LiquidCrystal_I2C.cpp | 332 ++++ .../LiquidCrystal_I2C.h | 131 ++ libraries/LiquidCrystal_I2C-master/README.md | 6 + .../examples/CustomChars/CustomChars.pde | 70 + .../examples/HelloWorld/HelloWorld.pde | 26 + .../examples/SerialDisplay/SerialDisplay.pde | 34 + .../LiquidCrystal_I2C-master/keywords.txt | 46 + .../LiquidCrystal_I2C-master/library.json | 16 + .../library.properties | 9 + libraries/Mouse/README.adoc | 25 + libraries/Mouse/keywords.txt | 24 + libraries/Mouse/library.properties | 9 + libraries/Mouse/src/Mouse.cpp | 123 ++ libraries/Mouse/src/Mouse.h | 60 + libraries/SD/README.adoc | 26 + libraries/SD/examples/CardInfo/CardInfo.ino | 116 ++ .../SD/examples/Datalogger/Datalogger.ino | 84 + libraries/SD/examples/DumpFile/DumpFile.ino | 65 + libraries/SD/examples/Files/Files.ino | 75 + .../NonBlockingWrite/NonBlockingWrite.ino | 91 + libraries/SD/examples/ReadWrite/ReadWrite.ino | 79 + libraries/SD/examples/listfiles/listfiles.ino | 80 + .../SD/extras/codespell-ignore-words-list.txt | 0 libraries/SD/keywords.txt | 31 + libraries/SD/library.properties | 9 + libraries/SD/src/File.cpp | 168 ++ libraries/SD/src/README.txt | 13 + libraries/SD/src/SD.cpp | 637 +++++++ libraries/SD/src/SD.h | 138 ++ libraries/SD/src/utility/FatStructs.h | 418 +++++ libraries/SD/src/utility/Sd2Card.cpp | 777 +++++++++ libraries/SD/src/utility/Sd2Card.h | 273 +++ libraries/SD/src/utility/Sd2PinMap.h | 525 ++++++ libraries/SD/src/utility/SdFat.h | 641 +++++++ libraries/SD/src/utility/SdFatUtil.h | 77 + libraries/SD/src/utility/SdFatmainpage.h | 202 +++ libraries/SD/src/utility/SdFile.cpp | 1527 +++++++++++++++++ libraries/SD/src/utility/SdInfo.h | 232 +++ libraries/SD/src/utility/SdVolume.cpp | 351 ++++ libraries/Servo/LICENSE.txt | 504 ++++++ libraries/Servo/README.adoc | 13 + libraries/Servo/docs/api.md | 181 ++ libraries/Servo/docs/readme.md | 21 + libraries/Servo/examples/Knob/Knob.ino | 26 + .../Servo/examples/Knob/images/knob_BB.png | Bin 0 -> 20514 bytes .../Servo/examples/Knob/images/knob_schem.png | Bin 0 -> 26918 bytes libraries/Servo/examples/Knob/readme.md | 35 + libraries/Servo/examples/Sweep/Sweep.ino | 31 + .../Servo/examples/Sweep/images/sweep_bb.png | Bin 0 -> 18442 bytes .../examples/Sweep/images/sweep_schem.png | Bin 0 -> 20480 bytes libraries/Servo/examples/Sweep/readme.md | 29 + libraries/Servo/keywords.txt | 24 + libraries/Servo/library.properties | 9 + libraries/Servo/src/Servo.h | 123 ++ libraries/Servo/src/avr/Servo.cpp | 317 ++++ libraries/Servo/src/avr/ServoTimers.h | 58 + libraries/Servo/src/mbed/Servo.cpp | 139 ++ libraries/Servo/src/mbed/ServoTimers.h | 1 + libraries/Servo/src/megaavr/Servo.cpp | 214 +++ libraries/Servo/src/megaavr/ServoTimers.h | 54 + libraries/Servo/src/nrf52/Servo.cpp | 134 ++ libraries/Servo/src/nrf52/ServoTimers.h | 38 + libraries/Servo/src/sam/Servo.cpp | 282 +++ libraries/Servo/src/sam/ServoTimers.h | 87 + libraries/Servo/src/samd/Servo.cpp | 297 ++++ libraries/Servo/src/samd/ServoTimers.h | 71 + libraries/Servo/src/stm32f4/Servo.cpp | 194 +++ libraries/Servo/src/stm32f4/ServoTimers.h | 207 +++ libraries/Stepper/README.adoc | 26 + .../Stepper/examples/MotorKnob/MotorKnob.ino | 39 + .../stepper_oneRevolution.ino | 44 + .../stepper_oneStepAtATime.ino | 44 + .../stepper_speedControl.ino | 48 + libraries/Stepper/keywords.txt | 28 + libraries/Stepper/library.properties | 9 + libraries/Stepper/src/Stepper.cpp | 365 ++++ libraries/Stepper/src/Stepper.h | 121 ++ libraries/TFT/README.adoc | 26 + .../Arduino/TFTBitmapLogo/TFTBitmapLogo.ino | 108 ++ .../Arduino/TFTBitmapLogo/arduino.bmp | Bin 0 -> 6966 bytes .../Arduino/TFTColorPicker/TFTColorPicker.ino | 67 + .../Arduino/TFTDisplayText/TFTDisplayText.ino | 74 + .../Arduino/TFTEtchASketch/TFTEtchASketch.ino | 83 + .../examples/Arduino/TFTGraph/TFTGraph.ino | 70 + .../TFT/examples/Arduino/TFTPong/TFTPong.ino | 135 ++ .../EsploraTFTBitmapLogo.ino | 101 ++ .../Esplora/EsploraTFTBitmapLogo/arduino.bmp | Bin 0 -> 6966 bytes .../EsploraTFTColorPicker.ino | 54 + .../EsploraTFTEtchASketch.ino | 80 + .../EsploraTFTGraph/EsploraTFTGraph.ino | 55 + .../EsploraTFTHorizon/EsploraTFTHorizon.ino | 62 + .../Esplora/EsploraTFTPong/EsploraTFTPong.ino | 126 ++ .../Esplora/EsploraTFTTemp/EsploraTFTTemp.ino | 64 + libraries/TFT/extras/Adafruit-README.txt | 21 + libraries/TFT/extras/Adafruit-license.txt | 25 + libraries/TFT/extras/README.md | 18 + libraries/TFT/keywords.txt | 20 + libraries/TFT/library.properties | 9 + libraries/TFT/src/TFT.cpp | 51 + libraries/TFT/src/TFT.h | 58 + libraries/TFT/src/utility/Adafruit_GFX.cpp | 715 ++++++++ libraries/TFT/src/utility/Adafruit_GFX.h | 372 ++++ libraries/TFT/src/utility/Adafruit_ST7735.cpp | 751 ++++++++ libraries/TFT/src/utility/Adafruit_ST7735.h | 156 ++ libraries/TFT/src/utility/PImage.h | 65 + libraries/TFT/src/utility/glcdfont.c | 269 +++ libraries/TFT/src/utility/keywords.txt | 70 + 256 files changed, 41193 insertions(+) create mode 100644 libraries/Arduino_BuiltIn/LICENSE.txt create mode 100644 libraries/Arduino_BuiltIn/README.md create mode 100644 libraries/Arduino_BuiltIn/library.properties create mode 100644 libraries/Arduino_BuiltIn/src/Arduino_BuiltIn.h create mode 100644 libraries/EncButton/LICENSE create mode 100644 libraries/EncButton/README.md create mode 100644 libraries/EncButton/doc/diagram.png create mode 100644 libraries/EncButton/doc/enc.png create mode 100644 libraries/EncButton/doc/encAli.png create mode 100644 libraries/EncButton/examples/EncButton2/EncButton2.ino create mode 100644 libraries/EncButton/examples/EncButton2_array/EncButton2_array.ino create mode 100644 libraries/EncButton/examples/callbackISR/callbackISR.ino create mode 100644 libraries/EncButton/examples/callbackMode/callbackMode.ino create mode 100644 libraries/EncButton/examples/optimisation/optimisation.ino create mode 100644 libraries/EncButton/examples/pcint/pcint.ino create mode 100644 libraries/EncButton/examples/preClicks/preClicks.ino create mode 100644 libraries/EncButton/examples/stepMode/stepMode.ino create mode 100644 libraries/EncButton/examples/tickISR/tickISR.ino create mode 100644 libraries/EncButton/examples/tickMode/tickMode.ino create mode 100644 libraries/EncButton/examples/virtual/virtual.ino create mode 100644 libraries/EncButton/examples/virtual_AnalogKey/virtual_AnalogKey.ino create mode 100644 libraries/EncButton/examples/virtual_SimpleKeypad/virtual_SimpleKeypad.ino create mode 100644 libraries/EncButton/examples/virtual_SimpleKeypad_array/virtual_SimpleKeypad_array.ino create mode 100644 libraries/EncButton/keywords.txt create mode 100644 libraries/EncButton/library.properties create mode 100644 libraries/EncButton/src/EncButton.h create mode 100644 libraries/EncButton/src/EncButton2.h create mode 100644 libraries/Ethernet/AUTHORS create mode 100644 libraries/Ethernet/README.adoc create mode 100644 libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino create mode 100644 libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino create mode 100644 libraries/Ethernet/examples/ChatServer/ChatServer.ino create mode 100644 libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino create mode 100644 libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino create mode 100644 libraries/Ethernet/examples/LinkStatus/LinkStatus.ino create mode 100644 libraries/Ethernet/examples/TelnetClient/TelnetClient.ino create mode 100644 libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino create mode 100644 libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino create mode 100644 libraries/Ethernet/examples/WebClient/WebClient.ino create mode 100644 libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino create mode 100644 libraries/Ethernet/examples/WebServer/WebServer.ino create mode 100644 libraries/Ethernet/keywords.txt create mode 100644 libraries/Ethernet/library.properties create mode 100644 libraries/Ethernet/src/Dhcp.cpp create mode 100644 libraries/Ethernet/src/Dhcp.h create mode 100644 libraries/Ethernet/src/Dns.cpp create mode 100644 libraries/Ethernet/src/Dns.h create mode 100644 libraries/Ethernet/src/Ethernet.cpp create mode 100644 libraries/Ethernet/src/Ethernet.h create mode 100644 libraries/Ethernet/src/EthernetClient.cpp create mode 100644 libraries/Ethernet/src/EthernetClient.h create mode 100644 libraries/Ethernet/src/EthernetServer.cpp create mode 100644 libraries/Ethernet/src/EthernetServer.h create mode 100644 libraries/Ethernet/src/EthernetUdp.cpp create mode 100644 libraries/Ethernet/src/EthernetUdp.h create mode 100644 libraries/Ethernet/src/socket.cpp create mode 100644 libraries/Ethernet/src/utility/w5100.cpp create mode 100644 libraries/Ethernet/src/utility/w5100.h create mode 100644 libraries/Firmata/Boards.h create mode 100644 libraries/Firmata/Firmata.cpp create mode 100644 libraries/Firmata/Firmata.h create mode 100644 libraries/Firmata/FirmataConstants.h create mode 100644 libraries/Firmata/FirmataDefines.h create mode 100644 libraries/Firmata/FirmataMarshaller.cpp create mode 100644 libraries/Firmata/FirmataMarshaller.h create mode 100644 libraries/Firmata/FirmataParser.cpp create mode 100644 libraries/Firmata/FirmataParser.h create mode 100644 libraries/Firmata/LICENSE.txt create mode 100644 libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino create mode 100644 libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino create mode 100644 libraries/Firmata/examples/EchoString/EchoString.ino create mode 100644 libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt create mode 100644 libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino create mode 100644 libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino create mode 100644 libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino create mode 100644 libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino create mode 100644 libraries/Firmata/examples/StandardFirmata/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino create mode 100644 libraries/Firmata/examples/StandardFirmataBLE/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataBLE/StandardFirmataBLE.ino create mode 100644 libraries/Firmata/examples/StandardFirmataBLE/bleConfig.h create mode 100644 libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino create mode 100644 libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino create mode 100644 libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h create mode 100644 libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino create mode 100644 libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino create mode 100644 libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h create mode 100644 libraries/Firmata/extras/revisions.txt create mode 100644 libraries/Firmata/keywords.txt create mode 100644 libraries/Firmata/library.properties create mode 100644 libraries/Firmata/readme.md create mode 100644 libraries/Firmata/release.sh create mode 100644 libraries/Firmata/test/firmata_test/firmata_test.ino create mode 100644 libraries/Firmata/test/readme.md create mode 100644 libraries/Firmata/utility/BLEStream.cpp create mode 100644 libraries/Firmata/utility/BLEStream.h create mode 100644 libraries/Firmata/utility/BluefruitLE_SPI_Stream.cpp create mode 100644 libraries/Firmata/utility/BluefruitLE_SPI_Stream.h create mode 100644 libraries/Firmata/utility/EthernetClientStream.cpp create mode 100644 libraries/Firmata/utility/EthernetClientStream.h create mode 100644 libraries/Firmata/utility/EthernetServerStream.cpp create mode 100644 libraries/Firmata/utility/EthernetServerStream.h create mode 100644 libraries/Firmata/utility/FirmataFeature.h create mode 100644 libraries/Firmata/utility/SerialFirmata.cpp create mode 100644 libraries/Firmata/utility/SerialFirmata.h create mode 100644 libraries/Firmata/utility/WiFiClientStream.h create mode 100644 libraries/Firmata/utility/WiFiServerStream.h create mode 100644 libraries/Firmata/utility/WiFiStream.cpp create mode 100644 libraries/Firmata/utility/WiFiStream.h create mode 100644 libraries/Firmata/utility/firmataDebug.h create mode 100644 libraries/GyverButton/LICENSE create mode 100644 libraries/GyverButton/README.md create mode 100644 libraries/GyverButton/examples/Gbutton_demo/Gbutton_demo.ino create mode 100644 libraries/GyverButton/examples/Gbutton_example/Gbutton_example.ino create mode 100644 libraries/GyverButton/examples/Gbutton_example_auto/Gbutton_example_auto.ino create mode 100644 libraries/GyverButton/examples/Gbutton_interrupt/Gbutton_interrupt.ino create mode 100644 libraries/GyverButton/examples/Gbutton_timer_interrupt/Gbutton_timer_interrupt.ino create mode 100644 libraries/GyverButton/examples/_1-2-3-click/_1-2-3-click.ino create mode 100644 libraries/GyverButton/examples/_5_buttons/_5_buttons.ino create mode 100644 libraries/GyverButton/examples/_5_buttons_auto/_5_buttons_auto.ino create mode 100644 libraries/GyverButton/examples/analogKeyboard/analogBtns.jpg create mode 100644 libraries/GyverButton/examples/analogKeyboard/analogKeyboard.ino create mode 100644 libraries/GyverButton/examples/analogKeyboardG/analogKeyboardG.ino create mode 100644 libraries/GyverButton/examples/btn_pinChangeInt/btn_pinChangeInt.ino create mode 100644 libraries/GyverButton/examples/clicks_step/clicks_step.ino create mode 100644 libraries/GyverButton/examples/increment/increment.ino create mode 100644 libraries/GyverButton/examples/many_clicks/many_clicks.ino create mode 100644 libraries/GyverButton/keywords.txt create mode 100644 libraries/GyverButton/library.properties create mode 100644 libraries/GyverButton/src/AnalogKey.h create mode 100644 libraries/GyverButton/src/GyverButton.cpp create mode 100644 libraries/GyverButton/src/GyverButton.h create mode 100644 libraries/Keyboard/LICENSE create mode 100644 libraries/Keyboard/README.adoc create mode 100644 libraries/Keyboard/examples/Serial/Serial.ino create mode 100644 libraries/Keyboard/keywords.txt create mode 100644 libraries/Keyboard/library.properties create mode 100644 libraries/Keyboard/src/Keyboard.cpp create mode 100644 libraries/Keyboard/src/Keyboard.h create mode 100644 libraries/Keyboard/src/KeyboardLayout.h create mode 100644 libraries/Keyboard/src/KeyboardLayout_de_DE.cpp create mode 100644 libraries/Keyboard/src/KeyboardLayout_en_US.cpp create mode 100644 libraries/Keyboard/src/KeyboardLayout_es_ES.cpp create mode 100644 libraries/Keyboard/src/KeyboardLayout_fr_FR.cpp create mode 100644 libraries/Keyboard/src/KeyboardLayout_it_IT.cpp create mode 100644 libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.cpp create mode 100644 libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.h create mode 100644 libraries/LiquidCrystal_I2C-master/README.md create mode 100644 libraries/LiquidCrystal_I2C-master/examples/CustomChars/CustomChars.pde create mode 100644 libraries/LiquidCrystal_I2C-master/examples/HelloWorld/HelloWorld.pde create mode 100644 libraries/LiquidCrystal_I2C-master/examples/SerialDisplay/SerialDisplay.pde create mode 100644 libraries/LiquidCrystal_I2C-master/keywords.txt create mode 100644 libraries/LiquidCrystal_I2C-master/library.json create mode 100644 libraries/LiquidCrystal_I2C-master/library.properties create mode 100644 libraries/Mouse/README.adoc create mode 100644 libraries/Mouse/keywords.txt create mode 100644 libraries/Mouse/library.properties create mode 100644 libraries/Mouse/src/Mouse.cpp create mode 100644 libraries/Mouse/src/Mouse.h create mode 100644 libraries/SD/README.adoc create mode 100644 libraries/SD/examples/CardInfo/CardInfo.ino create mode 100644 libraries/SD/examples/Datalogger/Datalogger.ino create mode 100644 libraries/SD/examples/DumpFile/DumpFile.ino create mode 100644 libraries/SD/examples/Files/Files.ino create mode 100644 libraries/SD/examples/NonBlockingWrite/NonBlockingWrite.ino create mode 100644 libraries/SD/examples/ReadWrite/ReadWrite.ino create mode 100644 libraries/SD/examples/listfiles/listfiles.ino create mode 100644 libraries/SD/extras/codespell-ignore-words-list.txt create mode 100644 libraries/SD/keywords.txt create mode 100644 libraries/SD/library.properties create mode 100644 libraries/SD/src/File.cpp create mode 100644 libraries/SD/src/README.txt create mode 100644 libraries/SD/src/SD.cpp create mode 100644 libraries/SD/src/SD.h create mode 100644 libraries/SD/src/utility/FatStructs.h create mode 100644 libraries/SD/src/utility/Sd2Card.cpp create mode 100644 libraries/SD/src/utility/Sd2Card.h create mode 100644 libraries/SD/src/utility/Sd2PinMap.h create mode 100644 libraries/SD/src/utility/SdFat.h create mode 100644 libraries/SD/src/utility/SdFatUtil.h create mode 100644 libraries/SD/src/utility/SdFatmainpage.h create mode 100644 libraries/SD/src/utility/SdFile.cpp create mode 100644 libraries/SD/src/utility/SdInfo.h create mode 100644 libraries/SD/src/utility/SdVolume.cpp create mode 100644 libraries/Servo/LICENSE.txt create mode 100644 libraries/Servo/README.adoc create mode 100644 libraries/Servo/docs/api.md create mode 100644 libraries/Servo/docs/readme.md create mode 100644 libraries/Servo/examples/Knob/Knob.ino create mode 100644 libraries/Servo/examples/Knob/images/knob_BB.png create mode 100644 libraries/Servo/examples/Knob/images/knob_schem.png create mode 100644 libraries/Servo/examples/Knob/readme.md create mode 100644 libraries/Servo/examples/Sweep/Sweep.ino create mode 100644 libraries/Servo/examples/Sweep/images/sweep_bb.png create mode 100644 libraries/Servo/examples/Sweep/images/sweep_schem.png create mode 100644 libraries/Servo/examples/Sweep/readme.md create mode 100644 libraries/Servo/keywords.txt create mode 100644 libraries/Servo/library.properties create mode 100644 libraries/Servo/src/Servo.h create mode 100644 libraries/Servo/src/avr/Servo.cpp create mode 100644 libraries/Servo/src/avr/ServoTimers.h create mode 100644 libraries/Servo/src/mbed/Servo.cpp create mode 100644 libraries/Servo/src/mbed/ServoTimers.h create mode 100644 libraries/Servo/src/megaavr/Servo.cpp create mode 100644 libraries/Servo/src/megaavr/ServoTimers.h create mode 100644 libraries/Servo/src/nrf52/Servo.cpp create mode 100644 libraries/Servo/src/nrf52/ServoTimers.h create mode 100644 libraries/Servo/src/sam/Servo.cpp create mode 100644 libraries/Servo/src/sam/ServoTimers.h create mode 100644 libraries/Servo/src/samd/Servo.cpp create mode 100644 libraries/Servo/src/samd/ServoTimers.h create mode 100644 libraries/Servo/src/stm32f4/Servo.cpp create mode 100644 libraries/Servo/src/stm32f4/ServoTimers.h create mode 100644 libraries/Stepper/README.adoc create mode 100644 libraries/Stepper/examples/MotorKnob/MotorKnob.ino create mode 100644 libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino create mode 100644 libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino create mode 100644 libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino create mode 100644 libraries/Stepper/keywords.txt create mode 100644 libraries/Stepper/library.properties create mode 100644 libraries/Stepper/src/Stepper.cpp create mode 100644 libraries/Stepper/src/Stepper.h create mode 100644 libraries/TFT/README.adoc create mode 100644 libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino create mode 100644 libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp create mode 100644 libraries/TFT/examples/Arduino/TFTColorPicker/TFTColorPicker.ino create mode 100644 libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino create mode 100644 libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino create mode 100644 libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino create mode 100644 libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTColorPicker/EsploraTFTColorPicker.ino create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino create mode 100644 libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino create mode 100644 libraries/TFT/extras/Adafruit-README.txt create mode 100644 libraries/TFT/extras/Adafruit-license.txt create mode 100644 libraries/TFT/extras/README.md create mode 100644 libraries/TFT/keywords.txt create mode 100644 libraries/TFT/library.properties create mode 100644 libraries/TFT/src/TFT.cpp create mode 100644 libraries/TFT/src/TFT.h create mode 100644 libraries/TFT/src/utility/Adafruit_GFX.cpp create mode 100644 libraries/TFT/src/utility/Adafruit_GFX.h create mode 100644 libraries/TFT/src/utility/Adafruit_ST7735.cpp create mode 100644 libraries/TFT/src/utility/Adafruit_ST7735.h create mode 100644 libraries/TFT/src/utility/PImage.h create mode 100644 libraries/TFT/src/utility/glcdfont.c create mode 100644 libraries/TFT/src/utility/keywords.txt diff --git a/libraries/Arduino_BuiltIn/LICENSE.txt b/libraries/Arduino_BuiltIn/LICENSE.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/libraries/Arduino_BuiltIn/LICENSE.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/libraries/Arduino_BuiltIn/README.md b/libraries/Arduino_BuiltIn/README.md new file mode 100644 index 0000000..a7e3f68 --- /dev/null +++ b/libraries/Arduino_BuiltIn/README.md @@ -0,0 +1,8 @@ +# Arduino_BuiltIn library for Arduino + +[![Check Arduino status](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/check-arduino.yml/badge.svg)](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/check-arduino.yml) +[![Spell Check status](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/spell-check.yml/badge.svg)](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/spell-check.yml) + +Shell Arduino library to provide the standard built-in libraries. + +The sole purpose of this library is to install the standard Arduino libraries which are typically included with the Arduino IDE. This is accomplished by defining the built-in libraries as dependencies in [the library.properties metadata file](https://arduino.github.io/arduino-cli/latest/library-specification/#library-metadata). diff --git a/libraries/Arduino_BuiltIn/library.properties b/libraries/Arduino_BuiltIn/library.properties new file mode 100644 index 0000000..963c34c --- /dev/null +++ b/libraries/Arduino_BuiltIn/library.properties @@ -0,0 +1,10 @@ +name=Arduino_BuiltIn +version=1.0.0 +author=Arduino +maintainer=Arduino +sentence=Shell Arduino library to provide the standard built-in libraries +paragraph=The sole purpose of this library is to install the standard Arduino libraries which are typically included with the Arduino IDE. +category=Other +url=https://github.com/arduino-libraries/Arduino_BuiltIn +architectures=* +depends=Ethernet,Firmata,Keyboard,LiquidCrystal,Mouse,SD,Servo,Stepper,TFT diff --git a/libraries/Arduino_BuiltIn/src/Arduino_BuiltIn.h b/libraries/Arduino_BuiltIn/src/Arduino_BuiltIn.h new file mode 100644 index 0000000..16a34d4 --- /dev/null +++ b/libraries/Arduino_BuiltIn/src/Arduino_BuiltIn.h @@ -0,0 +1,2 @@ +// This file intentionally left empty. +// It serves only to make this shell library fully valid. diff --git a/libraries/EncButton/LICENSE b/libraries/EncButton/LICENSE new file mode 100644 index 0000000..353b7ee --- /dev/null +++ b/libraries/EncButton/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Alex + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/libraries/EncButton/README.md b/libraries/EncButton/README.md new file mode 100644 index 0000000..58b5662 --- /dev/null +++ b/libraries/EncButton/README.md @@ -0,0 +1,539 @@ +[![Foo](https://img.shields.io/badge/Version-1.20-brightgreen.svg?style=flat-square)](#versions) +[![Foo](https://img.shields.io/badge/Website-AlexGyver.ru-blue.svg?style=flat-square)](https://alexgyver.ru/) +[![Foo](https://img.shields.io/badge/%E2%82%BD$%E2%82%AC%20%D0%9D%D0%B0%20%D0%BF%D0%B8%D0%B2%D0%BE-%D1%81%20%D1%80%D1%8B%D0%B1%D0%BA%D0%BE%D0%B9-orange.svg?style=flat-square)](https://alexgyver.ru/support_alex/) + +# EncButton +Ультра лёгкая и быстрая библиотека для энкодера, энкодера с кнопкой или просто кнопки +- Максимально быстрое чтение пинов для AVR (ATmega328/ATmega168, ATtiny85/ATtiny13) +- Максимально лёгкий вес +- Быстрые и лёгкие алгоритмы опроса кнопки и энкодера +- Энкодер: обычный поворот, нажатый поворот, быстрый поворот, доступ к счётчику +- Кнопка: антидребезг, клик, несколько кликов, счётчик кликов, удержание, режим импульсного удержания +- Подключение - **только с подтяжкой к питанию** (внешней или внутренней)! +- Опциональный режим с обработчиками callback (+24 байта SRAM на каждый экземпляр) +- Виртуальный режим (кнопка, энк, энк с кнопкой) + +### Совместимость +Совместима со всеми Arduino платформами (используются Arduino-функции) + +## Содержание +- [Установка](#install) +- [Железо](#hardware) +- [Инициализация](#init) +- [Использование](#usage) +- [Пример](#example) +- [Версии](#versions) +- [Баги и обратная связь](#feedback) + + +## Установка +- Библиотеку можно найти по названию **EncButton** и установить через менеджер библиотек в: + - Arduino IDE + - Arduino IDE v2 + - PlatformIO +- [Скачать библиотеку](https://github.com/GyverLibs/EncButton/archive/refs/heads/main.zip) .zip архивом для ручной установки: + - Распаковать и положить в *C:\Program Files (x86)\Arduino\libraries* (Windows x64) + - Распаковать и положить в *C:\Program Files\Arduino\libraries* (Windows x32) + - Распаковать и положить в *Документы/Arduino/libraries/* + - (Arduino IDE) автоматическая установка из .zip: *Скетч/Подключить библиотеку/Добавить .ZIP библиотеку…* и указать скачанный архив +- Читай более подробную инструкцию по установке библиотек [здесь](https://alexgyver.ru/arduino-first/#%D0%A3%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0_%D0%B1%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA) + + +## Железо +Для работы по сценарию "энкодер с кнопкой" рекомендую вот такие ([ссылка](https://ali.ski/CYir4), [ссылка](https://ali.ski/49q5hy)) круглые китайские модули с распаянными цепями антидребезга: +![scheme](/doc/encAli.png) + +Самостоятельно обвязать энкодер можно по следующей схеме (RC фильтры на каналы энкодера + подтяжка всех пинов к VCC): +![scheme](/doc/enc.png) + +## Производительность +Время холостого выполнения функции tick() при реальном устройстве (кнопка/энкодер подключены к пинам МК) на ATmega328, библиотека EncButton: +| Режим | Время, мкс | +| ----- | ---------- | +| Энкодер + кнопка | 3.8 | +| Энкодер | 2.4 | +| Кнопка | 1.9 | + +*Для сравнения, стандартный digitalRead() на AVR выполняется 3.5 us* + +## Сравнение с аналогами +- EncButton в режиме кнопки на 6 мкс быстрее, на ~450 байт Flash и 12 байт SRAM легче моей старой библиотеки [GyverButton](https://github.com/GyverLibs/GyverButton), имея при этом больше возможностей +- EncButton в режиме энкодера с кнопкой на 6 мкс быстрее, на ~400 байт Flash и 18 байт SRAM легче моей старой библиотеки [GyverEncoder](https://github.com/GyverLibs/GyverEncoder), имея при этом больше возможностей + + +## Инициализация +**Если нужен массив кнопок/энкодеров, используй EncButton2!** +
+Инициализация EncButton + +```cpp +// ============== БАЗОВАЯ ============= +EncButton enc; // энкодер с кнопкой +EncButton enc; // просто энкодер +EncButton btn; // просто кнопка +// A, B, KEY: номера пинов +// MODE: EB_TICK или EB_CALLBACK - режим работы ручной или с обработчиками +// для изменения направления энкодера поменяй A и B при инициализации + +// ============ ПОДКЛЮЧЕНИЕ ============ +// По умолчанию пины настраиваются в INPUT_PULLUP +// Если используется внешняя подтяжка - лучше перевести в INPUT +EncButton<...> enc(INPUT); + +// ========= ВИРТУАЛЬНЫЙ РЕЖИМ ========= +EncButton enc; // виртуальная кнопка +EncButton enc; // виртуальный энк с кнопкой +EncButton enc; // виртуальный энк +// в tick нужно будет передавать виртуальное значение, см. пример +``` +
+
+Инициализация EncButton2 + +Хранит пины НЕ в шаблоне, а как член класса. Всё кроме инициализации такое же как у EncButton! +```cpp +// ================ TICK =============== +EncButton2 enc(INPUT, A, B, KEY); // энкодер с кнопкой +EncButton2 enc(INPUT, A, B); // просто энкодер +EncButton2 enc(INPUT, KEY); // просто кнопка +// режим пинов INPUT/INPUT_PULLUP + +// ============== CALLBACK ============= +EncButton2 enc(INPUT, A, B, KEY); // энкодер с кнопкой +EncButton2 enc(INPUT, A, B); // просто энкодер +EncButton2 enc(INPUT, KEY); // просто кнопка +// режим пинов INPUT/INPUT_PULLUP + +// ============== VIRT TICK ============ +EncButton2 enc; // энкодер с кнопкой +EncButton2 enc; // просто энкодер +EncButton2 enc; // просто кнопка + +// ============ VIRT CALLBACK ========== +EncButton2 enc; // энкодер с кнопкой +EncButton2 enc; // просто энкодер +EncButton2 enc; // просто кнопка +``` +
+
+Массив экземпляров EncButton2 + +```cpp +EncButton2 enc[количество]; +EncButton2 enc[количество]; +EncButton2 enc[количество]; + +EncButton2 enc[количество]; +EncButton2 enc[количество]; +EncButton2 enc[количество]; +// и так далее +// Задавать пины можно через setPins() +setPins(uint8_t mode, uint8_t P1, uint8_t P2, uint8_t P3); +// mode - INPUT/INPUT_PULLUP (для всех пинов) +// указываем только нужные для выбранного режима пины: +// EB_ENCBTN - A, B, KEY +// EB_ENC - A, B +// EB_BTN - KEY +// см. пример EucButton2_array +``` +
+ +## Документация +
+ПОЛНОЕ ОПИСАНИЕ КЛАССА + +```cpp +// =============== SETTINGS ============== +void pullUp(); // подтянуть все пины внутренней подтяжкой +void holdEncButton(bool state); // виртуально зажать кнопку энкодера +void setHoldTimeout(int tout); // установить время удержания кнопки, мс (до 30 000) +void setButtonLevel(bool level); // уровень кнопки: LOW - кнопка подключает GND (по умолч.), HIGH - кнопка подключает VCC + +// ================= TICK ================ +// тикер, вызывать как можно чаще или в прерывании +// вернёт отличное от нуля значение, если произошло какое то событие (см. пример optimisation) +uint8_t tick(); + +// tick(uint8_t s1 = 0, uint8_t s2 = 0, uint8_t key = 0) +// может принимать виртуальный сигнал при режиме VIRT_xxx: +// (сигнал кнопки) +// (сигнал энкодера А, сигнал энкодера B) +// (сигнал энкодера А, сигнал энкодера B, сигнал кнопки) + +// Тикер для прерывания в режиме callback. Не вызывает подключенные функции! +// Требует наличие обычного tick() в loop() (см. примеры tickISR и callbackISR) +uint8_t tickISR(); + +// проверяет и вызывает подключенные функции для режима callback +// Встроено в tick(), но вынесено отдельной функцией для нестандартных сценариев работы +void checkCallback(); + +// =============== STATUS ================ +uint8_t getState(); // получить статус кнопки/энкодера +void resetState(); // сбросить статус + +// =============== ENCODER =============== +bool turn(); // поворот на один щелчок в любую сторону +bool turnH(); // поворот на один щелчок в любую сторону с зажатой кнопкой +bool fast(); // быстрый поворот на один щелчок в любую сторону +bool right(); // поворот на один щелчок направо +bool left(); // поворот на один щелчок налево +bool rightH(); // поворот на один щелчок направо с зажатой кнопкой +bool leftH(); // поворот на один щелчок налево с зажатой кнопкой +int8_t getDir(); // направление последнего поворота, 1 или -1 +int counter; // доступ к счётчику энкодера + +// ================ BUTTON ================ +bool busy(); // вернёт true, если всё ещё нужно вызывать tick для опроса таймаутов +bool state(); // текущее состояние кнопки (true нажата, false не нажата) +bool press(); // кнопка была нажата [однократное срабатывание] +bool release(); // кнопка была отпущена [однократное срабатывание] +bool click(); // клик (нажата и отпущена) [однократное срабатывание] +bool held(); // кнопка была удержана [однократное срабатывание] +bool hold(); // кнопка удерживается [постоянное срабатывание] +bool step(); // режим импульсного удержания +bool step(uint8_t clicks); // режим импульсного удержания с предварительным накликиванием +bool releaseStep(); // отпущена после режима step +bool releaseStep(uint8_t clicks); // отпущена после режима step с предварительным накликиванием +uint8_t clicks; // доступ к счётчику кликов +uint8_t hasClicks(); // вернёт количество кликов, если они есть +bool hasClicks(uint8_t num); // проверка на наличие указанного количества кликов + +// =============== CALLBACK =============== +void attach(eb_callback type, void (*handler)()); // подключить обработчик +void detach(eb_callback type); // отключить обработчик +void attachClicks(uint8_t amount, void (*handler)()); // подключить обработчик на количество кликов (может быть только один!) +void detachClicks(); // отключить обработчик на количество кликов + +// eb_callback может быть: +TURN_HANDLER +TURN_H_HANDLER +RIGHT_HANDLER +LEFT_HANDLER +RIGHT_H_HANDLER +LEFT_H_HANDLER +CLICK_HANDLER +HOLDED_HANDLER +STEP_HANDLER +HOLD_HANDLER +CLICKS_HANDLER +PRESS_HANDLER +RELEASE_HANDLER +``` + +**Дополнительно у EncButton2** +```cpp +void pullUp(); // здесь не реализована! + +void setPins(uint8_t mode, uint8_t P1, uint8_t P2, uint8_t P3); // настроить пины +// mode - INPUT/INPUT_PULLUP (для всех пинов) +// указываем только нужные для выбранного режима пины: +// EB_ENCBTN - (A, B, KEY) +// EB_ENC - (A, B) +// EB_BTN - (KEY) +// см. пример EucButton2_array +``` +
+ +### Заметки +- Библиотека универсальная, но сделана с упором на максимальную оптимизацию памяти при работе во всех режимах внутри одного класса, поэтому используется шаблон и дефайны + - При создании объекта с разным количеством пинов (энкодер, кнопка, энкодер с кнопкой) библиотека будет компилироваться по разному, ненужный код будет вырезан. Это позволяет экономить Flash память. + - То же самое касается режимов работы TICK/CALLBACK, при использовании TICK весь относящийся к CALLBACK код вырезается компилятором +- Два алгоритма опроса энкодера, обычный и точный. Точный использует на 16 байт больше SRAM памяти (на всю библиотеку), но позволяет работать даже с низкокачественными и убитыми энкодерами + - Точный алгоритм активируется добавлением `#define EB_BETTER_ENC` перед подключением библиотеки +- Версия библиотеки *EncButton2.h* хранит номера пинов в классе. Используйте эту версию для создания массива объектов EncButton! + + +## Особенности и сценарии использования +### Дефайны настроек +```cpp +// дефайнить ПЕРЕД ПОДКЛЮЧЕНИЕМ БИБЛИОТЕКИ, показаны значения по умолчанию (если они есть) +// энкодер +#define EB_FAST 30 // таймаут быстрого поворота, мс +#define EB_BETTER_ENC // улучшенный алгоритм опроса энкодера. Добавит 16 байт SRAM при подключении библиотеки +#define EB_HALFSTEP_ENC // режим опроса полушагового энкодера (включи, если твой энкодер делает два тика за один) + +// кнопка +#define EB_DEB 50 // дебаунс кнопки, мс +#define EB_STEP 500 // период срабатывания степ, мс +#define EB_CLICK 400 // таймаут накликивания, мс +#define EB_HOLD 1000 // таймаут удержания кнопки (можно переназначить setHoldTimeout() из программы), мс +``` + +### Режим tick +- Опрос пинов энкодера/кнопки и расчёт таймаутов осуществляется внутри функции `tick()`. Эту функцию нужно однократно вызывать в основном цикле программы. +- Для повышения качества обработки энкодера/кнопки в загруженной программе (чтобы не пропустить поворот или клик) рекомендуется продублировать опрос в прерывании по *CHANGE*: внутри обработчика прерывания вызываем специальный тикер `tickISR()`, и в основном цикле программы оставляем обычный `tick()`. Он нужен для того, чтобы корректно считались все таймауты. +- `tick()` возвращает текущий статус энкодера/кнопки: + - 0 - никаких действий не было + - 1 - left + turn + - 2 - right + turn + - 3 - leftH + turnH + - 4 - rightH + turnH + - 5 - click + - 6 - held + - 7 - step + - 8 - press +Это позволяет например производить дальнейший опрос действий кнопки/энкодера только по факту их совершения: можно поместить весь опрос в блок `if (enc.tick()) {}`. В конце рекомендуется вызвать `resetState()` для сборса неопрошенных флагов, чтобы `tick()` перестал "сигналить" о действии. Подробнее смотри в примере *optimisation*. +- Основная идея работы: "тикнули", а затем вручную через условия опрашиваем нужные действия кнопки/энкодера. Почти все функции опроса имеют механизм "однократного срабатывания", то есть возвращают `true` и автоматически сбрасываются в `false` до наступления следующего события. Таким образом конструкция `if (btn.click())` позволяет выполнить какой-то блок кода однократно по клику. Подробнее разберём ниже. + +#### Кнопка +- `press()` - кнопка была нажата. *[однократно вернёт true]* +- `release()` - кнопка была отпущена. *[однократно вернёт true]* +- `click()` - кнопка была кликнута, т.е. нажата и отпущена до таймаута удержания. *[однократно вернёт true]* +- `held()` - кнопка была удержана дольше таймаута удержания. *[однократно вернёт true]* +- `held(clicks)` - то же самое, но функция принимает количество кликов, сделанных до удержания. Примечание: held() без аргумента перехватит вызов! См. пример *preClicks*. *[однократно вернёт true]* +- `hold()` - кнопка была удержана дольше таймаута удержания. *[возвращает true, пока удерживается]* +- `hold(clicks)` - то же самое, но функция принимает количество кликов, сделанных до удержания. Примечание: hold() без аргумента перехватит вызов! См. пример *preClicks*. *[возвращает true, пока удерживается]* +- `step()` - режим "импульсного удержания": после удержания кнопки дольше таймаута данная функция *[возвращает true с периодом EB_STEP]*. Удобно использовать для пошагового изменения переменных: `if (btn.step()) val++;`. +- `step(clicks)` - то же самое, но функция принимает количество кликов, сделанных до удержания. Примечание: step() без аргумента перехватит вызов! См. пример *StepMode* и *preClicks*. +- `releaseStep()` - кнопка была отпущена после импульсного удержания. Может использоваться для изменения знака инкремента переменной. См. пример *StepMode*. *[однократно вернёт true]* +- `releaseStep(clicks)` - то же самое, но функция принимает количество кликов, сделанных до удержания. Примечание: releaseStep() без аргумента перехватит вызов! См. пример *StepMode* и *preClicks*. *[однократно вернёт true]* +- `hasClicks(clicks)` - было сделано указанное количество кликов с периодом менее *EB_CLICK*. *[однократно вернёт true]* +- `state()` - возвращает теукщее состояние кнопки (сигнал с пина, без антидребезга): `true` - нажата, `false` - не нажата. +- `busy()` - вернёт `true`, если всё ещё нужно вызывать tick для опроса таймаутов +- `hasClicks()` - вернёт количество кликов, сделанных с периодом менее *EB_CLICK*. В противном случае вернёт 0. +- `uint8_t clicks` - публичная переменная (член класса), хранит количество сделанных кликов с периодом менее *EB_CLICK*. Сбрасывается в 0 после нового клика. +![diagram](/doc/diagram.png) + +#### Энкодер +- `turn()` - поворот на один щелчок в любую сторону. *[однократно вернёт true]* +- `turnH()` - поворот на один щелчок в любую сторону с зажатой кнопкой. *[однократно вернёт true]* +- `fast()` - был совершён быстрый поворот (с периодом менее *EB_FAST* мс) на один щелчок в любую сторону. *[возвращает true, пока энкодер крутится быстро]* +- `right()` - поворот на один щелчок направо. *[однократно вернёт true]* +- `left()` - поворот на один щелчок налево. *[однократно вернёт true]* +- `rightH()` - поворот на один щелчок направо с зажатой кнопкой. *[однократно вернёт true]* +- `leftH()` - поворот на один щелчок налево с зажатой кнопкой. *[однократно вернёт true]* +- `getDir()` - направление последнего поворота, 1 или -1. +- `int16_t counter` - публичная переменная (член класса), хранит счётчик энкодера. + +### Режим callback +- В данном режиме можно подключить свою функцию-обработчик на любое действие кнопки/энкодера. Они будут автоматически вызываться при наступлении события. +- Для работы нужно вызывать `tick()` в основном цикле программы, а также можно продублировать `tickISR()` в прерывании по *CHANGE* для улучшения точности обработки энкодера. +- При работе в прерывании подключенные функции вызываются из `tick()`, т.е. из основного цикла программы. В `tickISR()` происходит только обработка алгоритмов библиотеки! +- Смотри пример *callbackMode* +```cpp +void attach(type, func); // подключить обработчик +void detach(type); // отключить обработчик +void attachClicks(uint8_t amount, func); // подключить обработчик на количество кликов (может быть только один!) +void detachClicks(); // отключить обработчик на количество кликов +``` +Где `type` - тип события: +- *TURN_HANDLER* - поворот +- *TURN_H_HANDLER* - нажатый поворот +- *RIGHT_HANDLER* - поворот направо +- *LEFT_HANDLER* - поворот налево +- *RIGHT_H_HANDLER* - нажатый поворот направо +- *LEFT_H_HANDLER* - нажатый поворот налево +- *PRESS_HANDLER* - нажатие +- *RELEASE_HANDLER* - отпускание +- *CLICK_HANDLER* - клик +- *HOLDED_HANDLER* - удержание (однократное срабатывание) +- *HOLD_HANDLER* - удержание (постоянное срабатывание) +- *STEP_HANDLER* - импульсное удержание +- *CLICKS_HANDLER* - несколько кликов + +### Виртуальный режим +Виртуальный режим позволяет получить все возможности библиотеки EncButton в ситуациях, когда кнопка не подключена напрямую к микроконтроллеру, либо для её опроса используется другая библиотека: +- Аналоговая клавиатура (например через библиотеку [AnalogKey](https://github.com/GyverLibs/AnalogKey)). Смотри пример *virtual_AnalogKey* +- Матричная клавиатура (например через библиотеку [SimpleKeypad](https://github.com/maximebohrer/SimpleKeypad)). Смотри пример *virtual_SimpleKeypad* и *virtual_SimpleKeypad_array* +- Кнопки или энкодеры, подключенные через расширители пинов или сдвиговые регистры + +Таким образом можно получить несколько нажатий с матричной клавиатуры, удержание кнопок матричной клавиатуры, импульсное удержание и прочие фишки EncButton. + +Для работы нужно передать в `tick()` текущие состояния "пинов" кнопки/энкодера: `tick(s1, s2, s3)` в следующем порядке +- Кнопка - (сигнал кнопки) +- Энкодер - (сигнал энкодера А, сигнал энкодера B) +- Энкодер с кнопкой - (сигнал энкодера А, сигнал энкодера B, сигнал кнопки) + +### Настройки +```cpp +void pullUp(); // подтянуть все пины внутренней подтяжкой +void holdEncButton(bool state); // виртуально зажать кнопку энкодера +void setHoldTimeout(int tout); // установить время удержания кнопки, мс (до 30 000) +void setButtonLevel(bool level); // уровень кнопки: LOW - кнопка подключает GND (по умолч.), HIGH - кнопка подключает VCC +``` + + +## Примеры +### Полное демо tick +Остальные примеры смотри в **examples**! +```cpp +// Пример с прямой работой библиотеки + +#include +EncButton enc; // энкодер с кнопкой +//EncButton enc; // просто энкодер +//EncButton enc; // просто кнопка + +void setup() { + Serial.begin(9600); + // ещё настройки + //enc.counter = 100; // изменение счётчика энкодера + //enc.setHoldTimeout(500); // установка таймаута удержания кнопки + //enc.setButtonLevel(HIGH); // LOW - кнопка подключает GND (умолч.), HIGH - кнопка подключает VCC +} + +void loop() { + enc.tick(); // опрос происходит здесь + + // =============== ЭНКОДЕР =============== + // обычный поворот + if (enc.turn()) { + Serial.println("turn"); + + // можно опросить ещё: + //Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + Serial.println(enc.getDir()); // направление поворота + } + + // "нажатый поворот" + if (enc.turnH()) { + Serial.println("hold + turn"); + + // можно опросить ещё: + //Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + Serial.println(enc.getDir()); // направление поворота + } + + if (enc.left()) Serial.println("left"); // поворот налево + if (enc.right()) Serial.println("right"); // поворот направо + if (enc.leftH()) Serial.println("leftH"); // нажатый поворот налево + if (enc.rightH()) Serial.println("rightH"); // нажатый поворот направо + + // =============== КНОПКА =============== + if (enc.press()) Serial.println("press"); + if (enc.click()) Serial.println("click"); + if (enc.release()) Serial.println("release"); + + if (enc.held()) Serial.println("held"); // однократно вернёт true при удержании + //if (enc.hold()) Serial.println("hold"); // будет постоянно возвращать true после удержания + if (enc.step()) Serial.println("step"); // импульсное удержание + if (enc.releaseStep()) Serial.println("release step"); // отпущена после импульсного удержания + + // проверка на количество кликов + if (enc.hasClicks(1)) Serial.println("action 1 clicks"); + if (enc.hasClicks(2)) Serial.println("action 2 clicks"); + if (enc.hasClicks(3)) Serial.println("action 3 clicks"); + if (enc.hasClicks(5)) Serial.println("action 5 clicks"); + + // вывести количество кликов + if (enc.hasClicks()) { + Serial.print("has clicks "); + Serial.println(enc.clicks); + } +} +``` + +### Массив кнопок EncButton2 +```cpp +// объявляем массив кнопок +#define BTN_AMOUNT 5 +#include +EncButton2 btn[BTN_AMOUNT]; + +void setup() { + Serial.begin(9600); + btn[0].setPins(INPUT_PULLUP, D3); + btn[1].setPins(INPUT_PULLUP, D2); +} + +void loop() { + for (int i = 0; i < BTN_AMOUNT; i++) btn[i].tick(); + for (int i = 0; i < BTN_AMOUNT; i++) { + if (btn[i].click()) { + Serial.print("click btn: "); + Serial.println(i); + } + } +} +``` + +### Одна кнопка управляет несколькими переменными +```cpp +// используем одну КНОПКУ для удобного изменения трёх переменных +// первая - один клик, затем удержание (нажал-отпустил-нажал-держим) +// вторая - два клика, затем удержание +// третья - три клика, затем удержание +// смотри монитор порта + +#include +EncButton btn; + +// переменные для изменения +int val_a, val_b, val_c; + +// шаги изменения (signed) +int8_t step_a = 1; +int8_t step_b = 5; +int8_t step_c = 10; + +void setup() { + Serial.begin(9600); +} + +void loop() { + btn.tick(); + + // передаём количество предварительных кликов + if (btn.step(1)) { + val_a += step_a; + Serial.print("val_a: "); + Serial.println(val_a); + } + if (btn.step(2)) { + val_b += step_b; + Serial.print("val_b: "); + Serial.println(val_b); + } + if (btn.step(3)) { + val_c += step_c; + Serial.print("val_c: "); + Serial.println(val_c); + } + + // разворачиваем шаг для изменения в обратную сторону + // передаём количество предварительных кликов + if (btn.releaseStep(1)) step_a = -step_a; + if (btn.releaseStep(2)) step_b = -step_b; + if (btn.releaseStep(3)) step_c = -step_c; +} +``` + + +## Версии +- v1.1 - пуллап отдельныи методом +- v1.2 - можно передать конструктору параметр INPUT_PULLUP / INPUT(умолч) +- v1.3 - виртуальное зажатие кнопки энкодера вынесено в отдельную функцию + мелкие улучшения +- v1.4 - обработка нажатия и отпускания кнопки +- v1.5 - добавлен виртуальный режим +- v1.6 - оптимизация работы в прерывании +- v1.6.1 - подтяжка по умолчанию INPUT_PULLUP +- v1.7 - большая оптимизация памяти, переделан FastIO +- v1.8 - индивидуальная настройка таймаута удержания кнопки (была общая на всех) +- v1.8.1 - убран FastIO +- v1.9 - добавлена отдельная отработка нажатого поворота и запрос направления +- v1.10 - улучшил обработку released, облегчил вес в режиме callback и исправил баги +- v1.11 - ещё больше всякой оптимизации + настройка уровня кнопки +- v1.11.1 - совместимость Digispark +- v1.12 - добавил более точный алгоритм энкодера EB_BETTER_ENC +- v1.13 - добавлен экспериментальный EncButton2 +- v1.14 - добавлена releaseStep(). Отпускание кнопки внесено в дебаунс +- v1.15 - добавлен setPins() для EncButton2 +- v1.16 - добавлен режим EB_HALFSTEP_ENC для полушаговых энкодеров +- v1.17 - добавлен step с предварительными кликами +- v1.18 - не считаем клики после активации step. held() и hold() тоже могут принимать предварительные клики. Переделан и улучшен дебаунс +- v1.18.1 - исправлена ошибка в releaseStep() (не возвращала результат) +- v1.18.2 - fix compiler warnings +- v1.19 - оптимизация скорости, уменьшен вес в sram +- v1.19.1 - ещё чутка увеличена производительность +- v1.19.2 - ещё немного увеличена производительность, спасибо XRay3D +- v1.19.3 - сделал высокий уровень кнопки по умолчанию в виртуальном режиме +- v1.19.4 - фикс EncButton2 +- v1.20 - исправлена критическая ошибка в EncButton2 + + +## Баги и обратная связь +При нахождении багов создавайте **Issue**, а лучше сразу пишите на почту [alex@alexgyver.ru](mailto:alex@alexgyver.ru) +Библиотека открыта для доработки и ваших **Pull Request**'ов! diff --git a/libraries/EncButton/doc/diagram.png b/libraries/EncButton/doc/diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..2207e0f89d731c5fa763baf2434b1925e4751151 GIT binary patch literal 37800 zcmdRW2|Uza_rK~(E80*9X}64Z#!itoYca+?S;oFI_MsArkjkEvLJTHk8;m6DprRT3 z-jID~##sKJp>OH=Jw4y&`90tN|MmKNRbxK)-gD16_kGSi=iK}0zNY$R#y#wN=;-Je zuU@%$gO2VG5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S!^eO{e?1QilijMDhX^kLhydCyHy9102tFv6Mf>%kkQ#I3Sz;=jC88HiW<_KTID_K($UZg;z8)e% zpO}%ECjV&daald_@f{Y~vIzSt+P3R#$SVWg!1tQdo?(@Q7+6=S%;~o|?+nYPa;O{P zIs@xKFX((gqxmD?$&m1RJT5(<5Vv6!>R-tuK0U?xIUN6xh2>*5b#*( zI&T?GFXr%ZVgJ3t{yZhj>0LkT0mRM2rGEXF88}??fX}#JAqoTQylVKOqYWjTV<}+$ zgOHgCoBq=<@34`;O(ejs^@IDC3lrY6lo^0`H~?Sn{{@%;hzA%`=n4i5dBE0x&!P?X z6VKUr`}`M|C}kX&CRr2UIVPkvn{fUQsOJ9xctq3w=goT)<$?JV`oI8W{jcW{{|A(A ao*F3;7;SrE^npgtAbDA3nM!GskpBUO{Kc^V literal 0 HcmV?d00001 diff --git a/libraries/EncButton/doc/encAli.png b/libraries/EncButton/doc/encAli.png new file mode 100644 index 0000000000000000000000000000000000000000..dc41b7372dcc75a4e269e19cf0bbc468e8a83a71 GIT binary patch literal 79766 zcmce8g;N|))a@=FEQ`A>E(s37ZE<&ZmjFS6!{UoWaCciA0tv1mKyV2bAh^3F5a8|a z``-H(UQJDHRoBc`PtU!#PoHyoVl>p`aWKg-0RRAwq5?z<008kz+s~E9 zJkLtOn|Lw@Y!vjA3I%8?q{(3{!-bu-(n_1GELJ<_6I@5@`J2Sof4%R*OCiO|w#JMp zC8U)cv1J$_dJ4$Y+QH%NFSm|4p@0TDiIbqSfVCk>Xabr|-s`Hx^EIE1?)`#I5$B*| zW9QOrsc2j(;jWjW*Z#=DUI!PNQu2aS!d_qH4-P71qH*srsMfp=rZ=gJOLGy|{i65s znk$xx4v0u}MO^KkG(Dq=xc>}KxZ`lTcu-9G|I^KXE(QQ6lj!R=@-2lSXVI^p!`Gp> zRN_|(9HD3;5uwu_I7p2Ob9^mKjj;QAj#x9zv~ss_)X)FeFp2;d#W?i;b$2s73J8ek zoAVcce>Aeyb$pK=9!z6k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O1I7q0kBr8RHxJV)QC<)O<>Q zBZ@sTV>`@CeBQY|5d(C2<&@*f6UH_Sq#M6W@b^$(g!*CSpfe)i9H)DcPX`hdHUgkd zL8)q#LR M@vSPf9AX&sKLgR}L;wH) literal 0 HcmV?d00001 diff --git a/libraries/EncButton/examples/EncButton2/EncButton2.ino b/libraries/EncButton/examples/EncButton2/EncButton2.ino new file mode 100644 index 0000000..f3e66cd --- /dev/null +++ b/libraries/EncButton/examples/EncButton2/EncButton2.ino @@ -0,0 +1,77 @@ +// пример с библиотекой EncButton2 + +// Опциональные дефайн-настройки (показаны по умолчанию) +//#define EB_FAST 30 // таймаут быстрого поворота, мс +//#define EB_DEB 50 // дебаунс кнопки, мс +//#define EB_HOLD 1000 // таймаут удержания кнопки, мс +//#define EB_STEP 500 // период срабатывания степ, мс +//#define EB_CLICK 400 // таймаут накликивания, мс + +#include +EncButton2 enc(INPUT, 2, 3, 4); // энкодер с кнопкой +//EncButton2 enc(INPUT, 2, 3); // просто энкодер +//EncButton2 enc(INPUT, 4); // просто кнопка +// для изменения направления энкодера поменяй A и B при инициализации + +// по умолчанию пины настроены в INPUT_PULLUP +// Если используется внешняя подтяжка - лучше перевести в INPUT +//EncButton enc(INPUT); + +void setup() { + Serial.begin(9600); + // ещё настройки + //enc.counter = 100; // изменение счётчика энкодера + //enc.setHoldTimeout(500); // установка таймаута удержания кнопки + //enc.setButtonLevel(HIGH); // LOW - кнопка подключает GND (умолч.), HIGH - кнопка подключает VCC +} + +void loop() { + enc.tick(); // опрос происходит здесь + + // =============== ЭНКОДЕР =============== + // обычный поворот + if (enc.turn()) { + Serial.println("turn"); + + // можно опросить ещё: + //Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + Serial.println(enc.getDir()); // направление поворота + } + + // "нажатый поворот" + if (enc.turnH()) { + Serial.println("hold + turn"); + + // можно опросить ещё: + //Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + Serial.println(enc.getDir()); // направление поворота + } + + if (enc.left()) Serial.println("left"); // поворот налево + if (enc.right()) Serial.println("right"); // поворот направо + if (enc.leftH()) Serial.println("leftH"); // нажатый поворот налево + if (enc.rightH()) Serial.println("rightH"); // нажатый поворот направо + + // =============== КНОПКА =============== + if (enc.press()) Serial.println("press"); + if (enc.click()) Serial.println("click"); + if (enc.release()) Serial.println("release"); + + if (enc.held()) Serial.println("held"); // однократно вернёт true при удержании + //if (enc.hold()) Serial.println("hold"); // будет постоянно возвращать true после удержания + if (enc.step()) Serial.println("step"); // импульсное удержание + + // проверка на количество кликов + if (enc.hasClicks(1)) Serial.println("action 1 clicks"); + if (enc.hasClicks(2)) Serial.println("action 2 clicks"); + if (enc.hasClicks(3)) Serial.println("action 3 clicks"); + if (enc.hasClicks(5)) Serial.println("action 5 clicks"); + + // вывести количество кликов + if (enc.hasClicks()) { + Serial.print("has clicks "); + Serial.println(enc.clicks); + } +} diff --git a/libraries/EncButton/examples/EncButton2_array/EncButton2_array.ino b/libraries/EncButton/examples/EncButton2_array/EncButton2_array.ino new file mode 100644 index 0000000..5367836 --- /dev/null +++ b/libraries/EncButton/examples/EncButton2_array/EncButton2_array.ino @@ -0,0 +1,20 @@ +// объявляем массив кнопок +#define BTN_AMOUNT 5 +#include +EncButton2 btn[BTN_AMOUNT]; + +void setup() { + Serial.begin(9600); + btn[0].setPins(INPUT_PULLUP, D3); + btn[1].setPins(INPUT_PULLUP, D2); +} + +void loop() { + for (int i = 0; i < BTN_AMOUNT; i++) btn[i].tick(); + for (int i = 0; i < BTN_AMOUNT; i++) { + if (btn[i].click()) { + Serial.print("click btn: "); + Serial.println(i); + } + } +} diff --git a/libraries/EncButton/examples/callbackISR/callbackISR.ino b/libraries/EncButton/examples/callbackISR/callbackISR.ino new file mode 100644 index 0000000..a9345d0 --- /dev/null +++ b/libraries/EncButton/examples/callbackISR/callbackISR.ino @@ -0,0 +1,29 @@ +// Пример с обработчиками в прерывании + +#include +EncButton enc; // энкодер с кнопкой + +void setup() { + Serial.begin(9600); + enc.attach(TURN_HANDLER, myTurn); // подключим поворот + + // прерывание обеих фаз энкодера на функцию isr + attachInterrupt(0, isr, CHANGE); + attachInterrupt(1, isr, CHANGE); +} + +void myTurn() { + Serial.print("TURN_HANDLER: "); + Serial.println(enc.counter); +} + +void isr() { + enc.tickISR(); // тикер в прерывании + // Не вызывает подключенные коллбэки внутри прерывания!!! +} + +void loop() { + enc.tick(); // дополнительный опрос таймаутов и коллбэков в loop + // вызов подключенных функций будет здесь, + // чтобы не грузить прерывание +} diff --git a/libraries/EncButton/examples/callbackMode/callbackMode.ino b/libraries/EncButton/examples/callbackMode/callbackMode.ino new file mode 100644 index 0000000..63d4cc5 --- /dev/null +++ b/libraries/EncButton/examples/callbackMode/callbackMode.ino @@ -0,0 +1,91 @@ +// Пример с обработчиками + +#include +EncButton enc; // энкодер с кнопкой +//EncButton enc; // просто энкодер +//EncButton enc; // просто кнопка + +void setup() { + Serial.begin(9600); + + enc.attach(TURN_HANDLER, myTurn); + enc.attach(TURN_H_HANDLER, myTurnH); + + enc.attach(RIGHT_HANDLER, myRight); + enc.attach(LEFT_HANDLER, myLeft); + + enc.attach(RIGHT_H_HANDLER, myRightH); + enc.attach(LEFT_H_HANDLER, myLeftH); + + enc.attach(CLICK_HANDLER, myClick); + enc.attach(HOLDED_HANDLER, myHolded); + enc.attach(STEP_HANDLER, myStep); + + enc.attach(PRESS_HANDLER, myPress); + enc.attach(RELEASE_HANDLER, myRelease); + //enc.attach(HOLD_HANDLER, myHold); + + enc.attach(CLICKS_HANDLER, myClicks); + enc.attachClicks(5, fiveClicks); +} + +void myTurn() { + Serial.println("TURN_HANDLER: "); + + // тут можно: + Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + //Serial.println(enc.getDir()); // направление поворота +} + +void myTurnH() { + Serial.println("TURN_H_HANDLER"); + + // тут можно: + //Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + Serial.println(enc.getDir()); // направление поворота +} + +void myRight() { + Serial.println("RIGHT_HANDLER"); +} +void myLeft() { + Serial.println("LEFT_HANDLER"); +} +void myRightH() { + Serial.println("RIGHT_H_HANDLER"); +} +void myLeftH() { + Serial.println("LEFT_H_HANDLER"); +} +void myClick() { + Serial.println("CLICK_HANDLER"); +} +void myHolded() { + Serial.println("HOLDED_HANDLER"); +} +void myStep() { + Serial.println("STEP_HANDLER"); +} +void myClicks() { + Serial.print("CLICKS_HANDLER: "); + Serial.println(enc.clicks); +} +void fiveClicks() { + Serial.println("action fiveClicks"); +} +void myPress() { + Serial.println("PRESS_HANDLER"); +} +void myRelease() { + Serial.println("RELEASE_HANDLER"); +} +void myHold() { + Serial.println("HOLD_HANDLER"); +} + +// =============== LOOP ============= +void loop() { + enc.tick(); // обработка всё равно здесь +} diff --git a/libraries/EncButton/examples/optimisation/optimisation.ino b/libraries/EncButton/examples/optimisation/optimisation.ino new file mode 100644 index 0000000..1eb9f3f --- /dev/null +++ b/libraries/EncButton/examples/optimisation/optimisation.ino @@ -0,0 +1,41 @@ +// пример с небольшой оптимизацией опроса + +#include +EncButton enc; // энкодер с кнопкой +//EncButton enc; // просто энкодер +//EncButton enc; // просто кнопка + +void setup() { + Serial.begin(9600); +} + +void loop() { + // тик вернёт отличное от нуля значение, если произошло событие: + // 1 - left + turn + // 2 - right + turn + // 3 - leftH + turnH + // 4 - rightH + turnH + // 5 - click + // 6 - held + // 7 - step + // 8 - press + + // опрос этих событий можно проводить в условии, + // чтобы "не тратить время" на постоянный опрос в loop + if (enc.tick()) { + if (enc.turn()) Serial.println("turn"); + if (enc.turnH()) Serial.println("hold + turn"); + if (enc.left()) Serial.println("left"); + if (enc.right()) Serial.println("right"); + if (enc.leftH()) Serial.println("leftH"); + if (enc.rightH()) Serial.println("rightH"); + + if (enc.press()) Serial.println("press"); + if (enc.click()) Serial.println("click"); + if (enc.held()) Serial.println("held"); + if (enc.step()) Serial.println("step"); + + // в конце лучше вызвать resetState(), чтобы сбросить необработанные флаги! + enc.resetState(); + } +} diff --git a/libraries/EncButton/examples/pcint/pcint.ino b/libraries/EncButton/examples/pcint/pcint.ino new file mode 100644 index 0000000..92426d4 --- /dev/null +++ b/libraries/EncButton/examples/pcint/pcint.ino @@ -0,0 +1,70 @@ +// пример с прерываниями pinChangeInterrupt (прерывания на любом пине) +// только для ATmega328 (UNO, Nano, Pro Mini) + +#define CLK 4 +#define DT 5 +#define SW 6 + +#include +EncButton enc; + +void setup() { + Serial.begin(9600); + + // настроить PCINT + attachPCINT(CLK); + attachPCINT(DT); +} + +void loop() { + // оставляем тут для работы "временных" функций и антидребезга + enc.tick(); + + if (enc.turn()) { // любой поворот + Serial.print("turn "); + Serial.println(enc.counter); // вывод счётчика + } + + if (enc.left()) { + if (enc.fast()) Serial.println("fast left"); + else Serial.println("left"); + } + + if (enc.right()) { + if (enc.fast()) Serial.println("fast right"); + else Serial.println("right"); + } +} + +// функция для настройки PCINT для ATmega328 (UNO, Nano, Pro Mini) +uint8_t attachPCINT(uint8_t pin) { + if (pin < 8) { // D0-D7 - PCINT2 + PCICR |= (1 << PCIE2); + PCMSK2 |= (1 << pin); + return 2; + } + else if (pin > 13) { // A0-A5 - PCINT1 + PCICR |= (1 << PCIE1); + PCMSK1 |= (1 << pin - 14); + return 1; + } + else { // D8-D13 - PCINT0 + PCICR |= (1 << PCIE0); + PCMSK0 |= (1 << pin - 8); + return 0; + } +} + +// Векторы PCINT, нужно кинуть сюда tickISR +// пины 0-7: PCINT2 +// пины 8-13: PCINT0 +// пины A0-A5: PCINT1 +ISR(PCINT0_vect) { + +} +ISR(PCINT1_vect) { + +} +ISR(PCINT2_vect) { + enc.tickISR(); +} diff --git a/libraries/EncButton/examples/preClicks/preClicks.ino b/libraries/EncButton/examples/preClicks/preClicks.ino new file mode 100644 index 0000000..393c262 --- /dev/null +++ b/libraries/EncButton/examples/preClicks/preClicks.ino @@ -0,0 +1,33 @@ +// срабатывание функций held/hold/step после предварительных кликов + +#include +EncButton btn; + +void setup() { + Serial.begin(9600); +} + +void loop() { + btn.tick(); + if (btn.click()) Serial.println("click"); + + // вызов без количества кликов перехватит все остальные вызовы! + //if (btn.held()) Serial.println("held any clicks"); + if (btn.held(0)) Serial.println("held after 0 clicks"); + if (btn.held(2)) Serial.println("held after 2 clicks"); + + // вызов без количества кликов перехватит все остальные вызовы! + //if (btn.hold()) Serial.println("hold any clicks"); + //if (btn.hold(0)) Serial.println("hold after 0 clicks"); + //if (btn.hold(2)) Serial.println("hold after 2 clicks"); + + // вызов без количества кликов перехватит все остальные вызовы! + //if (btn.step()) Serial.println("step after any clicks"); + if (btn.step(0)) Serial.println("step after 0 clicks"); + if (btn.step(2)) Serial.println("step after 2 clicks"); + + // вызов без количества кликов перехватит все остальные вызовы! + //if (btn.releaseStep()) Serial.println("release step after any clicks"); + if (btn.releaseStep(0)) Serial.println("release step after 0 clicks"); + if (btn.releaseStep(2)) Serial.println("release step after 2 clicks"); +} diff --git a/libraries/EncButton/examples/stepMode/stepMode.ino b/libraries/EncButton/examples/stepMode/stepMode.ino new file mode 100644 index 0000000..7c96910 --- /dev/null +++ b/libraries/EncButton/examples/stepMode/stepMode.ino @@ -0,0 +1,47 @@ +// используем одну КНОПКУ для удобного изменения трёх переменных +// первая - один клик, затем удержание (нажал-отпустил-нажал-держим) +// вторая - два клика, затем удержание +// третья - три клика, затем удержание +// смотри монитор порта + +#include +EncButton btn; + +// переменные для изменения +int val_a, val_b, val_c; + +// шаги изменения (signed) +int8_t step_a = 1; +int8_t step_b = 5; +int8_t step_c = 10; + +void setup() { + Serial.begin(9600); +} + +void loop() { + btn.tick(); + + // передаём количество предварительных кликов + if (btn.step(1)) { + val_a += step_a; + Serial.print("val_a: "); + Serial.println(val_a); + } + if (btn.step(2)) { + val_b += step_b; + Serial.print("val_b: "); + Serial.println(val_b); + } + if (btn.step(3)) { + val_c += step_c; + Serial.print("val_c: "); + Serial.println(val_c); + } + + // разворачиваем шаг для изменения в обратную сторону + // передаём количество предварительных кликов + if (btn.releaseStep(1)) step_a = -step_a; + if (btn.releaseStep(2)) step_b = -step_b; + if (btn.releaseStep(3)) step_c = -step_c; +} \ No newline at end of file diff --git a/libraries/EncButton/examples/tickISR/tickISR.ino b/libraries/EncButton/examples/tickISR/tickISR.ino new file mode 100644 index 0000000..b27c57b --- /dev/null +++ b/libraries/EncButton/examples/tickISR/tickISR.ino @@ -0,0 +1,34 @@ +// Пример с прямой работой библиотеки на прерываниях + +#include +EncButton enc; // энкодер с кнопкой +//EncButton enc; // просто энкодер +//EncButton enc; // просто кнопка + +void setup() { + Serial.begin(9600); + + // желательно подключить оба пина энкодера на внешние прерывания по CHANGE + // можно использовать PCINT https://github.com/NicoHood/PinChangeInterrupt + attachInterrupt(0, isr, CHANGE); // D2 + attachInterrupt(1, isr, CHANGE); // D3 + // подключил оба прерывания на одну функцию +} + +void isr() { + enc.tickISR(); // в прерывании вызываем тик ISR +} + +void loop() { + // тут тоже вызываем тик, нужен для + // корректной работы дебаунсов и прочих таймеров!!! + enc.tick(); + + if (enc.turn()) { // любой поворот + Serial.print("turn "); + Serial.println(enc.counter); // вывод счётчика + } + + // имитация загруженной программы, обработка происходит в прерывании + delay(50); +} diff --git a/libraries/EncButton/examples/tickMode/tickMode.ino b/libraries/EncButton/examples/tickMode/tickMode.ino new file mode 100644 index 0000000..8727788 --- /dev/null +++ b/libraries/EncButton/examples/tickMode/tickMode.ino @@ -0,0 +1,78 @@ +// Пример с прямой работой библиотеки +// просто загрузи и потыкай - всё будет понятно =) + +// Опциональные дефайн-настройки (показаны по умолчанию) +//#define EB_FAST 30 // таймаут быстрого поворота, мс +//#define EB_DEB 50 // дебаунс кнопки, мс +//#define EB_HOLD 1000 // таймаут удержания кнопки, мс +//#define EB_STEP 500 // период срабатывания степ, мс +//#define EB_CLICK 400 // таймаут накликивания, мс + +#include +//EncButton enc; // энкодер с кнопкой +//EncButton enc; // просто энкодер +EncButton enc; // просто кнопка +// для изменения направления энкодера поменяй A и B при инициализации + +// по умолчанию пины настроены в INPUT_PULLUP +// Если используется внешняя подтяжка - лучше перевести в INPUT +//EncButton enc(INPUT); + +void setup() { + Serial.begin(9600); + // ещё настройки + //enc.counter = 100; // изменение счётчика энкодера + //enc.setHoldTimeout(500); // установка таймаута удержания кнопки + //enc.setButtonLevel(HIGH); // LOW - кнопка подключает GND (умолч.), HIGH - кнопка подключает VCC +} + +void loop() { + enc.tick(); // опрос происходит здесь + + // =============== ЭНКОДЕР =============== + // обычный поворот + if (enc.turn()) { + Serial.println("turn"); + + // можно опросить ещё: + //Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + Serial.println(enc.getDir()); // направление поворота + } + + // "нажатый поворот" + if (enc.turnH()) { + Serial.println("hold + turn"); + + // можно опросить ещё: + //Serial.println(enc.counter); // вывести счётчик + //Serial.println(enc.fast()); // проверить быстрый поворот + Serial.println(enc.getDir()); // направление поворота + } + + if (enc.left()) Serial.println("left"); // поворот налево + if (enc.right()) Serial.println("right"); // поворот направо + if (enc.leftH()) Serial.println("leftH"); // нажатый поворот налево + if (enc.rightH()) Serial.println("rightH"); // нажатый поворот направо + + // =============== КНОПКА =============== + if (enc.press()) Serial.println("press"); + if (enc.click()) Serial.println("click"); + if (enc.release()) Serial.println("release"); + + if (enc.held()) Serial.println("held"); // однократно вернёт true при удержании + //if (enc.hold()) Serial.println("hold"); // будет постоянно возвращать true после удержания + if (enc.step()) Serial.println("step"); // импульсное удержание + + // проверка на количество кликов + if (enc.hasClicks(1)) Serial.println("action 1 clicks"); + if (enc.hasClicks(2)) Serial.println("action 2 clicks"); + if (enc.hasClicks(3)) Serial.println("action 3 clicks"); + if (enc.hasClicks(5)) Serial.println("action 5 clicks"); + + // вывести количество кликов + if (enc.hasClicks()) { + Serial.print("has clicks "); + Serial.println(enc.clicks); + } +} diff --git a/libraries/EncButton/examples/virtual/virtual.ino b/libraries/EncButton/examples/virtual/virtual.ino new file mode 100644 index 0000000..0960d58 --- /dev/null +++ b/libraries/EncButton/examples/virtual/virtual.ino @@ -0,0 +1,33 @@ +#include + +EncButton enc; // виртуальная кнопка +//EncButton enc; // виртуальный энк с кнопкой +//EncButton enc; // виртуальный энк + +void setup() { + Serial.begin(9600); + pinMode(4, INPUT_PULLUP); // подтянем пин + //enc.setHoldTimeout(500); // установка таймаута удержания кнопки +} + +void loop() { + // tick может принимать виртуальный сигнал: + // (сигнал кнопки) + // (сигнал энкодера А, сигнал энкодера B) + // (сигнал энкодера А, сигнал энкодера B, сигнал кнопки) + enc.tick(!digitalRead(4)); + + if (enc.press()) Serial.println("press"); + if (enc.click()) Serial.println("click"); + if (enc.held()) Serial.println("held"); + if (enc.step()) Serial.println("step"); + if (enc.release()) Serial.println("release"); + + if (enc.hasClicks(1)) Serial.println("1 click"); + if (enc.hasClicks(2)) Serial.println("2 click"); + if (enc.hasClicks(3)) Serial.println("3 click"); + if (enc.hasClicks(5)) Serial.println("5 click"); + + if (enc.hasClicks()) Serial.println(enc.clicks); + //if (enc.hold()) Serial.println("hold"); +} diff --git a/libraries/EncButton/examples/virtual_AnalogKey/virtual_AnalogKey.ino b/libraries/EncButton/examples/virtual_AnalogKey/virtual_AnalogKey.ino new file mode 100644 index 0000000..a361616 --- /dev/null +++ b/libraries/EncButton/examples/virtual_AnalogKey/virtual_AnalogKey.ino @@ -0,0 +1,35 @@ +// пример работы в виртуальном режиме совместно с библиотекой AnalogKey +// https://github.com/GyverLibs/AnalogKey + +#include +EncButton btn0; +EncButton btn1; + +#include +// создаём массив значений сигналов с кнопок +int16_t sigs[16] = { + 1023, 927, 856, 783, + 671, 632, 590, 560, + 504, 480, 455, 440, + 399, 319, 255, 230 +}; + +// указываем пин, количество кнопок и массив значений +AnalogKey keys; + + +void setup() { + Serial.begin(9600); +} + +void loop() { + btn0.tick(keys.status(0)); + btn1.tick(keys.status(1)); + + // забираем действия с кнопок + if (btn0.click()) Serial.println("click 0"); + if (btn0.held()) Serial.println("held 0"); + + if (btn1.press()) Serial.println("press 1"); + if (btn1.step()) Serial.println("step 1"); +} diff --git a/libraries/EncButton/examples/virtual_SimpleKeypad/virtual_SimpleKeypad.ino b/libraries/EncButton/examples/virtual_SimpleKeypad/virtual_SimpleKeypad.ino new file mode 100644 index 0000000..763b61d --- /dev/null +++ b/libraries/EncButton/examples/virtual_SimpleKeypad/virtual_SimpleKeypad.ino @@ -0,0 +1,44 @@ +// пример работы в виртуальном режиме совместно с библиотекой SimpleKeypad +// https://github.com/maximebohrer/SimpleKeypad + +#include +EncButton btn0; +EncButton btn1; + +// пины подключения (по порядку штекера) +byte colPins[] = {7, 6, 5, 4}; +byte rowPins[] = {11, 10, 9, 8}; + +// массив имён кнопок +char keys[4][4] = { + {'1', '2', '3', 'A'}, + {'4', '5', '6', 'B'}, + {'7', '8', '9', 'C'}, + {'*', '0', '#', 'D'} +}; + +#include +SimpleKeypad pad((char*)keys, rowPins, colPins, 4, 4); + +void setup() { + Serial.begin(9600); +} + +void loop() { + // тикаем все кнопки, передавая сравнение с кодом кнопки в цикле + // делаем это по таймеру, чтобы не опрашивать клавиатуру постоянно + static uint32_t tmr; + if (millis() - tmr >= 10) { + tmr = millis(); + char key = pad.scan(); + btn0.tick(key == '1'); + btn1.tick(key == '2'); + } + + // забираем действия с кнопок + if (btn0.click()) Serial.println("click 0"); + if (btn0.held()) Serial.println("held 0"); + + if (btn1.press()) Serial.println("press 1"); + if (btn1.step()) Serial.println("step 1"); +} diff --git a/libraries/EncButton/examples/virtual_SimpleKeypad_array/virtual_SimpleKeypad_array.ino b/libraries/EncButton/examples/virtual_SimpleKeypad_array/virtual_SimpleKeypad_array.ino new file mode 100644 index 0000000..885d348 --- /dev/null +++ b/libraries/EncButton/examples/virtual_SimpleKeypad_array/virtual_SimpleKeypad_array.ino @@ -0,0 +1,44 @@ +// пример работы в виртуальном режиме совместно с библиотекой SimpleKeypad +// https://github.com/maximebohrer/SimpleKeypad +// передаём EncButton сразу всю клавиатуру через массивы и циклы + +#include +EncButton btn[16]; + +// пины подключения (по порядку штекера) +byte colPins[] = {7, 6, 5, 4}; +byte rowPins[] = {11, 10, 9, 8}; + +// массив имён кнопок +char keys[4][4] = { + {'1', '2', '3', 'A'}, + {'4', '5', '6', 'B'}, + {'7', '8', '9', 'C'}, + {'*', '0', '#', 'D'} +}; + +#include +SimpleKeypad pad((char*)keys, rowPins, colPins, 4, 4); + +void setup() { + Serial.begin(9600); +} + +void loop() { + // массово тикаем все кнопки, передавая сравнение с кодом кнопки в цикле + // делаем это по таймеру, чтобы не опрашивать клавиатуру постоянно + static uint32_t tmr; + if (millis() - tmr >= 10) { + tmr = millis(); + char key = pad.scan(); + char* keysPtr = (char*)keys; // указатель для удобства опроса + for (int i = 0; i < 16; i++) btn[i].tick(key == keysPtr[i]); + } + + // забираем действия с кнопок + if (btn[0].click()) Serial.println("click 0"); + if (btn[0].held()) Serial.println("held 0"); + + if (btn[1].press()) Serial.println("press 1"); + if (btn[1].step()) Serial.println("step 1"); +} diff --git a/libraries/EncButton/keywords.txt b/libraries/EncButton/keywords.txt new file mode 100644 index 0000000..320f922 --- /dev/null +++ b/libraries/EncButton/keywords.txt @@ -0,0 +1,102 @@ +####################################### +# Syntax Coloring Map For EncButton +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### +EncButton KEYWORD1 +EncButton2 KEYWORD1 + +EB_FAST KEYWORD1 +EB_DEB KEYWORD1 +EB_HOLD KEYWORD1 +EB_STEP KEYWORD1 +EB_CLICK KEYWORD1 + +EB_BETTER_ENC KEYWORD1 +EB_HALFSTEP_ENC KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +tick KEYWORD2 +tickISR KEYWORD2 +getState KEYWORD2 +resetState KEYWORD2 +checkCallback KEYWORD2 +setPins KEYWORD2 + +press KEYWORD2 +release KEYWORD2 +releaseStep KEYWORD2 +fast KEYWORD2 +turn KEYWORD2 +turnH KEYWORD2 +right KEYWORD2 +left KEYWORD2 +rightH KEYWORD2 +leftH KEYWORD2 +click KEYWORD2 +held KEYWORD2 +hold KEYWORD2 +step KEYWORD2 +busy KEYWORD2 + +getDir KEYWORD2 +counter KEYWORD2 +state KEYWORD2 +hasClicks KEYWORD2 +clicks KEYWORD2 +attach KEYWORD2 +detach KEYWORD2 +attachClicks KEYWORD2 +detachClicks KEYWORD2 +pullUp KEYWORD2 +holdEncButton KEYWORD2 +setHoldTimeout KEYWORD2 +setButtonLevel KEYWORD2 + +# deprecated +isPress KEYWORD2 +isRelease KEYWORD2 +isFast KEYWORD2 +isTurn KEYWORD2 +isTurnH KEYWORD2 +isRight KEYWORD2 +isLeft KEYWORD2 +isRightH KEYWORD2 +isLeftH KEYWORD2 +isClick KEYWORD2 +isHolded KEYWORD2 +isHeld KEYWORD2 +isHold KEYWORD2 +isStep KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +EB_TICK LITERAL1 +EB_CALLBACK LITERAL1 + +EB_BTN LITERAL1 +EB_ENC LITERAL1 +EB_ENCBTN LITERAL1 + +VIRT_BTN LITERAL1 +VIRT_ENC LITERAL1 +VIRT_ENCBTN LITERAL1 + +TURN_HANDLER LITERAL1 +TURN_H_HANDLER LITERAL1 +RIGHT_HANDLER LITERAL1 +LEFT_HANDLER LITERAL1 +RIGHT_H_HANDLER LITERAL1 +LEFT_H_HANDLER LITERAL1 +CLICK_HANDLER LITERAL1 +HOLDED_HANDLER LITERAL1 +STEP_HANDLER LITERAL1 +HOLD_HANDLER LITERAL1 +CLICKS_HANDLER LITERAL1 +PRESS_HANDLER LITERAL1 +RELEASE_HANDLER LITERAL1 \ No newline at end of file diff --git a/libraries/EncButton/library.properties b/libraries/EncButton/library.properties new file mode 100644 index 0000000..328a1b9 --- /dev/null +++ b/libraries/EncButton/library.properties @@ -0,0 +1,9 @@ +name=EncButton +version=1.20 +author=AlexGyver +maintainer=AlexGyver +sentence=Light and fast library for button and encoder operation for Arduino +paragraph=Turns, clicks, pool and callback mode, optimised for interrupt using +category=Sensors +url=https://github.com/GyverLibs/EncButton +architectures=* diff --git a/libraries/EncButton/src/EncButton.h b/libraries/EncButton/src/EncButton.h new file mode 100644 index 0000000..aa79417 --- /dev/null +++ b/libraries/EncButton/src/EncButton.h @@ -0,0 +1,488 @@ +/* + Ультра лёгкая и быстрая библиотека для энкодера, энкодера с кнопкой или просто кнопки + Документация: + GitHub: https://github.com/GyverLibs/EncButton + Возможности: + - Максимально быстрое чтение пинов для AVR (ATmega328/ATmega168, ATtiny85/ATtiny13) + - Оптимизированный вес + - Быстрые и лёгкие алгоритмы кнопки и энкодера + - Энкодер: поворот, нажатый поворот, быстрый поворот, счётчик + - Кнопка: антидребезг, клик, несколько кликов, счётчик кликов, удержание, режим step + - Подключение - только HIGH PULL! + - Опциональный режим callback (+22б SRAM на каждый экземпляр) + + AlexGyver, alex@alexgyver.ru + https://alexgyver.ru/ + MIT License + Опционально используется алгоритм из библиотеки // https://github.com/mathertel/RotaryEncoder + + Версии: + v1.1 - пуллап отдельныи методом + v1.2 - можно передать конструктору параметр INPUT_PULLUP / INPUT(умолч) + v1.3 - виртуальное зажатие кнопки энкодера вынесено в отдельную функцию + мелкие улучшения + v1.4 - обработка нажатия и отпускания кнопки + v1.5 - добавлен виртуальный режим + v1.6 - оптимизация работы в прерывании + v1.6.1 - PULLUP по умолчанию + v1.7 - большая оптимизация памяти, переделан FastIO + v1.8 - индивидуальная настройка таймаута удержания кнопки (была общая на всех) + v1.8.1 - убран FastIO + v1.9 - добавлена отдельная отработка нажатого поворота и запрос направления + v1.10 - улучшил обработку released, облегчил вес в режиме callback и исправил баги + v1.11 - ещё больше всякой оптимизации + настройка уровня кнопки + v1.11.1 - совместимость Digispark + v1.12 - добавил более точный алгоритм энкодера EB_BETTER_ENC + v1.13 - добавлен экспериментальный EncButton2 + v1.14 - добавлена releaseStep(). Отпускание кнопки внесено в дебаунс + v1.15 - добавлен setPins() для EncButton2 + v1.16 - добавлен режим EB_HALFSTEP_ENC для полушаговых энкодеров + v1.17 - добавлен step с предварительными кликами + v1.18 - не считаем клики после активации step. held() и hold() тоже могут принимать предварительные клики. Переделан и улучшен дебаунс + v1.18.1 - исправлена ошибка в releaseStep() (не возвращала результат) + v1.18.2 - fix compiler warnings + v1.19 - оптимизация скорости, уменьшен вес в sram + v1.19.1 - ещё чутка увеличена производительность + v1.19.2 - ещё немного увеличена производительность, спасибо XRay3D + v1.19.3 - сделал высокий уровень кнопки по умолчанию в виртуальном режиме + v1.19.4 - фикс EncButton2 + v1.20 - исправлена критическая ошибка в EncButton2 +*/ + +#ifndef _EncButton_h +#define _EncButton_h + +// ========= НАСТРОЙКИ (можно передефайнить из скетча) ========== +#define _EB_FAST 30 // таймаут быстрого поворота +#define _EB_DEB 50 // дебаунс кнопки +#define _EB_HOLD 1000 // таймаут удержания кнопки +#define _EB_STEP 500 // период срабатывания степ +#define _EB_CLICK 400 // таймаут накликивания +//#define EB_BETTER_ENC // точный алгоритм отработки энкодера (можно задефайнить в скетче) + +// =========== НЕ ТРОГАЙ ============ +#include + +#ifndef nullptr +#define nullptr NULL +#endif + +#ifndef EB_FAST +#define EB_FAST _EB_FAST +#endif +#ifndef EB_DEB +#define EB_DEB _EB_DEB +#endif +#ifndef EB_HOLD +#define EB_HOLD _EB_HOLD +#endif +#ifndef EB_STEP +#define EB_STEP _EB_STEP +#endif +#ifndef EB_CLICK +#define EB_CLICK _EB_CLICK +#endif + +enum eb_callback { + TURN_HANDLER, // 0 + LEFT_HANDLER, // 1 + RIGHT_HANDLER, // 2 + LEFT_H_HANDLER, // 3 + RIGHT_H_HANDLER, // 4 + CLICK_HANDLER, // 5 + HOLDED_HANDLER, // 6 + STEP_HANDLER, // 7 + PRESS_HANDLER, // 8 + CLICKS_HANDLER, // 9 + RELEASE_HANDLER, // 10 + HOLD_HANDLER, // 11 + TURN_H_HANDLER, // 12 + // clicks amount 13 +}; + +// константы +#define EB_TICK 0 +#define EB_CALLBACK 1 + +#define EB_NO_PIN 255 + +#define VIRT_ENC 254 +#define VIRT_ENCBTN 253 +#define VIRT_BTN 252 + +#ifdef EB_BETTER_ENC +static const int8_t _EB_DIR[] = { + 0, -1, 1, 0, + 1, 0, 0, -1, + -1, 0, 0, 1, + 0, 1, -1, 0 +}; +#endif + +// ===================================== CLASS ===================================== +template < uint8_t _EB_MODE, uint8_t _S1 = EB_NO_PIN, uint8_t _S2 = EB_NO_PIN, uint8_t _KEY = EB_NO_PIN > +class EncButton { +public: + // можно указать режим работы пина + EncButton(const uint8_t mode = INPUT_PULLUP) { + if (_S1 < 252 && mode == INPUT_PULLUP) pullUp(); + setButtonLevel(_S1 < 252 ? LOW : HIGH); // высокий уровень в виртуальном режиме + } + + // подтянуть пины внутренней подтяжкой + void pullUp() { + if (_S1 < 252) { // реальное устройство + if (_S2 == EB_NO_PIN) { // обычная кнопка + pinMode(_S1, INPUT_PULLUP); + } else if (_KEY == EB_NO_PIN) { // энк без кнопки + pinMode(_S1, INPUT_PULLUP); + pinMode(_S2, INPUT_PULLUP); + } else { // энк с кнопкой + pinMode(_S1, INPUT_PULLUP); + pinMode(_S2, INPUT_PULLUP); + pinMode(_KEY, INPUT_PULLUP); + } + } + } + + // установить таймаут удержания кнопки для isHold(), мс (до 30 000) + void setHoldTimeout(int tout) { + _holdT = tout >> 7; + } + + // виртуально зажать кнопку энкодера + void holdEncButton(bool state) { + if (state) setF(8); + else clrF(8); + } + + // уровень кнопки: LOW - кнопка подключает GND (умолч.), HIGH - кнопка подключает VCC + void setButtonLevel(bool level) { + if (level) clrF(11); + else setF(11); + } + + // ===================================== TICK ===================================== + // тикер, вызывать как можно чаще + // вернёт отличное от нуля значение, если произошло какое то событие + uint8_t tick(uint8_t s1 = 0, uint8_t s2 = 0, uint8_t key = 0) { + tickISR(s1, s2, key); + checkCallback(); + return EBState; + } + + // тикер специально для прерывания, не проверяет коллбэки + uint8_t tickISR(uint8_t s1 = 0, uint8_t s2 = 0, uint8_t key = 0) { + if (!_isrFlag) { + _isrFlag = 1; + // обработка энка (компилятор вырежет блок если не используется) + // если объявлены два пина или выбран вирт. энкодер или энкодер с кнопкой + if ((_S1 < 252 && _S2 < 252) || _S1 == VIRT_ENC || _S1 == VIRT_ENCBTN) { + uint8_t state; + if (_S1 >= 252) state = s1 | (s2 << 1); // получаем код + else state = fastRead(_S1) | (fastRead(_S2) << 1); // получаем код + poolEnc(state); + } + + // обработка кнопки (компилятор вырежет блок если не используется) + // если S2 не указан (кнопка) или указан KEY или выбран вирт. энкодер с кнопкой или кнопка + if ((_S1 < 252 && _S2 == EB_NO_PIN) || _KEY != EB_NO_PIN || _S1 == VIRT_BTN || _S1 == VIRT_ENCBTN) { + if (_S1 < 252 && _S2 == EB_NO_PIN) _btnState = fastRead(_S1); // обычная кнопка + if (_KEY != EB_NO_PIN) _btnState = fastRead(_KEY); // энк с кнопкой + if (_S1 == VIRT_BTN) _btnState = s1; // вирт кнопка + if (_S1 == VIRT_ENCBTN) _btnState = key; // вирт энк с кнопкой + _btnState ^= readF(11); // инверсия кнопки + if (_btnState || readF(15)) poolBtn(); // опрос если кнопка нажата или не вышли таймауты + } + _isrFlag = 0; + } + return EBState; + } + + // ===================================== CALLBACK ===================================== + // проверить callback, чтобы не дёргать в прерывании + void checkCallback() { + if (_EB_MODE) { + if (turn()) exec(0); + if (turnH()) exec(12); + if (EBState > 0 && EBState <= 8) exec(EBState); + if (release()) exec(10); + if (hold()) exec(11); + if (checkFlag(6)) { + exec(9); + if (clicks == _amount) exec(13); + } + EBState = 0; + } + } + + // подключить обработчик + void attach(eb_callback type, void (*handler)()) { + _callback[type] = *handler; + } + + // отключить обработчик + void detach(eb_callback type) { + _callback[type] = nullptr; + } + + // подключить обработчик на количество кликов (может быть только один!) + void attachClicks(uint8_t amount, void (*handler)()) { + _amount = amount; + _callback[13] = *handler; + } + + // отключить обработчик на количество кликов + void detachClicks() { + _callback[13] = nullptr; + } + + // ===================================== STATUS ===================================== + uint8_t getState() { return EBState; } // получить статус + void resetState() { EBState = 0; } // сбросить статус + + // ======================================= ENC ======================================= + bool left() { return checkState(1); } // поворот влево + bool right() { return checkState(2); } // поворот вправо + bool leftH() { return checkState(3); } // поворот влево нажатый + bool rightH() { return checkState(4); } // поворот вправо нажатый + + bool fast() { return readF(1); } // быстрый поворот + bool turn() { return checkFlag(0); } // энкодер повёрнут + bool turnH() { return checkFlag(9); } // энкодер повёрнут нажато + + int8_t getDir() { return _dir; } // направление последнего поворота, 1 или -1 + int16_t counter = 0; // счётчик энкодера + + // ======================================= BTN ======================================= + bool busy() { return readF(15); } // вернёт true, если всё ещё нужно вызывать tick для опроса таймаутов + bool state() { return _btnState; } // статус кнопки + bool press() { return checkState(8); } // кнопка нажата + bool release() { return checkFlag(10); } // кнопка отпущена + bool click() { return checkState(5); } // клик по кнопке + + bool held() { return checkState(6); } // кнопка удержана + bool hold() { return readF(4); } // кнопка удерживается + bool step() { return checkState(7); } // режим импульсного удержания + bool releaseStep() { return checkFlag(12); } // кнопка отпущена после импульсного удержания + + bool held(uint8_t clk) { return (clicks == clk) ? checkState(6) : 0; } // кнопка удержана с предварительным накликиванием + bool hold(uint8_t clk) { return (clicks == clk) ? readF(4) : 0; } // кнопка удерживается с предварительным накликиванием + bool step(uint8_t clk) { return (clicks == clk) ? checkState(7) : 0; } // режим импульсного удержания с предварительным накликиванием + bool releaseStep(uint8_t clk) { return (clicks == clk) ? checkFlag(12) : 0; } // кнопка отпущена после импульсного удержания с предварительным накликиванием + + uint8_t clicks = 0; // счётчик кликов + bool hasClicks(uint8_t num) { return (clicks == num && checkFlag(7)) ? 1 : 0; } // имеются клики + uint8_t hasClicks() { return checkFlag(6) ? clicks : 0; } // имеются клики + + // =================================================================================== + // =================================== DEPRECATED ==================================== + bool isStep() { return step(); } + bool isHold() { return hold(); } + bool isHolded() { return held(); } + bool isHeld() { return held(); } + bool isClick() { return click(); } + bool isRelease() { return release(); } + bool isPress() { return press(); } + bool isTurnH() { return turnH(); } + bool isTurn() { return turn(); } + bool isFast() { return fast(); } + bool isLeftH() { return leftH(); } + bool isRightH() { return rightH(); } + bool isLeft() { return left(); } + bool isRight() { return right(); } + + // ===================================== PRIVATE ===================================== +private: + bool fastRead(const uint8_t pin) { +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) + if (pin < 8) return bitRead(PIND, pin); + else if (pin < 14) return bitRead(PINB, pin - 8); + else if (pin < 20) return bitRead(PINC, pin - 14); +#elif defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny13__) + return bitRead(PINB, pin); +#else + return digitalRead(pin); +#endif + return 0; + } + + // ===================================== POOL ENC ===================================== + void poolEnc(uint8_t state) { + #ifdef EB_BETTER_ENC + if (_prev != state) { + _ecount += _EB_DIR[state | (_prev << 2)]; // сдвиг внутреннего счётчика + _prev = state; + #ifdef EB_HALFSTEP_ENC // полушаговый энкодер + // спасибо https://github.com/GyverLibs/EncButton/issues/10#issue-1092009489 + if ((state == 0x3 || state == 0x0) && _ecount) { + #else // полношаговый + if (state == 0x3 && _ecount) { // защёлкнули позицию + #endif + uint16_t ms = millis() & 0xFFFF; + EBState = (_ecount < 0) ? 1 : 2; + _ecount = 0; + if (_S2 == EB_NO_PIN || _KEY != EB_NO_PIN) { // энкодер с кнопкой + if (!readF(4) && (_btnState || readF(8))) EBState += 2; // если кнопка не "удерживается" + } + _dir = (EBState & 1) ? -1 : 1; // направление + counter += _dir; // счётчик + if (EBState <= 2) setF(0); // флаг поворота для юзера + else if (EBState <= 4) setF(9); // флаг нажатого поворота для юзера + if (ms - _debTmr < EB_FAST) setF(1); // быстрый поворот + else clrF(1); // обычный поворот + _debTmr = ms; + } + } + #else + if (_encRST && state == 0b11) { // ресет и энк защёлкнул позицию + uint16_t ms = millis() & 0xFFFF; + if (_S2 == EB_NO_PIN || _KEY != EB_NO_PIN) { // энкодер с кнопкой + if ((_prev == 1 || _prev == 2) && !readF(4)) { // если кнопка не "удерживается" и энкодер в позиции 1 или 2 + EBState = _prev; + if (_btnState || readF(8)) EBState += 2; + } + } else { // просто энкодер + if (_prev == 1 || _prev == 2) EBState = _prev; + } + + if (EBState > 0) { // был поворот + _dir = (EBState & 1) ? -1 : 1; // направление + counter += _dir; // счётчик + if (EBState <= 2) setF(0); // флаг поворота для юзера + else if (EBState <= 4) setF(9); // флаг нажатого поворота для юзера + if (ms - _debTmr < EB_FAST) setF(1); // быстрый поворот + else clrF(1); // обычный поворот + } + + _encRST = 0; + _debTmr = ms; + } + if (state == 0b00) _encRST = 1; + _prev = state; + #endif + } + + // ===================================== POOL BTN ===================================== + void poolBtn() { + uint16_t ms = millis() & 0xFFFF; + uint16_t debounce = ms - _debTmr; + if (_btnState) { // кнопка нажата + setF(15); // busy флаг + if (!readF(3)) { // и не была нажата ранее + if (readF(14)) { // ждём дебаунс + if (debounce > EB_DEB) { // прошел дебаунс + setF(3); // флаг кнопка была нажата + EBState = 8; // кнопка нажата + _debTmr = ms; // сброс таймаутов + } + } else { // первое нажатие + EBState = 0; + setF(14); // запомнили что хотим нажать + if (debounce > EB_CLICK || readF(5)) { // кнопка нажата после EB_CLICK + clicks = 0; // сбросить счётчик и флаг кликов + flags &= ~0b0011000011100000; // clear 5 6 7 12 13 (клики) + } + _debTmr = ms; + } + } else { // кнопка уже была нажата + if (!readF(4)) { // и удержание ещё не зафиксировано + if (debounce < (uint32_t)(_holdT << 7)) { // прошло меньше удержания + if (EBState != 0 && EBState != 8) setF(2); // но энкодер повёрнут! Запомнили + } else { // прошло больше времени удержания + if (!readF(2)) { // и энкодер не повёрнут + EBState = 6; // значит это удержание (сигнал) + flags |= 0b00110000; // set 4 5 запомнили что удерживается и отключаем сигнал о кликах + _debTmr = ms; // сброс таймаута + } + } + } else { // удержание зафиксировано + if (debounce > EB_STEP) { // таймер степа + EBState = 7; // сигналим + setF(13); // зафиксирован режим step + _debTmr = ms; // сброс таймаута + } + } + } + } else { // кнопка не нажата + if (readF(3)) { // но была нажата + if (debounce > EB_DEB) { + if (!readF(4) && !readF(2)) { // энкодер не трогали и не удерживали - это клик + EBState = 5; // click + clicks++; + } + flags &= ~0b00011100; // clear 2 3 4 + _debTmr = ms; // сброс таймаута + setF(10); // кнопка отпущена + if (checkFlag(13)) setF(12); // кнопка отпущена после step + } + } else if (clicks && !readF(5)) { // есть клики + if (debounce > EB_CLICK) flags |= 0b11100000; // set 5 6 7 (клики) + } else clrF(15); // снимаем busy флаг + checkFlag(14); // сброс ожидания нажатия + } + } + + // ===================================== MISC ===================================== + bool checkState(uint8_t val) { + return (EBState == val) ? EBState = 0, 1 : 0; + } + bool checkFlag(uint8_t val) { + return readF(val) ? clrF(val), 1 : 0; + } + void exec(uint8_t num) { + if (*_callback[num]) _callback[num](); + } + + inline void setF(const uint8_t x) __attribute__((always_inline)) {flags |= 1 << x;} + inline void clrF(const uint8_t x) __attribute__((always_inline)) {flags &= ~(1 << x);} + inline bool readF(const uint8_t x) __attribute__((always_inline)) {return flags & (1 << x);} + + uint8_t _amount : 6; + int8_t _dir : 2; + + uint8_t EBState : 4; + uint8_t _prev : 2; // можно ускорить ещё на 0.5us, если убрать битовые поля тут и ниже + bool _btnState : 1; + bool _encRST : 1; + bool _isrFlag = 0; + uint16_t flags = 0; + + uint16_t _debTmr = 0; + uint8_t _holdT = (EB_HOLD >> 7); + void (*_callback[_EB_MODE ? 14 : 0])() = {}; + +#ifdef EB_BETTER_ENC + int8_t _ecount = 0; +#endif + + // flags + // 0 - enc turn + // 1 - enc fast + // 2 - enc был поворот + // 3 - флаг кнопки + // 4 - hold + // 5 - clicks flag + // 6 - clicks get + // 7 - clicks get num + // 8 - enc button hold + // 9 - enc turn holded + // 10 - btn released + // 11 - btn level + // 12 - btn released after step + // 13 - step flag + // 14 - deb flag + // 15 - busy flag + + // EBState + // 0 - idle + // 1 - left + // 2 - right + // 3 - leftH + // 4 - rightH + // 5 - click + // 6 - held + // 7 - step + // 8 - press +}; + +#endif diff --git a/libraries/EncButton/src/EncButton2.h b/libraries/EncButton/src/EncButton2.h new file mode 100644 index 0000000..45f5fec --- /dev/null +++ b/libraries/EncButton/src/EncButton2.h @@ -0,0 +1,444 @@ +#ifndef _EncButton2_h +#define _EncButton2_h + +// ========= НАСТРОЙКИ (можно передефайнить из скетча) ========== +#define _EB_FAST 30 // таймаут быстрого поворота +#define _EB_DEB 50 // дебаунс кнопки +#define _EB_HOLD 1000 // таймаут удержания кнопки +#define _EB_STEP 500 // период срабатывания степ +#define _EB_CLICK 400 // таймаут накликивания +//#define EB_BETTER_ENC // точный алгоритм отработки энкодера (можно задефайнить в скетче) + +// =========== НЕ ТРОГАЙ ============ +#include + +#ifndef nullptr +#define nullptr NULL +#endif + +#ifndef EB_FAST +#define EB_FAST _EB_FAST +#endif +#ifndef EB_DEB +#define EB_DEB _EB_DEB +#endif +#ifndef EB_HOLD +#define EB_HOLD _EB_HOLD +#endif +#ifndef EB_STEP +#define EB_STEP _EB_STEP +#endif +#ifndef EB_CLICK +#define EB_CLICK _EB_CLICK +#endif + +enum eb_callback { + TURN_HANDLER, // 0 + LEFT_HANDLER, // 1 + RIGHT_HANDLER, // 2 + LEFT_H_HANDLER, // 3 + RIGHT_H_HANDLER, // 4 + CLICK_HANDLER, // 5 + HOLDED_HANDLER, // 6 + STEP_HANDLER, // 7 + PRESS_HANDLER, // 8 + CLICKS_HANDLER, // 9 + RELEASE_HANDLER, // 10 + HOLD_HANDLER, // 11 + TURN_H_HANDLER, // 12 + // clicks amount 13 +}; + +#ifdef EB_BETTER_ENC +static const int8_t _EB_DIR[] = { + 0, -1, 1, 0, + 1, 0, 0, -1, + -1, 0, 0, 1, + 0, 1, -1, 0 +}; +#endif + +// константы +#define EB_TICK 0 +#define EB_CALLBACK 1 + +#define EB_BTN 1 +#define EB_ENCBTN 2 +#define EB_ENC 3 +#define VIRT_BTN 4 +#define VIRT_ENCBTN 5 +#define VIRT_ENC 6 + +#define EB_PIN_AM ((_EB_TYPE == EB_BTN) ? 1 : (_EB_TYPE == EB_ENCBTN ? 3 : 2)) + +// ===================================== CLASS ===================================== +template < uint8_t _EB_TYPE, uint8_t _EB_MODE = EB_TICK > +class EncButton2 { +public: + // pinMode, pin1, pin2, pin3 + EncButton2(uint8_t mode = INPUT_PULLUP, uint8_t P1 = 255, uint8_t P2 = 255, uint8_t P3 = 255) { + setButtonLevel(_EB_TYPE <= 3 ? LOW : HIGH); // высокий уровень в виртуальном режиме + setPins(mode, P1, P2, P3); + } + + // установить пины + void setPins(uint8_t mode, uint8_t P1 = 255, uint8_t P2 = 255, uint8_t P3 = 255) { + if (_EB_TYPE == EB_BTN) { + pinMode(P1, mode); + _pins[0] = P1; + } else if (_EB_TYPE == EB_ENC) { + pinMode(P1, mode); + pinMode(P2, mode); + _pins[0] = P1; + _pins[1] = P2; + } else if (_EB_TYPE == EB_ENCBTN) { + pinMode(P1, mode); + pinMode(P2, mode); + pinMode(P3, mode); + _pins[0] = P1; + _pins[1] = P2; + _pins[2] = P3; + } + } + + // подтянуть пины внутренней подтяжкой + void pullUp() { + } + + // установить таймаут удержания кнопки для isHold(), мс (до 30 000) + void setHoldTimeout(int tout) { + _holdT = tout >> 7; + } + + // виртуально зажать кнопку энкодера + void holdEncButton(bool state) { + if (state) setF(8); + else clrF(8); + } + + // уровень кнопки: LOW - кнопка подключает GND (умолч.), HIGH - кнопка подключает VCC + void setButtonLevel(bool level) { + if (level) clrF(11); + else setF(11); + } + + // ===================================== TICK ===================================== + // тикер, вызывать как можно чаще + // вернёт отличное от нуля значение, если произошло какое то событие + uint8_t tick(uint8_t s1 = 0, uint8_t s2 = 0, uint8_t key = 0) { + tickISR(s1, s2, key); + checkCallback(); + return EBState; + } + +#define EB_BTN 1 +#define EB_ENCBTN 2 +#define EB_ENC 3 +#define VIRT_BTN 4 +#define VIRT_ENCBTN 5 +#define VIRT_ENC 6 + + // тикер специально для прерывания, не проверяет коллбэки + uint8_t tickISR(uint8_t p0 = 0, uint8_t p1 = 0, uint8_t p2 = 0) { + if (!_isrFlag) { + _isrFlag = 1; + if (_EB_TYPE <= 3) { // РЕАЛЬНОЕ УСТРОЙСТВО + if (_EB_TYPE >= 2) poolEnc(fastRead(0) | (fastRead(1) << 1)); // энк или энк с кнопкой + if (_EB_TYPE <= 2) { // кнопка или энк с кнопкой + if (_EB_TYPE == EB_BTN) _btnState = fastRead(0); // кнопка + else _btnState = fastRead(2); // энк с кнопкой + _btnState ^= readF(11); // инверсия кнопки + poolBtn(); + } + } else { // ВИРТУАЛЬНОЕ УСТРОЙСТВО + if (_EB_TYPE >= 5) poolEnc(p0 | (p1 << 1)); // энк или энк с кнопкой + if (_EB_TYPE <= 5) { // кнопка или энк с кнопкой + if (_EB_TYPE == VIRT_BTN) _btnState = p0; // кнопка + else _btnState = p2; // энк с кнопкой + _btnState ^= readF(11); // инверсия кнопки + if (_btnState || readF(15)) poolBtn(); // опрос если кнопка нажата или не вышли таймауты + } + } + _isrFlag = 0; + } + return EBState; + } + + // ===================================== CALLBACK ===================================== + // проверить callback, чтобы не дёргать в прерывании + void checkCallback() { + if (_EB_MODE) { + if (turn()) exec(0); + if (turnH()) exec(12); + if (EBState > 0 && EBState <= 8) exec(EBState); + if (release()) exec(10); + if (hold()) exec(11); + if (checkFlag(6)) { + exec(9); + if (clicks == _amount) exec(13); + } + EBState = 0; + } + } + + // подключить обработчик + void attach(eb_callback type, void (*handler)()) { + _callback[type] = *handler; + } + + // отключить обработчик + void detach(eb_callback type) { + _callback[type] = nullptr; + } + + // подключить обработчик на количество кликов (может быть только один!) + void attachClicks(uint8_t amount, void (*handler)()) { + _amount = amount; + _callback[13] = *handler; + } + + // отключить обработчик на количество кликов + void detachClicks() { + _callback[13] = nullptr; + } + + // ===================================== STATUS ===================================== + uint8_t getState() { return EBState; } // получить статус + void resetState() { EBState = 0; } // сбросить статус + + // ======================================= ENC ======================================= + bool left() { return checkState(1); } // поворот влево + bool right() { return checkState(2); } // поворот вправо + bool leftH() { return checkState(3); } // поворот влево нажатый + bool rightH() { return checkState(4); } // поворот вправо нажатый + + bool fast() { return readF(1); } // быстрый поворот + bool turn() { return checkFlag(0); } // энкодер повёрнут + bool turnH() { return checkFlag(9); } // энкодер повёрнут нажато + int8_t getDir() { return _dir; } // направление последнего поворота, 1 или -1 + int16_t counter = 0; // счётчик энкодера + + // ======================================= BTN ======================================= + bool busy() { return readF(15); } // вернёт true, если всё ещё нужно вызывать tick для опроса таймаутов + bool state() { return _btnState; } // статус кнопки + bool press() { return checkState(8); } // кнопка нажата + bool release() { return checkFlag(10); } // кнопка отпущена + bool click() { return checkState(5); } // клик по кнопке + + bool held() { return checkState(6); } // кнопка удержана + bool hold() { return readF(4); } // кнопка удерживается + bool step() { return checkState(7); } // режим импульсного удержания + bool releaseStep() { return checkFlag(12); }// кнопка отпущена после импульсного удержания + + bool held(uint8_t clk) { return (clicks == clk) ? checkState(6) : 0; } // кнопка удержана с предварительным накликиванием + bool hold(uint8_t clk) { return (clicks == clk) ? readF(4) : 0; } // кнопка удерживается с предварительным накликиванием + bool step(uint8_t clk) { return (clicks == clk) ? checkState(7) : 0; } // режим импульсного удержания с предварительным накликиванием + bool releaseStep(uint8_t clk = 0) { return (clicks == clk) ? checkFlag(12) : 0; } // кнопка отпущена после импульсного удержания с предварительным накликиванием + + uint8_t clicks = 0; // счётчик кликов + bool hasClicks(uint8_t num) { return (clicks == num && checkFlag(7)) ? 1 : 0; } // имеются клики + uint8_t hasClicks() { return checkFlag(6) ? clicks : 0; } // имеются клики + + // =================================================================================== + // =================================== DEPRECATED ==================================== + bool isStep() { return step(); } + bool isHold() { return hold(); } + bool isHolded() { return held(); } + bool isHeld() { return held(); } + bool isClick() { return click(); } + bool isRelease() { return release(); } + bool isPress() { return press(); } + bool isTurnH() { return turnH(); } + bool isTurn() { return turn(); } + bool isFast() { return fast(); } + bool isLeftH() { return leftH(); } + bool isRightH() { return rightH(); } + bool isLeft() { return left(); } + bool isRight() { return right(); } + + // ===================================== PRIVATE ===================================== +private: + // ===================================== POOL ENC ===================================== + void poolEnc(uint8_t state) { + #ifdef EB_BETTER_ENC + if (_prev != state) { + _ecount += _EB_DIR[state | (_prev << 2)]; // сдвиг внутреннего счётчика + _prev = state; + #ifdef EB_HALFSTEP_ENC // полушаговый энкодер + // спасибо https://github.com/GyverLibs/EncButton/issues/10#issue-1092009489 + if ((state == 0x3 || state == 0x0) && _ecount) { + #else // полношаговый + if (state == 0x3 && _ecount) { // защёлкнули позицию + #endif + uint16_t ms = millis() & 0xFFFF; + EBState = (_ecount < 0) ? 1 : 2; + _ecount = 0; + if (_EB_TYPE == EB_ENCBTN || _EB_TYPE == VIRT_ENCBTN) { // энкодер с кнопкой + if (!readF(4) && (_btnState || readF(8))) EBState += 2; // если кнопка не "удерживается" + } + _dir = (EBState & 1) ? -1 : 1; // направление + counter += _dir; // счётчик + if (EBState <= 2) setF(0); // флаг поворота для юзера + else if (EBState <= 4) setF(9); // флаг нажатого поворота для юзера + if (ms - _debTmr < EB_FAST) setF(1); // быстрый поворот + else clrF(1); // обычный поворот + _debTmr = ms; + } + } + #else + if (_encRST && state == 0b11) { // ресет и энк защёлкнул позицию + uint16_t ms = millis() & 0xFFFF; + if (_EB_TYPE == EB_ENCBTN || _EB_TYPE == VIRT_ENCBTN) { // энкодер с кнопкой + if ((_prev == 1 || _prev == 2) && !readF(4)) { // если кнопка не "удерживается" и энкодер в позиции 1 или 2 + EBState = _prev; + if (_btnState || readF(8)) EBState += 2; + } + } else { // просто энкодер + if (_prev == 1 || _prev == 2) EBState = _prev; + } + + if (EBState > 0) { // был поворот + _dir = (EBState & 1) ? -1 : 1; // направление + counter += _dir; // счётчик + if (EBState <= 2) setF(0); // флаг поворота для юзера + else if (EBState <= 4) setF(9); // флаг нажатого поворота для юзера + if (ms - _debTmr < EB_FAST) setF(1); // быстрый поворот + else clrF(1); // обычный поворот + } + + _encRST = 0; + _debTmr = ms; + } + if (state == 0b00) _encRST = 1; + _prev = state; + #endif + } + + // ===================================== POOL BTN ===================================== + void poolBtn() { + uint16_t ms = millis() & 0xFFFF; + uint16_t debounce = ms - _debTmr; + if (_btnState) { // кнопка нажата + setF(15); // busy флаг + if (!readF(3)) { // и не была нажата ранее + if (readF(14)) { // ждём дебаунс + if (debounce > EB_DEB) { // прошел дебаунс + setF(3); // флаг кнопка была нажата + EBState = 8; // кнопка нажата + _debTmr = ms; // сброс таймаутов + } + } else { // первое нажатие + EBState = 0; + setF(14); // запомнили что хотим нажать + if (debounce > EB_CLICK || readF(5)) { // кнопка нажата после EB_CLICK + clicks = 0; // сбросить счётчик и флаг кликов + flags &= ~0b0011000011100000; // clear 5 6 7 12 13 (клики) + } + _debTmr = ms; + } + } else { // кнопка уже была нажата + if (!readF(4)) { // и удержание ещё не зафиксировано + if (debounce < (uint32_t)(_holdT << 7)) { // прошло меньше удержания + if (EBState != 0 && EBState != 8) setF(2); // но энкодер повёрнут! Запомнили + } else { // прошло больше времени удержания + if (!readF(2)) { // и энкодер не повёрнут + EBState = 6; // значит это удержание (сигнал) + flags |= 0b00110000; // set 4 5 запомнили что удерживается и отключаем сигнал о кликах + _debTmr = ms; // сброс таймаута + } + } + } else { // удержание зафиксировано + if (debounce > EB_STEP) { // таймер степа + EBState = 7; // сигналим + setF(13); // зафиксирован режим step + _debTmr = ms; // сброс таймаута + } + } + } + } else { // кнопка не нажата + if (readF(3)) { // но была нажата + if (debounce > EB_DEB) { + if (!readF(4) && !readF(2)) { // энкодер не трогали и не удерживали - это клик + EBState = 5; // click + clicks++; + } + flags &= ~0b00011100; // clear 2 3 4 + _debTmr = ms; // сброс таймаута + setF(10); // кнопка отпущена + if (checkFlag(13)) setF(12); // кнопка отпущена после step + } + } else if (clicks && !readF(5)) { // есть клики + if (debounce > EB_CLICK) flags |= 0b11100000; // set 5 6 7 (клики) + } else clrF(15); // снимаем busy флаг + checkFlag(14); // сброс ожидания нажатия + } + } + + // ===================================== MISC ===================================== + bool fastRead(uint8_t pin) { + return digitalRead(_pins[pin]); + } + bool checkState(uint8_t val) { + return (EBState == val) ? EBState = 0, 1 : 0; + } + bool checkFlag(uint8_t val) { + return readF(val) ? clrF(val), 1 : 0; + } + void exec(uint8_t num) { + if (*_callback[num]) _callback[num](); + } + + inline void setF(const uint8_t x) __attribute__((always_inline)) {flags |= 1 << x;} + inline void clrF(const uint8_t x) __attribute__((always_inline)) {flags &= ~(1 << x);} + inline bool readF(const uint8_t x) __attribute__((always_inline)) {return flags & (1 << x);} + + uint8_t _amount : 6; + int8_t _dir : 2; + + uint8_t EBState : 4; + uint8_t _prev : 2; + bool _btnState : 1; + bool _encRST : 1; + bool _isrFlag = 0; + uint16_t flags = 0; + + uint16_t _debTmr = 0; + uint8_t _holdT = (EB_HOLD >> 7); + void (*_callback[_EB_MODE ? 14 : 0])() = {}; + +#ifdef EB_BETTER_ENC + int8_t _ecount = 0; +#endif + + uint8_t _pins[EB_PIN_AM]; + + // flags + // 0 - enc turn + // 1 - enc fast + // 2 - enc был поворот + // 3 - флаг кнопки + // 4 - hold + // 5 - clicks flag + // 6 - clicks get + // 7 - clicks get num + // 8 - enc button hold + // 9 - enc turn holded + // 10 - btn released + // 11 - btn level + // 12 - btn released after step + // 13 - step flag + // 14 - deb flag + // 15 - busy flag + + // EBState + // 0 - idle + // 1 - left + // 2 - right + // 3 - leftH + // 4 - rightH + // 5 - click + // 6 - held + // 7 - step + // 8 - press +}; +#endif diff --git a/libraries/Ethernet/AUTHORS b/libraries/Ethernet/AUTHORS new file mode 100644 index 0000000..14097df --- /dev/null +++ b/libraries/Ethernet/AUTHORS @@ -0,0 +1,38 @@ + +Alberto Panu https://github.com/bigjohnson +Alasdair Allan https://github.com/aallan +Alice Pintus https://github.com/00alis +Adrian McEwen https://github.com/amcewen +Arduino LLC http://arduino.cc/ +Arnie97 https://github.com/Arnie97 +Arturo Guadalupi https://github.com/agdl +Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/ +chaveiro https://github.com/chaveiro +Cristian Maglie https://github.com/cmaglie +David A. Mellis https://github.com/damellis +Dino Tinitigan https://github.com/bigdinotech +Eddy https://github.com/eddyst +Federico Vanzati https://github.com/Fede85 +Federico Fissore https://github.com/ffissore +Jack Christensen https://github.com/JChristensen +Johann Richard https://github.com/johannrichard +Jordan Terrell https://github.com/iSynaptic +Justin Paulin https://github.com/interwho +lathoub https://github.com/lathoub +Martino Facchin https://github.com/facchinm +Matthias Hertel https://github.com/mathertel +Matthijs Kooijman https://github.com/matthijskooijman +Matt Robinson https://github.com/ribbons +MCQN Ltd. http://mcqn.com/ +Michael Amie https://github.com/michaelamie +Michael Margolis https://github.com/michaelmargolis +Norbert Truchsess https://github.com/ntruchsess +Paul Stoffregen https://github.com/PaulStoffregen +per1234 https://github.com/per1234 +Richard Sim +Scott Fitzgerald https://github.com/shfitz +Thibaut Viard https://github.com/aethaniel +Tom Igoe https://github.com/tigoe +WizNet http://www.wiznet.co.kr +Zach Eveland https://github.com/zeveland + diff --git a/libraries/Ethernet/README.adoc b/libraries/Ethernet/README.adoc new file mode 100644 index 0000000..8f890f0 --- /dev/null +++ b/libraries/Ethernet/README.adoc @@ -0,0 +1,24 @@ += Ethernet Library for Arduino = + +With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/Ethernet + +== License == + +Copyright (c) 2010 Arduino LLC. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino b/libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino new file mode 100644 index 0000000..3b431c8 --- /dev/null +++ b/libraries/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino @@ -0,0 +1,119 @@ +/* + Advanced Chat Server + + A more advanced server that distributes any incoming messages + to all connected clients but the client the message comes from. + To use, telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + Using an Arduino Wiznet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + redesigned to make use of operator== 25 Nov 2013 + by Norbert Truchsess + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network. +// gateway and subnet are optional: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + + +// telnet defaults to port 23 +EthernetServer server(23); + +EthernetClient clients[8]; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // initialize the Ethernet device + Ethernet.begin(mac, ip, myDns, gateway, subnet); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start listening for clients + server.begin(); + + Serial.print("Chat server address:"); + Serial.println(Ethernet.localIP()); +} + +void loop() { + // check for any new client connecting, and say hello (before any incoming data) + EthernetClient newClient = server.accept(); + if (newClient) { + for (byte i=0; i < 8; i++) { + if (!clients[i]) { + Serial.print("We have a new client #"); + Serial.println(i); + newClient.print("Hello, client number: "); + newClient.println(i); + // Once we "accept", the client is no longer tracked by EthernetServer + // so we must store it into our list of clients + clients[i] = newClient; + break; + } + } + } + + // check for incoming data from all clients + for (byte i=0; i < 8; i++) { + if (clients[i] && clients[i].available() > 0) { + // read bytes from a client + byte buffer[80]; + int count = clients[i].read(buffer, 80); + // write the bytes to all other connected clients + for (byte j=0; j < 8; j++) { + if (j != i && clients[j].connected()) { + clients[j].write(buffer, count); + } + } + } + } + + // stop any clients which disconnect + for (byte i=0; i < 8; i++) { + if (clients[i] && !clients[i].connected()) { + Serial.print("disconnect client #"); + Serial.println(i); + clients[i].stop(); + } + } +} diff --git a/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino new file mode 100644 index 0000000..2e8e639 --- /dev/null +++ b/libraries/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino @@ -0,0 +1,247 @@ +/* + SCP1000 Barometric Pressure Sensor Display + + Serves the output of a Barometric Pressure Sensor as a web page. + Uses the SPI library. For details on the sensor, see: + http://www.sparkfun.com/commerce/product_info.php?products_id=8161 + + This sketch adapted from Nathan Seidle's SCP1000 example for PIC: + http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip + + TODO: this hardware is long obsolete. This example program should + be rewritten to use https://www.sparkfun.com/products/9721 + + Circuit: + SCP1000 sensor attached to pins 6,7, and 11 - 13: + DRDY: pin 6 + CSB: pin 7 + MOSI: pin 11 + MISO: pin 12 + SCK: pin 13 + + created 31 July 2010 + by Tom Igoe + */ + +#include +// the sensor communicates using SPI, so include the library: +#include + + +// assign a MAC address for the Ethernet controller. +// fill in your address here: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +// assign an IP address for the controller: +IPAddress ip(192, 168, 1, 20); + + +// Initialize the Ethernet server library +// with the IP address and port you want to use +// (port 80 is default for HTTP): +EthernetServer server(80); + + +//Sensor's memory register addresses: +const int PRESSURE = 0x1F; //3 most significant bits of pressure +const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure +const int TEMPERATURE = 0x21; //16 bit temperature reading + +// pins used for the connection with the sensor +// the others you need are controlled by the SPI library): +const int dataReadyPin = 6; +const int chipSelectPin = 7; + +float temperature = 0.0; +long pressure = 0; +long lastReadingTime = 0; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // start the SPI library: + SPI.begin(); + + // start the Ethernet connection + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start listening for clients + server.begin(); + + // initalize the data ready and chip select pins: + pinMode(dataReadyPin, INPUT); + pinMode(chipSelectPin, OUTPUT); + + //Configure SCP1000 for low noise configuration: + writeRegister(0x02, 0x2D); + writeRegister(0x01, 0x03); + writeRegister(0x03, 0x02); + + // give the sensor and Ethernet shield time to set up: + delay(1000); + + //Set the sensor to high resolution mode tp start readings: + writeRegister(0x03, 0x0A); + +} + +void loop() { + // check for a reading no more than once a second. + if (millis() - lastReadingTime > 1000) { + // if there's a reading ready, read it: + // don't do anything until the data ready pin is high: + if (digitalRead(dataReadyPin) == HIGH) { + getData(); + // timestamp the last time you got a reading: + lastReadingTime = millis(); + } + } + + // listen for incoming Ethernet connections: + listenForEthernetClients(); +} + + +void getData() { + Serial.println("Getting reading"); + //Read the temperature data + int tempData = readRegister(0x21, 2); + + // convert the temperature to celsius and display it: + temperature = (float)tempData / 20.0; + + //Read the pressure data highest 3 bits: + byte pressureDataHigh = readRegister(0x1F, 1); + pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0 + + //Read the pressure data lower 16 bits: + unsigned int pressureDataLow = readRegister(0x20, 2); + //combine the two parts into one 19-bit number: + pressure = ((pressureDataHigh << 16) | pressureDataLow) / 4; + + Serial.print("Temperature: "); + Serial.print(temperature); + Serial.println(" degrees C"); + Serial.print("Pressure: " + String(pressure)); + Serial.println(" Pa"); +} + +void listenForEthernetClients() { + // listen for incoming clients + EthernetClient client = server.available(); + if (client) { + Serial.println("Got a client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println(); + // print the current readings, in HTML format: + client.print("Temperature: "); + client.print(temperature); + client.print(" degrees C"); + client.println("
"); + client.print("Pressure: " + String(pressure)); + client.print(" Pa"); + client.println("
"); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + // close the connection: + client.stop(); + } +} + + +//Send a write command to SCP1000 +void writeRegister(byte registerName, byte registerValue) { + // SCP1000 expects the register name in the upper 6 bits + // of the byte: + registerName <<= 2; + // command (read or write) goes in the lower two bits: + registerName |= 0b00000010; //Write command + + // take the chip select low to select the device: + digitalWrite(chipSelectPin, LOW); + + SPI.transfer(registerName); //Send register location + SPI.transfer(registerValue); //Send value to record into register + + // take the chip select high to de-select: + digitalWrite(chipSelectPin, HIGH); +} + + +//Read register from the SCP1000: +unsigned int readRegister(byte registerName, int numBytes) { + byte inByte = 0; // incoming from the SPI read + unsigned int result = 0; // result to return + + // SCP1000 expects the register name in the upper 6 bits + // of the byte: + registerName <<= 2; + // command (read or write) goes in the lower two bits: + registerName &= 0b11111100; //Read command + + // take the chip select low to select the device: + digitalWrite(chipSelectPin, LOW); + // send the device the register you want to read: + int command = SPI.transfer(registerName); + // send a value of 0 to read the first byte returned: + inByte = SPI.transfer(0x00); + + result = inByte; + // if there's more than one byte returned, + // shift the first byte then get the second byte: + if (numBytes > 1) { + result = inByte << 8; + inByte = SPI.transfer(0x00); + result = result | inByte; + } + // take the chip select high to de-select: + digitalWrite(chipSelectPin, HIGH); + // return the result: + return (result); +} diff --git a/libraries/Ethernet/examples/ChatServer/ChatServer.ino b/libraries/Ethernet/examples/ChatServer/ChatServer.ino new file mode 100644 index 0000000..3249c1a --- /dev/null +++ b/libraries/Ethernet/examples/ChatServer/ChatServer.ino @@ -0,0 +1,99 @@ +/* + Chat Server + + A simple server that distributes any incoming messages to all + connected clients. To use, telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + Using an Arduino Wiznet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network. +// gateway and subnet are optional: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + + +// telnet defaults to port 23 +EthernetServer server(23); +boolean alreadyConnected = false; // whether or not the client was connected previously + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // initialize the ethernet device + Ethernet.begin(mac, ip, myDns, gateway, subnet); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start listening for clients + server.begin(); + + Serial.print("Chat server address:"); + Serial.println(Ethernet.localIP()); +} + +void loop() { + // wait for a new client: + EthernetClient client = server.available(); + + // when the client sends the first byte, say hello: + if (client) { + if (!alreadyConnected) { + // clear out the input buffer: + client.flush(); + Serial.println("We have a new client"); + client.println("Hello, client!"); + alreadyConnected = true; + } + + if (client.available() > 0) { + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to the client: + server.write(thisChar); + // echo the bytes to the server as well: + Serial.write(thisChar); + } + } +} + + + diff --git a/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino new file mode 100644 index 0000000..e40cdfe --- /dev/null +++ b/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino @@ -0,0 +1,95 @@ +/* + DHCP-based IP printer + + This sketch uses the DHCP extensions to the Ethernet library + to get an IP address via DHCP and print the address obtained. + using an Arduino Wiznet Ethernet shield. + + Circuit: + Ethernet shield attached to pins 10, 11, 12, 13 + + created 12 April 2011 + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + + */ + +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { + 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 +}; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + } else if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // no point in carrying on, so do nothing forevermore: + while (true) { + delay(1); + } + } + // print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); +} + +void loop() { + switch (Ethernet.maintain()) { + case 1: + //renewed fail + Serial.println("Error: renewed fail"); + break; + + case 2: + //renewed success + Serial.println("Renewed success"); + //print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + break; + + case 3: + //rebind fail + Serial.println("Error: rebind fail"); + break; + + case 4: + //rebind success + Serial.println("Rebind success"); + //print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + break; + + default: + //nothing happened + break; + } +} + diff --git a/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino b/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino new file mode 100644 index 0000000..445d81d --- /dev/null +++ b/libraries/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino @@ -0,0 +1,102 @@ +/* + DHCP Chat Server + + A simple server that distributes any incoming messages to all + connected clients. To use, telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + Using an Arduino Wiznet Ethernet shield. + + THis version attempts to get an IP address using DHCP + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 21 May 2011 + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + Based on ChatServer example by David A. Mellis + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network. +// gateway and subnet are optional: +byte mac[] = { + 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 +}; +IPAddress ip(192, 168, 1, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + +// telnet defaults to port 23 +EthernetServer server(23); +boolean gotAMessage = false; // whether or not you got a message from the client yet + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Trying to get an IP address using DHCP"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // initialize the Ethernet device not using DHCP: + Ethernet.begin(mac, ip, myDns, gateway, subnet); + } + // print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + + // start listening for clients + server.begin(); +} + +void loop() { + // wait for a new client: + EthernetClient client = server.available(); + + // when the client sends the first byte, say hello: + if (client) { + if (!gotAMessage) { + Serial.println("We have a new client"); + client.println("Hello, client!"); + gotAMessage = true; + } + + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to the client: + server.write(thisChar); + // echo the bytes to the server as well: + Serial.print(thisChar); + Ethernet.maintain(); + } +} + diff --git a/libraries/Ethernet/examples/LinkStatus/LinkStatus.ino b/libraries/Ethernet/examples/LinkStatus/LinkStatus.ino new file mode 100644 index 0000000..af62ebb --- /dev/null +++ b/libraries/Ethernet/examples/LinkStatus/LinkStatus.ino @@ -0,0 +1,43 @@ +/* + Link Status + This sketch prints the ethernet link status. When the + ethernet cable is connected the link status should go to "ON". + NOTE: Only WizNet W5200 and W5500 are capable of reporting + the link status. W5100 will report "Unknown". + Hardware: + - Ethernet shield or equivalent board/shield with WizNet 5200/5500 + Written by Cristian Maglie + This example is public domain. +*/ + +#include +#include + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + Serial.begin(9600); +} + +void loop() { + auto link = Ethernet.linkStatus(); + Serial.print("Link status: "); + switch (link) { + case Unknown: + Serial.println("Unknown"); + break; + case LinkON: + Serial.println("ON"); + break; + case LinkOFF: + Serial.println("OFF"); + break; + } + delay(1000); +} diff --git a/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino b/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino new file mode 100644 index 0000000..85386b5 --- /dev/null +++ b/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino @@ -0,0 +1,113 @@ +/* + Telnet client + + This sketch connects to a a telnet server (http://www.google.com) + using an Arduino Wiznet Ethernet shield. You'll need a telnet server + to test this with. + Processing's ChatServer example (part of the network library) works well, + running on port 10002. It can be found as part of the examples + in the Processing application, available at + http://processing.org/ + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 14 Sep 2010 + modified 9 Apr 2012 + by Tom Igoe + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); + +// Enter the IP address of the server you're connecting to: +IPAddress server(1, 1, 1, 1); + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 23 is default for telnet; +// if you're using Processing's ChatServer, use port 10002): +EthernetClient client; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // start the Ethernet connection: + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + while (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + delay(500); + } + + // give the Ethernet shield a second to initialize: + delay(1000); + Serial.println("connecting..."); + + // if you get a connection, report back via serial: + if (client.connect(server, 10002)) { + Serial.println("connected"); + } else { + // if you didn't get a connection to the server: + Serial.println("connection failed"); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + // as long as there are bytes in the serial queue, + // read them and send them out the socket if it's open: + while (Serial.available() > 0) { + char inChar = Serial.read(); + if (client.connected()) { + client.print(inChar); + } + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + // do nothing: + while (true) { + delay(1); + } + } +} + + + + diff --git a/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino new file mode 100644 index 0000000..0c76b02 --- /dev/null +++ b/libraries/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino @@ -0,0 +1,139 @@ +/* + UDPSendReceiveString: + This sketch receives UDP message strings, prints them to the serial port + and sends an "acknowledge" string back to the sender + + A Processing sketch is included at the end of file that can be used to send + and received messages for testing with a computer. + + created 21 Aug 2010 + by Michael Margolis + + This code is in the public domain. + */ + + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// buffers for receiving and sending data +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet, +char ReplyBuffer[] = "acknowledged"; // a string to send back + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // start the Ethernet + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start UDP + Udp.begin(localPort); +} + +void loop() { + // if there's data available, read a packet + int packetSize = Udp.parsePacket(); + if (packetSize) { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i=0; i < 4; i++) { + Serial.print(remote[i], DEC); + if (i < 3) { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBufffer + Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); + + // send a reply to the IP address and port that sent us the packet we received + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write(ReplyBuffer); + Udp.endPacket(); + } + delay(10); +} + + +/* + Processing sketch to run with this example + ===================================================== + + // Processing UDP example to send and receive string data from Arduino + // press any key to send the "Hello Arduino" message + + + import hypermedia.net.*; + + UDP udp; // define the UDP object + + + void setup() { + udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000 + //udp.log( true ); // <-- printout the connection activity + udp.listen( true ); // and wait for incoming message + } + + void draw() + { + } + + void keyPressed() { + String ip = "192.168.1.177"; // the remote IP address + int port = 8888; // the destination port + + udp.send("Hello World", ip, port ); // the message to send + + } + + void receive( byte[] data ) { // <-- default handler + //void receive( byte[] data, String ip, int port ) { // <-- extended handler + + for(int i=0; i < data.length; i++) + print(char(data[i])); + println(); + } + */ + + diff --git a/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino new file mode 100644 index 0000000..ec52717 --- /dev/null +++ b/libraries/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino @@ -0,0 +1,156 @@ +/* + + Udp NTP Client + + Get the time from a Network Time Protocol (NTP) time server + Demonstrates use of UDP sendPacket and ReceivePacket + For more on NTP time servers and the messages needed to communicate with them, + see http://en.wikipedia.org/wiki/Network_Time_Protocol + + created 4 Sep 2010 + by Michael Margolis + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + + This code is in the public domain. + + */ + +#include +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; + +unsigned int localPort = 8888; // local port to listen for UDP packets + +const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server + +const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message + +byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets + +// A UDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start Ethernet and UDP + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + } else if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // no point in carrying on, so do nothing forevermore: + while (true) { + delay(1); + } + } + Udp.begin(localPort); +} + +void loop() { + sendNTPpacket(timeServer); // send an NTP packet to a time server + + // wait to see if a reply is available + delay(1000); + if (Udp.parsePacket()) { + // We've received a packet, read the data from it + Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer + + // the timestamp starts at byte 40 of the received packet and is four bytes, + // or two words, long. First, extract the two words: + + unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); + // combine the four bytes (two words) into a long integer + // this is NTP time (seconds since Jan 1 1900): + unsigned long secsSince1900 = highWord << 16 | lowWord; + Serial.print("Seconds since Jan 1 1900 = "); + Serial.println(secsSince1900); + + // now convert NTP time into everyday time: + Serial.print("Unix time = "); + // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: + const unsigned long seventyYears = 2208988800UL; + // subtract seventy years: + unsigned long epoch = secsSince1900 - seventyYears; + // print Unix time: + Serial.println(epoch); + + + // print the hour, minute and second: + Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) + Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print(':'); + if (((epoch % 3600) / 60) < 10) { + // In the first 10 minutes of each hour, we'll want a leading '0' + Serial.print('0'); + } + Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) + Serial.print(':'); + if ((epoch % 60) < 10) { + // In the first 10 seconds of each minute, we'll want a leading '0' + Serial.print('0'); + } + Serial.println(epoch % 60); // print the second + } + // wait ten seconds before asking for the time again + delay(10000); + Ethernet.maintain(); +} + +// send an NTP request to the time server at the given address +void sendNTPpacket(const char * address) { + // set all bytes in the buffer to 0 + memset(packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; + + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + Udp.beginPacket(address, 123); // NTP requests are to port 123 + Udp.write(packetBuffer, NTP_PACKET_SIZE); + Udp.endPacket(); +} + + + + + + + + + + diff --git a/libraries/Ethernet/examples/WebClient/WebClient.ino b/libraries/Ethernet/examples/WebClient/WebClient.ino new file mode 100644 index 0000000..45e01ee --- /dev/null +++ b/libraries/Ethernet/examples/WebClient/WebClient.ino @@ -0,0 +1,137 @@ +/* + Web client + + This sketch connects to a website (http://www.google.com) + using an Arduino Wiznet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe, based on work by Adrian McEwen + + */ + +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Set the static IP address to use if the DHCP fails to assign +IPAddress ip(192, 168, 0, 177); +IPAddress myDns(192, 168, 0, 1); + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +EthernetClient client; + +// Variables to measure the speed +unsigned long beginMicros, endMicros; +unsigned long byteCount = 0; +bool printWebData = true; // set to false for better speed measurement + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // try to congifure using IP address instead of DHCP: + Ethernet.begin(mac, ip, myDns); + } else { + Serial.print(" DHCP assigned IP "); + Serial.println(Ethernet.localIP()); + } + // give the Ethernet shield a second to initialize: + delay(1000); + Serial.print("connecting to "); + Serial.print(server); + Serial.println("..."); + + // if you get a connection, report back via serial: + if (client.connect(server, 80)) { + Serial.print("connected to "); + Serial.println(client.remoteIP()); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } else { + // if you didn't get a connection to the server: + Serial.println("connection failed"); + } + beginMicros = micros(); +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + int len = client.available(); + if (len > 0) { + byte buffer[80]; + if (len > 80) len = 80; + client.read(buffer, len); + if (printWebData) { + Serial.write(buffer, len); // show in the serial monitor (slows some boards) + } + byteCount = byteCount + len; + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + endMicros = micros(); + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + Serial.print("Received "); + Serial.print(byteCount); + Serial.print(" bytes in "); + float seconds = (float)(endMicros - beginMicros) / 1000000.0; + Serial.print(seconds, 4); + float rate = (float)byteCount / seconds / 1000.0; + Serial.print(", rate = "); + Serial.print(rate); + Serial.print(" kbytes/second"); + Serial.println(); + + // do nothing forevermore: + while (true) { + delay(1); + } + } +} + diff --git a/libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino b/libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino new file mode 100644 index 0000000..6607f43 --- /dev/null +++ b/libraries/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino @@ -0,0 +1,130 @@ +/* + Repeating Web client + + This sketch connects to a a web server and makes a request + using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or + the Adafruit Ethernet shield, either one will work, as long as it's got + a Wiznet Ethernet module on board. + + This example uses DNS, by assigning the Ethernet client with a MAC address, + IP address, and DNS address. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 19 Apr 2012 + by Tom Igoe + modified 21 Jan 2014 + by Federico Vanzati + + http://www.arduino.cc/en/Tutorial/WebClientRepeating + This code is in the public domain. + + */ + +#include +#include + +// assign a MAC address for the ethernet controller. +// fill in your address here: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +// Set the static IP address to use if the DHCP fails to assign +IPAddress ip(192, 168, 0, 177); +IPAddress myDns(192, 168, 0, 1); + +// initialize the library instance: +EthernetClient client; + +char server[] = "www.arduino.cc"; // also change the Host line in httpRequest() +//IPAddress server(64,131,82,241); + +unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds +const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // start serial port: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // try to congifure using IP address instead of DHCP: + Ethernet.begin(mac, ip, myDns); + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + } else { + Serial.print(" DHCP assigned IP "); + Serial.println(Ethernet.localIP()); + } + // give the Ethernet shield a second to initialize: + delay(1000); +} + +void loop() { + // if there's incoming data from the net connection. + // send it out the serial port. This is for debugging + // purposes only: + if (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if ten seconds have passed since your last connection, + // then connect again and send data: + if (millis() - lastConnectionTime > postingInterval) { + httpRequest(); + } + +} + +// this method makes a HTTP connection to the server: +void httpRequest() { + // close any connection before send a new request. + // This will free the socket on the WiFi shield + client.stop(); + + // if there's a successful connection: + if (client.connect(server, 80)) { + Serial.println("connecting..."); + // send the HTTP GET request: + client.println("GET /latest.txt HTTP/1.1"); + client.println("Host: www.arduino.cc"); + client.println("User-Agent: arduino-ethernet"); + client.println("Connection: close"); + client.println(); + + // note the time that the connection was made: + lastConnectionTime = millis(); + } else { + // if you couldn't make a connection: + Serial.println("connection failed"); + } +} + + + + diff --git a/libraries/Ethernet/examples/WebServer/WebServer.ino b/libraries/Ethernet/examples/WebServer/WebServer.ino new file mode 100644 index 0000000..7c0bf60 --- /dev/null +++ b/libraries/Ethernet/examples/WebServer/WebServer.ino @@ -0,0 +1,123 @@ +/* + Web Server + + A simple web server that shows the value of the analog input pins. + using an Arduino Wiznet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + * Analog inputs attached to pins A0 through A5 (optional) + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); + +// Initialize the Ethernet server library +// with the IP address and port you want to use +// (port 80 is default for HTTP): +EthernetServer server(80); + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + Serial.println("Ethernet WebServer Example"); + + // start the Ethernet connection and the server: + Ethernet.begin(mac, ip); + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start the server + server.begin(); + Serial.print("server is at "); + Serial.println(Ethernet.localIP()); +} + + +void loop() { + // listen for incoming clients + EthernetClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + boolean currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} + diff --git a/libraries/Ethernet/keywords.txt b/libraries/Ethernet/keywords.txt new file mode 100644 index 0000000..9fd2541 --- /dev/null +++ b/libraries/Ethernet/keywords.txt @@ -0,0 +1,67 @@ +####################################### +# Syntax Coloring Map For Ethernet +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Ethernet KEYWORD1 Ethernet +EthernetClient KEYWORD1 EthernetClient +EthernetServer KEYWORD1 EthernetServer +IPAddress KEYWORD1 EthernetIPAddress + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +status KEYWORD2 +connect KEYWORD2 +write KEYWORD2 +available KEYWORD2 +availableForWrite KEYWORD2 +read KEYWORD2 +peek KEYWORD2 +flush KEYWORD2 +stop KEYWORD2 +connected KEYWORD2 +accept KEYWORD2 +begin KEYWORD2 +beginMulticast KEYWORD2 +beginPacket KEYWORD2 +endPacket KEYWORD2 +parsePacket KEYWORD2 +remoteIP KEYWORD2 +remotePort KEYWORD2 +getSocketNumber KEYWORD2 +localIP KEYWORD2 +localPort KEYWORD2 +maintain KEYWORD2 +linkStatus KEYWORD2 +hardwareStatus KEYWORD2 +MACAddress KEYWORD2 +subnetMask KEYWORD2 +gatewayIP KEYWORD2 +dnsServerIP KEYWORD2 +setMACAddress KEYWORD2 +setLocalIP KEYWORD2 +setSubnetMask KEYWORD2 +setGatewayIP KEYWORD2 +setDnsServerIP KEYWORD2 +setRetransmissionTimeout KEYWORD2 +setRetransmissionCount KEYWORD2 +setConnectionTimeout KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +EthernetLinkStatus LITERAL1 +Unknown LITERAL1 +LinkON LITERAL1 +LinkOFF LITERAL1 +EthernetHardwareStatus LITERAL1 +EthernetNoHardware LITERAL1 +EthernetW5100 LITERAL1 +EthernetW5200 LITERAL1 +EthernetW5500 LITERAL1 diff --git a/libraries/Ethernet/library.properties b/libraries/Ethernet/library.properties new file mode 100644 index 0000000..de68a94 --- /dev/null +++ b/libraries/Ethernet/library.properties @@ -0,0 +1,10 @@ +name=Ethernet +version=2.0.0 +author=Various (see AUTHORS file for details) +maintainer=Paul Stoffregen , Arduino +sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield. +paragraph=With this library you can use the Arduino Ethernet (shield or board) to connect to Internet. The library provides both Client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS. +category=Communication +url=http://www.arduino.cc/en/Reference/Ethernet +architectures=* +includes=Ethernet.h diff --git a/libraries/Ethernet/src/Dhcp.cpp b/libraries/Ethernet/src/Dhcp.cpp new file mode 100644 index 0000000..2bfd584 --- /dev/null +++ b/libraries/Ethernet/src/Dhcp.cpp @@ -0,0 +1,433 @@ +// DHCP Library v0.3 - April 25, 2009 +// Author: Jordan Terrell - blog.jordanterrell.com + +#include +#include "Ethernet.h" +#include "Dhcp.h" +#include "utility/w5100.h" + +int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) +{ + _dhcpLeaseTime=0; + _dhcpT1=0; + _dhcpT2=0; + _timeout = timeout; + _responseTimeout = responseTimeout; + + // zero out _dhcpMacAddr + memset(_dhcpMacAddr, 0, 6); + reset_DHCP_lease(); + + memcpy((void*)_dhcpMacAddr, (void*)mac, 6); + _dhcp_state = STATE_DHCP_START; + return request_DHCP_lease(); +} + +void DhcpClass::reset_DHCP_lease() +{ + // zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp + memset(_dhcpLocalIp, 0, 20); +} + + //return:0 on error, 1 if request is sent and response is received +int DhcpClass::request_DHCP_lease() +{ + uint8_t messageType = 0; + + // Pick an initial transaction ID + _dhcpTransactionId = random(1UL, 2000UL); + _dhcpInitialTransactionId = _dhcpTransactionId; + + _dhcpUdpSocket.stop(); + if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0) { + // Couldn't get a socket + return 0; + } + + presend_DHCP(); + + int result = 0; + + unsigned long startTime = millis(); + + while (_dhcp_state != STATE_DHCP_LEASED) { + if (_dhcp_state == STATE_DHCP_START) { + _dhcpTransactionId++; + send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000)); + _dhcp_state = STATE_DHCP_DISCOVER; + } else if (_dhcp_state == STATE_DHCP_REREQUEST) { + _dhcpTransactionId++; + send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000)); + _dhcp_state = STATE_DHCP_REQUEST; + } else if (_dhcp_state == STATE_DHCP_DISCOVER) { + uint32_t respId; + messageType = parseDHCPResponse(_responseTimeout, respId); + if (messageType == DHCP_OFFER) { + // We'll use the transaction ID that the offer came with, + // rather than the one we were up to + _dhcpTransactionId = respId; + send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000)); + _dhcp_state = STATE_DHCP_REQUEST; + } + } else if (_dhcp_state == STATE_DHCP_REQUEST) { + uint32_t respId; + messageType = parseDHCPResponse(_responseTimeout, respId); + if (messageType == DHCP_ACK) { + _dhcp_state = STATE_DHCP_LEASED; + result = 1; + //use default lease time if we didn't get it + if (_dhcpLeaseTime == 0) { + _dhcpLeaseTime = DEFAULT_LEASE; + } + // Calculate T1 & T2 if we didn't get it + if (_dhcpT1 == 0) { + // T1 should be 50% of _dhcpLeaseTime + _dhcpT1 = _dhcpLeaseTime >> 1; + } + if (_dhcpT2 == 0) { + // T2 should be 87.5% (7/8ths) of _dhcpLeaseTime + _dhcpT2 = _dhcpLeaseTime - (_dhcpLeaseTime >> 3); + } + _renewInSec = _dhcpT1; + _rebindInSec = _dhcpT2; + } else if (messageType == DHCP_NAK) { + _dhcp_state = STATE_DHCP_START; + } + } + + if (messageType == 255) { + messageType = 0; + _dhcp_state = STATE_DHCP_START; + } + + if (result != 1 && ((millis() - startTime) > _timeout)) + break; + } + + // We're done with the socket now + _dhcpUdpSocket.stop(); + _dhcpTransactionId++; + + _lastCheckLeaseMillis = millis(); + return result; +} + +void DhcpClass::presend_DHCP() +{ +} + +void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed) +{ + uint8_t buffer[32]; + memset(buffer, 0, 32); + IPAddress dest_addr(255, 255, 255, 255); // Broadcast address + + if (_dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT) == -1) { + //Serial.printf("DHCP transmit error\n"); + // FIXME Need to return errors + return; + } + + buffer[0] = DHCP_BOOTREQUEST; // op + buffer[1] = DHCP_HTYPE10MB; // htype + buffer[2] = DHCP_HLENETHERNET; // hlen + buffer[3] = DHCP_HOPS; // hops + + // xid + unsigned long xid = htonl(_dhcpTransactionId); + memcpy(buffer + 4, &(xid), 4); + + // 8, 9 - seconds elapsed + buffer[8] = ((secondsElapsed & 0xff00) >> 8); + buffer[9] = (secondsElapsed & 0x00ff); + + // flags + unsigned short flags = htons(DHCP_FLAGSBROADCAST); + memcpy(buffer + 10, &(flags), 2); + + // ciaddr: already zeroed + // yiaddr: already zeroed + // siaddr: already zeroed + // giaddr: already zeroed + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 28); + + memset(buffer, 0, 32); // clear local buffer + + memcpy(buffer, _dhcpMacAddr, 6); // chaddr + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 16); + + memset(buffer, 0, 32); // clear local buffer + + // leave zeroed out for sname && file + // put in W5100 transmit buffer x 6 (192 bytes) + + for(int i = 0; i < 6; i++) { + _dhcpUdpSocket.write(buffer, 32); + } + + // OPT - Magic Cookie + buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF); + buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF); + buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF); + buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF); + + // OPT - message type + buffer[4] = dhcpMessageType; + buffer[5] = 0x01; + buffer[6] = messageType; //DHCP_REQUEST; + + // OPT - client identifier + buffer[7] = dhcpClientIdentifier; + buffer[8] = 0x07; + buffer[9] = 0x01; + memcpy(buffer + 10, _dhcpMacAddr, 6); + + // OPT - host name + buffer[16] = hostName; + buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address + strcpy((char*)&(buffer[18]), HOST_NAME); + + printByte((char*)&(buffer[24]), _dhcpMacAddr[3]); + printByte((char*)&(buffer[26]), _dhcpMacAddr[4]); + printByte((char*)&(buffer[28]), _dhcpMacAddr[5]); + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 30); + + if (messageType == DHCP_REQUEST) { + buffer[0] = dhcpRequestedIPaddr; + buffer[1] = 0x04; + buffer[2] = _dhcpLocalIp[0]; + buffer[3] = _dhcpLocalIp[1]; + buffer[4] = _dhcpLocalIp[2]; + buffer[5] = _dhcpLocalIp[3]; + + buffer[6] = dhcpServerIdentifier; + buffer[7] = 0x04; + buffer[8] = _dhcpDhcpServerIp[0]; + buffer[9] = _dhcpDhcpServerIp[1]; + buffer[10] = _dhcpDhcpServerIp[2]; + buffer[11] = _dhcpDhcpServerIp[3]; + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 12); + } + + buffer[0] = dhcpParamRequest; + buffer[1] = 0x06; + buffer[2] = subnetMask; + buffer[3] = routersOnSubnet; + buffer[4] = dns; + buffer[5] = domainName; + buffer[6] = dhcpT1value; + buffer[7] = dhcpT2value; + buffer[8] = endOption; + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 9); + + _dhcpUdpSocket.endPacket(); +} + +uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId) +{ + uint8_t type = 0; + uint8_t opt_len = 0; + + unsigned long startTime = millis(); + + while (_dhcpUdpSocket.parsePacket() <= 0) { + if ((millis() - startTime) > responseTimeout) { + return 255; + } + delay(50); + } + // start reading in the packet + RIP_MSG_FIXED fixedMsg; + _dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED)); + + if (fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT) { + transactionId = ntohl(fixedMsg.xid); + if (memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || + (transactionId < _dhcpInitialTransactionId) || + (transactionId > _dhcpTransactionId)) { + // Need to read the rest of the packet here regardless + _dhcpUdpSocket.flush(); // FIXME + return 0; + } + + memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4); + + // Skip to the option part + _dhcpUdpSocket.read((uint8_t *)NULL, 240 - (int)sizeof(RIP_MSG_FIXED)); + + while (_dhcpUdpSocket.available() > 0) { + switch (_dhcpUdpSocket.read()) { + case endOption : + break; + + case padOption : + break; + + case dhcpMessageType : + opt_len = _dhcpUdpSocket.read(); + type = _dhcpUdpSocket.read(); + break; + + case subnetMask : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read(_dhcpSubnetMask, 4); + break; + + case routersOnSubnet : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read(_dhcpGatewayIp, 4); + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); + break; + + case dns : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read(_dhcpDnsServerIp, 4); + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); + break; + + case dhcpServerIdentifier : + opt_len = _dhcpUdpSocket.read(); + if ( IPAddress(_dhcpDhcpServerIp) == IPAddress((uint32_t)0) || + IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) { + _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp)); + } else { + // Skip over the rest of this option + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); + } + break; + + case dhcpT1value : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1)); + _dhcpT1 = ntohl(_dhcpT1); + break; + + case dhcpT2value : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2)); + _dhcpT2 = ntohl(_dhcpT2); + break; + + case dhcpIPaddrLeaseTime : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime)); + _dhcpLeaseTime = ntohl(_dhcpLeaseTime); + _renewInSec = _dhcpLeaseTime; + break; + + default : + opt_len = _dhcpUdpSocket.read(); + // Skip over the rest of this option + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); + break; + } + } + } + + // Need to skip to end of the packet regardless here + _dhcpUdpSocket.flush(); // FIXME + + return type; +} + + +/* + returns: + 0/DHCP_CHECK_NONE: nothing happened + 1/DHCP_CHECK_RENEW_FAIL: renew failed + 2/DHCP_CHECK_RENEW_OK: renew success + 3/DHCP_CHECK_REBIND_FAIL: rebind fail + 4/DHCP_CHECK_REBIND_OK: rebind success +*/ +int DhcpClass::checkLease() +{ + int rc = DHCP_CHECK_NONE; + + unsigned long now = millis(); + unsigned long elapsed = now - _lastCheckLeaseMillis; + + // if more then one sec passed, reduce the counters accordingly + if (elapsed >= 1000) { + // set the new timestamps + _lastCheckLeaseMillis = now - (elapsed % 1000); + elapsed = elapsed / 1000; + + // decrease the counters by elapsed seconds + // we assume that the cycle time (elapsed) is fairly constant + // if the remainder is less than cycle time * 2 + // do it early instead of late + if (_renewInSec < elapsed * 2) { + _renewInSec = 0; + } else { + _renewInSec -= elapsed; + } + if (_rebindInSec < elapsed * 2) { + _rebindInSec = 0; + } else { + _rebindInSec -= elapsed; + } + } + + // if we have a lease but should renew, do it + if (_renewInSec == 0 &&_dhcp_state == STATE_DHCP_LEASED) { + _dhcp_state = STATE_DHCP_REREQUEST; + rc = 1 + request_DHCP_lease(); + } + + // if we have a lease or is renewing but should bind, do it + if (_rebindInSec == 0 && (_dhcp_state == STATE_DHCP_LEASED || + _dhcp_state == STATE_DHCP_START)) { + // this should basically restart completely + _dhcp_state = STATE_DHCP_START; + reset_DHCP_lease(); + rc = 3 + request_DHCP_lease(); + } + return rc; +} + +IPAddress DhcpClass::getLocalIp() +{ + return IPAddress(_dhcpLocalIp); +} + +IPAddress DhcpClass::getSubnetMask() +{ + return IPAddress(_dhcpSubnetMask); +} + +IPAddress DhcpClass::getGatewayIp() +{ + return IPAddress(_dhcpGatewayIp); +} + +IPAddress DhcpClass::getDhcpServerIp() +{ + return IPAddress(_dhcpDhcpServerIp); +} + +IPAddress DhcpClass::getDnsServerIp() +{ + return IPAddress(_dhcpDnsServerIp); +} + +void DhcpClass::printByte(char * buf, uint8_t n ) +{ + char *str = &buf[1]; + buf[0]='0'; + do { + unsigned long m = n; + n /= 16; + char c = m - 16 * n; + *str-- = c < 10 ? c + '0' : c + 'A' - 10; + } while(n); +} diff --git a/libraries/Ethernet/src/Dhcp.h b/libraries/Ethernet/src/Dhcp.h new file mode 100644 index 0000000..43ec4f8 --- /dev/null +++ b/libraries/Ethernet/src/Dhcp.h @@ -0,0 +1,137 @@ +// DHCP Library v0.3 - April 25, 2009 +// Author: Jordan Terrell - blog.jordanterrell.com + +#ifndef Dhcp_h +#define Dhcp_h + +/* DHCP state machine. */ +#define STATE_DHCP_START 0 +#define STATE_DHCP_DISCOVER 1 +#define STATE_DHCP_REQUEST 2 +#define STATE_DHCP_LEASED 3 +#define STATE_DHCP_REREQUEST 4 +#define STATE_DHCP_RELEASE 5 + +#define DHCP_FLAGSBROADCAST 0x8000 + +/* UDP port numbers for DHCP */ +#define DHCP_SERVER_PORT 67 /* from server to client */ +#define DHCP_CLIENT_PORT 68 /* from client to server */ + +/* DHCP message OP code */ +#define DHCP_BOOTREQUEST 1 +#define DHCP_BOOTREPLY 2 + +/* DHCP message type */ +#define DHCP_DISCOVER 1 +#define DHCP_OFFER 2 +#define DHCP_REQUEST 3 +#define DHCP_DECLINE 4 +#define DHCP_ACK 5 +#define DHCP_NAK 6 +#define DHCP_RELEASE 7 +#define DHCP_INFORM 8 + +#define DHCP_HTYPE10MB 1 +#define DHCP_HTYPE100MB 2 + +#define DHCP_HLENETHERNET 6 +#define DHCP_HOPS 0 +#define DHCP_SECS 0 + +#define MAGIC_COOKIE 0x63825363 +#define MAX_DHCP_OPT 16 + +#define HOST_NAME "WIZnet" +#define DEFAULT_LEASE (900) //default lease time in seconds + +#define DHCP_CHECK_NONE (0) +#define DHCP_CHECK_RENEW_FAIL (1) +#define DHCP_CHECK_RENEW_OK (2) +#define DHCP_CHECK_REBIND_FAIL (3) +#define DHCP_CHECK_REBIND_OK (4) + +enum +{ + padOption = 0, + subnetMask = 1, + timerOffset = 2, + routersOnSubnet = 3, + /* timeServer = 4, + nameServer = 5,*/ + dns = 6, + /*logServer = 7, + cookieServer = 8, + lprServer = 9, + impressServer = 10, + resourceLocationServer = 11,*/ + hostName = 12, + /*bootFileSize = 13, + meritDumpFile = 14,*/ + domainName = 15, + /*swapServer = 16, + rootPath = 17, + extentionsPath = 18, + IPforwarding = 19, + nonLocalSourceRouting = 20, + policyFilter = 21, + maxDgramReasmSize = 22, + defaultIPTTL = 23, + pathMTUagingTimeout = 24, + pathMTUplateauTable = 25, + ifMTU = 26, + allSubnetsLocal = 27, + broadcastAddr = 28, + performMaskDiscovery = 29, + maskSupplier = 30, + performRouterDiscovery = 31, + routerSolicitationAddr = 32, + staticRoute = 33, + trailerEncapsulation = 34, + arpCacheTimeout = 35, + ethernetEncapsulation = 36, + tcpDefaultTTL = 37, + tcpKeepaliveInterval = 38, + tcpKeepaliveGarbage = 39, + nisDomainName = 40, + nisServers = 41, + ntpServers = 42, + vendorSpecificInfo = 43, + netBIOSnameServer = 44, + netBIOSdgramDistServer = 45, + netBIOSnodeType = 46, + netBIOSscope = 47, + xFontServer = 48, + xDisplayManager = 49,*/ + dhcpRequestedIPaddr = 50, + dhcpIPaddrLeaseTime = 51, + /*dhcpOptionOverload = 52,*/ + dhcpMessageType = 53, + dhcpServerIdentifier = 54, + dhcpParamRequest = 55, + /*dhcpMsg = 56, + dhcpMaxMsgSize = 57,*/ + dhcpT1value = 58, + dhcpT2value = 59, + /*dhcpClassIdentifier = 60,*/ + dhcpClientIdentifier = 61, + endOption = 255 +}; + +typedef struct _RIP_MSG_FIXED +{ + uint8_t op; + uint8_t htype; + uint8_t hlen; + uint8_t hops; + uint32_t xid; + uint16_t secs; + uint16_t flags; + uint8_t ciaddr[4]; + uint8_t yiaddr[4]; + uint8_t siaddr[4]; + uint8_t giaddr[4]; + uint8_t chaddr[6]; +} RIP_MSG_FIXED; + +#endif diff --git a/libraries/Ethernet/src/Dns.cpp b/libraries/Ethernet/src/Dns.cpp new file mode 100644 index 0000000..dfa9112 --- /dev/null +++ b/libraries/Ethernet/src/Dns.cpp @@ -0,0 +1,354 @@ +// Arduino DNS client for WizNet5100-based Ethernet shield +// (c) Copyright 2009-2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#include +#include "Ethernet.h" +#include "Dns.h" +#include "utility/w5100.h" + + +#define SOCKET_NONE 255 +// Various flags and header field values for a DNS message +#define UDP_HEADER_SIZE 8 +#define DNS_HEADER_SIZE 12 +#define TTL_SIZE 4 +#define QUERY_FLAG (0) +#define RESPONSE_FLAG (1<<15) +#define QUERY_RESPONSE_MASK (1<<15) +#define OPCODE_STANDARD_QUERY (0) +#define OPCODE_INVERSE_QUERY (1<<11) +#define OPCODE_STATUS_REQUEST (2<<11) +#define OPCODE_MASK (15<<11) +#define AUTHORITATIVE_FLAG (1<<10) +#define TRUNCATION_FLAG (1<<9) +#define RECURSION_DESIRED_FLAG (1<<8) +#define RECURSION_AVAILABLE_FLAG (1<<7) +#define RESP_NO_ERROR (0) +#define RESP_FORMAT_ERROR (1) +#define RESP_SERVER_FAILURE (2) +#define RESP_NAME_ERROR (3) +#define RESP_NOT_IMPLEMENTED (4) +#define RESP_REFUSED (5) +#define RESP_MASK (15) +#define TYPE_A (0x0001) +#define CLASS_IN (0x0001) +#define LABEL_COMPRESSION_MASK (0xC0) +// Port number that DNS servers listen on +#define DNS_PORT 53 + +// Possible return codes from ProcessResponse +#define SUCCESS 1 +#define TIMED_OUT -1 +#define INVALID_SERVER -2 +#define TRUNCATED -3 +#define INVALID_RESPONSE -4 + +void DNSClient::begin(const IPAddress& aDNSServer) +{ + iDNSServer = aDNSServer; + iRequestId = 0; +} + + +int DNSClient::inet_aton(const char* address, IPAddress& result) +{ + uint16_t acc = 0; // Accumulator + uint8_t dots = 0; + + while (*address) { + char c = *address++; + if (c >= '0' && c <= '9') { + acc = acc * 10 + (c - '0'); + if (acc > 255) { + // Value out of [0..255] range + return 0; + } + } else if (c == '.') { + if (dots == 3) { + // Too much dots (there must be 3 dots) + return 0; + } + result[dots++] = acc; + acc = 0; + } else { + // Invalid char + return 0; + } + } + + if (dots != 3) { + // Too few dots (there must be 3 dots) + return 0; + } + result[3] = acc; + return 1; +} + +int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout) +{ + int ret = 0; + + // See if it's a numeric IP address + if (inet_aton(aHostname, aResult)) { + // It is, our work here is done + return 1; + } + + // Check we've got a valid DNS server to use + if (iDNSServer == INADDR_NONE) { + return INVALID_SERVER; + } + + // Find a socket to use + if (iUdp.begin(1024+(millis() & 0xF)) == 1) { + // Try up to three times + int retries = 0; + // while ((retries < 3) && (ret <= 0)) { + // Send DNS request + ret = iUdp.beginPacket(iDNSServer, DNS_PORT); + if (ret != 0) { + // Now output the request data + ret = BuildRequest(aHostname); + if (ret != 0) { + // And finally send the request + ret = iUdp.endPacket(); + if (ret != 0) { + // Now wait for a response + int wait_retries = 0; + ret = TIMED_OUT; + while ((wait_retries < 3) && (ret == TIMED_OUT)) { + ret = ProcessResponse(timeout, aResult); + wait_retries++; + } + } + } + } + retries++; + //} + + // We're done with the socket now + iUdp.stop(); + } + + return ret; +} + +uint16_t DNSClient::BuildRequest(const char* aName) +{ + // Build header + // 1 1 1 1 1 1 + // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | ID | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // |QR| Opcode |AA|TC|RD|RA| Z | RCODE | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | QDCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | ANCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | NSCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | ARCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // As we only support one request at a time at present, we can simplify + // some of this header + iRequestId = millis(); // generate a random ID + uint16_t twoByteBuffer; + + // FIXME We should also check that there's enough space available to write to, rather + // FIXME than assume there's enough space (as the code does at present) + iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId)); + + twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG); + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + twoByteBuffer = htons(1); // One question record + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + twoByteBuffer = 0; // Zero answer records + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + // and zero additional records + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + // Build question + const char* start =aName; + const char* end =start; + uint8_t len; + // Run through the name being requested + while (*end) { + // Find out how long this section of the name is + end = start; + while (*end && (*end != '.') ) { + end++; + } + + if (end-start > 0) { + // Write out the size of this section + len = end-start; + iUdp.write(&len, sizeof(len)); + // And then write out the section + iUdp.write((uint8_t*)start, end-start); + } + start = end+1; + } + + // We've got to the end of the question name, so + // terminate it with a zero-length section + len = 0; + iUdp.write(&len, sizeof(len)); + // Finally the type and class of question + twoByteBuffer = htons(TYPE_A); + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + twoByteBuffer = htons(CLASS_IN); // Internet class of question + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + // Success! Everything buffered okay + return 1; +} + + +uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) +{ + uint32_t startTime = millis(); + + // Wait for a response packet + while (iUdp.parsePacket() <= 0) { + if ((millis() - startTime) > aTimeout) { + return TIMED_OUT; + } + delay(50); + } + + // We've had a reply! + // Read the UDP header + //uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header + union { + uint8_t byte[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header + uint16_t word[DNS_HEADER_SIZE/2]; + } header; + + // Check that it's a response from the right server and the right port + if ( (iDNSServer != iUdp.remoteIP()) || (iUdp.remotePort() != DNS_PORT) ) { + // It's not from who we expected + return INVALID_SERVER; + } + + // Read through the rest of the response + if (iUdp.available() < DNS_HEADER_SIZE) { + return TRUNCATED; + } + iUdp.read(header.byte, DNS_HEADER_SIZE); + + uint16_t header_flags = htons(header.word[1]); + // Check that it's a response to this request + if ((iRequestId != (header.word[0])) || + ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) { + // Mark the entire packet as read + iUdp.flush(); // FIXME + return INVALID_RESPONSE; + } + // Check for any errors in the response (or in our request) + // although we don't do anything to get round these + if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) ) { + // Mark the entire packet as read + iUdp.flush(); // FIXME + return -5; //INVALID_RESPONSE; + } + + // And make sure we've got (at least) one answer + uint16_t answerCount = htons(header.word[3]); + if (answerCount == 0) { + // Mark the entire packet as read + iUdp.flush(); // FIXME + return -6; //INVALID_RESPONSE; + } + + // Skip over any questions + for (uint16_t i=0; i < htons(header.word[2]); i++) { + // Skip over the name + uint8_t len; + do { + iUdp.read(&len, sizeof(len)); + if (len > 0) { + // Don't need to actually read the data out for the string, just + // advance ptr to beyond it + iUdp.read((uint8_t *)NULL, (size_t)len); + } + } while (len != 0); + + // Now jump over the type and class + iUdp.read((uint8_t *)NULL, 4); + } + + // Now we're up to the bit we're interested in, the answer + // There might be more than one answer (although we'll just use the first + // type A answer) and some authority and additional resource records but + // we're going to ignore all of them. + + for (uint16_t i=0; i < answerCount; i++) { + // Skip the name + uint8_t len; + do { + iUdp.read(&len, sizeof(len)); + if ((len & LABEL_COMPRESSION_MASK) == 0) { + // It's just a normal label + if (len > 0) { + // And it's got a length + // Don't need to actually read the data out for the string, + // just advance ptr to beyond it + iUdp.read((uint8_t *)NULL, len); + } + } else { + // This is a pointer to a somewhere else in the message for the + // rest of the name. We don't care about the name, and RFC1035 + // says that a name is either a sequence of labels ended with a + // 0 length octet or a pointer or a sequence of labels ending in + // a pointer. Either way, when we get here we're at the end of + // the name + // Skip over the pointer + iUdp.read((uint8_t *)NULL, 1); // we don't care about the byte + // And set len so that we drop out of the name loop + len = 0; + } + } while (len != 0); + + // Check the type and class + uint16_t answerType; + uint16_t answerClass; + iUdp.read((uint8_t*)&answerType, sizeof(answerType)); + iUdp.read((uint8_t*)&answerClass, sizeof(answerClass)); + + // Ignore the Time-To-Live as we don't do any caching + iUdp.read((uint8_t *)NULL, TTL_SIZE); // don't care about the returned bytes + + // And read out the length of this answer + // Don't need header_flags anymore, so we can reuse it here + iUdp.read((uint8_t*)&header_flags, sizeof(header_flags)); + + if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) ) { + if (htons(header_flags) != 4) { + // It's a weird size + // Mark the entire packet as read + iUdp.flush(); // FIXME + return -9;//INVALID_RESPONSE; + } + // FIXME: seeems to lock up here on ESP8266, but why?? + iUdp.read(aAddress.raw_address(), 4); + return SUCCESS; + } else { + // This isn't an answer type we're after, move onto the next one + iUdp.read((uint8_t *)NULL, htons(header_flags)); + } + } + + // Mark the entire packet as read + iUdp.flush(); // FIXME + + // If we get here then we haven't found an answer + return -10; //INVALID_RESPONSE; +} + diff --git a/libraries/Ethernet/src/Dns.h b/libraries/Ethernet/src/Dns.h new file mode 100644 index 0000000..5f5b30f --- /dev/null +++ b/libraries/Ethernet/src/Dns.h @@ -0,0 +1,40 @@ +// Arduino DNS client for WizNet5100-based Ethernet shield +// (c) Copyright 2009-2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#ifndef DNSClient_h +#define DNSClient_h + +#include "Ethernet.h" + +class DNSClient +{ +public: + void begin(const IPAddress& aDNSServer); + + /** Convert a numeric IP address string into a four-byte IP address. + @param aIPAddrString IP address to convert + @param aResult IPAddress structure to store the returned IP address + @result 1 if aIPAddrString was successfully converted to an IP address, + else error code + */ + int inet_aton(const char *aIPAddrString, IPAddress& aResult); + + /** Resolve the given hostname to an IP address. + @param aHostname Name to be resolved + @param aResult IPAddress structure to store the returned IP address + @result 1 if aIPAddrString was successfully converted to an IP address, + else error code + */ + int getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout=5000); + +protected: + uint16_t BuildRequest(const char* aName); + uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress); + + IPAddress iDNSServer; + uint16_t iRequestId; + EthernetUDP iUdp; +}; + +#endif diff --git a/libraries/Ethernet/src/Ethernet.cpp b/libraries/Ethernet/src/Ethernet.cpp new file mode 100644 index 0000000..658bd64 --- /dev/null +++ b/libraries/Ethernet/src/Ethernet.cpp @@ -0,0 +1,242 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "utility/w5100.h" +#include "Dhcp.h" + +IPAddress EthernetClass::_dnsServerAddress; +DhcpClass* EthernetClass::_dhcp = NULL; + +int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) +{ + static DhcpClass s_dhcp; + _dhcp = &s_dhcp; + + // Initialise the basic info + if (W5100.init() == 0) return 0; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setMACAddress(mac); + W5100.setIPAddress(IPAddress(0,0,0,0).raw_address()); + SPI.endTransaction(); + + // Now try to get our config info from a DHCP server + int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout); + if (ret == 1) { + // We've successfully found a DHCP server and got our configuration + // info, so set things accordingly + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); + W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); + W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); + SPI.endTransaction(); + _dnsServerAddress = _dhcp->getDnsServerIp(); + socketPortRand(micros()); + } + return ret; +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip) +{ + // Assume the DNS server will be the machine on the same network as the local IP + // but with last octet being '1' + IPAddress dns = ip; + dns[3] = 1; + begin(mac, ip, dns); +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns) +{ + // Assume the gateway will be the machine on the same network as the local IP + // but with last octet being '1' + IPAddress gateway = ip; + gateway[3] = 1; + begin(mac, ip, dns, gateway); +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway) +{ + IPAddress subnet(255, 255, 255, 0); + begin(mac, ip, dns, gateway, subnet); +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet) +{ + if (W5100.init() == 0) return; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setMACAddress(mac); +#if ARDUINO > 106 || TEENSYDUINO > 121 + W5100.setIPAddress(ip._address.bytes); + W5100.setGatewayIp(gateway._address.bytes); + W5100.setSubnetMask(subnet._address.bytes); +#else + W5100.setIPAddress(ip._address); + W5100.setGatewayIp(gateway._address); + W5100.setSubnetMask(subnet._address); +#endif + SPI.endTransaction(); + _dnsServerAddress = dns; +} + +void EthernetClass::init(uint8_t sspin) +{ + W5100.setSS(sspin); +} + +EthernetLinkStatus EthernetClass::linkStatus() +{ + switch (W5100.getLinkStatus()) { + case UNKNOWN: return Unknown; + case LINK_ON: return LinkON; + case LINK_OFF: return LinkOFF; + default: return Unknown; + } +} + +EthernetHardwareStatus EthernetClass::hardwareStatus() +{ + switch (W5100.getChip()) { + case 51: return EthernetW5100; + case 52: return EthernetW5200; + case 55: return EthernetW5500; + default: return EthernetNoHardware; + } +} + +int EthernetClass::maintain() +{ + int rc = DHCP_CHECK_NONE; + if (_dhcp != NULL) { + // we have a pointer to dhcp, use it + rc = _dhcp->checkLease(); + switch (rc) { + case DHCP_CHECK_NONE: + //nothing done + break; + case DHCP_CHECK_RENEW_OK: + case DHCP_CHECK_REBIND_OK: + //we might have got a new IP. + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); + W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); + W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); + SPI.endTransaction(); + _dnsServerAddress = _dhcp->getDnsServerIp(); + break; + default: + //this is actually an error, it will retry though + break; + } + } + return rc; +} + + +void EthernetClass::MACAddress(uint8_t *mac_address) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getMACAddress(mac_address); + SPI.endTransaction(); +} + +IPAddress EthernetClass::localIP() +{ + IPAddress ret; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getIPAddress(ret.raw_address()); + SPI.endTransaction(); + return ret; +} + +IPAddress EthernetClass::subnetMask() +{ + IPAddress ret; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getSubnetMask(ret.raw_address()); + SPI.endTransaction(); + return ret; +} + +IPAddress EthernetClass::gatewayIP() +{ + IPAddress ret; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getGatewayIp(ret.raw_address()); + SPI.endTransaction(); + return ret; +} + +void EthernetClass::setMACAddress(const uint8_t *mac_address) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setMACAddress(mac_address); + SPI.endTransaction(); +} + +void EthernetClass::setLocalIP(const IPAddress local_ip) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + IPAddress ip = local_ip; + W5100.setIPAddress(ip.raw_address()); + SPI.endTransaction(); +} + +void EthernetClass::setSubnetMask(const IPAddress subnet) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + IPAddress ip = subnet; + W5100.setSubnetMask(ip.raw_address()); + SPI.endTransaction(); +} + +void EthernetClass::setGatewayIP(const IPAddress gateway) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + IPAddress ip = gateway; + W5100.setGatewayIp(ip.raw_address()); + SPI.endTransaction(); +} + +void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds) +{ + if (milliseconds > 6553) milliseconds = 6553; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setRetransmissionTime(milliseconds * 10); + SPI.endTransaction(); +} + +void EthernetClass::setRetransmissionCount(uint8_t num) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setRetransmissionCount(num); + SPI.endTransaction(); +} + + + + + + + + + + +EthernetClass Ethernet; diff --git a/libraries/Ethernet/src/Ethernet.h b/libraries/Ethernet/src/Ethernet.h new file mode 100644 index 0000000..376e6c5 --- /dev/null +++ b/libraries/Ethernet/src/Ethernet.h @@ -0,0 +1,322 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ethernet_h_ +#define ethernet_h_ + +// All symbols exposed to Arduino sketches are contained in this header file +// +// Older versions had much of this stuff in EthernetClient.h, EthernetServer.h, +// and socket.h. Including headers in different order could cause trouble, so +// these "friend" classes are now defined in the same header file. socket.h +// was removed to avoid possible conflict with the C library header files. + + +// Configure the maximum number of sockets to support. W5100 chips can have +// up to 4 sockets. W5200 & W5500 can have up to 8 sockets. Several bytes +// of RAM are used for each socket. Reducing the maximum can save RAM, but +// you are limited to fewer simultaneous connections. +#if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048) +#define MAX_SOCK_NUM 4 +#else +#define MAX_SOCK_NUM 8 +#endif + +// By default, each socket uses 2K buffers inside the Wiznet chip. If +// MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting +// this will use larger buffers within the Wiznet chip. Large buffers +// can really help with UDP protocols like Artnet. In theory larger +// buffers should allow faster TCP over high-latency links, but this +// does not always seem to work in practice (maybe Wiznet bugs?) +//#define ETHERNET_LARGE_BUFFERS + + +#include +#include "Client.h" +#include "Server.h" +#include "Udp.h" + +enum EthernetLinkStatus { + Unknown, + LinkON, + LinkOFF +}; + +enum EthernetHardwareStatus { + EthernetNoHardware, + EthernetW5100, + EthernetW5200, + EthernetW5500 +}; + +class EthernetUDP; +class EthernetClient; +class EthernetServer; +class DhcpClass; + +class EthernetClass { +private: + static IPAddress _dnsServerAddress; + static DhcpClass* _dhcp; +public: + // Initialise the Ethernet shield to use the provided MAC address and + // gain the rest of the configuration through DHCP. + // Returns 0 if the DHCP configuration failed, and 1 if it succeeded + static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); + static int maintain(); + static EthernetLinkStatus linkStatus(); + static EthernetHardwareStatus hardwareStatus(); + + // Manaul configuration + static void begin(uint8_t *mac, IPAddress ip); + static void begin(uint8_t *mac, IPAddress ip, IPAddress dns); + static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway); + static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet); + static void init(uint8_t sspin = 10); + + static void MACAddress(uint8_t *mac_address); + static IPAddress localIP(); + static IPAddress subnetMask(); + static IPAddress gatewayIP(); + static IPAddress dnsServerIP() { return _dnsServerAddress; } + + void setMACAddress(const uint8_t *mac_address); + void setLocalIP(const IPAddress local_ip); + void setSubnetMask(const IPAddress subnet); + void setGatewayIP(const IPAddress gateway); + void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; } + void setRetransmissionTimeout(uint16_t milliseconds); + void setRetransmissionCount(uint8_t num); + + friend class EthernetClient; + friend class EthernetServer; + friend class EthernetUDP; +private: + // Opens a socket(TCP or UDP or IP_RAW mode) + static uint8_t socketBegin(uint8_t protocol, uint16_t port); + static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port); + static uint8_t socketStatus(uint8_t s); + // Close socket + static void socketClose(uint8_t s); + // Establish TCP connection (Active connection) + static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port); + // disconnect the connection + static void socketDisconnect(uint8_t s); + // Establish TCP connection (Passive connection) + static uint8_t socketListen(uint8_t s); + // Send data (TCP) + static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len); + static uint16_t socketSendAvailable(uint8_t s); + // Receive data (TCP) + static int socketRecv(uint8_t s, uint8_t * buf, int16_t len); + static uint16_t socketRecvAvailable(uint8_t s); + static uint8_t socketPeek(uint8_t s); + // sets up a UDP datagram, the data for which will be provided by one + // or more calls to bufferData and then finally sent with sendUDP. + // return true if the datagram was successfully set up, or false if there was an error + static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port); + // copy up to len bytes of data from buf into a UDP datagram to be + // sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls. + // return Number of bytes successfully buffered + static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len); + // Send a UDP datagram built up from a sequence of startUDP followed by one or more + // calls to bufferData. + // return true if the datagram was successfully sent, or false if there was an error + static bool socketSendUDP(uint8_t s); + // Initialize the "random" source port number + static void socketPortRand(uint16_t n); +}; + +extern EthernetClass Ethernet; + + +#define UDP_TX_PACKET_MAX_SIZE 24 + +class EthernetUDP : public UDP { +private: + uint16_t _port; // local port to listen on + IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed + uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed + uint16_t _offset; // offset into the packet being sent + +protected: + uint8_t sockindex; + uint16_t _remaining; // remaining bytes of incoming packet yet to be processed + +public: + EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // Constructor + virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use + virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use + virtual void stop(); // Finish with the UDP socket + + // Sending UDP packets + + // Start building up a packet to send to the remote host specific in ip and port + // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port + virtual int beginPacket(IPAddress ip, uint16_t port); + // Start building up a packet to send to the remote host specific in host and port + // Returns 1 if successful, 0 if there was a problem resolving the hostname or port + virtual int beginPacket(const char *host, uint16_t port); + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket(); + // Write a single byte into the packet + virtual size_t write(uint8_t); + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + // Start processing the next available incoming packet + // Returns the size of the packet in bytes, or 0 if no packets are available + virtual int parsePacket(); + // Number of bytes remaining in the current packet + virtual int available(); + // Read a single byte from the current packet + virtual int read(); + // Read up to len bytes from the current packet and place them into buffer + // Returns the number of bytes read, or 0 if none are available + virtual int read(unsigned char* buffer, size_t len); + // Read up to len characters from the current packet and place them into buffer + // Returns the number of characters read, or 0 if none are available + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + // Return the next byte from the current packet without moving on to the next byte + virtual int peek(); + virtual void flush(); // Finish reading the current packet + + // Return the IP address of the host who sent the current incoming packet + virtual IPAddress remoteIP() { return _remoteIP; }; + // Return the port of the host who sent the current incoming packet + virtual uint16_t remotePort() { return _remotePort; }; + virtual uint16_t localPort() { return _port; } +}; + + + + +class EthernetClient : public Client { +public: + EthernetClient() : sockindex(MAX_SOCK_NUM), _timeout(1000) { } + EthernetClient(uint8_t s) : sockindex(s), _timeout(1000) { } + + uint8_t status(); + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char *host, uint16_t port); + virtual int availableForWrite(void); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + virtual void flush(); + virtual void stop(); + virtual uint8_t connected(); + virtual operator bool() { return sockindex < MAX_SOCK_NUM; } + virtual bool operator==(const bool value) { return bool() == value; } + virtual bool operator!=(const bool value) { return bool() != value; } + virtual bool operator==(const EthernetClient&); + virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); } + uint8_t getSocketNumber() const { return sockindex; } + virtual uint16_t localPort(); + virtual IPAddress remoteIP(); + virtual uint16_t remotePort(); + virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; } + + friend class EthernetServer; + + using Print::write; + +private: + uint8_t sockindex; // MAX_SOCK_NUM means client not in use + uint16_t _timeout; +}; + + +class EthernetServer : public Server { +private: + uint16_t _port; +public: + EthernetServer(uint16_t port) : _port(port) { } + EthernetClient available(); + EthernetClient accept(); + virtual void begin(); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual operator bool(); + using Print::write; + //void statusreport(); + + // TODO: make private when socket allocation moves to EthernetClass + static uint16_t server_port[MAX_SOCK_NUM]; +}; + + +class DhcpClass { +private: + uint32_t _dhcpInitialTransactionId; + uint32_t _dhcpTransactionId; + uint8_t _dhcpMacAddr[6]; +#ifdef __arm__ + uint8_t _dhcpLocalIp[4] __attribute__((aligned(4))); + uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4))); + uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4))); + uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4))); + uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4))); +#else + uint8_t _dhcpLocalIp[4]; + uint8_t _dhcpSubnetMask[4]; + uint8_t _dhcpGatewayIp[4]; + uint8_t _dhcpDhcpServerIp[4]; + uint8_t _dhcpDnsServerIp[4]; +#endif + uint32_t _dhcpLeaseTime; + uint32_t _dhcpT1, _dhcpT2; + uint32_t _renewInSec; + uint32_t _rebindInSec; + unsigned long _timeout; + unsigned long _responseTimeout; + unsigned long _lastCheckLeaseMillis; + uint8_t _dhcp_state; + EthernetUDP _dhcpUdpSocket; + + int request_DHCP_lease(); + void reset_DHCP_lease(); + void presend_DHCP(); + void send_DHCP_MESSAGE(uint8_t, uint16_t); + void printByte(char *, uint8_t); + + uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId); +public: + IPAddress getLocalIp(); + IPAddress getSubnetMask(); + IPAddress getGatewayIp(); + IPAddress getDhcpServerIp(); + IPAddress getDnsServerIp(); + + int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); + int checkLease(); +}; + + + + + +#endif diff --git a/libraries/Ethernet/src/EthernetClient.cpp b/libraries/Ethernet/src/EthernetClient.cpp new file mode 100644 index 0000000..e2406d7 --- /dev/null +++ b/libraries/Ethernet/src/EthernetClient.cpp @@ -0,0 +1,215 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "Dns.h" +#include "utility/w5100.h" + +int EthernetClient::connect(const char * host, uint16_t port) +{ + DNSClient dns; // Look up the host first + IPAddress remote_addr; + + if (sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { + Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? + } + sockindex = MAX_SOCK_NUM; + } + dns.begin(Ethernet.dnsServerIP()); + if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout + return connect(remote_addr, port); +} + +int EthernetClient::connect(IPAddress ip, uint16_t port) +{ + if (sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { + Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? + } + sockindex = MAX_SOCK_NUM; + } +#if defined(ESP8266) || defined(ESP32) + if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0; +#else + if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0; +#endif + sockindex = Ethernet.socketBegin(SnMR::TCP, 0); + if (sockindex >= MAX_SOCK_NUM) return 0; + Ethernet.socketConnect(sockindex, rawIPAddress(ip), port); + uint32_t start = millis(); + while (1) { + uint8_t stat = Ethernet.socketStatus(sockindex); + if (stat == SnSR::ESTABLISHED) return 1; + if (stat == SnSR::CLOSE_WAIT) return 1; + if (stat == SnSR::CLOSED) return 0; + if (millis() - start > _timeout) break; + delay(1); + } + Ethernet.socketClose(sockindex); + sockindex = MAX_SOCK_NUM; + return 0; +} + +int EthernetClient::availableForWrite(void) +{ + if (sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketSendAvailable(sockindex); +} + +size_t EthernetClient::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t EthernetClient::write(const uint8_t *buf, size_t size) +{ + if (sockindex >= MAX_SOCK_NUM) return 0; + if (Ethernet.socketSend(sockindex, buf, size)) return size; + setWriteError(); + return 0; +} + +int EthernetClient::available() +{ + if (sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketRecvAvailable(sockindex); + // TODO: do the Wiznet chips automatically retransmit TCP ACK + // packets if they are lost by the network? Someday this should + // be checked by a man-in-the-middle test which discards certain + // packets. If ACKs aren't resent, we would need to check for + // returning 0 here and after a timeout do another Sock_RECV + // command to cause the Wiznet chip to resend the ACK packet. +} + +int EthernetClient::read(uint8_t *buf, size_t size) +{ + if (sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketRecv(sockindex, buf, size); +} + +int EthernetClient::peek() +{ + if (sockindex >= MAX_SOCK_NUM) return -1; + if (!available()) return -1; + return Ethernet.socketPeek(sockindex); +} + +int EthernetClient::read() +{ + uint8_t b; + if (Ethernet.socketRecv(sockindex, &b, 1) > 0) return b; + return -1; +} + +void EthernetClient::flush() +{ + while (sockindex < MAX_SOCK_NUM) { + uint8_t stat = Ethernet.socketStatus(sockindex); + if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return; + if (Ethernet.socketSendAvailable(sockindex) >= W5100.SSIZE) return; + } +} + +void EthernetClient::stop() +{ + if (sockindex >= MAX_SOCK_NUM) return; + + // attempt to close the connection gracefully (send a FIN to other side) + Ethernet.socketDisconnect(sockindex); + unsigned long start = millis(); + + // wait up to a second for the connection to close + do { + if (Ethernet.socketStatus(sockindex) == SnSR::CLOSED) { + sockindex = MAX_SOCK_NUM; + return; // exit the loop + } + delay(1); + } while (millis() - start < _timeout); + + // if it hasn't closed, close it forcefully + Ethernet.socketClose(sockindex); + sockindex = MAX_SOCK_NUM; +} + +uint8_t EthernetClient::connected() +{ + if (sockindex >= MAX_SOCK_NUM) return 0; + + uint8_t s = Ethernet.socketStatus(sockindex); + return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT || + (s == SnSR::CLOSE_WAIT && !available())); +} + +uint8_t EthernetClient::status() +{ + if (sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED; + return Ethernet.socketStatus(sockindex); +} + +// the next function allows us to use the client returned by +// EthernetServer::available() as the condition in an if-statement. +bool EthernetClient::operator==(const EthernetClient& rhs) +{ + if (sockindex != rhs.sockindex) return false; + if (sockindex >= MAX_SOCK_NUM) return false; + if (rhs.sockindex >= MAX_SOCK_NUM) return false; + return true; +} + +// https://github.com/per1234/EthernetMod +// from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd +uint16_t EthernetClient::localPort() +{ + if (sockindex >= MAX_SOCK_NUM) return 0; + uint16_t port; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + port = W5100.readSnPORT(sockindex); + SPI.endTransaction(); + return port; +} + +// https://github.com/per1234/EthernetMod +// returns the remote IP address: http://forum.arduino.cc/index.php?topic=82416.0 +IPAddress EthernetClient::remoteIP() +{ + if (sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0); + uint8_t remoteIParray[4]; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.readSnDIPR(sockindex, remoteIParray); + SPI.endTransaction(); + return IPAddress(remoteIParray); +} + +// https://github.com/per1234/EthernetMod +// from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75 +uint16_t EthernetClient::remotePort() +{ + if (sockindex >= MAX_SOCK_NUM) return 0; + uint16_t port; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + port = W5100.readSnDPORT(sockindex); + SPI.endTransaction(); + return port; +} + + diff --git a/libraries/Ethernet/src/EthernetClient.h b/libraries/Ethernet/src/EthernetClient.h new file mode 100644 index 0000000..b5aef96 --- /dev/null +++ b/libraries/Ethernet/src/EthernetClient.h @@ -0,0 +1,3 @@ +// This file is in the public domain. No copyright is claimed. + +#include "Ethernet.h" diff --git a/libraries/Ethernet/src/EthernetServer.cpp b/libraries/Ethernet/src/EthernetServer.cpp new file mode 100644 index 0000000..ddebd15 --- /dev/null +++ b/libraries/Ethernet/src/EthernetServer.cpp @@ -0,0 +1,179 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "utility/w5100.h" + +uint16_t EthernetServer::server_port[MAX_SOCK_NUM]; + + +void EthernetServer::begin() +{ + uint8_t sockindex = Ethernet.socketBegin(SnMR::TCP, _port); + if (sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketListen(sockindex)) { + server_port[sockindex] = _port; + } else { + Ethernet.socketDisconnect(sockindex); + } + } +} + +EthernetClient EthernetServer::available() +{ + bool listening = false; + uint8_t sockindex = MAX_SOCK_NUM; + uint8_t chip, maxindex=MAX_SOCK_NUM; + + chip = W5100.getChip(); + if (!chip) return EthernetClient(MAX_SOCK_NUM); +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + uint8_t stat = Ethernet.socketStatus(i); + if (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT) { + if (Ethernet.socketRecvAvailable(i) > 0) { + sockindex = i; + } else { + // remote host closed connection, our end still open + if (stat == SnSR::CLOSE_WAIT) { + Ethernet.socketDisconnect(i); + // status becomes LAST_ACK for short time + } + } + } else if (stat == SnSR::LISTEN) { + listening = true; + } else if (stat == SnSR::CLOSED) { + server_port[i] = 0; + } + } + } + if (!listening) begin(); + return EthernetClient(sockindex); +} + +EthernetClient EthernetServer::accept() +{ + bool listening = false; + uint8_t sockindex = MAX_SOCK_NUM; + uint8_t chip, maxindex=MAX_SOCK_NUM; + + chip = W5100.getChip(); + if (!chip) return EthernetClient(MAX_SOCK_NUM); +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + uint8_t stat = Ethernet.socketStatus(i); + if (sockindex == MAX_SOCK_NUM && + (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT)) { + // Return the connected client even if no data received. + // Some protocols like FTP expect the server to send the + // first data. + sockindex = i; + server_port[i] = 0; // only return the client once + } else if (stat == SnSR::LISTEN) { + listening = true; + } else if (stat == SnSR::CLOSED) { + server_port[i] = 0; + } + } + } + if (!listening) begin(); + return EthernetClient(sockindex); +} + +EthernetServer::operator bool() +{ + uint8_t maxindex=MAX_SOCK_NUM; +#if MAX_SOCK_NUM > 4 + if (W5100.getChip() == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + if (Ethernet.socketStatus(i) == SnSR::LISTEN) { + return true; // server is listening for incoming clients + } + } + } + return false; +} + +#if 0 +void EthernetServer::statusreport() +{ + Serial.printf("EthernetServer, port=%d\n", _port); + for (uint8_t i=0; i < MAX_SOCK_NUM; i++) { + uint16_t port = server_port[i]; + uint8_t stat = Ethernet.socketStatus(i); + const char *name; + switch (stat) { + case 0x00: name = "CLOSED"; break; + case 0x13: name = "INIT"; break; + case 0x14: name = "LISTEN"; break; + case 0x15: name = "SYNSENT"; break; + case 0x16: name = "SYNRECV"; break; + case 0x17: name = "ESTABLISHED"; break; + case 0x18: name = "FIN_WAIT"; break; + case 0x1A: name = "CLOSING"; break; + case 0x1B: name = "TIME_WAIT"; break; + case 0x1C: name = "CLOSE_WAIT"; break; + case 0x1D: name = "LAST_ACK"; break; + case 0x22: name = "UDP"; break; + case 0x32: name = "IPRAW"; break; + case 0x42: name = "MACRAW"; break; + case 0x5F: name = "PPPOE"; break; + default: name = "???"; + } + int avail = Ethernet.socketRecvAvailable(i); + Serial.printf(" %d: port=%d, status=%s (0x%02X), avail=%d\n", + i, port, name, stat, avail); + } +} +#endif + +size_t EthernetServer::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t EthernetServer::write(const uint8_t *buffer, size_t size) +{ + uint8_t chip, maxindex=MAX_SOCK_NUM; + + chip = W5100.getChip(); + if (!chip) return 0; +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + available(); + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + if (Ethernet.socketStatus(i) == SnSR::ESTABLISHED) { + Ethernet.socketSend(i, buffer, size); + } + } + } + return size; +} diff --git a/libraries/Ethernet/src/EthernetServer.h b/libraries/Ethernet/src/EthernetServer.h new file mode 100644 index 0000000..b5aef96 --- /dev/null +++ b/libraries/Ethernet/src/EthernetServer.h @@ -0,0 +1,3 @@ +// This file is in the public domain. No copyright is claimed. + +#include "Ethernet.h" diff --git a/libraries/Ethernet/src/EthernetUdp.cpp b/libraries/Ethernet/src/EthernetUdp.cpp new file mode 100644 index 0000000..51669d6 --- /dev/null +++ b/libraries/Ethernet/src/EthernetUdp.cpp @@ -0,0 +1,191 @@ +/* + * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. + * This version only offers minimal wrapping of socket.cpp + * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ + * + * MIT License: + * Copyright (c) 2008 Bjoern Hartmann + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * bjoern@cs.stanford.edu 12/30/2008 + */ + +#include +#include "Ethernet.h" +#include "Dns.h" +#include "utility/w5100.h" + +/* Start EthernetUDP socket, listening at local port PORT */ +uint8_t EthernetUDP::begin(uint16_t port) +{ + if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); + sockindex = Ethernet.socketBegin(SnMR::UDP, port); + if (sockindex >= MAX_SOCK_NUM) return 0; + _port = port; + _remaining = 0; + return 1; +} + +/* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ +int EthernetUDP::available() +{ + return _remaining; +} + +/* Release any resources being used by this EthernetUDP instance */ +void EthernetUDP::stop() +{ + if (sockindex < MAX_SOCK_NUM) { + Ethernet.socketClose(sockindex); + sockindex = MAX_SOCK_NUM; + } +} + +int EthernetUDP::beginPacket(const char *host, uint16_t port) +{ + // Look up the host first + int ret = 0; + DNSClient dns; + IPAddress remote_addr; + + dns.begin(Ethernet.dnsServerIP()); + ret = dns.getHostByName(host, remote_addr); + if (ret != 1) return ret; + return beginPacket(remote_addr, port); +} + +int EthernetUDP::beginPacket(IPAddress ip, uint16_t port) +{ + _offset = 0; + //Serial.printf("UDP beginPacket\n"); + return Ethernet.socketStartUDP(sockindex, rawIPAddress(ip), port); +} + +int EthernetUDP::endPacket() +{ + return Ethernet.socketSendUDP(sockindex); +} + +size_t EthernetUDP::write(uint8_t byte) +{ + return write(&byte, 1); +} + +size_t EthernetUDP::write(const uint8_t *buffer, size_t size) +{ + //Serial.printf("UDP write %d\n", size); + uint16_t bytes_written = Ethernet.socketBufferData(sockindex, _offset, buffer, size); + _offset += bytes_written; + return bytes_written; +} + +int EthernetUDP::parsePacket() +{ + // discard any remaining bytes in the last packet + while (_remaining) { + // could this fail (loop endlessly) if _remaining > 0 and recv in read fails? + // should only occur if recv fails after telling us the data is there, lets + // hope the w5100 always behaves :) + read((uint8_t *)NULL, _remaining); + } + + if (Ethernet.socketRecvAvailable(sockindex) > 0) { + //HACK - hand-parse the UDP packet using TCP recv method + uint8_t tmpBuf[8]; + int ret=0; + //read 8 header bytes and get IP and port from it + ret = Ethernet.socketRecv(sockindex, tmpBuf, 8); + if (ret > 0) { + _remoteIP = tmpBuf; + _remotePort = tmpBuf[4]; + _remotePort = (_remotePort << 8) + tmpBuf[5]; + _remaining = tmpBuf[6]; + _remaining = (_remaining << 8) + tmpBuf[7]; + + // When we get here, any remaining bytes are the data + ret = _remaining; + } + return ret; + } + // There aren't any packets available + return 0; +} + +int EthernetUDP::read() +{ + uint8_t byte; + + if ((_remaining > 0) && (Ethernet.socketRecv(sockindex, &byte, 1) > 0)) { + // We read things without any problems + _remaining--; + return byte; + } + + // If we get here, there's no data available + return -1; +} + +int EthernetUDP::read(unsigned char *buffer, size_t len) +{ + if (_remaining > 0) { + int got; + if (_remaining <= len) { + // data should fit in the buffer + got = Ethernet.socketRecv(sockindex, buffer, _remaining); + } else { + // too much data for the buffer, + // grab as much as will fit + got = Ethernet.socketRecv(sockindex, buffer, len); + } + if (got > 0) { + _remaining -= got; + //Serial.printf("UDP read %d\n", got); + return got; + } + } + // If we get here, there's no data available or recv failed + return -1; +} + +int EthernetUDP::peek() +{ + // Unlike recv, peek doesn't check to see if there's any data available, so we must. + // If the user hasn't called parsePacket yet then return nothing otherwise they + // may get the UDP header + if (sockindex >= MAX_SOCK_NUM || _remaining == 0) return -1; + return Ethernet.socketPeek(sockindex); +} + +void EthernetUDP::flush() +{ + // TODO: we should wait for TX buffer to be emptied +} + +/* Start EthernetUDP socket, listening at local port PORT */ +uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port) +{ + if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); + sockindex = Ethernet.socketBeginMulticast(SnMR::UDP | SnMR::MULTI, ip, port); + if (sockindex >= MAX_SOCK_NUM) return 0; + _port = port; + _remaining = 0; + return 1; +} + diff --git a/libraries/Ethernet/src/EthernetUdp.h b/libraries/Ethernet/src/EthernetUdp.h new file mode 100644 index 0000000..2438ec9 --- /dev/null +++ b/libraries/Ethernet/src/EthernetUdp.h @@ -0,0 +1,38 @@ +/* + * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. + * This version only offers minimal wrapping of socket.cpp + * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ + * + * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) + * 1) UDP does not guarantee the order in which assembled UDP packets are received. This + * might not happen often in practice, but in larger network topologies, a UDP + * packet can be received out of sequence. + * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being + * aware of it. Again, this may not be a concern in practice on small local networks. + * For more information, see http://www.cafeaulait.org/course/week12/35.html + * + * MIT License: + * Copyright (c) 2008 Bjoern Hartmann + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * bjoern@cs.stanford.edu 12/30/2008 + */ + +#include "Ethernet.h" + diff --git a/libraries/Ethernet/src/socket.cpp b/libraries/Ethernet/src/socket.cpp new file mode 100644 index 0000000..f059dc9 --- /dev/null +++ b/libraries/Ethernet/src/socket.cpp @@ -0,0 +1,539 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "utility/w5100.h" + +#if ARDUINO >= 156 && !defined(ARDUINO_ARCH_PIC32) +extern void yield(void); +#else +#define yield() +#endif + +// TODO: randomize this when not using DHCP, but how? +static uint16_t local_port = 49152; // 49152 to 65535 + +typedef struct { + uint16_t RX_RSR; // Number of bytes received + uint16_t RX_RD; // Address to read + uint16_t TX_FSR; // Free space ready for transmit + uint8_t RX_inc; // how much have we advanced RX_RD +} socketstate_t; + +static socketstate_t state[MAX_SOCK_NUM]; + + +static uint16_t getSnTX_FSR(uint8_t s); +static uint16_t getSnRX_RSR(uint8_t s); +static void write_data(uint8_t s, uint16_t offset, const uint8_t *data, uint16_t len); +static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len); + + + +/*****************************************/ +/* Socket management */ +/*****************************************/ + + +void EthernetClass::socketPortRand(uint16_t n) +{ + n &= 0x3FFF; + local_port ^= n; + //Serial.printf("socketPortRand %d, srcport=%d\n", n, local_port); +} + +uint8_t EthernetClass::socketBegin(uint8_t protocol, uint16_t port) +{ + uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM; + + // first check hardware compatibility + chip = W5100.getChip(); + if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + // look at all the hardware sockets, use any that are closed (unused) + for (s=0; s < maxindex; s++) { + status[s] = W5100.readSnSR(s); + if (status[s] == SnSR::CLOSED) goto makesocket; + } + //Serial.printf("W5000socket step2\n"); + // as a last resort, forcibly close any already closing + for (s=0; s < maxindex; s++) { + uint8_t stat = status[s]; + if (stat == SnSR::LAST_ACK) goto closemakesocket; + if (stat == SnSR::TIME_WAIT) goto closemakesocket; + if (stat == SnSR::FIN_WAIT) goto closemakesocket; + if (stat == SnSR::CLOSING) goto closemakesocket; + } +#if 0 + Serial.printf("W5000socket step3\n"); + // next, use any that are effectively closed + for (s=0; s < MAX_SOCK_NUM; s++) { + uint8_t stat = status[s]; + // TODO: this also needs to check if no more data + if (stat == SnSR::CLOSE_WAIT) goto closemakesocket; + } +#endif + SPI.endTransaction(); + return MAX_SOCK_NUM; // all sockets are in use +closemakesocket: + //Serial.printf("W5000socket close\n"); + W5100.execCmdSn(s, Sock_CLOSE); +makesocket: + //Serial.printf("W5000socket %d\n", s); + EthernetServer::server_port[s] = 0; + delayMicroseconds(250); // TODO: is this needed?? + W5100.writeSnMR(s, protocol); + W5100.writeSnIR(s, 0xFF); + if (port > 0) { + W5100.writeSnPORT(s, port); + } else { + // if don't set the source port, set local_port number. + if (++local_port < 49152) local_port = 49152; + W5100.writeSnPORT(s, local_port); + } + W5100.execCmdSn(s, Sock_OPEN); + state[s].RX_RSR = 0; + state[s].RX_RD = W5100.readSnRX_RD(s); // always zero? + state[s].RX_inc = 0; + state[s].TX_FSR = 0; + //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD); + SPI.endTransaction(); + return s; +} + +// multicast version to set fields before open thd +uint8_t EthernetClass::socketBeginMulticast(uint8_t protocol, IPAddress ip, uint16_t port) +{ + uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM; + + // first check hardware compatibility + chip = W5100.getChip(); + if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + // look at all the hardware sockets, use any that are closed (unused) + for (s=0; s < maxindex; s++) { + status[s] = W5100.readSnSR(s); + if (status[s] == SnSR::CLOSED) goto makesocket; + } + //Serial.printf("W5000socket step2\n"); + // as a last resort, forcibly close any already closing + for (s=0; s < maxindex; s++) { + uint8_t stat = status[s]; + if (stat == SnSR::LAST_ACK) goto closemakesocket; + if (stat == SnSR::TIME_WAIT) goto closemakesocket; + if (stat == SnSR::FIN_WAIT) goto closemakesocket; + if (stat == SnSR::CLOSING) goto closemakesocket; + } +#if 0 + Serial.printf("W5000socket step3\n"); + // next, use any that are effectively closed + for (s=0; s < MAX_SOCK_NUM; s++) { + uint8_t stat = status[s]; + // TODO: this also needs to check if no more data + if (stat == SnSR::CLOSE_WAIT) goto closemakesocket; + } +#endif + SPI.endTransaction(); + return MAX_SOCK_NUM; // all sockets are in use +closemakesocket: + //Serial.printf("W5000socket close\n"); + W5100.execCmdSn(s, Sock_CLOSE); +makesocket: + //Serial.printf("W5000socket %d\n", s); + EthernetServer::server_port[s] = 0; + delayMicroseconds(250); // TODO: is this needed?? + W5100.writeSnMR(s, protocol); + W5100.writeSnIR(s, 0xFF); + if (port > 0) { + W5100.writeSnPORT(s, port); + } else { + // if don't set the source port, set local_port number. + if (++local_port < 49152) local_port = 49152; + W5100.writeSnPORT(s, local_port); + } + // Calculate MAC address from Multicast IP Address + byte mac[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00 }; + mac[3] = ip[1] & 0x7F; + mac[4] = ip[2]; + mac[5] = ip[3]; + W5100.writeSnDIPR(s, ip.raw_address()); //239.255.0.1 + W5100.writeSnDPORT(s, port); + W5100.writeSnDHAR(s, mac); + W5100.execCmdSn(s, Sock_OPEN); + state[s].RX_RSR = 0; + state[s].RX_RD = W5100.readSnRX_RD(s); // always zero? + state[s].RX_inc = 0; + state[s].TX_FSR = 0; + //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD); + SPI.endTransaction(); + return s; +} +// Return the socket's status +// +uint8_t EthernetClass::socketStatus(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint8_t status = W5100.readSnSR(s); + SPI.endTransaction(); + return status; +} + +// Immediately close. If a TCP connection is established, the +// remote host is left unaware we closed. +// +void EthernetClass::socketClose(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.execCmdSn(s, Sock_CLOSE); + SPI.endTransaction(); +} + + +// Place the socket in listening (server) mode +// +uint8_t EthernetClass::socketListen(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + if (W5100.readSnSR(s) != SnSR::INIT) { + SPI.endTransaction(); + return 0; + } + W5100.execCmdSn(s, Sock_LISTEN); + SPI.endTransaction(); + return 1; +} + + +// establish a TCP connection in Active (client) mode. +// +void EthernetClass::socketConnect(uint8_t s, uint8_t * addr, uint16_t port) +{ + // set destination IP + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.writeSnDIPR(s, addr); + W5100.writeSnDPORT(s, port); + W5100.execCmdSn(s, Sock_CONNECT); + SPI.endTransaction(); +} + + + +// Gracefully disconnect a TCP connection. +// +void EthernetClass::socketDisconnect(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.execCmdSn(s, Sock_DISCON); + SPI.endTransaction(); +} + + + +/*****************************************/ +/* Socket Data Receive Functions */ +/*****************************************/ + + +static uint16_t getSnRX_RSR(uint8_t s) +{ +#if 1 + uint16_t val, prev; + + prev = W5100.readSnRX_RSR(s); + while (1) { + val = W5100.readSnRX_RSR(s); + if (val == prev) { + return val; + } + prev = val; + } +#else + uint16_t val = W5100.readSnRX_RSR(s); + return val; +#endif +} + +static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len) +{ + uint16_t size; + uint16_t src_mask; + uint16_t src_ptr; + + //Serial.printf("read_data, len=%d, at:%d\n", len, src); + src_mask = (uint16_t)src & W5100.SMASK; + src_ptr = W5100.RBASE(s) + src_mask; + + if (W5100.hasOffsetAddressMapping() || src_mask + len <= W5100.SSIZE) { + W5100.read(src_ptr, dst, len); + } else { + size = W5100.SSIZE - src_mask; + W5100.read(src_ptr, dst, size); + dst += size; + W5100.read(W5100.RBASE(s), dst, len - size); + } +} + +// Receive data. Returns size, or -1 for no data, or 0 if connection closed +// +int EthernetClass::socketRecv(uint8_t s, uint8_t *buf, int16_t len) +{ + // Check how much data is available + int ret = state[s].RX_RSR; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + if (ret < len) { + uint16_t rsr = getSnRX_RSR(s); + ret = rsr - state[s].RX_inc; + state[s].RX_RSR = ret; + //Serial.printf("Sock_RECV, RX_RSR=%d, RX_inc=%d\n", ret, state[s].RX_inc); + } + if (ret == 0) { + // No data available. + uint8_t status = W5100.readSnSR(s); + if ( status == SnSR::LISTEN || status == SnSR::CLOSED || + status == SnSR::CLOSE_WAIT ) { + // The remote end has closed its side of the connection, + // so this is the eof state + ret = 0; + } else { + // The connection is still up, but there's no data waiting to be read + ret = -1; + } + } else { + if (ret > len) ret = len; // more data available than buffer length + uint16_t ptr = state[s].RX_RD; + if (buf) read_data(s, ptr, buf, ret); + ptr += ret; + state[s].RX_RD = ptr; + state[s].RX_RSR -= ret; + uint16_t inc = state[s].RX_inc + ret; + if (inc >= 250 || state[s].RX_RSR == 0) { + state[s].RX_inc = 0; + W5100.writeSnRX_RD(s, ptr); + W5100.execCmdSn(s, Sock_RECV); + //Serial.printf("Sock_RECV cmd, RX_RD=%d, RX_RSR=%d\n", + // state[s].RX_RD, state[s].RX_RSR); + } else { + state[s].RX_inc = inc; + } + } + SPI.endTransaction(); + //Serial.printf("socketRecv, ret=%d\n", ret); + return ret; +} + +uint16_t EthernetClass::socketRecvAvailable(uint8_t s) +{ + uint16_t ret = state[s].RX_RSR; + if (ret == 0) { + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint16_t rsr = getSnRX_RSR(s); + SPI.endTransaction(); + ret = rsr - state[s].RX_inc; + state[s].RX_RSR = ret; + //Serial.printf("sockRecvAvailable s=%d, RX_RSR=%d\n", s, ret); + } + return ret; +} + +// get the first byte in the receive queue (no checking) +// +uint8_t EthernetClass::socketPeek(uint8_t s) +{ + uint8_t b; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint16_t ptr = state[s].RX_RD; + W5100.read((ptr & W5100.SMASK) + W5100.RBASE(s), &b, 1); + SPI.endTransaction(); + return b; +} + + + +/*****************************************/ +/* Socket Data Transmit Functions */ +/*****************************************/ + +static uint16_t getSnTX_FSR(uint8_t s) +{ + uint16_t val, prev; + + prev = W5100.readSnTX_FSR(s); + while (1) { + val = W5100.readSnTX_FSR(s); + if (val == prev) { + state[s].TX_FSR = val; + return val; + } + prev = val; + } +} + + +static void write_data(uint8_t s, uint16_t data_offset, const uint8_t *data, uint16_t len) +{ + uint16_t ptr = W5100.readSnTX_WR(s); + ptr += data_offset; + uint16_t offset = ptr & W5100.SMASK; + uint16_t dstAddr = offset + W5100.SBASE(s); + + if (W5100.hasOffsetAddressMapping() || offset + len <= W5100.SSIZE) { + W5100.write(dstAddr, data, len); + } else { + // Wrap around circular buffer + uint16_t size = W5100.SSIZE - offset; + W5100.write(dstAddr, data, size); + W5100.write(W5100.SBASE(s), data + size, len - size); + } + ptr += len; + W5100.writeSnTX_WR(s, ptr); +} + + +/** + * @brief This function used to send the data in TCP mode + * @return 1 for success else 0. + */ +uint16_t EthernetClass::socketSend(uint8_t s, const uint8_t * buf, uint16_t len) +{ + uint8_t status=0; + uint16_t ret=0; + uint16_t freesize=0; + + if (len > W5100.SSIZE) { + ret = W5100.SSIZE; // check size not to exceed MAX size. + } else { + ret = len; + } + + // if freebuf is available, start. + do { + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + freesize = getSnTX_FSR(s); + status = W5100.readSnSR(s); + SPI.endTransaction(); + if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) { + ret = 0; + break; + } + yield(); + } while (freesize < ret); + + // copy data + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + write_data(s, 0, (uint8_t *)buf, ret); + W5100.execCmdSn(s, Sock_SEND); + + /* +2008.01 bj */ + while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { + /* m2008.01 [bj] : reduce code */ + if ( W5100.readSnSR(s) == SnSR::CLOSED ) { + SPI.endTransaction(); + return 0; + } + SPI.endTransaction(); + yield(); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + } + /* +2008.01 bj */ + W5100.writeSnIR(s, SnIR::SEND_OK); + SPI.endTransaction(); + return ret; +} + +uint16_t EthernetClass::socketSendAvailable(uint8_t s) +{ + uint8_t status=0; + uint16_t freesize=0; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + freesize = getSnTX_FSR(s); + status = W5100.readSnSR(s); + SPI.endTransaction(); + if ((status == SnSR::ESTABLISHED) || (status == SnSR::CLOSE_WAIT)) { + return freesize; + } + return 0; +} + +uint16_t EthernetClass::socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len) +{ + //Serial.printf(" bufferData, offset=%d, len=%d\n", offset, len); + uint16_t ret =0; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint16_t txfree = getSnTX_FSR(s); + if (len > txfree) { + ret = txfree; // check size not to exceed MAX size. + } else { + ret = len; + } + write_data(s, offset, buf, ret); + SPI.endTransaction(); + return ret; +} + +bool EthernetClass::socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port) +{ + if ( ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) || + ((port == 0x00)) ) { + return false; + } + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.writeSnDIPR(s, addr); + W5100.writeSnDPORT(s, port); + SPI.endTransaction(); + return true; +} + +bool EthernetClass::socketSendUDP(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.execCmdSn(s, Sock_SEND); + + /* +2008.01 bj */ + while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { + if (W5100.readSnIR(s) & SnIR::TIMEOUT) { + /* +2008.01 [bj]: clear interrupt */ + W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT)); + SPI.endTransaction(); + //Serial.printf("sendUDP timeout\n"); + return false; + } + SPI.endTransaction(); + yield(); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + } + + /* +2008.01 bj */ + W5100.writeSnIR(s, SnIR::SEND_OK); + SPI.endTransaction(); + + //Serial.printf("sendUDP ok\n"); + /* Sent ok */ + return true; +} + diff --git a/libraries/Ethernet/src/utility/w5100.cpp b/libraries/Ethernet/src/utility/w5100.cpp new file mode 100644 index 0000000..4ae4ee7 --- /dev/null +++ b/libraries/Ethernet/src/utility/w5100.cpp @@ -0,0 +1,474 @@ +/* + * Copyright 2018 Paul Stoffregen + * Copyright (c) 2010 by Cristian Maglie + * + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ + +#include +#include "Ethernet.h" +#include "w5100.h" + + +/***************************************************/ +/** Default SS pin setting **/ +/***************************************************/ + +// If variant.h or other headers specifically define the +// default SS pin for ethernet, use it. +#if defined(PIN_SPI_SS_ETHERNET_LIB) +#define SS_PIN_DEFAULT PIN_SPI_SS_ETHERNET_LIB + +// MKR boards default to pin 5 for MKR ETH +// Pins 8-10 are MOSI/SCK/MISO on MRK, so don't use pin 10 +#elif defined(USE_ARDUINO_MKR_PIN_LAYOUT) || defined(ARDUINO_SAMD_MKRZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRWAN1300) +#define SS_PIN_DEFAULT 5 + +// For boards using AVR, assume shields with SS on pin 10 +// will be used. This allows for Arduino Mega (where +// SS is pin 53) and Arduino Leonardo (where SS is pin 17) +// to work by default with Arduino Ethernet Shield R2 & R3. +#elif defined(__AVR__) +#define SS_PIN_DEFAULT 10 + +// If variant.h or other headers define these names +// use them if none of the other cases match +#elif defined(PIN_SPI_SS) +#define SS_PIN_DEFAULT PIN_SPI_SS +#elif defined(CORE_SS0_PIN) +#define SS_PIN_DEFAULT CORE_SS0_PIN + +// As a final fallback, use pin 10 +#else +#define SS_PIN_DEFAULT 10 +#endif + + + + +// W5100 controller instance +uint8_t W5100Class::chip = 0; +uint8_t W5100Class::CH_BASE_MSB; +uint8_t W5100Class::ss_pin = SS_PIN_DEFAULT; +#ifdef ETHERNET_LARGE_BUFFERS +uint16_t W5100Class::SSIZE = 2048; +uint16_t W5100Class::SMASK = 0x07FF; +#endif +W5100Class W5100; + +// pointers and bitmasks for optimized SS pin +#if defined(__AVR__) + volatile uint8_t * W5100Class::ss_pin_reg; + uint8_t W5100Class::ss_pin_mask; +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) + volatile uint8_t * W5100Class::ss_pin_reg; +#elif defined(__MKL26Z64__) + volatile uint8_t * W5100Class::ss_pin_reg; + uint8_t W5100Class::ss_pin_mask; +#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#elif defined(__PIC32MX__) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#elif defined(ARDUINO_ARCH_ESP8266) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#elif defined(__SAMD21G18A__) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#endif + + +uint8_t W5100Class::init(void) +{ + static bool initialized = false; + uint8_t i; + + if (initialized) return 1; + + // Many Ethernet shields have a CAT811 or similar reset chip + // connected to W5100 or W5200 chips. The W5200 will not work at + // all, and may even drive its MISO pin, until given an active low + // reset pulse! The CAT811 has a 240 ms typical pulse length, and + // a 400 ms worst case maximum pulse length. MAX811 has a worst + // case maximum 560 ms pulse length. This delay is meant to wait + // until the reset pulse is ended. If your hardware has a shorter + // reset time, this can be edited or removed. + delay(560); + //Serial.println("w5100 init"); + + SPI.begin(); + initSS(); + resetSS(); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + + // Attempt W5200 detection first, because W5200 does not properly + // reset its SPI state when CS goes high (inactive). Communication + // from detecting the other chips can leave the W5200 in a state + // where it won't recover, unless given a reset pulse. + if (isW5200()) { + CH_BASE_MSB = 0x40; +#ifdef ETHERNET_LARGE_BUFFERS +#if MAX_SOCK_NUM <= 1 + SSIZE = 16384; +#elif MAX_SOCK_NUM <= 2 + SSIZE = 8192; +#elif MAX_SOCK_NUM <= 4 + SSIZE = 4096; +#else + SSIZE = 2048; +#endif + SMASK = SSIZE - 1; +#endif + for (i=0; i> 10); + writeSnTX_SIZE(i, SSIZE >> 10); + } + for (; i<8; i++) { + writeSnRX_SIZE(i, 0); + writeSnTX_SIZE(i, 0); + } + // Try W5500 next. Wiznet finally seems to have implemented + // SPI well with this chip. It appears to be very resilient, + // so try it after the fragile W5200 + } else if (isW5500()) { + CH_BASE_MSB = 0x10; +#ifdef ETHERNET_LARGE_BUFFERS +#if MAX_SOCK_NUM <= 1 + SSIZE = 16384; +#elif MAX_SOCK_NUM <= 2 + SSIZE = 8192; +#elif MAX_SOCK_NUM <= 4 + SSIZE = 4096; +#else + SSIZE = 2048; +#endif + SMASK = SSIZE - 1; + for (i=0; i> 10); + writeSnTX_SIZE(i, SSIZE >> 10); + } + for (; i<8; i++) { + writeSnRX_SIZE(i, 0); + writeSnTX_SIZE(i, 0); + } +#endif + // Try W5100 last. This simple chip uses fixed 4 byte frames + // for every 8 bit access. Terribly inefficient, but so simple + // it recovers from "hearing" unsuccessful W5100 or W5200 + // communication. W5100 is also the only chip without a VERSIONR + // register for identification, so we check this last. + } else if (isW5100()) { + CH_BASE_MSB = 0x04; +#ifdef ETHERNET_LARGE_BUFFERS +#if MAX_SOCK_NUM <= 1 + SSIZE = 8192; + writeTMSR(0x03); + writeRMSR(0x03); +#elif MAX_SOCK_NUM <= 2 + SSIZE = 4096; + writeTMSR(0x0A); + writeRMSR(0x0A); +#else + SSIZE = 2048; + writeTMSR(0x55); + writeRMSR(0x55); +#endif + SMASK = SSIZE - 1; +#else + writeTMSR(0x55); + writeRMSR(0x55); +#endif + // No hardware seems to be present. Or it could be a W5200 + // that's heard other SPI communication if its chip select + // pin wasn't high when a SD card or other SPI chip was used. + } else { + //Serial.println("no chip :-("); + chip = 0; + SPI.endTransaction(); + return 0; // no known chip is responding :-( + } + SPI.endTransaction(); + initialized = true; + return 1; // successful init +} + +// Soft reset the Wiznet chip, by writing to its MR register reset bit +uint8_t W5100Class::softReset(void) +{ + uint16_t count=0; + + //Serial.println("Wiznet soft reset"); + // write to reset bit + writeMR(0x80); + // then wait for soft reset to complete + do { + uint8_t mr = readMR(); + //Serial.print("mr="); + //Serial.println(mr, HEX); + if (mr == 0) return 1; + delay(1); + } while (++count < 20); + return 0; +} + +uint8_t W5100Class::isW5100(void) +{ + chip = 51; + //Serial.println("w5100.cpp: detect W5100 chip"); + if (!softReset()) return 0; + writeMR(0x10); + if (readMR() != 0x10) return 0; + writeMR(0x12); + if (readMR() != 0x12) return 0; + writeMR(0x00); + if (readMR() != 0x00) return 0; + //Serial.println("chip is W5100"); + return 1; +} + +uint8_t W5100Class::isW5200(void) +{ + chip = 52; + //Serial.println("w5100.cpp: detect W5200 chip"); + if (!softReset()) return 0; + writeMR(0x08); + if (readMR() != 0x08) return 0; + writeMR(0x10); + if (readMR() != 0x10) return 0; + writeMR(0x00); + if (readMR() != 0x00) return 0; + int ver = readVERSIONR_W5200(); + //Serial.print("version="); + //Serial.println(ver); + if (ver != 3) return 0; + //Serial.println("chip is W5200"); + return 1; +} + +uint8_t W5100Class::isW5500(void) +{ + chip = 55; + //Serial.println("w5100.cpp: detect W5500 chip"); + if (!softReset()) return 0; + writeMR(0x08); + if (readMR() != 0x08) return 0; + writeMR(0x10); + if (readMR() != 0x10) return 0; + writeMR(0x00); + if (readMR() != 0x00) return 0; + int ver = readVERSIONR_W5500(); + //Serial.print("version="); + //Serial.println(ver); + if (ver != 4) return 0; + //Serial.println("chip is W5500"); + return 1; +} + +W5100Linkstatus W5100Class::getLinkStatus() +{ + uint8_t phystatus; + + if (!init()) return UNKNOWN; + switch (chip) { + case 52: + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + phystatus = readPSTATUS_W5200(); + SPI.endTransaction(); + if (phystatus & 0x20) return LINK_ON; + return LINK_OFF; + case 55: + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + phystatus = readPHYCFGR_W5500(); + SPI.endTransaction(); + if (phystatus & 0x01) return LINK_ON; + return LINK_OFF; + default: + return UNKNOWN; + } +} + +uint16_t W5100Class::write(uint16_t addr, const uint8_t *buf, uint16_t len) +{ + uint8_t cmd[8]; + + if (chip == 51) { + for (uint16_t i=0; i> 8); + SPI.transfer(addr & 0xFF); + addr++; + SPI.transfer(buf[i]); + resetSS(); + } + } else if (chip == 52) { + setSS(); + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + cmd[2] = ((len >> 8) & 0x7F) | 0x80; + cmd[3] = len & 0xFF; + SPI.transfer(cmd, 4); +#ifdef SPI_HAS_TRANSFER_BUF + SPI.transfer(buf, NULL, len); +#else + // TODO: copy 8 bytes at a time to cmd[] and block transfer + for (uint16_t i=0; i < len; i++) { + SPI.transfer(buf[i]); + } +#endif + resetSS(); + } else { // chip == 55 + setSS(); + if (addr < 0x100) { + // common registers 00nn + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = 0x04; + } else if (addr < 0x8000) { + // socket registers 10nn, 11nn, 12nn, 13nn, etc + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = ((addr >> 3) & 0xE0) | 0x0C; + } else if (addr < 0xC000) { + // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc + // 10## #nnn nnnn nnnn + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x14; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x14; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x14; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x14; // 2K buffers + #endif + } else { + // receive buffers + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x1C; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x1C; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x1C; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x1C; // 2K buffers + #endif + } + if (len <= 5) { + for (uint8_t i=0; i < len; i++) { + cmd[i + 3] = buf[i]; + } + SPI.transfer(cmd, len + 3); + } else { + SPI.transfer(cmd, 3); +#ifdef SPI_HAS_TRANSFER_BUF + SPI.transfer(buf, NULL, len); +#else + // TODO: copy 8 bytes at a time to cmd[] and block transfer + for (uint16_t i=0; i < len; i++) { + SPI.transfer(buf[i]); + } +#endif + } + resetSS(); + } + return len; +} + +uint16_t W5100Class::read(uint16_t addr, uint8_t *buf, uint16_t len) +{ + uint8_t cmd[4]; + + if (chip == 51) { + for (uint16_t i=0; i < len; i++) { + setSS(); + #if 1 + SPI.transfer(0x0F); + SPI.transfer(addr >> 8); + SPI.transfer(addr & 0xFF); + addr++; + buf[i] = SPI.transfer(0); + #else + cmd[0] = 0x0F; + cmd[1] = addr >> 8; + cmd[2] = addr & 0xFF; + cmd[3] = 0; + SPI.transfer(cmd, 4); // TODO: why doesn't this work? + buf[i] = cmd[3]; + addr++; + #endif + resetSS(); + } + } else if (chip == 52) { + setSS(); + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + cmd[2] = (len >> 8) & 0x7F; + cmd[3] = len & 0xFF; + SPI.transfer(cmd, 4); + memset(buf, 0, len); + SPI.transfer(buf, len); + resetSS(); + } else { // chip == 55 + setSS(); + if (addr < 0x100) { + // common registers 00nn + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = 0x00; + } else if (addr < 0x8000) { + // socket registers 10nn, 11nn, 12nn, 13nn, etc + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = ((addr >> 3) & 0xE0) | 0x08; + } else if (addr < 0xC000) { + // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc + // 10## #nnn nnnn nnnn + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x10; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x10; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x10; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x10; // 2K buffers + #endif + } else { + // receive buffers + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x18; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x18; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x18; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x18; // 2K buffers + #endif + } + SPI.transfer(cmd, 3); + memset(buf, 0, len); + SPI.transfer(buf, len); + resetSS(); + } + return len; +} + +void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) +{ + // Send command to socket + writeSnCR(s, _cmd); + // Wait for command to complete + while (readSnCR(s)) ; +} diff --git a/libraries/Ethernet/src/utility/w5100.h b/libraries/Ethernet/src/utility/w5100.h new file mode 100644 index 0000000..e6e01e1 --- /dev/null +++ b/libraries/Ethernet/src/utility/w5100.h @@ -0,0 +1,466 @@ +/* + * Copyright 2018 Paul Stoffregen + * Copyright (c) 2010 by Cristian Maglie + * + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ + +// w5100.h contains private W5x00 hardware "driver" level definitions +// which are not meant to be exposed to other libraries or Arduino users + +#ifndef W5100_H_INCLUDED +#define W5100_H_INCLUDED + +#include +#include + +// Safe for all chips +#define SPI_ETHERNET_SETTINGS SPISettings(14000000, MSBFIRST, SPI_MODE0) + +// Safe for W5200 and W5500, but too fast for W5100 +// Uncomment this if you know you'll never need W5100 support. +// Higher SPI clock only results in faster transfer to hosts on a LAN +// or with very low packet latency. With ordinary internet latency, +// the TCP window size & packet loss determine your overall speed. +//#define SPI_ETHERNET_SETTINGS SPISettings(30000000, MSBFIRST, SPI_MODE0) + + +// Require Ethernet.h, because we need MAX_SOCK_NUM +#ifndef ethernet_h_ +#error "Ethernet.h must be included before w5100.h" +#endif + + +// Arduino 101's SPI can not run faster than 8 MHz. +#if defined(ARDUINO_ARCH_ARC32) +#undef SPI_ETHERNET_SETTINGS +#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) +#endif + +// Arduino Zero can't use W5100-based shields faster than 8 MHz +// https://github.com/arduino-libraries/Ethernet/issues/37#issuecomment-408036848 +// W5500 does seem to work at 12 MHz. Delete this if only using W5500 +#if defined(__SAMD21G18A__) +#undef SPI_ETHERNET_SETTINGS +#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) +#endif + + +typedef uint8_t SOCKET; + +class SnMR { +public: + static const uint8_t CLOSE = 0x00; + static const uint8_t TCP = 0x21; + static const uint8_t UDP = 0x02; + static const uint8_t IPRAW = 0x03; + static const uint8_t MACRAW = 0x04; + static const uint8_t PPPOE = 0x05; + static const uint8_t ND = 0x20; + static const uint8_t MULTI = 0x80; +}; + +enum SockCMD { + Sock_OPEN = 0x01, + Sock_LISTEN = 0x02, + Sock_CONNECT = 0x04, + Sock_DISCON = 0x08, + Sock_CLOSE = 0x10, + Sock_SEND = 0x20, + Sock_SEND_MAC = 0x21, + Sock_SEND_KEEP = 0x22, + Sock_RECV = 0x40 +}; + +class SnIR { +public: + static const uint8_t SEND_OK = 0x10; + static const uint8_t TIMEOUT = 0x08; + static const uint8_t RECV = 0x04; + static const uint8_t DISCON = 0x02; + static const uint8_t CON = 0x01; +}; + +class SnSR { +public: + static const uint8_t CLOSED = 0x00; + static const uint8_t INIT = 0x13; + static const uint8_t LISTEN = 0x14; + static const uint8_t SYNSENT = 0x15; + static const uint8_t SYNRECV = 0x16; + static const uint8_t ESTABLISHED = 0x17; + static const uint8_t FIN_WAIT = 0x18; + static const uint8_t CLOSING = 0x1A; + static const uint8_t TIME_WAIT = 0x1B; + static const uint8_t CLOSE_WAIT = 0x1C; + static const uint8_t LAST_ACK = 0x1D; + static const uint8_t UDP = 0x22; + static const uint8_t IPRAW = 0x32; + static const uint8_t MACRAW = 0x42; + static const uint8_t PPPOE = 0x5F; +}; + +class IPPROTO { +public: + static const uint8_t IP = 0; + static const uint8_t ICMP = 1; + static const uint8_t IGMP = 2; + static const uint8_t GGP = 3; + static const uint8_t TCP = 6; + static const uint8_t PUP = 12; + static const uint8_t UDP = 17; + static const uint8_t IDP = 22; + static const uint8_t ND = 77; + static const uint8_t RAW = 255; +}; + +enum W5100Linkstatus { + UNKNOWN, + LINK_ON, + LINK_OFF +}; + +class W5100Class { + +public: + static uint8_t init(void); + + inline void setGatewayIp(const uint8_t * addr) { writeGAR(addr); } + inline void getGatewayIp(uint8_t * addr) { readGAR(addr); } + + inline void setSubnetMask(const uint8_t * addr) { writeSUBR(addr); } + inline void getSubnetMask(uint8_t * addr) { readSUBR(addr); } + + inline void setMACAddress(const uint8_t * addr) { writeSHAR(addr); } + inline void getMACAddress(uint8_t * addr) { readSHAR(addr); } + + inline void setIPAddress(const uint8_t * addr) { writeSIPR(addr); } + inline void getIPAddress(uint8_t * addr) { readSIPR(addr); } + + inline void setRetransmissionTime(uint16_t timeout) { writeRTR(timeout); } + inline void setRetransmissionCount(uint8_t retry) { writeRCR(retry); } + + static void execCmdSn(SOCKET s, SockCMD _cmd); + + + // W5100 Registers + // --------------- +//private: +public: + static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len); + static uint8_t write(uint16_t addr, uint8_t data) { + return write(addr, &data, 1); + } + static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len); + static uint8_t read(uint16_t addr) { + uint8_t data; + read(addr, &data, 1); + return data; + } + +#define __GP_REGISTER8(name, address) \ + static inline void write##name(uint8_t _data) { \ + write(address, _data); \ + } \ + static inline uint8_t read##name() { \ + return read(address); \ + } +#define __GP_REGISTER16(name, address) \ + static void write##name(uint16_t _data) { \ + uint8_t buf[2]; \ + buf[0] = _data >> 8; \ + buf[1] = _data & 0xFF; \ + write(address, buf, 2); \ + } \ + static uint16_t read##name() { \ + uint8_t buf[2]; \ + read(address, buf, 2); \ + return (buf[0] << 8) | buf[1]; \ + } +#define __GP_REGISTER_N(name, address, size) \ + static uint16_t write##name(const uint8_t *_buff) { \ + return write(address, _buff, size); \ + } \ + static uint16_t read##name(uint8_t *_buff) { \ + return read(address, _buff, size); \ + } + static W5100Linkstatus getLinkStatus(); + +public: + __GP_REGISTER8 (MR, 0x0000); // Mode + __GP_REGISTER_N(GAR, 0x0001, 4); // Gateway IP address + __GP_REGISTER_N(SUBR, 0x0005, 4); // Subnet mask address + __GP_REGISTER_N(SHAR, 0x0009, 6); // Source MAC address + __GP_REGISTER_N(SIPR, 0x000F, 4); // Source IP address + __GP_REGISTER8 (IR, 0x0015); // Interrupt + __GP_REGISTER8 (IMR, 0x0016); // Interrupt Mask + __GP_REGISTER16(RTR, 0x0017); // Timeout address + __GP_REGISTER8 (RCR, 0x0019); // Retry count + __GP_REGISTER8 (RMSR, 0x001A); // Receive memory size (W5100 only) + __GP_REGISTER8 (TMSR, 0x001B); // Transmit memory size (W5100 only) + __GP_REGISTER8 (PATR, 0x001C); // Authentication type address in PPPoE mode + __GP_REGISTER8 (PTIMER, 0x0028); // PPP LCP Request Timer + __GP_REGISTER8 (PMAGIC, 0x0029); // PPP LCP Magic Number + __GP_REGISTER_N(UIPR, 0x002A, 4); // Unreachable IP address in UDP mode (W5100 only) + __GP_REGISTER16(UPORT, 0x002E); // Unreachable Port address in UDP mode (W5100 only) + __GP_REGISTER8 (VERSIONR_W5200,0x001F); // Chip Version Register (W5200 only) + __GP_REGISTER8 (VERSIONR_W5500,0x0039); // Chip Version Register (W5500 only) + __GP_REGISTER8 (PSTATUS_W5200, 0x0035); // PHY Status + __GP_REGISTER8 (PHYCFGR_W5500, 0x002E); // PHY Configuration register, default: 10111xxx + + +#undef __GP_REGISTER8 +#undef __GP_REGISTER16 +#undef __GP_REGISTER_N + + // W5100 Socket registers + // ---------------------- +private: + static uint16_t CH_BASE(void) { + //if (chip == 55) return 0x1000; + //if (chip == 52) return 0x4000; + //return 0x0400; + return CH_BASE_MSB << 8; + } + static uint8_t CH_BASE_MSB; // 1 redundant byte, saves ~80 bytes code on AVR + static const uint16_t CH_SIZE = 0x0100; + + static inline uint8_t readSn(SOCKET s, uint16_t addr) { + return read(CH_BASE() + s * CH_SIZE + addr); + } + static inline uint8_t writeSn(SOCKET s, uint16_t addr, uint8_t data) { + return write(CH_BASE() + s * CH_SIZE + addr, data); + } + static inline uint16_t readSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { + return read(CH_BASE() + s * CH_SIZE + addr, buf, len); + } + static inline uint16_t writeSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { + return write(CH_BASE() + s * CH_SIZE + addr, buf, len); + } + +#define __SOCKET_REGISTER8(name, address) \ + static inline void write##name(SOCKET _s, uint8_t _data) { \ + writeSn(_s, address, _data); \ + } \ + static inline uint8_t read##name(SOCKET _s) { \ + return readSn(_s, address); \ + } +#define __SOCKET_REGISTER16(name, address) \ + static void write##name(SOCKET _s, uint16_t _data) { \ + uint8_t buf[2]; \ + buf[0] = _data >> 8; \ + buf[1] = _data & 0xFF; \ + writeSn(_s, address, buf, 2); \ + } \ + static uint16_t read##name(SOCKET _s) { \ + uint8_t buf[2]; \ + readSn(_s, address, buf, 2); \ + return (buf[0] << 8) | buf[1]; \ + } +#define __SOCKET_REGISTER_N(name, address, size) \ + static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \ + return writeSn(_s, address, _buff, size); \ + } \ + static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \ + return readSn(_s, address, _buff, size); \ + } + +public: + __SOCKET_REGISTER8(SnMR, 0x0000) // Mode + __SOCKET_REGISTER8(SnCR, 0x0001) // Command + __SOCKET_REGISTER8(SnIR, 0x0002) // Interrupt + __SOCKET_REGISTER8(SnSR, 0x0003) // Status + __SOCKET_REGISTER16(SnPORT, 0x0004) // Source Port + __SOCKET_REGISTER_N(SnDHAR, 0x0006, 6) // Destination Hardw Addr + __SOCKET_REGISTER_N(SnDIPR, 0x000C, 4) // Destination IP Addr + __SOCKET_REGISTER16(SnDPORT, 0x0010) // Destination Port + __SOCKET_REGISTER16(SnMSSR, 0x0012) // Max Segment Size + __SOCKET_REGISTER8(SnPROTO, 0x0014) // Protocol in IP RAW Mode + __SOCKET_REGISTER8(SnTOS, 0x0015) // IP TOS + __SOCKET_REGISTER8(SnTTL, 0x0016) // IP TTL + __SOCKET_REGISTER8(SnRX_SIZE, 0x001E) // RX Memory Size (W5200 only) + __SOCKET_REGISTER8(SnTX_SIZE, 0x001F) // RX Memory Size (W5200 only) + __SOCKET_REGISTER16(SnTX_FSR, 0x0020) // TX Free Size + __SOCKET_REGISTER16(SnTX_RD, 0x0022) // TX Read Pointer + __SOCKET_REGISTER16(SnTX_WR, 0x0024) // TX Write Pointer + __SOCKET_REGISTER16(SnRX_RSR, 0x0026) // RX Free Size + __SOCKET_REGISTER16(SnRX_RD, 0x0028) // RX Read Pointer + __SOCKET_REGISTER16(SnRX_WR, 0x002A) // RX Write Pointer (supported?) + +#undef __SOCKET_REGISTER8 +#undef __SOCKET_REGISTER16 +#undef __SOCKET_REGISTER_N + + +private: + static uint8_t chip; + static uint8_t ss_pin; + static uint8_t softReset(void); + static uint8_t isW5100(void); + static uint8_t isW5200(void); + static uint8_t isW5500(void); + +public: + static uint8_t getChip(void) { return chip; } +#ifdef ETHERNET_LARGE_BUFFERS + static uint16_t SSIZE; + static uint16_t SMASK; +#else + static const uint16_t SSIZE = 2048; + static const uint16_t SMASK = 0x07FF; +#endif + static uint16_t SBASE(uint8_t socknum) { + if (chip == 51) { + return socknum * SSIZE + 0x4000; + } else { + return socknum * SSIZE + 0x8000; + } + } + static uint16_t RBASE(uint8_t socknum) { + if (chip == 51) { + return socknum * SSIZE + 0x6000; + } else { + return socknum * SSIZE + 0xC000; + } + } + + static bool hasOffsetAddressMapping(void) { + if (chip == 55) return true; + return false; + } + static void setSS(uint8_t pin) { ss_pin = pin; } + +private: +#if defined(__AVR__) + static volatile uint8_t *ss_pin_reg; + static uint8_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg) &= ~ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg) |= ss_pin_mask; + } +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) + static volatile uint8_t *ss_pin_reg; + inline static void initSS() { + ss_pin_reg = portOutputRegister(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+256) = 1; + } + inline static void resetSS() { + *(ss_pin_reg+128) = 1; + } +#elif defined(__MKL26Z64__) + static volatile uint8_t *ss_pin_reg; + static uint8_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+8) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+4) = ss_pin_mask; + } +#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = &(digitalPinToPort(ss_pin)->PIO_PER); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+13) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+12) = ss_pin_mask; + } +#elif defined(__PIC32MX__) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+8+1) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+8+2) = ss_pin_mask; + } + +#elif defined(ARDUINO_ARCH_ESP8266) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = (volatile uint32_t*)GPO; + ss_pin_mask = 1 << ss_pin; + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + GPOC = ss_pin_mask; + } + inline static void resetSS() { + GPOS = ss_pin_mask; + } + +#elif defined(__SAMD21G18A__) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+5) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+6) = ss_pin_mask; + } +#else + inline static void initSS() { + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + digitalWrite(ss_pin, LOW); + } + inline static void resetSS() { + digitalWrite(ss_pin, HIGH); + } +#endif +}; + +extern W5100Class W5100; + + + +#endif + +#ifndef UTIL_H +#define UTIL_H + +#define htons(x) ( (((x)<<8)&0xFF00) | (((x)>>8)&0xFF) ) +#define ntohs(x) htons(x) + +#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \ + ((x)<< 8 & 0x00FF0000UL) | \ + ((x)>> 8 & 0x0000FF00UL) | \ + ((x)>>24 & 0x000000FFUL) ) +#define ntohl(x) htonl(x) + +#endif diff --git a/libraries/Firmata/Boards.h b/libraries/Firmata/Boards.h new file mode 100644 index 0000000..ace8d97 --- /dev/null +++ b/libraries/Firmata/Boards.h @@ -0,0 +1,953 @@ +/* + Boards.h - Hardware Abstraction Layer for Firmata library + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated April 15th, 2018 +*/ + +#ifndef Firmata_Boards_h +#define Firmata_Boards_h + +#include + +#if defined(ARDUINO) && ARDUINO >= 100 +#include "Arduino.h" // for digitalRead, digitalWrite, etc +#else +#include "WProgram.h" +#endif + +// Normally Servo.h must be included before Firmata.h (which then includes +// this file). If Servo.h wasn't included, this allows the code to still +// compile, but without support for any Servos. Hopefully that's what the +// user intended by not including Servo.h +#ifndef MAX_SERVOS +#define MAX_SERVOS 0 +#endif + +/* + Firmata Hardware Abstraction Layer + +Firmata is built on top of the hardware abstraction functions of Arduino, +specifically digitalWrite, digitalRead, analogWrite, analogRead, and +pinMode. While these functions offer simple integer pin numbers, Firmata +needs more information than is provided by Arduino. This file provides +all other hardware specific details. To make Firmata support a new board, +only this file should require editing. + +The key concept is every "pin" implemented by Firmata may be mapped to +any pin as implemented by Arduino. Usually a simple 1-to-1 mapping is +best, but such mapping should not be assumed. This hardware abstraction +layer allows Firmata to implement any number of pins which map onto the +Arduino implemented pins in almost any arbitrary way. + + +General Constants: + +These constants provide basic information Firmata requires. + +TOTAL_PINS: The total number of pins Firmata implemented by Firmata. + Usually this will match the number of pins the Arduino functions + implement, including any pins pins capable of analog or digital. + However, Firmata may implement any number of pins. For example, + on Arduino Mini with 8 analog inputs, 6 of these may be used + for digital functions, and 2 are analog only. On such boards, + Firmata can implement more pins than Arduino's pinMode() + function, in order to accommodate those special pins. The + Firmata protocol supports a maximum of 128 pins, so this + constant must not exceed 128. + +TOTAL_ANALOG_PINS: The total number of analog input pins implemented. + The Firmata protocol allows up to 16 analog inputs, accessed + using offsets 0 to 15. Because Firmata presents the analog + inputs using different offsets than the actual pin numbers + (a legacy of Arduino's analogRead function, and the way the + analog input capable pins are physically labeled on all + Arduino boards), the total number of analog input signals + must be specified. 16 is the maximum. + +VERSION_BLINK_PIN: When Firmata starts up, it will blink the version + number. This constant is the Arduino pin number where a + LED is connected. + + +Pin Mapping Macros: + +These macros provide the mapping between pins as implemented by +Firmata protocol and the actual pin numbers used by the Arduino +functions. Even though such mappings are often simple, pin +numbers received by Firmata protocol should always be used as +input to these macros, and the result of the macro should be +used with with any Arduino function. + +When Firmata is extended to support a new pin mode or feature, +a pair of macros should be added and used for all hardware +access. For simple 1:1 mapping, these macros add no actual +overhead, yet their consistent use allows source code which +uses them consistently to be easily adapted to all other boards +with different requirements. + +IS_PIN_XXXX(pin): The IS_PIN macros resolve to true or non-zero + if a pin as implemented by Firmata corresponds to a pin + that actually implements the named feature. + +PIN_TO_XXXX(pin): The PIN_TO macros translate pin numbers as + implemented by Firmata to the pin numbers needed as inputs + to the Arduino functions. The corresponding IS_PIN macro + should always be tested before using a PIN_TO macro, so + these macros only need to handle valid Firmata pin + numbers for the named feature. + + +Port Access Inline Funtions: + +For efficiency, Firmata protocol provides access to digital +input and output pins grouped by 8 bit ports. When these +groups of 8 correspond to actual 8 bit ports as implemented +by the hardware, these inline functions can provide high +speed direct port access. Otherwise, a default implementation +using 8 calls to digitalWrite or digitalRead is used. + +When porting Firmata to a new board, it is recommended to +use the default functions first and focus only on the constants +and macros above. When those are working, if optimized port +access is desired, these inline functions may be extended. +The recommended approach defines a symbol indicating which +optimization to use, and then conditional complication is +used within these functions. + +readPort(port, bitmask): Read an 8 bit port, returning the value. + port: The port number, Firmata pins port*8 to port*8+7 + bitmask: The actual pins to read, indicated by 1 bits. + +writePort(port, value, bitmask): Write an 8 bit port. + port: The port number, Firmata pins port*8 to port*8+7 + value: The 8 bit value to write + bitmask: The actual pins to write, indicated by 1 bits. +*/ + +/*============================================================================== + * Board Specific Configuration + *============================================================================*/ + +#ifndef digitalPinHasPWM +#define digitalPinHasPWM(p) IS_PIN_DIGITAL(p) +#endif + +// Arduino Duemilanove, Diecimila, and NG +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) +#if defined(NUM_ANALOG_INPUTS) && NUM_ANALOG_INPUTS == 6 +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#else +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 22 // 14 digital + 8 analog +#endif +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) +#define ARDUINO_PINOUT_OPTIMIZE 1 + + +// Wiring (and board) +#elif defined(WIRING) +#define VERSION_BLINK_PIN WLED +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= FIRST_ANALOG_PIN && (p) < (FIRST_ANALOG_PIN+TOTAL_ANALOG_PINS)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - FIRST_ANALOG_PIN) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// old Arduinos +#elif defined(__AVR_ATmega8__) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) +#define ARDUINO_PINOUT_OPTIMIZE 1 + + +// Arduino Mega +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TOTAL_ANALOG_PINS 16 +#define TOTAL_PINS 70 // 54 digital + 16 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 19 +#define PIN_SERIAL1_TX 18 +#define PIN_SERIAL2_RX 17 +#define PIN_SERIAL2_TX 16 +#define PIN_SERIAL3_RX 15 +#define PIN_SERIAL3_TX 14 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Arduino DUE +#elif defined(__SAM3X8E__) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 66 // 54 digital + 12 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 19 +#define PIN_SERIAL1_TX 18 +#define PIN_SERIAL2_RX 17 +#define PIN_SERIAL2_TX 16 +#define PIN_SERIAL3_RX 15 +#define PIN_SERIAL3_TX 14 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // 70 71 +#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Arduino/Genuino MKR1000 +#elif defined(ARDUINO_SAMD_MKR1000) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 22 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 21) +#define IS_PIN_ANALOG(p) ((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Arduino MKRZero +#elif defined(ARDUINO_SAMD_MKRZERO) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 34 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog + 3 usb + 1 aref + 5 sd + 1 bottom pad + 1 led + 1 battery adc +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21) || (p) == 32) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 33) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino MKRFox1200 +#elif defined(ARDUINO_SAMD_MKRFox1200) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 33 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog + 3 usb + 1 aref + 5 sd + 1 bottom pad + 1 battery adc +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21)) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 32) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino MKR WAN 1300 +#elif defined(ARDUINO_SAMD_MKRWAN1300) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 33 +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21)) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 32) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino MKR GSM 1400 +#elif defined(ARDUINO_SAMD_MKRGSM1400) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 33 +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21)) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 32) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino Zero +// Note this will work with an Arduino Zero Pro, but not with an Arduino M0 Pro +// Arduino M0 Pro does not properly map pins to the board labeled pin numbers +#elif defined(_VARIANT_ARDUINO_ZERO_) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 25 // 14 digital + 6 analog + 2 i2c + 3 spi +#define TOTAL_PORTS 3 // set when TOTAL_PINS > num digitial I/O pins +#define VERSION_BLINK_PIN LED_BUILTIN +//#define PIN_SERIAL1_RX 0 // already defined in zero core variant.h +//#define PIN_SERIAL1_TX 1 // already defined in zero core variant.h +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // SDA = 20, SCL = 21 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) // SS = A2 +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino Primo +#elif defined(ARDUINO_PRIMO) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 22 //14 digital + 6 analog + 2 i2c +#define VERSION_BLINK_PIN LED_BUILTIN +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < 20) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 20) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS+2) +#define IS_PIN_I2C(p) ((p) == PIN_WIRE_SDA || (p) == PIN_WIRE_SCL) // SDA = 20, SCL = 21 +#define IS_PIN_SPI(p) ((p) == SS || (p)== MOSI || (p) == MISO || (p == SCK)) // 10, 11, 12, 13 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + +// Arduino 101 +#elif defined(_VARIANT_ARDUINO_101_X_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS NUM_DIGITAL_PINS // 15 digital (including ATN pin) + 6 analog +#define VERSION_BLINK_PIN LED_BUILTIN +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 20) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) // 3, 5, 6, 9 +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) // SDA = 18, SCL = 19 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Teensy 1.0 +#elif defined(__AVR_AT90USB162__) +#define TOTAL_ANALOG_PINS 0 +#define TOTAL_PINS 21 // 21 digital + no analog +#define VERSION_BLINK_PIN 6 +#define PIN_SERIAL1_RX 2 +#define PIN_SERIAL1_TX 3 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) (0) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) (0) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (0) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 2.0 +#elif defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 25 // 11 digital + 12 analog +#define VERSION_BLINK_PIN 11 +#define PIN_SERIAL1_RX 7 +#define PIN_SERIAL1_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 11 && (p) <= 22) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 5 || (p) == 6) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 7 || (p) == 8) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (((p) < 22) ? 21 - (p) : 11) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 3.5 and 3.6 +// reference: https://github.com/PaulStoffregen/cores/blob/master/teensy3/pins_arduino.h +#elif defined(__MK64FX512__) || defined(__MK66FX1M0__) +#define TOTAL_ANALOG_PINS 27 // 3.5 has 27 and 3.6 has 25 +#define TOTAL_PINS 70 // 43 digital + 21 analog-digital + 6 analog (64-69) +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define PIN_SERIAL4_RX 31 +#define PIN_SERIAL4_TX 32 +#define PIN_SERIAL5_RX 34 +#define PIN_SERIAL5_TX 33 +#define PIN_SERIAL6_RX 47 +#define PIN_SERIAL6_TX 48 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 63) +#define IS_PIN_ANALOG(p) (((p) >= 14 && (p) <= 23) || ((p) >= 31 && (p) <= 39) || ((p) >= 49 && (p) <= 50) || ((p) >= 64 && (p) <= 69)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1) || ((p) > 30 && (p) < 35) || ((p) == 47 || (p) == 48)) +#define PIN_TO_DIGITAL(p) (p) +// A0-A9 = D14-D23; A12-A20 = D31-D39; A23-A24 = D49-D50; A10-A11 = D64-D65; A21-A22 = D66-D67; A25-A26 = D68-D69 +#define PIN_TO_ANALOG(p) (((p) <= 23) ? (p) - 14 : (((p) <= 39) ? (p) - 19 : (((p) <= 50) ? (p) - 26 : (((p) <= 65) ? (p) - 55 : (((p) <= 67) ? (p) - 45 : (p) - 43))))) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 3.0, 3.1 and 3.2 +#elif defined(__MK20DX128__) || defined(__MK20DX256__) +#define TOTAL_ANALOG_PINS 14 +#define TOTAL_PINS 38 // 24 digital + 10 analog-digital + 4 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 33) +#define IS_PIN_ANALOG(p) (((p) >= 14 && (p) <= 23) || ((p) >= 34 && (p) <= 38)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (((p) <= 23) ? (p) - 14 : (p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy-LC +#elif defined(__MKL26Z64__) +#define TOTAL_ANALOG_PINS 13 +#define TOTAL_PINS 27 // 27 digital + 13 analog-digital +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 26) +#define IS_PIN_ANALOG(p) ((p) >= 14) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy++ 1.0 and 2.0 +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 46 // 38 digital + 8 analog +#define VERSION_BLINK_PIN 6 +#define PIN_SERIAL1_RX 2 +#define PIN_SERIAL1_TX 3 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 38 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 0 || (p) == 1) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 38) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Leonardo +#elif defined(__AVR_ATmega32U4__) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 30 // 14 digital + 12 analog + 4 SPI (D14-D17 on ISP header) +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 18 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) - 18 +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Intel Galileo Board (gen 1 and 2) and Intel Edison +#elif defined(ARDUINO_LINUX) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// RedBearLab BLE Nano with factory switch settings (S1 - S10) +#elif defined(BLE_NANO) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 15 // 9 digital + 3 analog +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 14) +#define IS_PIN_ANALOG(p) ((p) == 8 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 12 || (p) == 14) //A0~A5 +#define IS_PIN_PWM(p) ((p) == 3 || (p) == 5 || (p) == 6) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) <= 7) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == CS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 8) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Sanguino +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 32 // 24 digital + 8 analog +#define VERSION_BLINK_PIN 0 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Illuminato +#elif defined(__AVR_ATmega645__) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 42 // 36 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 36 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 36) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Pic32 chipKIT FubarinoSD +#elif defined(_BOARD_FUBARINO_SD_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 15 +#define TOTAL_PINS NUM_DIGITAL_PINS // 45, All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) 1 +#define IS_PIN_ANALOG(p) ((p) >= 30 && (p) <= 44) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 1 || (p) == 2) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (14 - (p - 30)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT FubarinoMini +// Note, FubarinoMini analog pin 20 will not function in Firmata as analog input due to limitation in analog mapping +#elif defined(_BOARD_FUBARINO_MINI_) +#define TOTAL_ANALOG_PINS 14 // We have to fake this because of the poor analog pin mapping planning in FubarinoMini +#define TOTAL_PINS NUM_DIGITAL_PINS // 33 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) != 14 && (p) != 15 && (p) != 31 && (p) != 32) +#define IS_PIN_ANALOG(p) ((p) == 0 || ((p) >= 3 && (p) <= 13)) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 25 || (p) == 26) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT UNO32 +#elif defined(_BOARD_UNO_) && defined(__PIC32) // NOTE: no _BOARD_UNO32_ to use +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 +#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT DP32 +#elif defined(_BOARD_DP32_) +#define TOTAL_ANALOG_PINS 15 // Really only has 9, but have to override because of mistake in variant file +#define TOTAL_PINS NUM_DIGITAL_PINS // 19 +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) (((p) != 1) && ((p) != 4) && ((p) != 5) && ((p) != 15) && ((p) != 16)) +#define IS_PIN_ANALOG(p) ((p) >= 6 && (p) <= 14) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT uC32 +#elif defined(_BOARD_UC32_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 +#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT WF32 +#elif defined(_BOARD_WF32_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS +#define TOTAL_PINS NUM_DIGITAL_PINS +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 49) // Accounts for SD and WiFi dedicated pins +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT WiFire +#elif defined(_BOARD_WIFIRE_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 14 +#define TOTAL_PINS NUM_DIGITAL_PINS // 71 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 47) // Accounts for SD and WiFi dedicated pins +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) <= 25 ? ((p) - 14) : (p) - 36) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT MAX32 +#elif defined(_BOARD_MEGA_) && defined(__PIC32) // NOTE: no _BOARD_MAX32_ to use +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 16 +#define TOTAL_PINS NUM_DIGITAL_PINS // 87 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) <= 69) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT Pi +#elif defined(_BOARD_CHIPKIT_PI_) +#define TOTAL_ANALOG_PINS 16 +#define TOTAL_PINS NUM_DIGITAL_PINS // 19 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 3) || (((p) >= 8) && ((p) <= 13)) || (((p) >= 14) && ((p) <= 17))) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 17) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) <= 15 ? (p) - 14 : (p) - 12) +//#define PIN_TO_ANALOG(p) (((p) <= 16) ? ((p) - 14) : ((p) - 16)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + +// Pinoccio Scout +// Note: digital pins 9-16 are usable but not labeled on the board numerically. +// SS=9, MOSI=10, MISO=11, SCK=12, RX1=13, TX1=14, SCL=15, SDA=16 +#elif defined(ARDUINO_PINOCCIO) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS NUM_DIGITAL_PINS // 32 +#define VERSION_BLINK_PIN 23 +#define PIN_SERIAL1_RX 13 +#define PIN_SERIAL1_TX 14 +#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 16)) || (((p) >= 24) && ((p) <= 31)) +#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) <= 31) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == SCL || (p) == SDA) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 13 || (p) == 14) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + +// ESP8266 +// note: boot mode GPIOs 0, 2 and 15 can be used as outputs, GPIOs 6-11 are in use for flash IO +#elif defined(ESP8266) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS A0 + NUM_ANALOG_INPUTS +#define PIN_SERIAL_RX 3 +#define PIN_SERIAL_TX 1 +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 5) || ((p) >= 12 && (p) < A0)) +#define IS_PIN_ANALOG(p) ((p) >= A0 && (p) < A0 + NUM_ANALOG_INPUTS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_INTERRUPT(p) (digitalPinToInterrupt(p) > NOT_AN_INTERRUPT) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL_RX || (p) == PIN_SERIAL_TX) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - A0) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) +#define DEFAULT_PWM_RESOLUTION 10 + +// STM32 based boards +#elif defined(ARDUINO_ARCH_STM32) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS NUM_DIGITAL_PINS +#define TOTAL_PORTS MAX_NB_PORT +#define VERSION_BLINK_PIN LED_BUILTIN +// PIN_SERIALY_RX/TX defined in the variant.h +#define IS_PIN_DIGITAL(p) (digitalPinIsValid(p) && !pinIsSerial(p)) +#define IS_PIN_ANALOG(p) ((p >= A0) && (p < (A0 + TOTAL_ANALOG_PINS)) && !pinIsSerial(p)) +#define IS_PIN_PWM(p) (IS_PIN_DIGITAL(p) && digitalPinHasPWM(p)) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) (IS_PIN_DIGITAL(p) && digitalPinHasI2C(p)) +#define IS_PIN_SPI(p) (IS_PIN_DIGITAL(p) && digitalPinHasSPI(p)) +#define IS_PIN_INTERRUPT(p) (IS_PIN_DIGITAL(p) && (digitalPinToInterrupt(p) > NOT_AN_INTERRUPT))) +#define IS_PIN_SERIAL(p) (digitalPinHasSerial(p) && !pinIsSerial(p)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p-A0) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) +#define DEFAULT_PWM_RESOLUTION PWM_RESOLUTION + +// Adafruit Bluefruit nRF52 boards +#elif defined(ARDUINO_NRF52_ADAFRUIT) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS 32 +#define VERSION_BLINK_PIN LED_BUILTIN +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) == PIN_A0 || (p) == PIN_A1 || (p) == PIN_A2 || (p) == PIN_A3 || \ + (p) == PIN_A4 || (p) == PIN_A5 || (p) == PIN_A6 || (p) == PIN_A7) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == PIN_WIRE_SDA || (p) == PIN_WIRE_SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p)== MOSI || (p) == MISO || (p == SCK)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ( ((p) == PIN_A0) ? 0 : ((p) == PIN_A1) ? 1 : ((p) == PIN_A2) ? 2 : ((p) == PIN_A3) ? 3 : \ + ((p) == PIN_A4) ? 4 : ((p) == PIN_A5) ? 5 : ((p) == PIN_A6) ? 6 : ((p) == PIN_A7) ? 7 : (127)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + +// anything else +#else +#error "Please edit Boards.h with a hardware abstraction for this board" +#endif + +// as long this is not defined for all boards: +#ifndef IS_PIN_SPI +#define IS_PIN_SPI(p) 0 +#endif + +#ifndef IS_PIN_SERIAL +#define IS_PIN_SERIAL(p) 0 +#endif + +#ifndef DEFAULT_PWM_RESOLUTION +#define DEFAULT_PWM_RESOLUTION 8 +#endif + +/*============================================================================== + * readPort() - Read an 8 bit port + *============================================================================*/ + +static inline unsigned char readPort(byte, byte) __attribute__((always_inline, unused)); +static inline unsigned char readPort(byte port, byte bitmask) +{ +#if defined(ARDUINO_PINOUT_OPTIMIZE) + if (port == 0) return (PIND & 0xFC) & bitmask; // ignore Rx/Tx 0/1 + if (port == 1) return ((PINB & 0x3F) | ((PINC & 0x03) << 6)) & bitmask; + if (port == 2) return ((PINC & 0x3C) >> 2) & bitmask; + return 0; +#else + unsigned char out = 0, pin = port * 8; + if (IS_PIN_DIGITAL(pin + 0) && (bitmask & 0x01) && digitalRead(PIN_TO_DIGITAL(pin + 0))) out |= 0x01; + if (IS_PIN_DIGITAL(pin + 1) && (bitmask & 0x02) && digitalRead(PIN_TO_DIGITAL(pin + 1))) out |= 0x02; + if (IS_PIN_DIGITAL(pin + 2) && (bitmask & 0x04) && digitalRead(PIN_TO_DIGITAL(pin + 2))) out |= 0x04; + if (IS_PIN_DIGITAL(pin + 3) && (bitmask & 0x08) && digitalRead(PIN_TO_DIGITAL(pin + 3))) out |= 0x08; + if (IS_PIN_DIGITAL(pin + 4) && (bitmask & 0x10) && digitalRead(PIN_TO_DIGITAL(pin + 4))) out |= 0x10; + if (IS_PIN_DIGITAL(pin + 5) && (bitmask & 0x20) && digitalRead(PIN_TO_DIGITAL(pin + 5))) out |= 0x20; + if (IS_PIN_DIGITAL(pin + 6) && (bitmask & 0x40) && digitalRead(PIN_TO_DIGITAL(pin + 6))) out |= 0x40; + if (IS_PIN_DIGITAL(pin + 7) && (bitmask & 0x80) && digitalRead(PIN_TO_DIGITAL(pin + 7))) out |= 0x80; + return out; +#endif +} + +/*============================================================================== + * writePort() - Write an 8 bit port, only touch pins specified by a bitmask + *============================================================================*/ + +static inline unsigned char writePort(byte, byte, byte) __attribute__((always_inline, unused)); +static inline unsigned char writePort(byte port, byte value, byte bitmask) +{ +#if defined(ARDUINO_PINOUT_OPTIMIZE) + if (port == 0) { + bitmask = bitmask & 0xFC; // do not touch Tx & Rx pins + byte valD = value & bitmask; + byte maskD = ~bitmask; + cli(); + PORTD = (PORTD & maskD) | valD; + sei(); + } else if (port == 1) { + byte valB = (value & bitmask) & 0x3F; + byte valC = (value & bitmask) >> 6; + byte maskB = ~(bitmask & 0x3F); + byte maskC = ~((bitmask & 0xC0) >> 6); + cli(); + PORTB = (PORTB & maskB) | valB; + PORTC = (PORTC & maskC) | valC; + sei(); + } else if (port == 2) { + bitmask = bitmask & 0x0F; + byte valC = (value & bitmask) << 2; + byte maskC = ~(bitmask << 2); + cli(); + PORTC = (PORTC & maskC) | valC; + sei(); + } + return 1; +#else + byte pin = port * 8; + if ((bitmask & 0x01)) digitalWrite(PIN_TO_DIGITAL(pin + 0), (value & 0x01)); + if ((bitmask & 0x02)) digitalWrite(PIN_TO_DIGITAL(pin + 1), (value & 0x02)); + if ((bitmask & 0x04)) digitalWrite(PIN_TO_DIGITAL(pin + 2), (value & 0x04)); + if ((bitmask & 0x08)) digitalWrite(PIN_TO_DIGITAL(pin + 3), (value & 0x08)); + if ((bitmask & 0x10)) digitalWrite(PIN_TO_DIGITAL(pin + 4), (value & 0x10)); + if ((bitmask & 0x20)) digitalWrite(PIN_TO_DIGITAL(pin + 5), (value & 0x20)); + if ((bitmask & 0x40)) digitalWrite(PIN_TO_DIGITAL(pin + 6), (value & 0x40)); + if ((bitmask & 0x80)) digitalWrite(PIN_TO_DIGITAL(pin + 7), (value & 0x80)); + return 1; +#endif +} + + + + +#ifndef TOTAL_PORTS +#define TOTAL_PORTS ((TOTAL_PINS + 7) / 8) +#endif + + +#endif /* Firmata_Boards_h */ diff --git a/libraries/Firmata/Firmata.cpp b/libraries/Firmata/Firmata.cpp new file mode 100644 index 0000000..ee01f8f --- /dev/null +++ b/libraries/Firmata/Firmata.cpp @@ -0,0 +1,554 @@ +/* + Firmata.cpp - Firmata library v2.5.8 - 2018-04-15 + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +//****************************************************************************** +//* Includes +//****************************************************************************** + +#include "Firmata.h" +#include "HardwareSerial.h" + +#include +#include + +using namespace firmata; + +//****************************************************************************** +//* Static Members +//****************************************************************************** +// make one instance for the user to use +FirmataClass Firmata; + +/* callback functions */ +callbackFunction FirmataClass::currentAnalogCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentDigitalCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentPinModeCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentPinValueCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentReportAnalogCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentReportDigitalCallback = (callbackFunction)NULL; +stringCallbackFunction FirmataClass::currentStringCallback = (stringCallbackFunction)NULL; +sysexCallbackFunction FirmataClass::currentSysexCallback = (sysexCallbackFunction)NULL; +systemCallbackFunction FirmataClass::currentSystemResetCallback = (systemCallbackFunction)NULL; + +//****************************************************************************** +//* Support Functions +//****************************************************************************** + +/** + * Split a 16-bit byte into two 7-bit values and write each value. + * @param value The 16-bit value to be split and written separately. + */ +void FirmataClass::sendValueAsTwo7bitBytes(int value) +{ + marshaller.encodeByteStream(sizeof(value), reinterpret_cast(&value), sizeof(value)); +} + +/** + * A helper method to write the beginning of a Sysex message transmission. + */ +void FirmataClass::startSysex(void) +{ + FirmataStream->write(START_SYSEX); +} + +/** + * A helper method to write the end of a Sysex message transmission. + */ +void FirmataClass::endSysex(void) +{ + FirmataStream->write(END_SYSEX); +} + +//****************************************************************************** +//* Constructors +//****************************************************************************** + +/** + * The Firmata class. + * An instance named "Firmata" is created automatically for the user. + */ +FirmataClass::FirmataClass() +: + parser(FirmataParser(parserBuffer, MAX_DATA_BYTES)) +{ + firmwareVersionCount = 0; + firmwareVersionVector = 0; + blinkVersionDisabled = false; + + // Establish callback translation to parser callbacks + parser.attach(ANALOG_MESSAGE, (FirmataParser::callbackFunction)staticAnalogCallback, (void *)NULL); + parser.attach(DIGITAL_MESSAGE, (FirmataParser::callbackFunction)staticDigitalCallback, (void *)NULL); + parser.attach(REPORT_ANALOG, (FirmataParser::callbackFunction)staticReportAnalogCallback, (void *)NULL); + parser.attach(REPORT_DIGITAL, (FirmataParser::callbackFunction)staticReportDigitalCallback, (void *)NULL); + parser.attach(SET_PIN_MODE, (FirmataParser::callbackFunction)staticPinModeCallback, (void *)NULL); + parser.attach(SET_DIGITAL_PIN_VALUE, (FirmataParser::callbackFunction)staticPinValueCallback, (void *)NULL); + parser.attach(STRING_DATA, (FirmataParser::stringCallbackFunction)staticStringCallback, (void *)NULL); + parser.attach(START_SYSEX, (FirmataParser::sysexCallbackFunction)staticSysexCallback, (void *)NULL); + parser.attach(REPORT_FIRMWARE, (FirmataParser::versionCallbackFunction)staticReportFirmwareCallback, this); + parser.attach(REPORT_VERSION, (FirmataParser::systemCallbackFunction)staticReportVersionCallback, this); + parser.attach(SYSTEM_RESET, (FirmataParser::systemCallbackFunction)staticSystemResetCallback, (void *)NULL); +} + +//****************************************************************************** +//* Public Methods +//****************************************************************************** + +/** + * Initialize the default Serial transport at the default baud of 57600. + */ +void FirmataClass::begin(void) +{ + begin(57600); +} + +/** + * Initialize the default Serial transport and override the default baud. + * Sends the protocol version to the host application followed by the firmware version and name. + * blinkVersion is also called. To skip the call to blinkVersion, call Firmata.disableBlinkVersion() + * before calling Firmata.begin(baud). + * @param speed The baud to use. 57600 baud is the default value. + */ +void FirmataClass::begin(long speed) +{ + Serial.begin(speed); + blinkVersion(); + begin(Serial); +} + +/** + * Reassign the Firmata stream transport. + * @param s A reference to the Stream transport object. This can be any type of + * transport that implements the Stream interface. Some examples include Ethernet, WiFi + * and other UARTs on the board (Serial1, Serial2, etc). + */ +void FirmataClass::begin(Stream &s) +{ + FirmataStream = &s; + marshaller.begin(s); + // do not call blinkVersion() here because some hardware such as the + // Ethernet shield use pin 13 + printVersion(); // send the protocol version + printFirmwareVersion(); // send the firmware name and version +} + +/** + * Send the Firmata protocol version to the Firmata host application. + */ +void FirmataClass::printVersion(void) +{ + marshaller.sendVersion(FIRMATA_PROTOCOL_MAJOR_VERSION, FIRMATA_PROTOCOL_MINOR_VERSION); +} + +/** + * Blink the Firmata protocol version to the onboard LEDs (if the board has an onboard LED). + * If VERSION_BLINK_PIN is not defined in Boards.h for a particular board, then this method + * does nothing. + * The first series of flashes indicates the firmware major version (2 flashes = 2). + * The second series of flashes indicates the firmware minor version (5 flashes = 5). + */ +void FirmataClass::blinkVersion(void) +{ +#if defined(VERSION_BLINK_PIN) + if (blinkVersionDisabled) return; + // flash the pin with the protocol version + pinMode(VERSION_BLINK_PIN, OUTPUT); + strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MAJOR_VERSION, 40, 210); + delay(250); + strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MINOR_VERSION, 40, 210); + delay(125); +#endif +} + +/** + * Provides a means to disable the version blink sequence on the onboard LED, trimming startup + * time by a couple of seconds. + * Call this before Firmata.begin(). It only applies when using the default Serial transport. + */ +void FirmataClass::disableBlinkVersion() +{ + blinkVersionDisabled = true; +} + +/** + * Sends the firmware name and version to the Firmata host application. The major and minor version + * numbers are the first 2 bytes in the message. The following bytes are the characters of the + * firmware name. + */ +void FirmataClass::printFirmwareVersion(void) +{ + if (firmwareVersionCount) { // make sure that the name has been set before reporting + marshaller.sendFirmwareVersion(static_cast(firmwareVersionVector[0]), static_cast(firmwareVersionVector[1]), (firmwareVersionCount - 2), reinterpret_cast(&firmwareVersionVector[2])); + } +} + +/** + * Sets the name and version of the firmware. This is not the same version as the Firmata protocol + * (although at times the firmware version and protocol version may be the same number). + * @param name A pointer to the name char array + * @param major The major version number + * @param minor The minor version number + */ +void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor) +{ + const char *firmwareName; + const char *extension; + + // parse out ".cpp" and "applet/" that comes from using __FILE__ + extension = strstr(name, ".cpp"); + firmwareName = strrchr(name, '/'); + + if (!firmwareName) { + // windows + firmwareName = strrchr(name, '\\'); + } + if (!firmwareName) { + // user passed firmware name + firmwareName = name; + } else { + firmwareName ++; + } + + if (!extension) { + firmwareVersionCount = strlen(firmwareName) + 2; + } else { + firmwareVersionCount = extension - firmwareName + 2; + } + + // in case anyone calls setFirmwareNameAndVersion more than once + free(firmwareVersionVector); + + firmwareVersionVector = (byte *) malloc(firmwareVersionCount + 1); + firmwareVersionVector[firmwareVersionCount] = 0; + firmwareVersionVector[0] = major; + firmwareVersionVector[1] = minor; + strncpy((char *)firmwareVersionVector + 2, firmwareName, firmwareVersionCount - 2); +} + +//------------------------------------------------------------------------------ +// Serial Receive Handling + +/** + * A wrapper for Stream::available() + * @return The number of bytes remaining in the input stream buffer. + */ +int FirmataClass::available(void) +{ + return FirmataStream->available(); +} + +/** + * Read a single int from the input stream. If the value is not = -1, pass it on to parse(byte) + */ +void FirmataClass::processInput(void) +{ + int inputData = FirmataStream->read(); // this is 'int' to handle -1 when no data + if (inputData != -1) { + parser.parse(inputData); + } +} + +/** + * Parse data from the input stream. + * @param inputData A single byte to be added to the parser. + */ +void FirmataClass::parse(byte inputData) +{ + parser.parse(inputData); +} + +/** + * @return Returns true if the parser is actively parsing data. + */ +boolean FirmataClass::isParsingMessage(void) +{ + return parser.isParsingMessage(); +} + +//------------------------------------------------------------------------------ +// Output Stream Handling + +/** + * Send an analog message to the Firmata host application. The range of pins is limited to [0..15] + * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin to send the value of (limited to pins 0 - 15). + * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc). + * The maximum value is 14-bits (16384). + */ +void FirmataClass::sendAnalog(byte pin, int value) +{ + marshaller.sendAnalog(pin, value); +} + +/* (intentionally left out asterix here) + * STUB - NOT IMPLEMENTED + * Send a single digital pin value to the Firmata host application. + * @param pin The digital pin to send the value of. + * @param value The value of the pin. + */ +void FirmataClass::sendDigital(byte pin, int value) +{ + (void)pin; + (void)value; + /* TODO add single pin digital messages to the protocol, this needs to + * track the last digital data sent so that it can be sure to change just + * one bit in the packet. This is complicated by the fact that the + * numbering of the pins will probably differ on Arduino, Wiring, and + * other boards. + */ + + // TODO: the digital message should not be sent on the serial port every + // time sendDigital() is called. Instead, it should add it to an int + // which will be sent on a schedule. If a pin changes more than once + // before the digital message is sent on the serial port, it should send a + // digital message for each change. + + // if(value == 0) + // sendDigitalPortPair(); +} + + +/** + * Send an 8-bit port in a single digital message (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number to send. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + * @param portData The value of the port. The value of each pin in the port is represented by a bit. + */ +void FirmataClass::sendDigitalPort(byte portNumber, int portData) +{ + marshaller.sendDigitalPort(portNumber, portData); +} + +/** + * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes + * (this is not always the case so this function is not always used to send sysex messages). + * @param command The sysex command byte. + * @param bytec The number of data bytes in the message (excludes start, command and end bytes). + * @param bytev A pointer to the array of data bytes to send in the message. + */ +void FirmataClass::sendSysex(byte command, byte bytec, byte *bytev) +{ + marshaller.sendSysex(command, bytec, bytev); +} + +/** + * Send a string to the Firmata host application. + * @param command Must be STRING_DATA + * @param string A pointer to the char string + */ +void FirmataClass::sendString(byte command, const char *string) +{ + if (command == STRING_DATA) { + marshaller.sendString(string); + } +} + +/** + * Send a string to the Firmata host application. + * @param string A pointer to the char string + */ +void FirmataClass::sendString(const char *string) +{ + marshaller.sendString(string); +} + +/** + * A wrapper for Stream::available(). + * Write a single byte to the output stream. + * @param c The byte to be written. + */ +void FirmataClass::write(byte c) +{ + FirmataStream->write(c); +} + +/** + * Attach a generic sysex callback function to a command (options are: ANALOG_MESSAGE, + * DIGITAL_MESSAGE, REPORT_ANALOG, REPORT DIGITAL, SET_PIN_MODE and SET_DIGITAL_PIN_VALUE). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + */ +void FirmataClass::attach(uint8_t command, ::callbackFunction newFunction) +{ + switch (command) { + case ANALOG_MESSAGE: + currentAnalogCallback = newFunction; + break; + case DIGITAL_MESSAGE: + currentDigitalCallback = newFunction; + break; + case REPORT_ANALOG: + currentReportAnalogCallback = newFunction; + break; + case REPORT_DIGITAL: + currentReportDigitalCallback = newFunction; + break; + case SET_PIN_MODE: + currentPinModeCallback = newFunction; + break; + case SET_DIGITAL_PIN_VALUE: + currentPinValueCallback = newFunction; + break; + } +} + +/** + * Attach a callback function for the SYSTEM_RESET command. + * @param command Must be set to SYSTEM_RESET or it will be ignored. + * @param newFunction A reference to the system reset callback function to attach. + */ +void FirmataClass::attach(uint8_t command, systemCallbackFunction newFunction) +{ + switch (command) { + case SYSTEM_RESET: + currentSystemResetCallback = newFunction; + break; + } +} + +/** + * Attach a callback function for the STRING_DATA command. + * @param command Must be set to STRING_DATA or it will be ignored. + * @param newFunction A reference to the string callback function to attach. + */ +void FirmataClass::attach(uint8_t command, stringCallbackFunction newFunction) +{ + switch (command) { + case STRING_DATA: + currentStringCallback = newFunction; + break; + } +} + +/** + * Attach a generic sysex callback function to sysex command. + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the sysex callback function to attach. + */ +void FirmataClass::attach(uint8_t command, sysexCallbackFunction newFunction) +{ + (void)command; + currentSysexCallback = newFunction; +} + +/** + * Detach a callback function for a specified command (such as SYSTEM_RESET, STRING_DATA, + * ANALOG_MESSAGE, DIGITAL_MESSAGE, etc). + * @param command The ID of the command to detatch the callback function from. + */ +void FirmataClass::detach(uint8_t command) +{ + switch (command) { + case SYSTEM_RESET: + attach(command, (systemCallbackFunction)NULL); + break; + case STRING_DATA: + attach(command, (stringCallbackFunction)NULL); + break; + case START_SYSEX: + attach(command, (sysexCallbackFunction)NULL); + break; + default: + attach(command, (callbackFunction)NULL); + break; + } +} + +/** + * @param pin The pin to get the configuration of. + * @return The configuration of the specified pin. + */ +byte FirmataClass::getPinMode(byte pin) +{ + return pinConfig[pin]; +} + +/** + * Set the pin mode/configuration. The pin configuration (or mode) in Firmata represents the + * current function of the pin. Examples are digital input or output, analog input, pwm, i2c, + * serial (uart), etc. + * @param pin The pin to configure. + * @param config The configuration value for the specified pin. + */ +void FirmataClass::setPinMode(byte pin, byte config) +{ + if (pinConfig[pin] == PIN_MODE_IGNORE) + return; + + pinConfig[pin] = config; +} + +/** + * @param pin The pin to get the state of. + * @return The state of the specified pin. + */ +int FirmataClass::getPinState(byte pin) +{ + return pinState[pin]; +} + +/** + * Set the pin state. The pin state of an output pin is the pin value. The state of an + * input pin is 0, unless the pin has it's internal pull up resistor enabled, then the value is 1. + * @param pin The pin to set the state of + * @param state Set the state of the specified pin + */ +void FirmataClass::setPinState(byte pin, int state) +{ + pinState[pin] = state; +} + +// sysex callbacks +/* + * this is too complicated for analogReceive, but maybe for Sysex? + void FirmataClass::attachSysex(sysexFunction newFunction) + { + byte i; + byte tmpCount = analogReceiveFunctionCount; + analogReceiveFunction* tmpArray = analogReceiveFunctionArray; + analogReceiveFunctionCount++; + analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction)); + for(i = 0; i < tmpCount; i++) { + analogReceiveFunctionArray[i] = tmpArray[i]; + } + analogReceiveFunctionArray[tmpCount] = newFunction; + free(tmpArray); + } +*/ + +//****************************************************************************** +//* Private Methods +//****************************************************************************** + +/** + * Flashing the pin for the version number + * @private + * @param pin The pin the LED is attached to. + * @param count The number of times to flash the LED. + * @param onInterval The number of milliseconds for the LED to be ON during each interval. + * @param offInterval The number of milliseconds for the LED to be OFF during each interval. + */ +void FirmataClass::strobeBlinkPin(byte pin, int count, int onInterval, int offInterval) +{ + byte i; + for (i = 0; i < count; i++) { + delay(offInterval); + digitalWrite(pin, HIGH); + delay(onInterval); + digitalWrite(pin, LOW); + } +} + diff --git a/libraries/Firmata/Firmata.h b/libraries/Firmata/Firmata.h new file mode 100644 index 0000000..fa0fa6c --- /dev/null +++ b/libraries/Firmata/Firmata.h @@ -0,0 +1,180 @@ +/* + Firmata.h - Firmata library v2.5.8 - 2018-04-15 + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef Firmata_h +#define Firmata_h + +#include "Boards.h" /* Hardware Abstraction Layer + Wiring/Arduino */ +#include "FirmataDefines.h" +#include "FirmataMarshaller.h" +#include "FirmataParser.h" + +/* DEPRECATED as of Firmata v2.5.1. As of 2.5.1 there are separate version numbers for + * the protocol version and the firmware version. + */ +#define FIRMATA_MAJOR_VERSION 2 // same as FIRMATA_PROTOCOL_MAJOR_VERSION +#define FIRMATA_MINOR_VERSION 5 // same as FIRMATA_PROTOCOL_MINOR_VERSION +#define FIRMATA_BUGFIX_VERSION 1 // same as FIRMATA_PROTOCOL_BUGFIX_VERSION + +// extended command set using sysex (0-127/0x00-0x7F) +/* 0x00-0x0F reserved for user-defined commands */ +// these are DEPRECATED to make the naming more consistent +#define FIRMATA_STRING 0x71 // same as STRING_DATA +#define SYSEX_I2C_REQUEST 0x76 // same as I2C_REQUEST +#define SYSEX_I2C_REPLY 0x77 // same as I2C_REPLY +#define SYSEX_SAMPLING_INTERVAL 0x7A // same as SAMPLING_INTERVAL + +// pin modes +//#define INPUT 0x00 // defined in Arduino.h +//#define OUTPUT 0x01 // defined in Arduino.h +// DEPRECATED as of Firmata v2.5 +#define ANALOG 0x02 // same as PIN_MODE_ANALOG +#define PWM 0x03 // same as PIN_MODE_PWM +#define SERVO 0x04 // same as PIN_MODE_SERVO +#define SHIFT 0x05 // same as PIN_MODE_SHIFT +#define I2C 0x06 // same as PIN_MODE_I2C +#define ONEWIRE 0x07 // same as PIN_MODE_ONEWIRE +#define STEPPER 0x08 // same as PIN_MODE_STEPPER +#define ENCODER 0x09 // same as PIN_MODE_ENCODER +#define IGNORE 0x7F // same as PIN_MODE_IGNORE + +namespace firmata { + +// TODO make it a subclass of a generic Serial/Stream base class +class FirmataClass +{ + public: + typedef void (*callbackFunction)(uint8_t, int); + typedef void (*systemCallbackFunction)(void); + typedef void (*stringCallbackFunction)(char *); + typedef void (*sysexCallbackFunction)(uint8_t command, uint8_t argc, uint8_t *argv); + + FirmataClass(); + + /* Arduino constructors */ + void begin(); + void begin(long); + void begin(Stream &s); + + /* querying functions */ + void printVersion(void); + void blinkVersion(void); + void printFirmwareVersion(void); + + //void setFirmwareVersion(byte major, byte minor); // see macro below + void setFirmwareNameAndVersion(const char *name, byte major, byte minor); + void disableBlinkVersion(); + + /* serial receive handling */ + int available(void); + void processInput(void); + void parse(unsigned char value); + boolean isParsingMessage(void); + + /* serial send handling */ + void sendAnalog(byte pin, int value); + void sendDigital(byte pin, int value); // TODO implement this + void sendDigitalPort(byte portNumber, int portData); + void sendString(const char *string); + void sendString(byte command, const char *string); + void sendSysex(byte command, byte bytec, byte *bytev); + void write(byte c); + + /* attach & detach callback functions to messages */ + void attach(uint8_t command, callbackFunction newFunction); + void attach(uint8_t command, systemCallbackFunction newFunction); + void attach(uint8_t command, stringCallbackFunction newFunction); + void attach(uint8_t command, sysexCallbackFunction newFunction); + void detach(uint8_t command); + + /* access pin state and config */ + byte getPinMode(byte pin); + void setPinMode(byte pin, byte config); + + /* access pin state */ + int getPinState(byte pin); + void setPinState(byte pin, int state); + + /* utility methods */ + void sendValueAsTwo7bitBytes(int value); + void startSysex(void); + void endSysex(void); + + private: + uint8_t parserBuffer[MAX_DATA_BYTES]; + FirmataMarshaller marshaller; + FirmataParser parser; + Stream *FirmataStream; + + /* firmware name and version */ + byte firmwareVersionCount; + byte *firmwareVersionVector; + + /* pin configuration */ + byte pinConfig[TOTAL_PINS]; + int pinState[TOTAL_PINS]; + + boolean blinkVersionDisabled; + + /* private methods ------------------------------ */ + void strobeBlinkPin(byte pin, int count, int onInterval, int offInterval); + friend void FirmataMarshaller::encodeByteStream (size_t bytec, uint8_t * bytev, size_t max_bytes = 0) const; + + /* callback functions */ + static callbackFunction currentAnalogCallback; + static callbackFunction currentDigitalCallback; + static callbackFunction currentPinModeCallback; + static callbackFunction currentPinValueCallback; + static callbackFunction currentReportAnalogCallback; + static callbackFunction currentReportDigitalCallback; + static stringCallbackFunction currentStringCallback; + static sysexCallbackFunction currentSysexCallback; + static systemCallbackFunction currentSystemResetCallback; + + /* static callbacks */ + inline static void staticAnalogCallback (void *, uint8_t command, uint16_t value) { if ( currentAnalogCallback ) { currentAnalogCallback(command,(int)value); } } + inline static void staticDigitalCallback (void *, uint8_t command, uint16_t value) { if ( currentDigitalCallback ) { currentDigitalCallback(command, (int)value); } } + inline static void staticPinModeCallback (void *, uint8_t command, uint16_t value) { if ( currentPinModeCallback ) { currentPinModeCallback(command, (int)value); } } + inline static void staticPinValueCallback (void *, uint8_t command, uint16_t value) { if ( currentPinValueCallback ) { currentPinValueCallback(command, (int)value); } } + inline static void staticReportAnalogCallback (void *, uint8_t command, uint16_t value) { if ( currentReportAnalogCallback ) { currentReportAnalogCallback(command, (int)value); } } + inline static void staticReportDigitalCallback (void *, uint8_t command, uint16_t value) { if ( currentReportDigitalCallback ) { currentReportDigitalCallback(command, (int)value); } } + inline static void staticStringCallback (void *, const char * c_str) { if ( currentStringCallback ) { currentStringCallback((char *)c_str); } } + inline static void staticSysexCallback (void *, uint8_t command, size_t argc, uint8_t *argv) { if ( currentSysexCallback ) { currentSysexCallback(command, (uint8_t)argc, argv); } } + inline static void staticReportFirmwareCallback (void * context, size_t, size_t, const char *) { if ( context ) { ((FirmataClass *)context)->printFirmwareVersion(); } } + inline static void staticReportVersionCallback (void * context) { if ( context ) { ((FirmataClass *)context)->printVersion(); } } + inline static void staticSystemResetCallback (void *) { if ( currentSystemResetCallback ) { currentSystemResetCallback(); } } +}; + +} // namespace firmata + +extern "C" { + // callback function types + typedef firmata::FirmataClass::callbackFunction callbackFunction; + typedef firmata::FirmataClass::systemCallbackFunction systemCallbackFunction; + typedef firmata::FirmataClass::stringCallbackFunction stringCallbackFunction; + typedef firmata::FirmataClass::sysexCallbackFunction sysexCallbackFunction; +} + +extern firmata::FirmataClass Firmata; + +/*============================================================================== + * MACROS + *============================================================================*/ + +/* shortcut for setFirmwareNameAndVersion() that uses __FILE__ to set the + * firmware name. It needs to be a macro so that __FILE__ is included in the + * firmware source file rather than the library source file. + */ +#define setFirmwareVersion(x, y) setFirmwareNameAndVersion(__FILE__, x, y) + +#endif /* Firmata_h */ diff --git a/libraries/Firmata/FirmataConstants.h b/libraries/Firmata/FirmataConstants.h new file mode 100644 index 0000000..dee8407 --- /dev/null +++ b/libraries/Firmata/FirmataConstants.h @@ -0,0 +1,97 @@ +/* + FirmataConstants.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataConstants_h +#define FirmataConstants_h + +namespace firmata { +/* Version numbers for the Firmata library. + * The firmware version will not always equal the protocol version going forward. + * Query using the REPORT_FIRMWARE message. + */ +static const int FIRMWARE_MAJOR_VERSION = 2; +static const int FIRMWARE_MINOR_VERSION = 5; +static const int FIRMWARE_BUGFIX_VERSION = 7; + +/* Version numbers for the protocol. The protocol is still changing, so these + * version numbers are important. + * Query using the REPORT_VERSION message. + */ +static const int PROTOCOL_MAJOR_VERSION = 2; // for non-compatible changes +static const int PROTOCOL_MINOR_VERSION = 5; // for backwards compatible changes +static const int PROTOCOL_BUGFIX_VERSION = 1; // for bugfix releases + +static const int MAX_DATA_BYTES = 64; // max number of data bytes in incoming messages + +// message command bytes (128-255/0x80-0xFF) + +static const int DIGITAL_MESSAGE = 0x90; // send data for a digital port (collection of 8 pins) +static const int ANALOG_MESSAGE = 0xE0; // send data for an analog pin (or PWM) +static const int REPORT_ANALOG = 0xC0; // enable analog input by pin # +static const int REPORT_DIGITAL = 0xD0; // enable digital input by port pair +// +static const int SET_PIN_MODE = 0xF4; // set a pin to INPUT/OUTPUT/PWM/etc +static const int SET_DIGITAL_PIN_VALUE = 0xF5; // set value of an individual digital pin +// +static const int REPORT_VERSION = 0xF9; // report protocol version +static const int SYSTEM_RESET = 0xFF; // reset from MIDI +// +static const int START_SYSEX = 0xF0; // start a MIDI Sysex message +static const int END_SYSEX = 0xF7; // end a MIDI Sysex message + +// extended command set using sysex (0-127/0x00-0x7F) +/* 0x00-0x0F reserved for user-defined commands */ + +static const int SERIAL_DATA = 0x60; // communicate with serial devices, including other boards +static const int ENCODER_DATA = 0x61; // reply with encoders current positions +static const int SERVO_CONFIG = 0x70; // set max angle, minPulse, maxPulse, freq +static const int STRING_DATA = 0x71; // a string message with 14-bits per char +static const int STEPPER_DATA = 0x72; // control a stepper motor +static const int ONEWIRE_DATA = 0x73; // send an OneWire read/write/reset/select/skip/search request +static const int SHIFT_DATA = 0x75; // a bitstream to/from a shift register +static const int I2C_REQUEST = 0x76; // send an I2C read/write request +static const int I2C_REPLY = 0x77; // a reply to an I2C read request +static const int I2C_CONFIG = 0x78; // config I2C settings such as delay times and power pins +static const int REPORT_FIRMWARE = 0x79; // report name and version of the firmware +static const int EXTENDED_ANALOG = 0x6F; // analog write (PWM, Servo, etc) to any pin +static const int PIN_STATE_QUERY = 0x6D; // ask for a pin's current mode and value +static const int PIN_STATE_RESPONSE = 0x6E; // reply with pin's current mode and value +static const int CAPABILITY_QUERY = 0x6B; // ask for supported modes and resolution of all pins +static const int CAPABILITY_RESPONSE = 0x6C; // reply with supported modes and resolution +static const int ANALOG_MAPPING_QUERY = 0x69; // ask for mapping of analog to pin numbers +static const int ANALOG_MAPPING_RESPONSE = 0x6A; // reply with mapping info +static const int SAMPLING_INTERVAL = 0x7A; // set the poll rate of the main loop +static const int SCHEDULER_DATA = 0x7B; // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler +static const int SYSEX_NON_REALTIME = 0x7E; // MIDI Reserved for non-realtime messages +static const int SYSEX_REALTIME = 0x7F; // MIDI Reserved for realtime messages + +// pin modes +static const int PIN_MODE_INPUT = 0x00; // same as INPUT defined in Arduino.h +static const int PIN_MODE_OUTPUT = 0x01; // same as OUTPUT defined in Arduino.h +static const int PIN_MODE_ANALOG = 0x02; // analog pin in analogInput mode +static const int PIN_MODE_PWM = 0x03; // digital pin in PWM output mode +static const int PIN_MODE_SERVO = 0x04; // digital pin in Servo output mode +static const int PIN_MODE_SHIFT = 0x05; // shiftIn/shiftOut mode +static const int PIN_MODE_I2C = 0x06; // pin included in I2C setup +static const int PIN_MODE_ONEWIRE = 0x07; // pin configured for 1-wire +static const int PIN_MODE_STEPPER = 0x08; // pin configured for stepper motor +static const int PIN_MODE_ENCODER = 0x09; // pin configured for rotary encoders +static const int PIN_MODE_SERIAL = 0x0A; // pin configured for serial communication +static const int PIN_MODE_PULLUP = 0x0B; // enable internal pull-up resistor for pin +static const int PIN_MODE_IGNORE = 0x7F; // pin configured to be ignored by digitalWrite and capabilityResponse + +static const int TOTAL_PIN_MODES = 13; + +} // namespace firmata + +#endif // FirmataConstants_h diff --git a/libraries/Firmata/FirmataDefines.h b/libraries/Firmata/FirmataDefines.h new file mode 100644 index 0000000..fb95fb5 --- /dev/null +++ b/libraries/Firmata/FirmataDefines.h @@ -0,0 +1,283 @@ +/* + FirmataDefines.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataDefines_h +#define FirmataDefines_h + +#include "FirmataConstants.h" + +/* Version numbers for the Firmata library. + * The firmware version will not always equal the protocol version going forward. + * Query using the REPORT_FIRMWARE message. + */ +#define FIRMATA_FIRMWARE_MAJOR_VERSION firmata::FIRMWARE_MAJOR_VERSION +#define FIRMATA_FIRMWARE_MINOR_VERSION firmata::FIRMWARE_MINOR_VERSION +#define FIRMATA_FIRMWARE_BUGFIX_VERSION firmata::FIRMWARE_BUGFIX_VERSION + +/* Version numbers for the protocol. The protocol is still changing, so these + * version numbers are important. + * Query using the REPORT_VERSION message. + */ +#define FIRMATA_PROTOCOL_MAJOR_VERSION firmata::PROTOCOL_MAJOR_VERSION // for non-compatible changes +#define FIRMATA_PROTOCOL_MINOR_VERSION firmata::PROTOCOL_MINOR_VERSION // for backwards compatible changes +#define FIRMATA_PROTOCOL_BUGFIX_VERSION firmata::PROTOCOL_BUGFIX_VERSION // for bugfix releases + +#ifdef MAX_DATA_BYTES +#undef MAX_DATA_BYTES +#endif +#define MAX_DATA_BYTES firmata::MAX_DATA_BYTES // max number of data bytes in incoming messages + +// message command bytes (128-255/0x80-0xFF) + +#ifdef DIGITAL_MESSAGE +#undef DIGITAL_MESSAGE +#endif +#define DIGITAL_MESSAGE firmata::DIGITAL_MESSAGE // send data for a digital port (collection of 8 pins) + +#ifdef ANALOG_MESSAGE +#undef ANALOG_MESSAGE +#endif +#define ANALOG_MESSAGE firmata::ANALOG_MESSAGE // send data for an analog pin (or PWM) + +#ifdef REPORT_ANALOG +#undef REPORT_ANALOG +#endif +#define REPORT_ANALOG firmata::REPORT_ANALOG // enable analog input by pin # + +#ifdef REPORT_DIGITAL +#undef REPORT_DIGITAL +#endif +#define REPORT_DIGITAL firmata::REPORT_DIGITAL // enable digital input by port pair + +// + +#ifdef SET_PIN_MODE +#undef SET_PIN_MODE +#endif +#define SET_PIN_MODE firmata::SET_PIN_MODE // set a pin to INPUT/OUTPUT/PWM/etc + +#ifdef SET_DIGITAL_PIN_VALUE +#undef SET_DIGITAL_PIN_VALUE +#endif +#define SET_DIGITAL_PIN_VALUE firmata::SET_DIGITAL_PIN_VALUE // set value of an individual digital pin + +// + +#ifdef REPORT_VERSION +#undef REPORT_VERSION +#endif +#define REPORT_VERSION firmata::REPORT_VERSION // report protocol version + +#ifdef SYSTEM_RESET +#undef SYSTEM_RESET +#endif +#define SYSTEM_RESET firmata::SYSTEM_RESET // reset from MIDI + +// + +#ifdef START_SYSEX +#undef START_SYSEX +#endif +#define START_SYSEX firmata::START_SYSEX // start a MIDI Sysex message + +#ifdef END_SYSEX +#undef END_SYSEX +#endif +#define END_SYSEX firmata::END_SYSEX // end a MIDI Sysex message + +// extended command set using sysex (0-127/0x00-0x7F) +/* 0x00-0x0F reserved for user-defined commands */ + +#ifdef SERIAL_MESSAGE +#undef SERIAL_MESSAGE +#endif +#define SERIAL_MESSAGE firmata::SERIAL_DATA // communicate with serial devices, including other boards + +#ifdef ENCODER_DATA +#undef ENCODER_DATA +#endif +#define ENCODER_DATA firmata::ENCODER_DATA // reply with encoders current positions + +#ifdef SERVO_CONFIG +#undef SERVO_CONFIG +#endif +#define SERVO_CONFIG firmata::SERVO_CONFIG // set max angle, minPulse, maxPulse, freq + +#ifdef STRING_DATA +#undef STRING_DATA +#endif +#define STRING_DATA firmata::STRING_DATA // a string message with 14-bits per char + +#ifdef STEPPER_DATA +#undef STEPPER_DATA +#endif +#define STEPPER_DATA firmata::STEPPER_DATA // control a stepper motor + +#ifdef ONEWIRE_DATA +#undef ONEWIRE_DATA +#endif +#define ONEWIRE_DATA firmata::ONEWIRE_DATA // send an OneWire read/write/reset/select/skip/search request + +#ifdef SHIFT_DATA +#undef SHIFT_DATA +#endif +#define SHIFT_DATA firmata::SHIFT_DATA // a bitstream to/from a shift register + +#ifdef I2C_REQUEST +#undef I2C_REQUEST +#endif +#define I2C_REQUEST firmata::I2C_REQUEST // send an I2C read/write request + +#ifdef I2C_REPLY +#undef I2C_REPLY +#endif +#define I2C_REPLY firmata::I2C_REPLY // a reply to an I2C read request + +#ifdef I2C_CONFIG +#undef I2C_CONFIG +#endif +#define I2C_CONFIG firmata::I2C_CONFIG // config I2C settings such as delay times and power pins + +#ifdef REPORT_FIRMWARE +#undef REPORT_FIRMWARE +#endif +#define REPORT_FIRMWARE firmata::REPORT_FIRMWARE // report name and version of the firmware + +#ifdef EXTENDED_ANALOG +#undef EXTENDED_ANALOG +#endif +#define EXTENDED_ANALOG firmata::EXTENDED_ANALOG // analog write (PWM, Servo, etc) to any pin + +#ifdef PIN_STATE_QUERY +#undef PIN_STATE_QUERY +#endif +#define PIN_STATE_QUERY firmata::PIN_STATE_QUERY // ask for a pin's current mode and value + +#ifdef PIN_STATE_RESPONSE +#undef PIN_STATE_RESPONSE +#endif +#define PIN_STATE_RESPONSE firmata::PIN_STATE_RESPONSE // reply with pin's current mode and value + +#ifdef CAPABILITY_QUERY +#undef CAPABILITY_QUERY +#endif +#define CAPABILITY_QUERY firmata::CAPABILITY_QUERY // ask for supported modes and resolution of all pins + +#ifdef CAPABILITY_RESPONSE +#undef CAPABILITY_RESPONSE +#endif +#define CAPABILITY_RESPONSE firmata::CAPABILITY_RESPONSE // reply with supported modes and resolution + +#ifdef ANALOG_MAPPING_QUERY +#undef ANALOG_MAPPING_QUERY +#endif +#define ANALOG_MAPPING_QUERY firmata::ANALOG_MAPPING_QUERY // ask for mapping of analog to pin numbers + +#ifdef ANALOG_MAPPING_RESPONSE +#undef ANALOG_MAPPING_RESPONSE +#endif +#define ANALOG_MAPPING_RESPONSE firmata::ANALOG_MAPPING_RESPONSE // reply with mapping info + +#ifdef SAMPLING_INTERVAL +#undef SAMPLING_INTERVAL +#endif +#define SAMPLING_INTERVAL firmata::SAMPLING_INTERVAL // set the poll rate of the main loop + +#ifdef SCHEDULER_DATA +#undef SCHEDULER_DATA +#endif +#define SCHEDULER_DATA firmata::SCHEDULER_DATA // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler + +#ifdef SYSEX_NON_REALTIME +#undef SYSEX_NON_REALTIME +#endif +#define SYSEX_NON_REALTIME firmata::SYSEX_NON_REALTIME // MIDI Reserved for non-realtime messages + +#ifdef SYSEX_REALTIME +#undef SYSEX_REALTIME +#endif +#define SYSEX_REALTIME firmata::SYSEX_REALTIME // MIDI Reserved for realtime messages + +// pin modes + +#ifdef PIN_MODE_INPUT +#undef PIN_MODE_INPUT +#endif +#define PIN_MODE_INPUT firmata::PIN_MODE_INPUT // same as INPUT defined in Arduino.h + +#ifdef PIN_MODE_OUTPUT +#undef PIN_MODE_OUTPUT +#endif +#define PIN_MODE_OUTPUT firmata::PIN_MODE_OUTPUT // same as OUTPUT defined in Arduino.h + +#ifdef PIN_MODE_ANALOG +#undef PIN_MODE_ANALOG +#endif +#define PIN_MODE_ANALOG firmata::PIN_MODE_ANALOG // analog pin in analogInput mode + +#ifdef PIN_MODE_PWM +#undef PIN_MODE_PWM +#endif +#define PIN_MODE_PWM firmata::PIN_MODE_PWM // digital pin in PWM output mode + +#ifdef PIN_MODE_SERVO +#undef PIN_MODE_SERVO +#endif +#define PIN_MODE_SERVO firmata::PIN_MODE_SERVO // digital pin in Servo output mode + +#ifdef PIN_MODE_SHIFT +#undef PIN_MODE_SHIFT +#endif +#define PIN_MODE_SHIFT firmata::PIN_MODE_SHIFT // shiftIn/shiftOut mode + +#ifdef PIN_MODE_I2C +#undef PIN_MODE_I2C +#endif +#define PIN_MODE_I2C firmata::PIN_MODE_I2C // pin included in I2C setup + +#ifdef PIN_MODE_ONEWIRE +#undef PIN_MODE_ONEWIRE +#endif +#define PIN_MODE_ONEWIRE firmata::PIN_MODE_ONEWIRE // pin configured for 1-wire + +#ifdef PIN_MODE_STEPPER +#undef PIN_MODE_STEPPER +#endif +#define PIN_MODE_STEPPER firmata::PIN_MODE_STEPPER // pin configured for stepper motor + +#ifdef PIN_MODE_ENCODER +#undef PIN_MODE_ENCODER +#endif +#define PIN_MODE_ENCODER firmata::PIN_MODE_ENCODER // pin configured for rotary encoders + +#ifdef PIN_MODE_SERIAL +#undef PIN_MODE_SERIAL +#endif +#define PIN_MODE_SERIAL firmata::PIN_MODE_SERIAL // pin configured for serial communication + +#ifdef PIN_MODE_PULLUP +#undef PIN_MODE_PULLUP +#endif +#define PIN_MODE_PULLUP firmata::PIN_MODE_PULLUP // enable internal pull-up resistor for pin + +#ifdef PIN_MODE_IGNORE +#undef PIN_MODE_IGNORE +#endif +#define PIN_MODE_IGNORE firmata::PIN_MODE_IGNORE // pin configured to be ignored by digitalWrite and capabilityResponse + +#ifdef TOTAL_PIN_MODES +#undef TOTAL_PIN_MODES +#endif +#define TOTAL_PIN_MODES firmata::TOTAL_PIN_MODES + +#endif // FirmataConstants_h diff --git a/libraries/Firmata/FirmataMarshaller.cpp b/libraries/Firmata/FirmataMarshaller.cpp new file mode 100644 index 0000000..6cb5200 --- /dev/null +++ b/libraries/Firmata/FirmataMarshaller.cpp @@ -0,0 +1,431 @@ +/* + FirmataMarshaller.cpp + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +//****************************************************************************** +//* Includes +//****************************************************************************** + +#include "FirmataMarshaller.h" + +#if defined(__cplusplus) && !defined(ARDUINO) + #include +#else + #include +#endif + +#include "FirmataConstants.h" + +using namespace firmata; + +//****************************************************************************** +//* Support Functions +//****************************************************************************** + +/** + * Request or halt a stream of analog readings from the Firmata host application. The range of pins is + * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin for which to request the value (limited to pins 0 - 15). + * @param stream_enable A zero value will disable the stream, a non-zero will enable the stream + * @note The maximum resulting value is 14-bits (16384). + */ +void FirmataMarshaller::reportAnalog(uint8_t pin, bool stream_enable) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + // pin can only be 0-15, so chop higher bits + FirmataStream->write(REPORT_ANALOG | (pin & 0xF)); + FirmataStream->write(stream_enable); +} + +/** + * Request or halt an 8-bit port stream from the Firmata host application (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number for which to request the value. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + * @param stream_enable A zero value will disable the stream, a non-zero will enable the stream + */ +void FirmataMarshaller::reportDigitalPort(uint8_t portNumber, bool stream_enable) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(REPORT_DIGITAL | (portNumber & 0xF)); + FirmataStream->write(stream_enable); +} + +/** + * An alternative to the normal analog message, this extended version allows addressing beyond + * pin 15 and supports sending analog values with any number of bits. + * @param pin The analog pin to which the value is sent. + * @param bytec The size of the storage for the analog value + * @param bytev The pointer to the location of the analog value + */ +void FirmataMarshaller::sendExtendedAnalog(uint8_t pin, size_t bytec, uint8_t * bytev) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(START_SYSEX); + FirmataStream->write(EXTENDED_ANALOG); + FirmataStream->write(pin); + encodeByteStream(bytec, bytev, bytec); + FirmataStream->write(END_SYSEX); +} + +/** + * Transform 8-bit stream into 7-bit message + * @param bytec The number of data bytes in the message. + * @param bytev A pointer to the array of data bytes to send in the message. + * @param max_bytes Force message to be n bytes, regardless of data bits. + */ +void FirmataMarshaller::encodeByteStream (size_t bytec, uint8_t * bytev, size_t max_bytes) +const +{ + static const size_t transmit_bits = 7; + static const uint8_t transmit_mask = ((1 << transmit_bits) - 1); + + size_t bytes_sent = 0; + size_t outstanding_bits = 0; + uint8_t outstanding_bit_cache = *bytev; + + if ( !max_bytes ) { max_bytes = static_cast(-1); } + for (size_t i = 0 ; (i < bytec) && (bytes_sent < max_bytes) ; ++i) { + uint8_t transmit_byte = (outstanding_bit_cache|(bytev[i] << outstanding_bits)); + FirmataStream->write(transmit_mask & transmit_byte); + ++bytes_sent; + outstanding_bit_cache = (bytev[i] >> (transmit_bits - outstanding_bits)); + outstanding_bits = (outstanding_bits + (8 - transmit_bits)); + for ( ; (outstanding_bits >= transmit_bits) && (bytes_sent < max_bytes) ; ) { + transmit_byte = outstanding_bit_cache; + FirmataStream->write(transmit_mask & transmit_byte); + ++bytes_sent; + outstanding_bit_cache >>= transmit_bits; + outstanding_bits -= transmit_bits; + } + } + if ( outstanding_bits && (bytes_sent < max_bytes) ) { + FirmataStream->write(static_cast((1 << outstanding_bits) - 1) & outstanding_bit_cache); + } +} + +//****************************************************************************** +//* Constructors +//****************************************************************************** + +/** + * The FirmataMarshaller class. + */ +FirmataMarshaller::FirmataMarshaller() +: + FirmataStream((Stream *)NULL) +{ +} + +//****************************************************************************** +//* Public Methods +//****************************************************************************** + +/** + * Reassign the Firmata stream transport. + * @param s A reference to the Stream transport object. This can be any type of + * transport that implements the Stream interface. Some examples include Ethernet, WiFi + * and other UARTs on the board (Serial1, Serial2, etc). + */ +void FirmataMarshaller::begin(Stream &s) +{ + FirmataStream = &s; +} + +/** + * Closes the FirmataMarshaller stream by setting its stream reference to `(Stream *)NULL` + */ +void FirmataMarshaller::end(void) +{ + FirmataStream = (Stream *)NULL; +} + +//****************************************************************************** +//* Output Stream Handling +//****************************************************************************** + +/** + * Query the target's firmware name and version + */ +void FirmataMarshaller::queryFirmwareVersion(void) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(START_SYSEX); + FirmataStream->write(REPORT_FIRMWARE); + FirmataStream->write(END_SYSEX); +} + +/** + * Query the target's Firmata protocol version + */ +void FirmataMarshaller::queryVersion(void) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(REPORT_VERSION); +} + +/** + * Halt the stream of analog readings from the Firmata host application. The range of pins is + * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin for which to request the value (limited to pins 0 - 15). + */ +void FirmataMarshaller::reportAnalogDisable(uint8_t pin) +const +{ + reportAnalog(pin, false); +} + +/** + * Request a stream of analog readings from the Firmata host application. The range of pins is + * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin for which to request the value (limited to pins 0 - 15). + */ +void FirmataMarshaller::reportAnalogEnable(uint8_t pin) +const +{ + reportAnalog(pin, true); +} + +/** + * Halt an 8-bit port stream from the Firmata host application (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number for which to request the value. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + */ +void FirmataMarshaller::reportDigitalPortDisable(uint8_t portNumber) +const +{ + reportDigitalPort(portNumber, false); +} + +/** + * Request an 8-bit port stream from the Firmata host application (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number for which to request the value. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + */ +void FirmataMarshaller::reportDigitalPortEnable(uint8_t portNumber) +const +{ + reportDigitalPort(portNumber, true); +} + +/** + * Send an analog message to the Firmata host application. The range of pins is limited to [0..15] + * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin to which the value is sent. + * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc). + * @note The maximum value is 14-bits (16384). + */ +void FirmataMarshaller::sendAnalog(uint8_t pin, uint16_t value) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + if ( (0xF >= pin) && (0x3FFF >= value) ) { + FirmataStream->write(ANALOG_MESSAGE|pin); + encodeByteStream(sizeof(value), reinterpret_cast(&value), sizeof(value)); + } else { + sendExtendedAnalog(pin, sizeof(value), reinterpret_cast(&value)); + } +} + +/** + * Send an analog mapping query to the Firmata host application. The resulting sysex message will + * have an ANALOG_MAPPING_RESPONSE command byte, followed by a list of pins [0-n]; where each + * pin will specify its corresponding analog pin number or 0x7F (127) if not applicable. + */ +void FirmataMarshaller::sendAnalogMappingQuery(void) +const +{ + sendSysex(ANALOG_MAPPING_QUERY, 0, NULL); +} + +/** + * Send a capability query to the Firmata host application. The resulting sysex message will have + * a CAPABILITY_RESPONSE command byte, followed by a list of byte tuples (mode and mode resolution) + * for each pin; where each pin list is terminated by 0x7F (127). + */ +void FirmataMarshaller::sendCapabilityQuery(void) +const +{ + sendSysex(CAPABILITY_QUERY, 0, NULL); +} + +/** + * Send a single digital pin value to the Firmata host application. + * @param pin The digital pin to send the value of. + * @param value The value of the pin. + */ +void FirmataMarshaller::sendDigital(uint8_t pin, uint8_t value) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(SET_DIGITAL_PIN_VALUE); + FirmataStream->write(pin & 0x7F); + FirmataStream->write(value != 0); +} + + +/** + * Send an 8-bit port in a single digital message (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number to send. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + * @param portData The value of the port. The value of each pin in the port is represented by a bit. + */ +void FirmataMarshaller::sendDigitalPort(uint8_t portNumber, uint16_t portData) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(DIGITAL_MESSAGE | (portNumber & 0xF)); + // Tx bits 0-6 (protocol v1 and higher) + // Tx bits 7-13 (bit 7 only for protocol v2 and higher) + encodeByteStream(sizeof(portData), reinterpret_cast(&portData), sizeof(portData)); +} + +/** + * Sends the firmware name and version to the Firmata host application. + * @param major The major verison number + * @param minor The minor version number + * @param bytec The length of the firmware name + * @param bytev The firmware name array + */ +void FirmataMarshaller::sendFirmwareVersion(uint8_t major, uint8_t minor, size_t bytec, uint8_t *bytev) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + size_t i; + FirmataStream->write(START_SYSEX); + FirmataStream->write(REPORT_FIRMWARE); + FirmataStream->write(major); + FirmataStream->write(minor); + for (i = 0; i < bytec; ++i) { + encodeByteStream(sizeof(bytev[i]), reinterpret_cast(&bytev[i])); + } + FirmataStream->write(END_SYSEX); +} + +/** + * Send the Firmata protocol version to the Firmata host application. + * @param major The major verison number + * @param minor The minor version number + */ +void FirmataMarshaller::sendVersion(uint8_t major, uint8_t minor) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(REPORT_VERSION); + FirmataStream->write(major); + FirmataStream->write(minor); +} + +/** + * Send the pin mode/configuration. The pin configuration (or mode) in Firmata represents the + * current function of the pin. Examples are digital input or output, analog input, pwm, i2c, + * serial (uart), etc. + * @param pin The pin to configure. + * @param config The configuration value for the specified pin. + */ +void FirmataMarshaller::sendPinMode(uint8_t pin, uint8_t config) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(SET_PIN_MODE); + FirmataStream->write(pin); + FirmataStream->write(config); +} + +/** + * Send a pin state query to the Firmata host application. The resulting sysex message will have + * a PIN_STATE_RESPONSE command byte, followed by the pin number, the pin mode and a stream of + * bits to indicate any *data* written to the pin (pin state). + * @param pin The pin to query + * @note The pin state is any data written to the pin (i.e. pin state != pin value) + */ +void FirmataMarshaller::sendPinStateQuery(uint8_t pin) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(START_SYSEX); + FirmataStream->write(PIN_STATE_QUERY); + FirmataStream->write(pin); + FirmataStream->write(END_SYSEX); +} + +/** + * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes + * (this is not always the case so this function is not always used to send sysex messages). + * @param command The sysex command byte. + * @param bytec The number of data bytes in the message (excludes start, command and end bytes). + * @param bytev A pointer to the array of data bytes to send in the message. + */ +void FirmataMarshaller::sendSysex(uint8_t command, size_t bytec, uint8_t *bytev) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + size_t i; + FirmataStream->write(START_SYSEX); + FirmataStream->write(command); + for (i = 0; i < bytec; ++i) { + encodeByteStream(sizeof(bytev[i]), reinterpret_cast(&bytev[i])); + } + FirmataStream->write(END_SYSEX); +} + +/** + * Send a string to the Firmata host application. + * @param string A pointer to the char string + */ +void FirmataMarshaller::sendString(const char *string) +const +{ + sendSysex(STRING_DATA, strlen(string), reinterpret_cast(const_cast(string))); +} + +/** + * The sampling interval sets how often analog data and i2c data is reported to the client. + * @param interval_ms The interval (in milliseconds) at which to sample + * @note The default sampling interval is 19ms + */ +void FirmataMarshaller::setSamplingInterval(uint16_t interval_ms) +const +{ + sendSysex(SAMPLING_INTERVAL, sizeof(interval_ms), reinterpret_cast(&interval_ms)); +} + +/** + * Perform a software reset on the target. For example, StandardFirmata.ino will initialize + * everything to a known state and reset the parsing buffer. + */ +void FirmataMarshaller::systemReset(void) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(SYSTEM_RESET); +} diff --git a/libraries/Firmata/FirmataMarshaller.h b/libraries/Firmata/FirmataMarshaller.h new file mode 100644 index 0000000..3fa83f6 --- /dev/null +++ b/libraries/Firmata/FirmataMarshaller.h @@ -0,0 +1,75 @@ +/* + FirmataMarshaller.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataMarshaller_h +#define FirmataMarshaller_h + +#if defined(__cplusplus) && !defined(ARDUINO) + #include + #include +#else + #include + #include +#endif + +#include + +namespace firmata { + +class FirmataMarshaller +{ + friend class FirmataClass; + + public: + /* constructors */ + FirmataMarshaller(); + + /* public methods */ + void begin(Stream &s); + void end(); + + /* serial send handling */ + void queryFirmwareVersion(void) const; + void queryVersion(void) const; + void reportAnalogDisable(uint8_t pin) const; + void reportAnalogEnable(uint8_t pin) const; + void reportDigitalPortDisable(uint8_t portNumber) const; + void reportDigitalPortEnable(uint8_t portNumber) const; + void sendAnalog(uint8_t pin, uint16_t value) const; + void sendAnalogMappingQuery(void) const; + void sendCapabilityQuery(void) const; + void sendDigital(uint8_t pin, uint8_t value) const; + void sendDigitalPort(uint8_t portNumber, uint16_t portData) const; + void sendFirmwareVersion(uint8_t major, uint8_t minor, size_t bytec, uint8_t *bytev) const; + void sendVersion(uint8_t major, uint8_t minor) const; + void sendPinMode(uint8_t pin, uint8_t config) const; + void sendPinStateQuery(uint8_t pin) const; + void sendString(const char *string) const; + void sendSysex(uint8_t command, size_t bytec, uint8_t *bytev) const; + void setSamplingInterval(uint16_t interval_ms) const; + void systemReset(void) const; + + private: + /* utility methods */ + void reportAnalog(uint8_t pin, bool stream_enable) const; + void reportDigitalPort(uint8_t portNumber, bool stream_enable) const; + void sendExtendedAnalog(uint8_t pin, size_t bytec, uint8_t * bytev) const; + void encodeByteStream (size_t bytec, uint8_t * bytev, size_t max_bytes = 0) const; + + Stream * FirmataStream; +}; + +} // namespace firmata + +#endif /* FirmataMarshaller_h */ + diff --git a/libraries/Firmata/FirmataParser.cpp b/libraries/Firmata/FirmataParser.cpp new file mode 100644 index 0000000..d402fdf --- /dev/null +++ b/libraries/Firmata/FirmataParser.cpp @@ -0,0 +1,480 @@ +/* + FirmataParser.cpp + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +//****************************************************************************** +//* Includes +//****************************************************************************** + +#include "FirmataParser.h" + +#include "FirmataConstants.h" + +using namespace firmata; + +//****************************************************************************** +//* Constructors +//****************************************************************************** + +/** + * The FirmataParser class. + * @param dataBuffer A pointer to an external buffer used to store parsed data + * @param dataBufferSize The size of the external buffer + */ +FirmataParser::FirmataParser(uint8_t * const dataBuffer, size_t dataBufferSize) +: + dataBuffer(dataBuffer), + dataBufferSize(dataBufferSize), + executeMultiByteCommand(0), + multiByteChannel(0), + waitForData(0), + parsingSysex(false), + sysexBytesRead(0), + currentAnalogCallbackContext((void *)NULL), + currentDigitalCallbackContext((void *)NULL), + currentReportAnalogCallbackContext((void *)NULL), + currentReportDigitalCallbackContext((void *)NULL), + currentPinModeCallbackContext((void *)NULL), + currentPinValueCallbackContext((void *)NULL), + currentReportFirmwareCallbackContext((void *)NULL), + currentReportVersionCallbackContext((void *)NULL), + currentDataBufferOverflowCallbackContext((void *)NULL), + currentStringCallbackContext((void *)NULL), + currentSysexCallbackContext((void *)NULL), + currentSystemResetCallbackContext((void *)NULL), + currentAnalogCallback((callbackFunction)NULL), + currentDigitalCallback((callbackFunction)NULL), + currentReportAnalogCallback((callbackFunction)NULL), + currentReportDigitalCallback((callbackFunction)NULL), + currentPinModeCallback((callbackFunction)NULL), + currentPinValueCallback((callbackFunction)NULL), + currentDataBufferOverflowCallback((dataBufferOverflowCallbackFunction)NULL), + currentStringCallback((stringCallbackFunction)NULL), + currentSysexCallback((sysexCallbackFunction)NULL), + currentReportFirmwareCallback((versionCallbackFunction)NULL), + currentReportVersionCallback((systemCallbackFunction)NULL), + currentSystemResetCallback((systemCallbackFunction)NULL) +{ + allowBufferUpdate = ((uint8_t *)NULL == dataBuffer); +} + +//****************************************************************************** +//* Public Methods +//****************************************************************************** + +//------------------------------------------------------------------------------ +// Serial Receive Handling + +/** + * Parse data from the input stream. + * @param inputData A single byte to be added to the parser. + */ +void FirmataParser::parse(uint8_t inputData) +{ + uint8_t command; + + if (parsingSysex) { + if (inputData == END_SYSEX) { + //stop sysex byte + parsingSysex = false; + //fire off handler function + processSysexMessage(); + } else { + //normal data byte - add to buffer + bufferDataAtPosition(inputData, sysexBytesRead); + ++sysexBytesRead; + } + } else if ( (waitForData > 0) && (inputData < 128) ) { + --waitForData; + bufferDataAtPosition(inputData, waitForData); + if ( (waitForData == 0) && executeMultiByteCommand ) { // got the whole message + switch (executeMultiByteCommand) { + case ANALOG_MESSAGE: + if (currentAnalogCallback) { + (*currentAnalogCallback)(currentAnalogCallbackContext, + multiByteChannel, + (dataBuffer[0] << 7) + + dataBuffer[1]); + } + break; + case DIGITAL_MESSAGE: + if (currentDigitalCallback) { + (*currentDigitalCallback)(currentDigitalCallbackContext, + multiByteChannel, + (dataBuffer[0] << 7) + + dataBuffer[1]); + } + break; + case SET_PIN_MODE: + if (currentPinModeCallback) + (*currentPinModeCallback)(currentPinModeCallbackContext, dataBuffer[1], dataBuffer[0]); + break; + case SET_DIGITAL_PIN_VALUE: + if (currentPinValueCallback) + (*currentPinValueCallback)(currentPinValueCallbackContext, dataBuffer[1], dataBuffer[0]); + break; + case REPORT_ANALOG: + if (currentReportAnalogCallback) + (*currentReportAnalogCallback)(currentReportAnalogCallbackContext, multiByteChannel, dataBuffer[0]); + break; + case REPORT_DIGITAL: + if (currentReportDigitalCallback) + (*currentReportDigitalCallback)(currentReportDigitalCallbackContext, multiByteChannel, dataBuffer[0]); + break; + } + executeMultiByteCommand = 0; + } + } else { + // remove channel info from command byte if less than 0xF0 + if (inputData < 0xF0) { + command = inputData & 0xF0; + multiByteChannel = inputData & 0x0F; + } else { + command = inputData; + // commands in the 0xF* range don't use channel data + } + switch (command) { + case ANALOG_MESSAGE: + case DIGITAL_MESSAGE: + case SET_PIN_MODE: + case SET_DIGITAL_PIN_VALUE: + waitForData = 2; // two data bytes needed + executeMultiByteCommand = command; + break; + case REPORT_ANALOG: + case REPORT_DIGITAL: + waitForData = 1; // one data byte needed + executeMultiByteCommand = command; + break; + case START_SYSEX: + parsingSysex = true; + sysexBytesRead = 0; + break; + case SYSTEM_RESET: + systemReset(); + break; + case REPORT_VERSION: + if (currentReportVersionCallback) + (*currentReportVersionCallback)(currentReportVersionCallbackContext); + break; + } + } +} + +/** + * @return Returns true if the parser is actively parsing data. + */ +bool FirmataParser::isParsingMessage(void) +const +{ + return (waitForData > 0 || parsingSysex); +} + +/** + * Provides a mechanism to either set or update the working buffer of the parser. + * The method will be enabled when no buffer has been provided, or an overflow + * condition exists. + * @param dataBuffer A pointer to an external buffer used to store parsed data + * @param dataBufferSize The size of the external buffer + */ +int FirmataParser::setDataBufferOfSize(uint8_t * dataBuffer, size_t dataBufferSize) +{ + int result; + + if ( !allowBufferUpdate ) { + result = __LINE__; + } else if ((uint8_t *)NULL == dataBuffer) { + result = __LINE__; + } else { + this->dataBuffer = dataBuffer; + this->dataBufferSize = dataBufferSize; + allowBufferUpdate = false; + result = 0; + } + + return result; +} + +/** + * Attach a generic sysex callback function to a command (options are: ANALOG_MESSAGE, + * DIGITAL_MESSAGE, REPORT_ANALOG, REPORT DIGITAL, SET_PIN_MODE and SET_DIGITAL_PIN_VALUE). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, callbackFunction newFunction, void * context) +{ + switch (command) { + case ANALOG_MESSAGE: + currentAnalogCallback = newFunction; + currentAnalogCallbackContext = context; + break; + case DIGITAL_MESSAGE: + currentDigitalCallback = newFunction; + currentDigitalCallbackContext = context; + break; + case REPORT_ANALOG: + currentReportAnalogCallback = newFunction; + currentReportAnalogCallbackContext = context; + break; + case REPORT_DIGITAL: + currentReportDigitalCallback = newFunction; + currentReportDigitalCallbackContext = context; + break; + case SET_PIN_MODE: + currentPinModeCallback = newFunction; + currentPinModeCallbackContext = context; + break; + case SET_DIGITAL_PIN_VALUE: + currentPinValueCallback = newFunction; + currentPinValueCallbackContext = context; + break; + } +} + +/** + * Attach a version callback function (supported option: REPORT_FIRMWARE). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, versionCallbackFunction newFunction, void * context) +{ + switch (command) { + case REPORT_FIRMWARE: + currentReportFirmwareCallback = newFunction; + currentReportFirmwareCallbackContext = context; + break; + } +} + +/** + * Attach a system callback function (supported options are: SYSTEM_RESET, REPORT_VERSION). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, systemCallbackFunction newFunction, void * context) +{ + switch (command) { + case REPORT_VERSION: + currentReportVersionCallback = newFunction; + currentReportVersionCallbackContext = context; + break; + case SYSTEM_RESET: + currentSystemResetCallback = newFunction; + currentSystemResetCallbackContext = context; + break; + } +} + +/** + * Attach a callback function for the STRING_DATA command. + * @param command Must be set to STRING_DATA or it will be ignored. + * @param newFunction A reference to the string callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, stringCallbackFunction newFunction, void * context) +{ + switch (command) { + case STRING_DATA: + currentStringCallback = newFunction; + currentStringCallbackContext = context; + break; + } +} + +/** + * Attach a generic sysex callback function to sysex command. + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the sysex callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, sysexCallbackFunction newFunction, void * context) +{ + (void)command; + currentSysexCallback = newFunction; + currentSysexCallbackContext = context; +} + +/** + * Attach a buffer overflow callback + * @param newFunction A reference to the buffer overflow callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(dataBufferOverflowCallbackFunction newFunction, void * context) +{ + currentDataBufferOverflowCallback = newFunction; + currentDataBufferOverflowCallbackContext = context; +} + +/** + * Detach a callback function for a specified command (such as SYSTEM_RESET, STRING_DATA, + * ANALOG_MESSAGE, DIGITAL_MESSAGE, etc). + * @param command The ID of the command to detatch the callback function from. + */ +void FirmataParser::detach(uint8_t command) +{ + switch (command) { + case REPORT_FIRMWARE: + attach(command, (versionCallbackFunction)NULL, NULL); + break; + case REPORT_VERSION: + case SYSTEM_RESET: + attach(command, (systemCallbackFunction)NULL, NULL); + break; + case STRING_DATA: + attach(command, (stringCallbackFunction)NULL, NULL); + break; + case START_SYSEX: + attach(command, (sysexCallbackFunction)NULL, NULL); + break; + default: + attach(command, (callbackFunction)NULL, NULL); + break; + } +} + +/** + * Detach the buffer overflow callback + * @param Any pointer of type dataBufferOverflowCallbackFunction. + */ +void FirmataParser::detach(dataBufferOverflowCallbackFunction) +{ + currentDataBufferOverflowCallback = (dataBufferOverflowCallbackFunction)NULL; + currentDataBufferOverflowCallbackContext = (void *)NULL; +} + +//****************************************************************************** +//* Private Methods +//****************************************************************************** + +/** + * Buffer abstraction to prevent memory corruption + * @param data The byte to put into the buffer + * @param pos The position to insert the byte into the buffer + * @return writeError A boolean to indicate if an error occured + * @private + */ +bool FirmataParser::bufferDataAtPosition(const uint8_t data, const size_t pos) +{ + bool bufferOverflow = (pos >= dataBufferSize); + + // Notify of overflow condition + if ( bufferOverflow + && ((dataBufferOverflowCallbackFunction)NULL != currentDataBufferOverflowCallback) ) + { + allowBufferUpdate = true; + currentDataBufferOverflowCallback(currentDataBufferOverflowCallbackContext); + // Check if overflow was resolved during callback + bufferOverflow = (pos >= dataBufferSize); + } + + // Write data to buffer if no overflow condition persist + if ( !bufferOverflow ) + { + dataBuffer[pos] = data; + } + + return bufferOverflow; +} + +/** + * Transform 7-bit firmata message into 8-bit stream + * @param bytec The encoded data byte length of the message (max: 16383). + * @param bytev A pointer to the encoded array of data bytes. + * @return The length of the decoded data. + * @note The conversion will be done in place on the provided buffer. + * @private + */ +size_t FirmataParser::decodeByteStream(size_t bytec, uint8_t * bytev) { + size_t decoded_bytes, i; + + for ( i = 0, decoded_bytes = 0 ; i < bytec ; ++decoded_bytes, ++i ) { + bytev[decoded_bytes] = bytev[i]; + bytev[decoded_bytes] |= (uint8_t)(bytev[++i] << 7); + } + + return decoded_bytes; +} + +/** + * Process incoming sysex messages. Handles REPORT_FIRMWARE and STRING_DATA internally. + * Calls callback function for STRING_DATA and all other sysex messages. + * @private + */ +void FirmataParser::processSysexMessage(void) +{ + switch (dataBuffer[0]) { //first byte in buffer is command + case REPORT_FIRMWARE: + if (currentReportFirmwareCallback) { + const size_t major_version_offset = 1; + const size_t minor_version_offset = 2; + const size_t string_offset = 3; + // Test for malformed REPORT_FIRMWARE message (used to query firmware prior to Firmata v3.0.0) + if ( 3 > sysexBytesRead ) { + (*currentReportFirmwareCallback)(currentReportFirmwareCallbackContext, 0, 0, (const char *)NULL); + } else { + const size_t end_of_string = (string_offset + decodeByteStream((sysexBytesRead - string_offset), &dataBuffer[string_offset])); + bufferDataAtPosition('\0', end_of_string); // NULL terminate the string + (*currentReportFirmwareCallback)(currentReportFirmwareCallbackContext, (size_t)dataBuffer[major_version_offset], (size_t)dataBuffer[minor_version_offset], (const char *)&dataBuffer[string_offset]); + } + } + break; + case STRING_DATA: + if (currentStringCallback) { + const size_t string_offset = 1; + const size_t end_of_string = (string_offset + decodeByteStream((sysexBytesRead - string_offset), &dataBuffer[string_offset])); + bufferDataAtPosition('\0', end_of_string); // NULL terminate the string + (*currentStringCallback)(currentStringCallbackContext, (const char *)&dataBuffer[string_offset]); + } + break; + default: + if (currentSysexCallback) + (*currentSysexCallback)(currentSysexCallbackContext, dataBuffer[0], sysexBytesRead - 1, dataBuffer + 1); + } +} + +/** + * Resets the system state upon a SYSTEM_RESET message from the host software. + * @private + */ +void FirmataParser::systemReset(void) +{ + size_t i; + + waitForData = 0; // this flag says the next serial input will be data + executeMultiByteCommand = 0; // execute this after getting multi-byte data + multiByteChannel = 0; // channel data for multiByteCommands + + for (i = 0; i < dataBufferSize; ++i) { + dataBuffer[i] = 0; + } + + parsingSysex = false; + sysexBytesRead = 0; + + if (currentSystemResetCallback) + (*currentSystemResetCallback)(currentSystemResetCallbackContext); +} diff --git a/libraries/Firmata/FirmataParser.h b/libraries/Firmata/FirmataParser.h new file mode 100644 index 0000000..bb0c8be --- /dev/null +++ b/libraries/Firmata/FirmataParser.h @@ -0,0 +1,105 @@ +/* + FirmataParser.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataParser_h +#define FirmataParser_h + +#if defined(__cplusplus) && !defined(ARDUINO) + #include + #include +#else + #include + #include +#endif + +namespace firmata { + +class FirmataParser +{ + public: + /* callback function types */ + typedef void (*callbackFunction)(void * context, uint8_t command, uint16_t value); + typedef void (*dataBufferOverflowCallbackFunction)(void * context); + typedef void (*stringCallbackFunction)(void * context, const char * c_str); + typedef void (*sysexCallbackFunction)(void * context, uint8_t command, size_t argc, uint8_t * argv); + typedef void (*systemCallbackFunction)(void * context); + typedef void (*versionCallbackFunction)(void * context, size_t sv_major, size_t sv_minor, const char * firmware); + + FirmataParser(uint8_t * dataBuffer = (uint8_t *)NULL, size_t dataBufferSize = 0); + + /* serial receive handling */ + void parse(uint8_t value); + bool isParsingMessage(void) const; + int setDataBufferOfSize(uint8_t * dataBuffer, size_t dataBufferSize); + + /* attach & detach callback functions to messages */ + void attach(uint8_t command, callbackFunction newFunction, void * context = NULL); + void attach(dataBufferOverflowCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, stringCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, sysexCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, systemCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, versionCallbackFunction newFunction, void * context = NULL); + void detach(uint8_t command); + void detach(dataBufferOverflowCallbackFunction); + + private: + /* input message handling */ + bool allowBufferUpdate; + uint8_t * dataBuffer; // multi-byte data + size_t dataBufferSize; + uint8_t executeMultiByteCommand; // execute this after getting multi-byte data + uint8_t multiByteChannel; // channel data for multiByteCommands + size_t waitForData; // this flag says the next serial input will be data + + /* sysex */ + bool parsingSysex; + size_t sysexBytesRead; + + /* callback context */ + void * currentAnalogCallbackContext; + void * currentDigitalCallbackContext; + void * currentReportAnalogCallbackContext; + void * currentReportDigitalCallbackContext; + void * currentPinModeCallbackContext; + void * currentPinValueCallbackContext; + void * currentReportFirmwareCallbackContext; + void * currentReportVersionCallbackContext; + void * currentDataBufferOverflowCallbackContext; + void * currentStringCallbackContext; + void * currentSysexCallbackContext; + void * currentSystemResetCallbackContext; + + /* callback functions */ + callbackFunction currentAnalogCallback; + callbackFunction currentDigitalCallback; + callbackFunction currentReportAnalogCallback; + callbackFunction currentReportDigitalCallback; + callbackFunction currentPinModeCallback; + callbackFunction currentPinValueCallback; + dataBufferOverflowCallbackFunction currentDataBufferOverflowCallback; + stringCallbackFunction currentStringCallback; + sysexCallbackFunction currentSysexCallback; + versionCallbackFunction currentReportFirmwareCallback; + systemCallbackFunction currentReportVersionCallback; + systemCallbackFunction currentSystemResetCallback; + + /* private methods ------------------------------ */ + bool bufferDataAtPosition(const uint8_t data, const size_t pos); + size_t decodeByteStream(size_t bytec, uint8_t * bytev); + void processSysexMessage(void); + void systemReset(void); +}; + +} // firmata + +#endif /* FirmataParser_h */ diff --git a/libraries/Firmata/LICENSE.txt b/libraries/Firmata/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino b/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino new file mode 100644 index 0000000..fb9b0fd --- /dev/null +++ b/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino @@ -0,0 +1,90 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please click on the following link + * to open the list of Firmata client libraries in your default browser. + * + * https://github.com/firmata/arduino#firmata-client-libraries + */ + +/* + * This firmware reads all inputs and sends them as fast as it can. It was + * inspired by the ease-of-use of the Arduino2Max program. + * + * This example code is in the public domain. + */ +#include + +byte pin; + +int analogValue; +int previousAnalogValues[TOTAL_ANALOG_PINS]; + +byte portStatus[TOTAL_PORTS]; // each bit: 1=pin is digital input, 0=other/ignore +byte previousPINs[TOTAL_PORTS]; + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +/* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you + get long, random delays. So only read analogs every 20ms or so */ +int samplingInterval = 19; // how often to run the main loop (in ms) + +void sendPort(byte portNumber, byte portValue) +{ + portValue = portValue & portStatus[portNumber]; + if (previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +void setup() +{ + byte i, port, status; + + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + for (pin = 0; pin < TOTAL_PINS; pin++) { + if IS_PIN_DIGITAL(pin) pinMode(PIN_TO_DIGITAL(pin), INPUT); + } + + for (port = 0; port < TOTAL_PORTS; port++) { + status = 0; + for (i = 0; i < 8; i++) { + if (IS_PIN_DIGITAL(port * 8 + i)) status |= (1 << i); + } + portStatus[port] = status; + } + + Firmata.begin(57600); +} + +void loop() +{ + byte i; + + for (i = 0; i < TOTAL_PORTS; i++) { + sendPort(i, readPort(i, 0xff)); + } + /* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you + get long, random delays. So only read analogs every 20ms or so */ + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + while (Firmata.available()) { + Firmata.processInput(); + } + for (pin = 0; pin < TOTAL_ANALOG_PINS; pin++) { + analogValue = analogRead(pin); + if (analogValue != previousAnalogValues[pin]) { + Firmata.sendAnalog(pin, analogValue); + previousAnalogValues[pin] = analogValue; + } + } + } +} + + diff --git a/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino b/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino new file mode 100644 index 0000000..689c685 --- /dev/null +++ b/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino @@ -0,0 +1,94 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please click on the following link + * to open the list of Firmata client libraries in your default browser. + * + * https://github.com/firmata/arduino#firmata-client-libraries + */ + +/* This firmware supports as many analog ports as possible, all analog inputs, + * four PWM outputs, and two with servo support. + * + * This example code is in the public domain. + */ +#include +#include + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +/* servos */ +Servo servo9, servo10; // one instance per pin +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting +int analogPin = 0; // counter for reading analog pins +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis + + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void analogWriteCallback(byte pin, int value) +{ + switch (pin) { + case 9: servo9.write(value); break; + case 10: servo10.write(value); break; + case 3: + case 5: + case 6: + case 11: // PWM pins + analogWrite(pin, value); + break; + } +} +// ----------------------------------------------------------------------------- +// sets bits in a bit array (int) to toggle the reporting of the analogIns +void reportAnalogCallback(byte pin, int value) +{ + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << pin); + } + else { // everything but 0 enables reporting of that pin + analogInputsToReport = analogInputsToReport | (1 << pin); + } + // TODO: save status to EEPROM here, if changed +} + +/*============================================================================== + * SETUP() + *============================================================================*/ +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + + servo9.attach(9); + servo10.attach(10); + Firmata.begin(57600); +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + while (Firmata.available()) + Firmata.processInput(); + currentMillis = millis(); + if (currentMillis - previousMillis > 20) { + previousMillis += 20; // run this every 20ms + for (analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) { + if ( analogInputsToReport & (1 << analogPin) ) + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } +} + diff --git a/libraries/Firmata/examples/EchoString/EchoString.ino b/libraries/Firmata/examples/EchoString/EchoString.ino new file mode 100644 index 0000000..e1651d5 --- /dev/null +++ b/libraries/Firmata/examples/EchoString/EchoString.ino @@ -0,0 +1,44 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please click on the following link + * to open the list of Firmata client libraries in your default browser. + * + * https://github.com/firmata/arduino#firmata-client-libraries + */ + +/* This sketch accepts strings and raw sysex messages and echos them back. + * + * This example code is in the public domain. + */ +#include + +void stringCallback(char *myString) +{ + Firmata.sendString(myString); +} + + +void sysexCallback(byte command, byte argc, byte *argv) +{ + Firmata.sendSysex(command, argc, argv); +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(STRING_DATA, stringCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.begin(57600); +} + +void loop() +{ + while (Firmata.available()) { + Firmata.processInput(); + } +} + + diff --git a/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt b/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino b/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino new file mode 100644 index 0000000..5b79de5 --- /dev/null +++ b/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino @@ -0,0 +1,239 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please click on the following link + * to open the list of Firmata client libraries in your default browser. + * + * https://github.com/firmata/arduino#firmata-client-libraries + */ + +/* + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + */ + +/* + * This is an old version of StandardFirmata (v2.0). It is kept here because + * its the last version that works on an ATMEGA8 chip. Also, it can be used + * for host software that has not been updated to a newer version of the + * protocol. It also uses the old baud rate of 115200 rather than 57600. + */ + +#include +#include + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting +int analogPin = 0; // counter for reading analog pins + +/* digital pins */ +byte reportPINs[TOTAL_PORTS]; // PIN == input port +byte previousPINs[TOTAL_PORTS]; // PIN == input port +byte pinStatus[TOTAL_PINS]; // store pin status, default OUTPUT +byte portStatus[TOTAL_PORTS]; + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis + + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void outputPort(byte portNumber, byte portValue) +{ + portValue = portValue & ~ portStatus[portNumber]; + if (previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + Firmata.sendDigitalPort(portNumber, portValue); + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + byte i, tmp; + for (i = 0; i < TOTAL_PORTS; i++) { + if (reportPINs[i]) { + switch (i) { + case 0: outputPort(0, PIND & ~ B00000011); break; // ignore Rx/Tx 0/1 + case 1: outputPort(1, PINB); break; + case 2: outputPort(2, PINC); break; + } + } + } +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) { + byte port = 0; + byte offset = 0; + + if (pin < 8) { + port = 0; + offset = 0; + } else if (pin < 14) { + port = 1; + offset = 8; + } else if (pin < 22) { + port = 2; + offset = 14; + } + + if (pin > 1) { // ignore RxTx (pins 0 and 1) + pinStatus[pin] = mode; + switch (mode) { + case INPUT: + pinMode(pin, INPUT); + portStatus[port] = portStatus[port] & ~ (1 << (pin - offset)); + break; + case OUTPUT: + digitalWrite(pin, LOW); // disable PWM + case PWM: + pinMode(pin, OUTPUT); + portStatus[port] = portStatus[port] | (1 << (pin - offset)); + break; + //case ANALOG: // TODO figure this out + default: + Firmata.sendString(""); + } + // TODO: save status to EEPROM here, if changed + } +} + +void analogWriteCallback(byte pin, int value) +{ + setPinModeCallback(pin, PIN_MODE_PWM); + analogWrite(pin, value); +} + +void digitalWriteCallback(byte port, int value) +{ + switch (port) { + case 0: // pins 2-7 (don't change Rx/Tx, pins 0 and 1) + // 0xFF03 == B1111111100000011 0x03 == B00000011 + PORTD = (value & ~ 0xFF03) | (PORTD & 0x03); + break; + case 1: // pins 8-13 (14,15 are disabled for the crystal) + PORTB = (byte)value; + break; + case 2: // analog pins used as digital + PORTC = (byte)value; + break; + } +} + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte pin, int value) +{ + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << pin); + } + else { // everything but 0 enables reporting of that pin + analogInputsToReport = analogInputsToReport | (1 << pin); + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + reportPINs[port] = (byte)value; + if (port == 2) // turn off analog reporting when used as digital + analogInputsToReport = 0; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ +void setup() +{ + byte i; + + Firmata.setFirmwareVersion(2, 0); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + + portStatus[0] = B00000011; // ignore Tx/RX pins + portStatus[1] = B11000000; // ignore 14/15 pins + portStatus[2] = B00000000; + + // for(i=0; i 20) { + previousMillis += 20; // run this every 20ms + /* SERIALREAD - Serial.read() uses a 128 byte circular buffer, so handle + * all serialReads at once, i.e. empty the buffer */ + while (Firmata.available()) + Firmata.processInput(); + /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over + * 60 bytes. use a timer to sending an event character every 4 ms to + * trigger the buffer to dump. */ + + /* ANALOGREAD - right after the event character, do all of the + * analogReads(). These only need to be done every 4ms. */ + for (analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) { + if ( analogInputsToReport & (1 << analogPin) ) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } +} diff --git a/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino b/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino new file mode 100644 index 0000000..52b1f1b --- /dev/null +++ b/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino @@ -0,0 +1,65 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please click on the following link + * to open the list of Firmata client libraries in your default browser. + * + * https://github.com/firmata/arduino#firmata-client-libraries + */ + +/* This firmware supports as many servos as possible using the Servo library + * included in Arduino 0017 + * + * This example code is in the public domain. + */ + +#include +#include + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte servoCount = 0; + +void analogWriteCallback(byte pin, int value) +{ + if (IS_PIN_DIGITAL(pin)) { + servos[servoPinMap[pin]].write(value); + } +} + +void systemResetCallback() +{ + servoCount = 0; +} + +void setup() +{ + byte pin; + + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + Firmata.begin(57600); + systemResetCallback(); + + // attach servos from first digital pin up to max number of + // servos supported for the board + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + if (servoCount < MAX_SERVOS) { + servoPinMap[pin] = servoCount; + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + servoCount++; + } + } + } +} + +void loop() +{ + while (Firmata.available()) + Firmata.processInput(); +} diff --git a/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino b/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino new file mode 100644 index 0000000..98a6adf --- /dev/null +++ b/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino @@ -0,0 +1,46 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please click on the following link + * to open the list of Firmata client libraries in your default browser. + * + * https://github.com/firmata/arduino#firmata-client-libraries + */ + +/* Supports as many analog inputs and analog PWM outputs as possible. + * + * This example code is in the public domain. + */ +#include + +byte analogPin = 0; + +void analogWriteCallback(byte pin, int value) +{ + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), value); + } +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.begin(57600); +} + +void loop() +{ + while (Firmata.available()) { + Firmata.processInput(); + } + // do one analogRead per loop, so if PC is sending a lot of + // analog write messages, we will only delay 1 analogRead + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + analogPin = analogPin + 1; + if (analogPin >= TOTAL_ANALOG_PINS) analogPin = 0; +} + diff --git a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino new file mode 100644 index 0000000..91db333 --- /dev/null +++ b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino @@ -0,0 +1,72 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please click on the following link + * to open the list of Firmata client libraries in your default browser. + * + * https://github.com/firmata/arduino#firmata-client-libraries + */ + +/* Supports as many digital inputs and outputs as possible. + * + * This example code is in the public domain. + */ +#include + +byte previousPIN[TOTAL_PORTS]; // PIN means PORT for input +byte previousPORT[TOTAL_PORTS]; + +void outputPort(byte portNumber, byte portValue) +{ + // only send the data when it changes, otherwise you get too many messages! + if (previousPIN[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPIN[portNumber] = portValue; + } +} + +void setPinModeCallback(byte pin, int mode) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), mode); + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte i; + byte currentPinValue, previousPinValue; + + if (port < TOTAL_PORTS && value != previousPORT[port]) { + for (i = 0; i < 8; i++) { + currentPinValue = (byte) value & (1 << i); + previousPinValue = previousPORT[port] & (1 << i); + if (currentPinValue != previousPinValue) { + digitalWrite(i + (port * 8), currentPinValue); + } + } + previousPORT[port] = value; + } +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.begin(57600); +} + +void loop() +{ + byte i; + + for (i = 0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, 0xff)); + } + + while (Firmata.available()) { + Firmata.processInput(); + } +} diff --git a/libraries/Firmata/examples/StandardFirmata/LICENSE.txt b/libraries/Firmata/examples/StandardFirmata/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmata/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino b/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino new file mode 100644 index 0000000..b043c11 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino @@ -0,0 +1,823 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please click on the following link + to open the list of Firmata client libraries in your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated August 17th, 2017 +*/ + +#include +#include +#include + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to run the main loop (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous more */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[64]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +// Forward declare a few functions to avoid compiler errors with older versions +// of the Arduino IDE. +void setPinModeCallback(byte, int); +void reportAnalogCallback(byte analogPin, int value); +void sysexCallback(byte, byte, byte*); + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == PIN_MODE_PWM) { + // Disable PWM if pin mode was previously set to PWM. + digitalWrite(PIN_TO_DIGITAL(pin), LOW); + } + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (argc > 1 && delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(DEFAULT_PWM_RESOLUTION); + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega, + // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this: + // Serial1.begin(57600); + // Firmata.begin(Serial1); + // However do not do this if you are using SERIAL_MESSAGE + + Firmata.begin(57600); + while (!Serial) { + ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101 + } + + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * FTDI buffer using Serial.print() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif +} diff --git a/libraries/Firmata/examples/StandardFirmataBLE/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataBLE/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataBLE/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataBLE/StandardFirmataBLE.ino b/libraries/Firmata/examples/StandardFirmataBLE/StandardFirmataBLE.ino new file mode 100644 index 0000000..7b17b89 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataBLE/StandardFirmataBLE.ino @@ -0,0 +1,835 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please click on the following link + to open the list of Firmata client libraries in your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated April 15th, 2018 +*/ + +#include +#include +#include + +//#define SERIAL_DEBUG +#include "utility/firmataDebug.h" + +/* + * Uncomment the following include to enable interfacing + * with Serial devices via hardware or software serial. + */ +// In order to use software serial, you will need to compile this sketch with +// Arduino IDE v1.6.6 or higher. Hardware serial should work back to Arduino 1.0. +//#include "utility/SerialFirmata.h" + +// follow the instructions in bleConfig.h to configure your BLE hardware +#include "bleConfig.h" + +#define I2C_WRITE 0x00 //B00000000 +#define I2C_READ 0x08 //B00001000 +#define I2C_READ_CONTINUOUSLY 0x10 //B00010000 +#define I2C_STOP_READING 0x18 //B00011000 +#define I2C_READ_WRITE_MODE_MASK 0x18 //B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK 0x20 //B00100000 +#define I2C_END_TX_MASK 0x40 //B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to run the main loop (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous more */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[64]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +// Forward declare a few functions to avoid compiler errors with older versions +// of the Arduino IDE. +void setPinModeCallback(byte, int); +void reportAnalogCallback(byte analogPin, int value); +void sysexCallback(byte, byte, byte*); + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == PIN_MODE_PWM) { + // Disable PWM if pin mode was previously set to PWM. + digitalWrite(PIN_TO_DIGITAL(pin), LOW); + } + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (argc > 1 && delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(8); // 8 = 8-bit resolution + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + isResetting = false; +} + +void setup() +{ + DEBUG_BEGIN(9600); + + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + stream.setLocalName(FIRMATA_BLE_LOCAL_NAME); + + // set the BLE connection interval - this is the fastest interval you can read inputs + stream.setConnectionInterval(FIRMATA_BLE_MIN_INTERVAL, FIRMATA_BLE_MAX_INTERVAL); + // set how often the BLE TX buffer is flushed (if not full) + stream.setFlushInterval(FIRMATA_BLE_TXBUFFER_FLUSH_INTERVAL); + +#ifdef IS_IGNORE_BLE_PINS + for (byte i = 0; i < TOTAL_PINS; i++) { + if (IS_IGNORE_BLE_PINS(i)) { + Firmata.setPinMode(i, PIN_MODE_IGNORE); + } + } +#endif + + stream.begin(); + Firmata.begin(stream); + + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + // do not process data if no BLE connection is established + // poll will send the TX buffer at the specified flush interval or when the buffer is full + if (!stream.poll()) return; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * Stream buffer using Stream.write() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis = currentMillis; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif +} diff --git a/libraries/Firmata/examples/StandardFirmataBLE/bleConfig.h b/libraries/Firmata/examples/StandardFirmataBLE/bleConfig.h new file mode 100644 index 0000000..412bb84 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataBLE/bleConfig.h @@ -0,0 +1,168 @@ +/*================================================================================================== + * BLE CONFIGURATION + * + * If you are using an Arduino 101, you do not need to make any changes to this file (unless you + * need a unique ble local name (see below). If you are using another supported BLE board or shield, + * follow the instructions for the specific board or shield below. + * + * Make sure you have the Intel Curie Boards package v2.0.2 or higher installed via the Arduino + * Boards Manager. + * + * Supported boards and shields: + * - Arduino 101 (recommended) + * - RedBearLab BLE Shield (v2) ** to be verified ** + * - RedBearLab BLE Nano ** works with modifications ** + * - Adafruit Feather M0 Bluefruit LE + * + *================================================================================================*/ + +// change this to a unique name per board if running StandardFirmataBLE on multiple boards +// within the same physical space +#define FIRMATA_BLE_LOCAL_NAME "FIRMATA" + +/* + * Arduino 101 + * + * Make sure you have the Intel Curie Boards package v2.0.2 or higher installed via the Arduino + * Boards Manager. + * + * Test script: https://gist.github.com/soundanalogous/927360b797574ed50e27 + */ +#ifdef _VARIANT_ARDUINO_101_X_ +// After conversion to units of 1.25ms, both values must be between +// 0x0006 (7.5ms) and 0x0c80 (4s) +#define FIRMATA_BLE_MIN_INTERVAL 8 // ( 8 * 1000) / 1250 == 0x06 -> 7.5ms +#define FIRMATA_BLE_MAX_INTERVAL 30 // (30 * 1000) / 1250 == 0x18 -> 30ms +#endif + + +/* + * RedBearLab BLE Shield + * + * If you are using a RedBearLab BLE shield, uncomment the define below. + * Also, change the define for BLE_RST if you have the jumper set to pin 7 rather than pin 4. + * + * You will need to use the shield with an Arduino Zero, Due, Mega, or other board with sufficient + * Flash and RAM. Arduino Uno, Leonardo and other ATmega328p and Atmega32u4 boards to not have + * enough memory to run StandardFirmataBLE. + * + * TODO: verify if this works and with which boards it works. + * + * Test script: https://gist.github.com/soundanalogous/927360b797574ed50e27 + */ +//#define REDBEAR_BLE_SHIELD + +#ifdef REDBEAR_BLE_SHIELD +#define BLE_REQ 9 +#define BLE_RDY 8 +#define BLE_RST 4 // 4 or 7 via jumper on shield +#endif + + +/* + * Adafruit Feather M0 Bluefruit LE + * + * If you are using an Adafruit Feather M0 Bluefruit LE, uncomment the define below. + * This configuration should also work with other Bluefruit LE boards/modules that communicate + * with the nRF51822 via SPI (e.g. Bluefruit LE SPI Friend, Bluefruit LE Shield), although + * you may need to change the values of BLE_SPI_CS, BLE_SPI_IRQ, and/or BLE_SPI_RST below. + * + * You will need to install a lightly-modified version of the Adafruit BluefruitLE nRF51 + * package, available at: + * https://github.com/cstawarz/Adafruit_BluefruitLE_nRF51/archive/firmata_fixes.zip + */ +//#define BLUEFRUIT_LE_SPI + +#ifdef BLUEFRUIT_LE_SPI +// Both values must be between 10ms and 4s +#define FIRMATA_BLE_MIN_INTERVAL 10 // 10ms +#define FIRMATA_BLE_MAX_INTERVAL 20 // 20ms + +#define BLE_SPI_CS 8 +#define BLE_SPI_IRQ 7 +#define BLE_SPI_RST 4 +#endif + + +/* + * Generic settings + */ +#if !defined(FIRMATA_BLE_MIN_INTERVAL) && !defined(FIRMATA_BLE_MAX_INTERVAL) +// These values apply to all devices using the Arduino BLEPeripheral library +// with a Nordic nRF8001 or nRF51822. Both values must be between +// 0x0006 (7.5ms) and 0x0c80 (4s). +#define FIRMATA_BLE_MIN_INTERVAL 0x0006 // 7.5ms (7.5 / 1.25) +#define FIRMATA_BLE_MAX_INTERVAL 0x0018 // 30ms (30 / 1.25) +#endif + +#if !defined(FIRMATA_BLE_TXBUFFER_FLUSH_INTERVAL) +#define FIRMATA_BLE_TXBUFFER_FLUSH_INTERVAL 30 // 30ms +#endif + + +/*================================================================================================== + * END BLE CONFIGURATION - you should not need to change anything below this line + *================================================================================================*/ + +#ifdef _VARIANT_ARDUINO_101_X_ +#include "utility/BLEStream.h" +BLEStream stream; +#endif + + +#ifdef REDBEAR_BLE_SHIELD +#include +#include "utility/BLEStream.h" +BLEStream stream(BLE_REQ, BLE_RDY, BLE_RST); +#endif + + +#ifdef BLUEFRUIT_LE_SPI +#include "utility/BluefruitLE_SPI_Stream.h" +BluefruitLE_SPI_Stream stream(BLE_SPI_CS, BLE_SPI_IRQ, BLE_SPI_RST); +#endif + + +/* + * RedBearLab BLE Nano (with default switch settings) + * + * Blocked on this issue: https://github.com/RedBearLab/nRF51822-Arduino/issues/46 + * Works with modifications. See comments at top of the test script referenced below. + * When the RBL nRF51822-Arduino library issue is resolved, this should work witout + * any modifications. + * + * Test script: https://gist.github.com/soundanalogous/d39bb3eb36333a0906df + * + * Note: If you have changed the solder jumpers on the Nano you may encounter issues since + * the pins are currently mapped in Firmata only for the default (factory) jumper settings. + */ +// #ifdef BLE_NANO +// #include "utility/BLEStream.h" +// BLEStream stream; +// #endif + + +/* + * RedBearLab Blend and Blend Micro + * + * StandardFirmataBLE requires too much Flash and RAM to run on the ATmega32u4-based Blend + * and Blend Micro boards. It may work with ConfigurableFirmata selecting only analog and/or + * digital I/O. + */ +// #if defined(BLEND_MICRO) || defined(BLEND) +// #include +// #include "utility/BLEStream.h" + +// #define BLE_REQ 6 +// #define BLE_RDY 7 +// #define BLE_RST 4 + +// BLEStream stream(BLE_REQ, BLE_RDY, BLE_RST); +// #endif + + +#if defined(BLE_REQ) && defined(BLE_RDY) && defined(BLE_RST) +#define IS_IGNORE_BLE_PINS(p) ((p) == BLE_REQ || (p) == BLE_RDY || (p) == BLE_RST) +#elif defined(BLE_SPI_CS) && defined(BLE_SPI_IRQ) && defined(BLE_SPI_RST) +#define IS_IGNORE_BLE_PINS(p) ((p) == BLE_SPI_CS || (p) == BLE_SPI_IRQ || (p) == BLE_SPI_RST) +#endif diff --git a/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino b/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino new file mode 100644 index 0000000..e13d166 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino @@ -0,0 +1,802 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please click on the following link + to open the list of Firmata client libraries in your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + Copyright (C) 2015 Brian Schmalz. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated August 17th, 2017 +*/ + +#include // Gives us PWM and Servo on every pin +#include +#include + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to run the main loop (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous more */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[64]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +SoftServo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +// Forward declare a few functions to avoid compiler errors with older versions +// of the Arduino IDE. +void setPinModeCallback(byte, int); +void reportAnalogCallback(byte analogPin, int value); +void sysexCallback(byte, byte, byte*); + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* Sets a pin that is in Servo mode to a particular output value + * (i.e. pulse width). Different boards may have different ways of + * setting servo values, so putting it in a function keeps things cleaner. + */ +void servoWrite(byte pin, int value) +{ + SoftPWMServoPWMWrite(PIN_TO_PWM(pin), value); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == PIN_MODE_PWM) { + // Disable PWM if pin mode was previously set to PWM. + digitalWrite(PIN_TO_DIGITAL(pin), LOW); + } + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + servoWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + servoWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (argc > 1 && delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(DEFAULT_PWM_RESOLUTION); + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + } +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + /* For chipKIT Pi board, we need to use Serial1. All others just use Serial. */ +#if defined(_BOARD_CHIPKIT_PI_) + Serial1.begin(57600); + Firmata.begin(Serial1); +#else + Firmata.begin(57600); +#endif + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * FTDI buffer using Serial.print() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } +} diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino b/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino new file mode 100644 index 0000000..f512cce --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino @@ -0,0 +1,969 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please click on the following link + to open the list of Firmata client libraries in your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated August 17th, 2017 +*/ + +/* + README + + StandardFirmataEthernet is a TCP client/server implementation. You will need a Firmata client library + with a network transport that can act as a TCP server or client in order to establish a connection between + StandardFirmataEthernet and the Firmata client application. + + To use StandardFirmataEthernet you will need to have one of the following + boards or shields: + + - Arduino Ethernet shield (or clone) + - Arduino Ethernet board (or clone) + - Arduino Yun + + Follow the instructions in the ethernetConfig.h file (ethernetConfig.h tab in Arduino IDE) to + configure your particular hardware. + + NOTE: If you are using an Arduino Ethernet shield you cannot use the following pins on + the following boards. Firmata will ignore any requests to use these pins: + + - Arduino Uno or other ATMega328 boards: (D4, D10, D11, D12, D13) + - Arduino Mega: (D4, D10, D50, D51, D52, D53) + - Arduino Leonardo: (D4, D10) + - Arduino Due: (D4, D10) + - Arduino Zero: (D4, D10) + + If you are using an ArduinoEthernet board, the following pins cannot be used (same as Uno): + - D4, D10, D11, D12, D13 +*/ + +#include +#include +#include + +/* + * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your + * connection that may help in the event of connection issues. If defined, some boards may not begin + * executing this sketch until the Serial console is opened. + */ +//#define SERIAL_DEBUG +#include "utility/firmataDebug.h" + +// follow the instructions in ethernetConfig.h to configure your particular hardware +#include "ethernetConfig.h" +#include "utility/EthernetClientStream.h" +#include "utility/EthernetServerStream.h" + +/* + * Uncomment the following include to enable interfacing with Serial devices via hardware or + * software serial. + * + * DO NOT uncomment if you are running StandardFirmataEthernet on an Arduino Leonardo, + * Arduino Micro or other ATMega32u4-based board or you will not have enough Flash and RAM + * remaining to reliably run Firmata. Arduino Yun is okay because it doesn't import the Ethernet + * libraries. + */ +// In order to use software serial, you will need to compile this sketch with +// Arduino IDE v1.6.6 or higher. Hardware serial should work back to Arduino 1.0. +//#include "utility/SerialFirmata.h" + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#if defined remote_ip && !defined remote_host +#ifdef local_ip +EthernetClientStream stream(client, local_ip, remote_ip, NULL, network_port); +#else +EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), remote_ip, NULL, network_port); +#endif +#endif + +#if !defined remote_ip && defined remote_host +#ifdef local_ip +EthernetClientStream stream(client, local_ip, IPAddress(0, 0, 0, 0), remote_host, network_port ); +#else +EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), IPAddress(0, 0, 0, 0), remote_host, network_port); +#endif +#endif + +#if !defined remote_ip && !defined remote_host +#ifdef local_ip +EthernetServerStream stream(local_ip, network_port); +#else +EthernetServerStream stream(IPAddress(0, 0, 0, 0), network_port); +#endif +#endif + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous mode */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[64]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +// Forward declare a few functions to avoid compiler errors with older versions +// of the Arduino IDE. +void setPinModeCallback(byte, int); +void reportAnalogCallback(byte analogPin, int value); +void sysexCallback(byte, byte, byte*); + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Stream output queue using Stream.write() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + // turn on/off reporting + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == PIN_MODE_PWM) { + // Disable PWM if pin mode was previously set to PWM. + digitalWrite(PIN_TO_DIGITAL(pin), LOW); + } + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (argc > 1 && delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(DEFAULT_PWM_RESOLUTION); + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void printEthernetStatus() +{ + DEBUG_PRINT("Local IP Address: "); + IPAddress ip = Ethernet.localIP(); + DEBUG_PRINTLN(ip); +#ifdef remote_ip + DEBUG_PRINT("Connecting to server at: "); + DEBUG_PRINTLN(remote_ip); +#endif +} + +/* + * StandardFirmataEthernet communicates with Ethernet shields over SPI. Therefore all + * SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. + * Additional pins may also need to be ignored depending on the particular board or + * shield in use. + */ +void ignorePins() +{ +#ifdef IS_IGNORE_PIN + for (byte i = 0; i < TOTAL_PINS; i++) { + if (IS_IGNORE_PIN(i)) { + Firmata.setPinMode(i, PIN_MODE_IGNORE); + } + } +#endif + +#ifdef WIZ5100_ETHERNET + // Arduino Ethernet and Arduino EthernetShield have SD SS wired to D4 + pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata + digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA +#endif + +#endif // WIZ5100_ETHERNET +} + +void initTransport() +{ +#ifdef YUN_ETHERNET + Bridge.begin(); +#else +#ifdef local_ip + Ethernet.begin((uint8_t *)mac, local_ip); //start ethernet +#else + DEBUG_PRINTLN("Local IP will be requested from DHCP..."); + //start ethernet using dhcp + if (Ethernet.begin((uint8_t *)mac) == 0) { + DEBUG_PRINTLN("Failed to configure Ethernet using DHCP"); + } +#endif +#endif + printEthernetStatus(); +} + +void initFirmata() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + ignorePins(); + + // start up Network Firmata: + Firmata.begin(stream); + systemResetCallback(); // Initialize default configuration +} + +void setup() +{ + DEBUG_BEGIN(9600); + + initTransport(); + + initFirmata(); +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * Stream buffer using Stream.write() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif + +#if !defined local_ip && !defined YUN_ETHERNET + // only necessary when using DHCP, ensures local IP is updated appropriately if it changes + if (Ethernet.maintain()) { + stream.maintain(Ethernet.localIP()); + } +#endif + +} diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h b/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h new file mode 100644 index 0000000..baf3465 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h @@ -0,0 +1,94 @@ +/*============================================================================== + * NETWORK CONFIGURATION + * + * You must configure your particular hardware. Follow the steps below. + * + * By default, StandardFirmataEthernet is configured as a TCP client. + * To configure as a TCP server, see STEP 2 + *============================================================================*/ + +// STEP 1 [REQUIRED] +// Uncomment / comment the appropriate set of includes for your hardware (OPTION A or B) +// Option A is enabled by default. + +/* + * OPTION A: Configure for Arduino Ethernet board or Arduino Ethernet shield (or clone) + * + * To configure StandardFirmataEthernet to use the original WIZ5100-based + * ethernet shield or Arduino Ethernet uncomment the WIZ5100_ETHERNET define below + */ +#define WIZ5100_ETHERNET + +#ifdef WIZ5100_ETHERNET +#include +#include +EthernetClient client; +#endif + +/* + * OPTION B: Configure for Arduin Yun + * + * The Ethernet port on the Arduino Yun board can be used with Firmata in this configuration. + * + * To execute StandardFirmataEthernet on Yun uncomment the YUN_ETHERNET define below and make + * sure the WIZ5100_ETHERNET define (above) is commented out. + * + * On Yun there's no need to configure local_ip and mac address as this is automatically + * configured on the linux-side of Yun. + * + * Note that it may take several seconds to establish a connection with the Yun. + */ +//#define YUN_ETHERNET + +#ifdef YUN_ETHERNET +#include +#include +YunClient client; +#endif + +// STEP 2 [REQUIRED for all boards and shields] +// TCP Client configuration: +// To configure your board as a TCP client, set the IP address of the server you want to connect to. +// TCP Server configuration: +// To configure your board as a TCP server, comment out the following line and also ensure that +// remote_host is also commented out. +#define remote_ip IPAddress(10, 0, 0, 3) +// *** REMOTE HOST IS NOT YET WORKING *** +// replace with hostname of server you want to connect to, comment out if using 'remote_ip' +// #define remote_host "server.local" + +// STEP 3 [REQUIRED] +// Replace with the port that your client or server is listening on. +#define network_port 3030 + +// STEP 4 [REQUIRED unless using DHCP] +// Replace with your board or ethernet shield's IP address +// Comment out if you want to use DHCP +#define local_ip IPAddress(10, 0, 0, 15) + +// STEP 5 [REQUIRED] +// replace with ethernet shield mac. Must be unique for your network +const byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x53, 0xE5}; + +/*============================================================================== + * CONFIGURATION ERROR CHECK (don't change anything here) + *============================================================================*/ + +#if !defined WIZ5100_ETHERNET && !defined YUN_ETHERNET +#error "you must define either WIZ5100_ETHERNET or YUN_ETHERNET in ethernetConfig.h" +#endif + +#if defined remote_ip && defined remote_host +#error "cannot define both remote_ip and remote_host at the same time in ethernetConfig.h" +#endif + +/*============================================================================== + * PIN IGNORE MACROS (don't change anything here) + *============================================================================*/ + +#if defined(WIZ5100_ETHERNET) + +// ignore SPI pins, pin 10 (Ethernet SS) and pin 4 (SS for SD-Card on Ethernet shield) +#define IS_IGNORE_PIN(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 10) + +#endif diff --git a/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino b/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino new file mode 100644 index 0000000..8fb51eb --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino @@ -0,0 +1,851 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please click on the following link + to open the list of Firmata client libraries in your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated August 17th, 2017 +*/ + +/* + README + + StandardFirmataPlus adds additional features that may exceed the Flash and + RAM sizes of Arduino boards such as ATMega328p (Uno) and ATMega32u4 + (Leonardo, Micro, Yun, etc). It is best to use StandardFirmataPlus with higher + memory boards such as the Arduino Mega, Arduino Due, Teensy 3.0/3.1/3.2. + + All Firmata examples that are appended with "Plus" add the following features: + + - Ability to interface with serial devices using UART, USART, or SoftwareSerial + depending on the capatilities of the board. + + NOTE: In order to use SoftwareSerial with the Firmata Serial feature, + StandardFirmataPlus must be compiled with Arduino v1.6.6 or newer. + + At the time of this writing, StandardFirmataPlus will still compile and run + on ATMega328p and ATMega32u4-based boards, but future versions of this sketch + may not as new features are added. +*/ + +#include +#include +#include + +// In order to use software serial, you will need to compile this sketch with +// Arduino IDE v1.6.6 or higher. Hardware serial should work back to Arduino 1.0. +#include "utility/SerialFirmata.h" + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to run the main loop (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous more */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[64]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +// Forward declare a few functions to avoid compiler errors with older versions +// of the Arduino IDE. +void setPinModeCallback(byte, int); +void reportAnalogCallback(byte analogPin, int value); +void sysexCallback(byte, byte, byte*); + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == PIN_MODE_PWM) { + // Disable PWM if pin mode was previously set to PWM. + digitalWrite(PIN_TO_DIGITAL(pin), LOW); + } + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (argc > 1 && delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(DEFAULT_PWM_RESOLUTION); + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + // Save a couple of seconds by disabling the startup blink sequence. + Firmata.disableBlinkVersion(); + + // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega, + // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this: + // Serial1.begin(57600); + // Firmata.begin(Serial1); + // However do not do this if you are using SERIAL_MESSAGE + + Firmata.begin(57600); + while (!Serial) { + ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101 + } + + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * FTDI buffer using Serial.print() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif +} diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino b/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino new file mode 100644 index 0000000..4f7e416 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino @@ -0,0 +1,1048 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please click on the following link + to open the list of Firmata client libraries in your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + Copyright (C) 2015-2016 Jesse Frush. All rights reserved. + Copyright (C) 2016 Jens B. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated August 17th, 2017 +*/ + +/* + README + + StandardFirmataWiFi enables the use of Firmata over a TCP connection. It can be configured as + either a TCP server or TCP client. + + To use StandardFirmataWiFi you will need to have one of the following + boards or shields: + + - Arduino WiFi Shield (or clone) + - Arduino WiFi Shield 101 + - Arduino MKR1000 board + - ESP8266 WiFi board compatible with ESP8266 Arduino core + + Follow the instructions in the wifiConfig.h file (wifiConfig.h tab in Arduino IDE) to + configure your particular hardware. + + Dependencies: + - WiFi Shield 101 requires version 0.7.0 or higher of the WiFi101 library (available in Arduino + 1.6.8 or higher, or update the library via the Arduino Library Manager or clone from source: + https://github.com/arduino-libraries/WiFi101) + - ESP8266 requires the Arduino ESP8266 core v2.1.0 or higher which can be obtained here: + https://github.com/esp8266/Arduino + + In order to use the WiFi Shield 101 with Firmata you will need a board with at least 35k of Flash + memory. This means you cannot use the WiFi Shield 101 with an Arduino Uno or any other + ATmega328p-based microcontroller or with an Arduino Leonardo or other ATmega32u4-based + microcontroller. Some boards that will work are: + + - Arduino Zero + - Arduino Due + - Arduino 101 + - Arduino Mega + + NOTE: If you are using an Arduino WiFi (legacy) shield you cannot use the following pins on + the following boards. Firmata will ignore any requests to use these pins: + + - Arduino Uno or other ATMega328 boards: (D4, D7, D10, D11, D12, D13) + - Arduino Mega: (D4, D7, D10, D50, D51, D52, D53) + - Arduino Due, Zero or Leonardo: (D4, D7, D10) + + If you are using an Arduino WiFi 101 shield you cannot use the following pins on the following + boards: + + - Arduino Due or Zero: (D5, D7, D10) + - Arduino Mega: (D5, D7, D10, D50, D52, D53) +*/ + +#include +#include +#include + +/* + * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your + * connection that may help in the event of connection issues. If defined, some boards may not begin + * executing this sketch until the Serial console is opened. + */ +//#define SERIAL_DEBUG +#include "utility/firmataDebug.h" + +/* + * Uncomment the following include to enable interfacing with Serial devices via hardware or + * software serial. + */ +// In order to use software serial, you will need to compile this sketch with +// Arduino IDE v1.6.6 or higher. Hardware serial should work back to Arduino 1.0. +//#include "utility/SerialFirmata.h" + +// follow the instructions in wifiConfig.h to configure your particular hardware +#include "wifiConfig.h" + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + +#define MAX_CONN_ATTEMPTS 20 // [500 ms] -> 10 s + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +#ifdef STATIC_IP_ADDRESS +IPAddress local_ip(STATIC_IP_ADDRESS); +#endif +#ifdef SUBNET_MASK +IPAddress subnet(SUBNET_MASK); +#endif +#ifdef GATEWAY_IP_ADDRESS +IPAddress gateway(GATEWAY_IP_ADDRESS); +#endif + +int connectionAttempts = 0; +bool streamConnected = false; + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous mode */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[64]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +// Forward declare a few functions to avoid compiler errors with older versions +// of the Arduino IDE. +void setPinModeCallback(byte, int); +void reportAnalogCallback(byte analogPin, int value); +void sysexCallback(byte, byte, byte*); + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Stream output queue using Stream.write() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +// function forward declarations for xtensa compiler (ESP8266) +void enableI2CPins(); +void disableI2CPins(); +void reportAnalogCallback(byte analogPin, int value); + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == PIN_MODE_PWM) { + // Disable PWM if pin mode was previously set to PWM. + digitalWrite(PIN_TO_DIGITAL(pin), LOW); + } + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (argc > 1 && delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(DEFAULT_PWM_RESOLUTION); + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +/* + * Called when a TCP connection is either connected or disconnected. + * TODO: + * - report connected or reconnected state to host (to be added to protocol) + * - report current state to host (to be added to protocol) + */ +void hostConnectionCallback(byte state) +{ + switch (state) { + case HOST_CONNECTION_CONNECTED: + DEBUG_PRINTLN( "TCP connection established" ); + break; + case HOST_CONNECTION_DISCONNECTED: + DEBUG_PRINTLN( "TCP connection disconnected" ); + break; + } +} + +/* + * Print the status of the WiFi connection. This is the connection to the access point rather + * than the TCP connection. + */ +void printWifiStatus() { + if ( WiFi.status() != WL_CONNECTED ) + { + DEBUG_PRINT( "WiFi connection failed. Status value: " ); + DEBUG_PRINTLN( WiFi.status() ); + } + else + { + // print the SSID of the network you're attached to: + DEBUG_PRINT( "SSID: " ); + DEBUG_PRINTLN( WiFi.SSID() ); + + // print your WiFi shield's IP address: + DEBUG_PRINT( "IP Address: " ); + IPAddress ip = WiFi.localIP(); + DEBUG_PRINTLN( ip ); + + // print the received signal strength: + DEBUG_PRINT( "signal strength (RSSI): " ); + long rssi = WiFi.RSSI(); + DEBUG_PRINT( rssi ); + DEBUG_PRINTLN( " dBm" ); + } +} + +/* + * StandardFirmataWiFi communicates with WiFi shields over SPI. Therefore all + * SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. + * Additional pins may also need to be ignored depending on the particular board or + * shield in use. + */ +void ignorePins() +{ +#ifdef IS_IGNORE_PIN + for (byte i = 0; i < TOTAL_PINS; i++) { + if (IS_IGNORE_PIN(i)) { + Firmata.setPinMode(i, PIN_MODE_IGNORE); + } + } +#endif + + //Set up controls for the Arduino WiFi Shield SS for the SD Card +#ifdef ARDUINO_WIFI_SHIELD + // Arduino WiFi Shield has SD SS wired to D4 + pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata + digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA +#endif //defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + +#endif //ARDUINO_WIFI_SHIELD +} + +void initTransport() +{ + // This statement will clarify how a connection is being made + DEBUG_PRINT( "StandardFirmataWiFi will attempt a WiFi connection " ); +#if defined(WIFI_101) + DEBUG_PRINTLN( "using the WiFi 101 library." ); +#elif defined(ARDUINO_WIFI_SHIELD) + DEBUG_PRINTLN( "using the legacy WiFi library." ); +#elif defined(ESP8266_WIFI) + DEBUG_PRINTLN( "using the ESP8266 WiFi library." ); +#elif defined(HUZZAH_WIFI) + DEBUG_PRINTLN( "using the HUZZAH WiFi library." ); + //else should never happen here as error-checking in wifiConfig.h will catch this +#endif //defined(WIFI_101) + + // Configure WiFi IP Address +#ifdef STATIC_IP_ADDRESS + DEBUG_PRINT( "Using static IP: " ); + DEBUG_PRINTLN( local_ip ); +#if defined(ESP8266_WIFI) || (defined(SUBNET_MASK) && defined(GATEWAY_IP_ADDRESS)) + stream.config( local_ip , gateway, subnet ); +#else + // you can also provide a static IP in the begin() functions, but this simplifies + // ifdef logic in this sketch due to support for all different encryption types. + stream.config( local_ip ); +#endif +#else + DEBUG_PRINTLN( "IP will be requested from DHCP ..." ); +#endif + + stream.attach(hostConnectionCallback); + + // Configure WiFi security and initiate WiFi connection +#if defined(WIFI_WEP_SECURITY) + DEBUG_PRINT( "Attempting to connect to WEP SSID: " ); + DEBUG_PRINTLN(ssid); + stream.begin(ssid, wep_index, wep_key); +#elif defined(WIFI_WPA_SECURITY) + DEBUG_PRINT( "Attempting to connect to WPA SSID: " ); + DEBUG_PRINTLN(ssid); + stream.begin(ssid, wpa_passphrase); +#else //OPEN network + DEBUG_PRINTLN( "Attempting to connect to open SSID: " ); + DEBUG_PRINTLN(ssid); + stream.begin(ssid); +#endif //defined(WIFI_WEP_SECURITY) + DEBUG_PRINTLN( "WiFi setup done" ); + + // Wait for connection to access point to be established. + while (WiFi.status() != WL_CONNECTED && ++connectionAttempts <= MAX_CONN_ATTEMPTS) { + delay(500); + DEBUG_PRINT("."); + } + printWifiStatus(); +} + +void initFirmata() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + ignorePins(); + + // Initialize Firmata to use the WiFi stream object as the transport. + Firmata.begin(stream); + systemResetCallback(); // reset to default config +} + +void setup() +{ + DEBUG_BEGIN(9600); + + initTransport(); + + initFirmata(); +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * Stream buffer using Stream.write() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) { + Firmata.processInput(); + } + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif + + stream.maintain(); +} diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h b/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h new file mode 100644 index 0000000..bedc744 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h @@ -0,0 +1,240 @@ +/*============================================================================== + * WIFI CONFIGURATION + * + * You must configure your particular hardware. Follow the steps below. + * + * By default, StandardFirmataWiFi is configured as a TCP server, to configure + * as a TCP client, see STEP 2. + *============================================================================*/ + +// STEP 1 [REQUIRED] +// Uncomment / comment the appropriate set of includes for your hardware (OPTION A, B or C) +// Arduino MKR1000 or ESP8266 are enabled by default if compiling for either of those boards. + +/* + * OPTION A: Configure for Arduino MKR1000 or Arduino WiFi Shield 101 + * + * This will configure StandardFirmataWiFi to use the WiFi101 library, which works with the + * Arduino WiFi101 shield and devices that have the WiFi101 chip built in (such as the MKR1000). + * It is compatible with 802.11 B/G/N networks. + * + * If you are using the MKR1000 board, continue on to STEP 2. If you are using the WiFi 101 shield, + * follow the instructions below. + * + * To enable for the WiFi 101 shield, uncomment the #define WIFI_101 below and verify the + * #define ARDUINO_WIFI_SHIELD is commented out for OPTION B. + * + * IMPORTANT: You must have the WiFI 101 library installed. To easily install this library, open + * the library manager via: Arduino IDE Menus: Sketch > Include Library > Manage Libraries > filter + * search for "WiFi101" > Select the result and click 'install' + */ +//#define WIFI_101 + +//do not modify the following 11 lines +#if defined(ARDUINO_SAMD_MKR1000) && !defined(WIFI_101) +// automatically include if compiling for MRK1000 +#define WIFI_101 +#endif +#ifdef WIFI_101 +#include +#include "utility/WiFiClientStream.h" +#include "utility/WiFiServerStream.h" + #define WIFI_LIB_INCLUDED +#endif + +/* + * OPTION B: Configure for legacy Arduino WiFi shield + * + * This will configure StandardFirmataWiFi to use the original WiFi library (deprecated) provided + * with the Arduino IDE. It is supported by the Arduino WiFi shield (a discontinued product) and + * is compatible with 802.11 B/G networks. + * + * To configure StandardFirmataWiFi to use the legacy Arduino WiFi shield + * leave the #define below uncommented and ensure #define WIFI_101 is commented out for OPTION A. + */ +//#define ARDUINO_WIFI_SHIELD + +//do not modify the following 10 lines +#ifdef ARDUINO_WIFI_SHIELD +#include +#include "utility/WiFiClientStream.h" +#include "utility/WiFiServerStream.h" + #ifdef WIFI_LIB_INCLUDED + #define MULTIPLE_WIFI_LIB_INCLUDES + #else + #define WIFI_LIB_INCLUDED + #endif +#endif + +/* + * OPTION C: Configure for ESP8266 + * + * This will configure StandardFirmataWiFi to use the ESP8266WiFi library for boards + * with an ESP8266 chip. It is compatible with 802.11 B/G/N networks. + * + * The appropriate libraries are included automatically when compiling for the ESP8266 so + * continue on to STEP 2. + * + * IMPORTANT: You must have the esp8266 board support installed. To easily install this board see + * the instructions here: https://github.com/esp8266/Arduino#installing-with-boards-manager. + */ +//do not modify the following 14 lines +#ifdef ESP8266 +// automatically include if compiling for ESP8266 +#define ESP8266_WIFI +#endif +#ifdef ESP8266_WIFI +#include +#include "utility/WiFiClientStream.h" +#include "utility/WiFiServerStream.h" + #ifdef WIFI_LIB_INCLUDED + #define MULTIPLE_WIFI_LIB_INCLUDES + #else + #define WIFI_LIB_INCLUDED + #endif +#endif + +/* + * OPTION D: Configure for HUZZAH + * + * HUZZAH with CC3000 is not yet supported, this will be added in a later revision to + * StandardFirmataWiFi. + * For HUZZAH with ESP8266 use ESP8266_WIFI. + */ + +//------------------------------ +// TODO +//------------------------------ +//#define HUZZAH_WIFI + + +// STEP 2 [OPTIONAL for all boards and shields] +// If you want to setup you board as a TCP client, uncomment the following define and replace +// the IP address with the IP address of your server. +//#define SERVER_IP 10, 0, 0, 15 + + +// STEP 3 [REQUIRED for all boards and shields] +// replace this with your wireless network SSID +char ssid[] = "your_network_name"; + + +// STEP 4 [OPTIONAL for all boards and shields] +// If you want to use a static IP (v4) address, uncomment the line below. You can also change the IP. +// If the first line is commented out, the WiFi shield will attempt to get an IP from the DHCP server. +// If you are using a static IP with the ESP8266 then you must also uncomment the SUBNET and GATEWAY. +//#define STATIC_IP_ADDRESS 192,168,1,113 +//#define SUBNET_MASK 255,255,255,0 // REQUIRED for ESP8266_WIFI, optional for others +//#define GATEWAY_IP_ADDRESS 0,0,0,0 // REQUIRED for ESP8266_WIFI, optional for others + + +// STEP 5 [REQUIRED for all boards and shields] +// define your port number here, you will need this to open a TCP connection to your Arduino +#define SERVER_PORT 3030 + + +// STEP 6 [REQUIRED for all boards and shields] +// determine your network security type (OPTION A, B, or C). Option A is the most common, and the +// default. + +/* + * OPTION A: WPA / WPA2 + * + * WPA is the most common network security type. A passphrase is required to connect to this type. + * + * To enable, leave #define WIFI_WPA_SECURITY uncommented below, set your wpa_passphrase value + * appropriately, and do not uncomment the #define values under options B and C + */ +#define WIFI_WPA_SECURITY + +#ifdef WIFI_WPA_SECURITY +char wpa_passphrase[] = "your_wpa_passphrase"; +#endif //WIFI_WPA_SECURITY + + +/* + * OPTION B: WEP + * + * WEP is a less common (and regarded as less safe) security type. A WEP key and its associated + * index are required to connect to this type. + * + * To enable, Uncomment the #define below, set your wep_index and wep_key values appropriately, + * and verify the #define values under options A and C are commented out. + */ +//#define WIFI_WEP_SECURITY + +#ifdef WIFI_WEP_SECURITY +//The wep_index below is a zero-indexed value. +//Valid indices are [0-3], even if your router/gateway numbers your keys [1-4]. +byte wep_index = 0; +char wep_key[] = "your_wep_key"; +#endif //WIFI_WEP_SECURITY + + +/* + * OPTION C: Open network (no security) + * + * Open networks have no security, can be connected to by any device that knows the ssid, and are + * unsafe. + * + * To enable, uncomment #define WIFI_NO_SECURITY below and verify the #define values + * under options A and B are commented out. + */ +//#define WIFI_NO_SECURITY + +/*============================================================================== + * CONFIGURATION ERROR CHECK (don't change anything here) + *============================================================================*/ + +#ifdef MULTIPLE_WIFI_LIB_INCLUDES +#error "you may not define more than one wifi device type in wifiConfig.h." +#endif + +#ifndef WIFI_LIB_INCLUDED +#error "you must define a wifi device type in wifiConfig.h." +#endif + +#if ((defined(WIFI_NO_SECURITY) && (defined(WIFI_WEP_SECURITY) || defined(WIFI_WPA_SECURITY))) || (defined(WIFI_WEP_SECURITY) && defined(WIFI_WPA_SECURITY))) +#error "you may not define more than one security type at the same time in wifiConfig.h." +#endif //WIFI_* security define check + +#if !(defined(WIFI_NO_SECURITY) || defined(WIFI_WEP_SECURITY) || defined(WIFI_WPA_SECURITY)) +#error "you must define a wifi security type in wifiConfig.h." +#endif //WIFI_* security define check + +#if (defined(ESP8266_WIFI) && !(defined(WIFI_NO_SECURITY) || (defined(WIFI_WPA_SECURITY)))) +#error "you must choose between WIFI_NO_SECURITY and WIFI_WPA_SECURITY" +#endif + +/*============================================================================== + * WIFI STREAM (don't change anything here) + *============================================================================*/ + +#ifdef SERVER_IP + WiFiClientStream stream(IPAddress(SERVER_IP), SERVER_PORT); +#else + WiFiServerStream stream(SERVER_PORT); +#endif + +/*============================================================================== + * PIN IGNORE MACROS (don't change anything here) + *============================================================================*/ + +#if defined(WIFI_101) && !defined(ARDUINO_SAMD_MKR1000) +// ignore SPI pins, pin 5 (reset WiFi101 shield), pin 7 (WiFi handshake) and pin 10 (WiFi SS) +// also don't ignore SS pin if it's not pin 10. Not needed for Arduino MKR1000. +#define IS_IGNORE_PIN(p) ((p) == 10 || (IS_PIN_SPI(p) && (p) != SS) || (p) == 5 || (p) == 7) + +#elif defined(ARDUINO_WIFI_SHIELD) && defined(__AVR_ATmega32U4__) +// ignore SPI pins, pin 4 (SS for SD-Card on WiFi-shield), pin 7 (WiFi handshake) and pin 10 (WiFi SS) +// On Leonardo, pin 24 maps to D4 and pin 28 maps to D10 +#define IS_IGNORE_PIN(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 7 || (p) == 10 || (p) == 24 || (p) == 28) + +#elif defined(ARDUINO_WIFI_SHIELD) +// ignore SPI pins, pin 4 (SS for SD-Card on WiFi-shield), pin 7 (WiFi handshake) and pin 10 (WiFi SS) +#define IS_IGNORE_PIN(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 7 || (p) == 10) + +#elif defined(ESP8266_WIFI) && defined(SERIAL_DEBUG) +#define IS_IGNORE_PIN(p) ((p) == 1) + +#endif diff --git a/libraries/Firmata/extras/revisions.txt b/libraries/Firmata/extras/revisions.txt new file mode 100644 index 0000000..6290a72 --- /dev/null +++ b/libraries/Firmata/extras/revisions.txt @@ -0,0 +1,265 @@ +FIRMATA 2.5.7 - Aug 19, 2017 + +[core library] +* Added support for Adafruit nrf52 boards (hathach) +* Added TCP server option to StandardFirmataEthernet (MJPees) +* Added support for STM32-based boards (fpistm) +* Added support for MKRFox1200 (sandeepmistry) + +[StandardFirmata & variants] +* Fixed I2C config parameter interpretation (zfields) +* Improve debug output in StandardFirmataEthernet + +FIRMATA 2.5.6 - Mar 18, 2017 + +[core library] +* Fixed string encoder/decoder bug that also affected I2C (Zak Fields) +* Added support for Arduino Primo (chiararuggeri) +* Added unit tests for Firmata string message encoding/decoding + +FIRMATA 2.5.5 - Mar 6, 2017 + +[core library] +* Updated BLEStream for compatibility with CurieBLE v2 (Sandeep Mistry) +* Added support for MKRZero (Sandeep Mistry) + +This update also includes a number of changes from an ongoing refactor by +Zak Fields of the Firmata core. These changes don't impact user facing sketches, +they are all internal only. Changes include: + +* Split out parser logic into new lib free of Arduino-specific dependencies. +* Add new class to support cross platform marshalling of Firmata procedure calls. +* Split out core constants to separate file. +* Split out core defines to separate file. +* Added firmata namespace to core library classes. + +FIRMATA 2.5.4 - Oct 23, 2016 + +[core library] +* Added Teensy 3.5 and 3.6 to Boards.h +* Assign blinkVersionDisabled in constructor to fix compiler issue in Arduino 1.0.6 + +[StandardFirmata & variants] +* Only disable PWM when setting pinMode to OUTPUT if pinMode was previously PWM +* Forward declare some functions to fix compiler issues with older IDE versions + +FIRMATA 2.5.3 - Jun 18, 2016 + +[core library] +* Added ESP8266 support (Jens B. & Jacob Rosenthal) +* Added host connection callback (Jens B.) +* Added Wi-Fi TCP client (Jens B.) +* Added BLE transport (BLEStream based on BLESerial by Volta Molda) +* Fixed Arduino Galileo and Edison compile issues + +[StandardFirmata & variants] +* Added StandardFirmataBLE (for use with Arduino 101) +* Added ability to choose between Wi-Fi TCP client or server (Jens B.) +* Various updates to StandardFirmataWiFi (Jens B.) +* Increased I2C RX data buffer from 32 to 64 bytes (Rick Waldron) +* Removed StandardFirmataEthernetPlus +* Made StandardFirmataEtherent configurable (to optionally add Plus functionality) +* Improved configuration instructions for StandardFirmataEthernet and StandardFirmataWiFi + +FIRMATA 2.5.2 - Feb 15, 2016 + +[core library] +* Added Wi-Fi transport (Jesse Frush) +* Added support for Arduino MKR1000 (Jesse Frush) +* Moved Serial feature to own class SerialFirmata +* Moved pin config and pin state handling to Firmata.cpp +* Added new method disableBlinkVersion to provide a way to optionally bypass startup blink sequence + +[StandardFirmata & variants] +* Added StandardFirmataWiFi (Jesse Frush) +* Added ethernetConfig.h for StandardFirmataEthernet and StandardFirmtaEthernetPlus +* Removed serialUtils.h and using SerialFirmata class instead for Serial feature + +FIRMATA 2.5.1 - Dec 26, 2015 + +[core library] +* Added support for Arduino 101 +* Make VERSION_BLINK_PIN optional +* Separate protocol version from firmware version. + Use FIRMATA_PROTOCOL_VERSION_[MAJOR/MINOR/BUGFIX] for protocol and use + FIRMATA_FIRMWARE_VERSION_[MAJOR/MINOR/BUGFIX] for firmware (library version). + +[StandardFirmata & variants] +* Added ability to auto-restart I2C transmission by setting bit 6 of byte 3 + of the I2C_REQUEST message. + +FIRMATA 2.5.0 - Nov 7, 2015 + +[core library] +* Added Serial feature for interfacing with serial devices via hardware + or software serial. See github.com/firmata/protocol/serial.md for details +* Added ability to set the value of a pin by sending a single value instead + of a port value. See 'set digital pin value' in github.com/firmata/protocol/protocol.md + for details +* Added support for Arduino Zero board +* Added support for Teensy LC board (copied from Teensy Firmata lib) +* Added support for Pinoccio Scout board (Pawel Szymczykowski) +* Lowered minimun sampling interval from 10 to 1 millisecond +* Added new pin mode (PIN_MODE_PULLUP) for setting the INPUT_PULLUP pin mode +* Changed pin mode defines to safer names (old names still included but + deprecated) - see Firmata.h + +[StandardFirmata & variants] +* Created new StandardFirmataPlus that implements the Serial feature + Note: The new Serial features is only implemented in the "Plus" versions of + StandardFirmata. +* Created new StandardFirmataEthernetPlus that implements the Serial feature +* Fixed issue where StandardFirmata was not compiling for Intel Galileo boards +* Moved StandardFirmataYun to its own repo (github.com/firmata/StandardFirmataYun) + +FIRMATA 2.4.4 - Aug 9, 2015 + +[core library] +* Added support for chipKIT boards (Brian Schmalz, Rick Anderson and Keith Vogel) +* Added support for ATmega328 boards (previously only ATmega328p was supported) + +[StandardFirmata] +* Added StandardFirmataChipKIT for ChipKIT boards (Brian Schmalz, Rick Anderson and Keith Vogel) +* Ensure Serial is ready on Leonardo and other ATMega32u4-based boards + +FIRMATA 2.4.3 - Apr 11, 2015 + +[core library] +* Added debug macros (utility/firmataDebug.h) +* Added Norbert Truchsess' EthernetClientStream lib from the configurable branch + +[examples] +* Added StandardFirmataEthernet to enable Firmata over Ethernet +* Minor updates to StandardFirmata and StandardFirmataYun + +FIRMATA 2.4.2 - Mar 16, 2015 + +[core library] +* Add support for Teesy 3.1 (Olivier Louvignes) + +FIRMATA 2.4.1 - Feb 7, 2015 + +[core library] +* Fixed off-by-one bug in setFirmwareNameAndVersion (Brian Schmalz) + +[StandardFirmata] +* Prevent analog values from being reported during system reset + +FIRMATA 2.4.0 - Dec 21, 2014 + +Changes from 2.3.6 to 2.4 that may impact existing Firmata client implementations: + +* When sending a string from the client application to the board (STRING_DATA) a +static buffer is now used for the incoming string in place of a dynamically allocated +block of memory (see Firmata.cpp lines 181 - 205). In Firmata 2.3.6 and older, +the dynamically allocated block was never freed, causing a memory leak. If your +client library had freed this memory in the string callback method, that code +will break in Firmata 2.4. If the string data needs to persist beyond the string +callback, it should be copied within the string callback. + +* As of Firmata 2.4, when digital port reporting or analog pin reporting is enabled, +the value of the port (digital) or pin (analog) is immediately sent back to the client +application. This will likely not have a negative impact on existing client +implementations, but may be unexpected. This feature was added to better support +non-serial streams (such as Ethernet, Wi-Fi, Bluetooth, etc) that may lose +connectivity and need a quick way to get the current state of the pins upon +reestablishing a connection. + +[core library] +* Changed sendValueAsTwo7bitBytes, startSysex and endSysex from private to + public methods. +* Added Intel Galileo to Boards.h +* Renamed FirmataSerial to FirmataStream +* Updated to latest Arduino library format +* writePort function in Boards.h now returns 1 (to suppress compiler warning) +* Updated syntax highlighting (keywords.txt) +* Fixed IS_PIN_SPI ifndef condition in boards.h +* Added constants to Firmata.h to reserve configurable firmata features +* Fixed issue where firmwareName was not reported correctly in Windows +* Ensure incoming String via STRING_DATA command is null-terminated +* Fixed memory leak when receiving String via STRING_DATA command + (note this change may break existing code if you were manually deallocating + the incoming string in your string callback function. See code for details) +* Added ability for user to specify a filename when calling setFirmwareNameAndVersion +* Increased input data buffer size from 32 to 64 bytes + +[StandardFirmata] +* Updated I2C_READ_CONTINUOUSLY to work with or without slaveRegister (Rick Waldron) +* Added Yun variant of StandardFirmata +* When a digital port is enabled, its value is now immediately sent to the client +* When an analog pin is enabled, its value is now immediately sent to the client +* Changed the way servo pins are mapped to enable use of servos on + a wider range of pins, including analog pins. +* Fixed management of unexpected sized I2C replies (Nahuel Greco) +* Fixed a bug when removing a monitored device with I2C_STOP_Reading (Nahuel Greco) +* Fixed conditional expression in I2C_STOP_READING case +* Changed samplingInterval from type int to type unsigned int +* Shortened error message strings to save a few bytes + +[examples] +* Updated FirmataServo example to use new pin mapping technique +* Removed makefiles from examples (because they were not being updated) +* Updated all examples to set current firmware version + +FIRMATA 2.3.6 - Jun 18, 2013 (Version included with Arduino core libraries) + +[core library] +* Fixed bug introduced in 2.3.5 that broke ability to use Ethernet. + +FIRMATA 2.3.5 - May 21, 2013 + +[core library] +* Added Arduino Due to Boards.h +* Added Teensy 3.0 to Boards.h +* Updated unit tests to use ArduinoUnit v2.0 +* Renamed pin13strobe to strobeBlinkPin +* Removed blinkVersion method from begin method for non-serial streams +* Fixed memory leak in setting firmware version (Matthew Murdoch) +* Added unit tests for a few core functions (Matthew Murdoch) +* Added IS_PIN_SPI macro to all board definitions in Board.h (Norbert Truchsess) + +FIRMATA 2.3.4 - Feb 11, 2013 + +[core library] +* Fixed Stream implementation so Firmata can be used with Streams other than + Serial (Norbert Truchsess) + +FIRMATA 2.3.3 - Oct 6, 2012 + +[core library] +* Added write method to expose FirmataSerial.write +* Added Arduino Leonardo to Boards.h + +[StandardFirmata] +* Changed all instances of Serial.write to Firmata.write +* Fixed delayMicroseconds(0) bug in readAndReportData + +FIRMATA 2.3.0 - 2.3.2 + +* Removed angle from servo config +* Changed file extensions from .pde to .ino +* Added MEGA2560 to Boards.h +* Added I2C pins to Boards.h +* Modified examples to be compatible with Arduino 0022 and 1.0 or greater +* Removed I2CFirmata example +* Changes to StandardFirmata + * Added I2C support + * Added system reset message to reset all pins to default config on sysex reset + +FIRMATA 2.2 (changes prior to Firmata 2.3.0 were not well documented) + +* changes undocumented + +FIRMATA 2.1 + +* added support for changing the sampling interval +* added Servo support + +FIRMATA 2.0 + +* changed to 8-bit port-based digital messages to mirror ports from previous 14-bit ports modeled after the standard Arduino board. +* switched order of version message so major version is reported first + +FIRMATA 1.0 + +* switched to MIDI-compatible packet format (though the message interpretation differs) diff --git a/libraries/Firmata/keywords.txt b/libraries/Firmata/keywords.txt new file mode 100644 index 0000000..5ab13d0 --- /dev/null +++ b/libraries/Firmata/keywords.txt @@ -0,0 +1,90 @@ +####################################### +# Syntax Coloring Map For Firmata +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Firmata KEYWORD1 Firmata +callbackFunction KEYWORD1 callbackFunction +systemResetCallbackFunction KEYWORD1 systemResetCallbackFunction +stringCallbackFunction KEYWORD1 stringCallbackFunction +sysexCallbackFunction KEYWORD1 sysexCallbackFunction + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +printVersion KEYWORD2 +blinkVersion KEYWORD2 +printFirmwareVersion KEYWORD2 +setFirmwareVersion KEYWORD2 +setFirmwareNameAndVersion KEYWORD2 +available KEYWORD2 +processInput KEYWORD2 +isParsingMessage KEYWORD2 +parse KEYWORD2 +sendAnalog KEYWORD2 +sendDigital KEYWORD2 +sendDigitalPort KEYWORD2 +sendString KEYWORD2 +sendSysex KEYWORD2 +getPinMode KEYWORD2 +setPinMode KEYWORD2 +getPinState KEYWORD2 +setPinState KEYWORD2 +attach KEYWORD2 +detach KEYWORD2 +write KEYWORD2 +sendValueAsTwo7bitBytes KEYWORD2 +startSysex KEYWORD2 +endSysex KEYWORD2 +writePort KEYWORD2 +readPort KEYWORD2 +disableBlinkVersion KEYWORD2 + + +####################################### +# Constants (LITERAL1) +####################################### + +FIRMATA_MAJOR_VERSION LITERAL1 +FIRMATA_MINOR_VERSION LITERAL1 +FIRMATA_BUGFIX_VERSION LITERAL1 + +MAX_DATA_BYTES LITERAL1 + +DIGITAL_MESSAGE LITERAL1 +ANALOG_MESSAGE LITERAL1 +REPORT_ANALOG LITERAL1 +REPORT_DIGITAL LITERAL1 +REPORT_VERSION LITERAL1 +SET_PIN_MODE LITERAL1 +SET_DIGITAL_PIN_VALUE LITERAL1 +SYSTEM_RESET LITERAL1 +START_SYSEX LITERAL1 +END_SYSEX LITERAL1 +REPORT_FIRMWARE LITERAL1 +STRING_DATA LITERAL1 + +PIN_MODE_ANALOG LITERAL1 +PIN_MODE_PWM LITERAL1 +PIN_MODE_SERVO LITERAL1 +PIN_MODE_SHIFT LITERAL1 +PIN_MODE_I2C LITERAL1 +PIN_MODE_ONEWIRE LITERAL1 +PIN_MODE_STEPPER LITERAL1 +PIN_MODE_ENCODER LITERAL1 +PIN_MODE_SERIAL LITERAL1 +PIN_MODE_PULLUP LITERAL1 +PIN_MODE_IGNORE LITERAL1 + +TOTAL_PINS LITERAL1 +TOTAL_ANALOG_PINS LITERAL1 +TOTAL_DIGITAL_PINS LITERAL1 +TOTAL_PIN_MODES LITERAL1 +TOTAL_PORTS LITERAL1 +ANALOG_PORT LITERAL1 +MAX_SERVOS LITERAL1 diff --git a/libraries/Firmata/library.properties b/libraries/Firmata/library.properties new file mode 100644 index 0000000..8557370 --- /dev/null +++ b/libraries/Firmata/library.properties @@ -0,0 +1,9 @@ +name=Firmata +version=2.5.8 +author=Firmata Developers +maintainer=https://github.com/firmata/arduino +sentence=Enables the communication with computer apps using a standard serial protocol. For all Arduino/Genuino boards. +paragraph=The Firmata library implements the Firmata protocol for communicating with software on the host computer. This allows you to write custom firmware without having to create your own protocol and objects for the programming environment that you are using. +category=Device Control +url=https://github.com/firmata/arduino +architectures=* diff --git a/libraries/Firmata/readme.md b/libraries/Firmata/readme.md new file mode 100644 index 0000000..988edfd --- /dev/null +++ b/libraries/Firmata/readme.md @@ -0,0 +1,194 @@ +# Firmata + +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/firmata/arduino?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +Firmata is a protocol for communicating with microcontrollers from software on a host computer. The [protocol](https://github.com/firmata/protocol) can be implemented in firmware on any microcontroller architecture as well as software on any host computer software package. The Arduino repository described here is a Firmata library for Arduino and Arduino-compatible devices. If you would like to contribute to Firmata, please see the [Contributing](#contributing) section below. + +# Contents + +- [Usage](#usage) +- [Firmata Client Libraries](#firmata-client-libraries) +- [Updating Firmata in the Arduino IDE - Arduino 1.6.4 and higher](#updating-firmata-in-the-arduino-ide---arduino-164-and-higher) +- [Cloning Firmata](#cloning-firmata) +- [Updating Firmata in the Arduino IDE - older versions (<= 1.6.3 or 1.0.x)](#updating-firmata-in-the-arduino-ide---older-versions--163-or-10x) + - [Mac OSX:](#mac-osx) + - [Windows](#windows) + - [Linux](#linux) +- [Using the Source code rather than release archive (only for versions older than Arduino 1.6.3)](#using-the-source-code-rather-than-release-archive-only-for-versions-older-than-arduino-163) +- [Contributing](#contributing) + +## Usage + +There are two main models of usage of Firmata. In one model, the author of the Arduino sketch uses the various methods provided by the Firmata library to selectively send and receive data between the Arduino device and the software running on the host computer. For example, a user can send analog data to the host using ``` Firmata.sendAnalog(analogPin, analogRead(analogPin)) ``` or send data packed in a string using ``` Firmata.sendString(stringToSend) ```. See File -> Examples -> Firmata -> AnalogFirmata & EchoString respectively for examples. + +The second and more common model is to load a general purpose sketch called StandardFirmata (or one of the variants such as StandardFirmataPlus or StandardFirmataEthernet depending on your needs) on the Arduino board and then use the host computer exclusively to interact with the Arduino board. StandardFirmata is located in the Arduino IDE in File -> Examples -> Firmata. + +## Firmata Client Libraries +Most of the time you will be interacting with Arduino with a client library on the host computers. Several Firmata client libraries have been implemented in a variety of popular programming languages: + +* processing + * [https://github.com/firmata/processing](https://github.com/firmata/processing) + * [http://funnel.cc](http://funnel.cc) +* python + * [https://github.com/MrYsLab/pymata-aio](https://github.com/MrYsLab/pymata-aio) + * [https://github.com/MrYsLab/PyMata]([https://github.com/MrYsLab/PyMata) + * [https://github.com/tino/pyFirmata](https://github.com/tino/pyFirmata) + * [https://github.com/lupeke/python-firmata](https://github.com/lupeke/python-firmata) + * [https://github.com/firmata/pyduino](https://github.com/firmata/pyduino) +* perl + * [https://github.com/ntruchsess/perl-firmata](https://github.com/ntruchsess/perl-firmata) + * [https://github.com/rcaputo/rx-firmata](https://github.com/rcaputo/rx-firmata) +* ruby + * [https://github.com/hardbap/firmata](https://github.com/hardbap/firmata) + * [https://github.com/PlasticLizard/rufinol](https://github.com/PlasticLizard/rufinol) + * [http://funnel.cc](http://funnel.cc) +* clojure + * [https://github.com/nakkaya/clodiuno](https://github.com/nakkaya/clodiuno) + * [https://github.com/peterschwarz/clj-firmata](https://github.com/peterschwarz/clj-firmata) +* javascript + * [https://github.com/firmata/firmata.js](https://github.com/firmata/firmata.js) + * [https://github.com/rwldrn/johnny-five](https://github.com/rwldrn/johnny-five) + * [http://breakoutjs.com](http://breakoutjs.com) +* java + * [https://github.com/kurbatov/firmata4j](https://github.com/kurbatov/firmata4j) + * [https://github.com/4ntoine/Firmata](https://github.com/4ntoine/Firmata) + * [https://github.com/reapzor/FiloFirmata](https://github.com/reapzor/FiloFirmata) +* .NET + * [https://github.com/SolidSoils/Arduino](https://github.com/SolidSoils/Arduino) + * [http://www.acraigie.com/programming/firmatavb/default.html](http://www.acraigie.com/programming/firmatavb/default.html) +* Flash/AS3 + * [http://funnel.cc](http://funnel.cc) + * [http://code.google.com/p/as3glue/](http://code.google.com/p/as3glue/) +* PHP + * [https://github.com/ThomasWeinert/carica-firmata]() + * [https://github.com/oasynnoum/phpmake_firmata](https://github.com/oasynnoum/phpmake_firmata) +* Haskell + * [http://hackage.haskell.org/package/hArduino](http://hackage.haskell.org/package/hArduino) +* iOS + * [https://github.com/jacobrosenthal/iosfirmata](https://github.com/jacobrosenthal/iosfirmata) +* Dart + * [https://github.com/nfrancois/firmata](https://github.com/nfrancois/firmata) +* Max/MSP + * [http://www.maxuino.org/](http://www.maxuino.org/) +* Elixir + * [https://github.com/kfatehi/firmata](https://github.com/kfatehi/firmata) +* Modelica + * [https://www.wolfram.com/system-modeler/libraries/model-plug/](https://www.wolfram.com/system-modeler/libraries/model-plug/) +* Go + * [https://github.com/kraman/go-firmata](https://github.com/kraman/go-firmata) +* vvvv + * [https://vvvv.org/blog/arduino-second-service](https://vvvv.org/blog/arduino-second-service) +* openFrameworks + * [http://openframeworks.cc/documentation/communication/ofArduino/](http://openframeworks.cc/documentation/communication/ofArduino/) +* Rust + * [https://github.com/zankich/rust-firmata](https://github.com/zankich/rust-firmata) + +Note: The above libraries may support various versions of the Firmata protocol and therefore may not support all features of the latest Firmata spec nor all Arduino and Arduino-compatible boards. Refer to the respective projects for details. + +## Updating Firmata in the Arduino IDE - Arduino 1.6.4 and higher + +If you want to update to the latest stable version: + +1. Open the Arduino IDE and navigate to: `Sketch > Include Library > Manage Libraries` +2. Filter by "Firmata" and click on the "Firmata by Firmata Developers" item in the list of results. +3. Click the `Select version` dropdown and select the most recent version (note you can also install previous versions) +4. Click `Install`. + +### Cloning Firmata + +If you are contributing to Firmata or otherwise need a version newer than the latest tagged release, you can clone Firmata directly to your Arduino/libraries/ directory (where 3rd party libraries are installed). This only works for Arduino 1.6.4 and higher, for older versions you need to clone into the Arduino application directory (see section below titled "Using the Source code rather than release archive"). Be sure to change the name to Firmata as follows: + +```bash +$ git clone git@github.com:firmata/arduino.git ~/Documents/Arduino/libraries/Firmata +``` + +*Update path above if you're using Windows or Linux or changed the default Arduino directory on OS X* + + +## Updating Firmata in the Arduino IDE - older versions (<= 1.6.3 or 1.0.x) + +Download the latest [release](https://github.com/firmata/arduino/releases/tag/2.5.8) (for Arduino 1.0.x or Arduino 1.5.6 or higher) and replace the existing Firmata folder in your Arduino application. See the instructions below for your platform. + +*Note that Arduino 1.5.0 - 1.5.5 are not supported. Please use Arduino 1.5.6 or higher (or Arduino 1.0.5 or 1.0.6).* + +### Mac OSX: + +The Firmata library is contained within the Arduino package. + +1. Navigate to the Arduino application +2. Right click on the application icon and select `Show Package Contents` +3. Navigate to: `/Contents/Resources/Java/libraries/` and replace the existing +`Firmata` folder with latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.8) (note there is a different download +for Arduino 1.0.x vs 1.6.x) +4. Restart the Arduino application and the latest version of Firmata will be available. + +*If you are using the Java 7 version of Arduino 1.5.7 or higher, the file path +will differ slightly: `Contents/Java/libraries/Firmata` (no Resources directory).* + +### Windows: + +1. Navigate to `c:/Program\ Files/arduino-1.x/libraries/` and replace the existing +`Firmata` folder with the latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.8) (note there is a different download +for Arduino 1.0.x vs 1.6.x). +2. Restart the Arduino application and the latest version of Firmata will be available. + +*Update the path and Arduino version as necessary* + +### Linux: + +1. Navigate to `~/arduino-1.x/libraries/` and replace the existing +`Firmata` folder with the latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.8) (note there is a different download +for Arduino 1.0.x vs 1.6.x). +2. Restart the Arduino application and the latest version of Firmata will be available. + +*Update the path and Arduino version as necessary* + +### Using the Source code rather than release archive (only for versions older than Arduino 1.6.3) + +*It is recommended you update to Arduino 1.6.4 or higher if possible, that way you can clone directly into the external Arduino/libraries/ directory which persists between Arduino application updates. Otherwise you will need to move your clone each time you update to a newer version of the Arduino IDE.* + +If you're stuck with an older version of the IDE, then follow these keep reading otherwise jump up to the "Cloning Firmata section above". + +Clone this repo directly into the core Arduino application libraries directory. If you are using +Arduino 1.5.x or <= 1.6.3, the repo directory structure will not match the Arduino +library format, however it should still compile as long as you are using Arduino 1.5.7 +or higher. + +You will first need to remove the existing Firmata library, then clone firmata/arduino +into an empty Firmata directory: + +```bash +$ rm -r /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata +$ git clone git@github.com:firmata/arduino.git /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata +``` + +*Update paths if you're using Windows or Linux* + +To generate properly formatted versions of Firmata (for Arduino 1.0.x and Arduino 1.6.x), run the +`release.sh` script. + +## Contributing + +If you discover a bug or would like to propose a new feature, please open a new [issue](https://github.com/firmata/arduino/issues?sort=created&state=open). Due to the limited memory of standard Arduino boards we cannot add every requested feature to StandardFirmata. Requests to add new features to StandardFirmata will be evaluated by the Firmata developers. However it is still possible to add new features to other Firmata implementations (Firmata is a protocol whereas StandardFirmata is just one of many possible implementations). + +To contribute, fork this repository and create a new topic branch for the bug, feature or other existing issue you are addressing. Submit the pull request against the *master* branch. + +If you would like to contribute but don't have a specific bugfix or new feature to contribute, you can take on an existing issue, see issues labeled "pull-request-encouraged". Add a comment to the issue to express your intent to begin work and/or to get any additional information about the issue. + +You must thoroughly test your contributed code. In your pull request, describe tests performed to ensure that no existing code is broken and that any changes maintain backwards compatibility with the existing api. Test on multiple Arduino board variants if possible. We hope to enable some form of automated (or at least semi-automated) testing in the future, but for now any tests will need to be executed manually by the contributor and reviewers. + +Use [Artistic Style](http://astyle.sourceforge.net/) (astyle) to format your code. Set the following rules for the astyle formatter: + +``` +style = "" +indent-spaces = 2 +indent-classes = true +indent-switches = true +indent-cases = true +indent-col1-comments = true +pad-oper = true +pad-header = true +keep-one-line-statements = true +``` + +If you happen to use Sublime Text, [this astyle plugin](https://github.com/timonwong/SublimeAStyleFormatter) is helpful. Set the above rules in the user settings file. diff --git a/libraries/Firmata/release.sh b/libraries/Firmata/release.sh new file mode 100644 index 0000000..0c47db8 --- /dev/null +++ b/libraries/Firmata/release.sh @@ -0,0 +1,33 @@ +#!/bin/sh + +# use this script to package Firmata for distribution + +# package for Arduino 1.0.x +mkdir -p temp/Firmata +cp -r examples temp/Firmata +cp -r extras temp/Firmata +cp -r utility temp/Firmata +cp *.cpp temp/Firmata +cp *.h temp/Firmata +cp keywords.txt temp/Firmata +cp readme.md temp/Firmata +cd temp +find . -name "*.DS_Store" -type f -delete +zip -r Firmata.zip ./Firmata/ +cd .. +mv ./temp/Firmata.zip Arduino-1.0.x-Firmata-2.5.8.zip + +#package for Arduino 1.6.x and 1.8.x +cp library.properties temp/Firmata +cd temp/Firmata +mv readme.md ./extras/ +mkdir src +mv *.cpp ./src/ +mv *.h ./src/ +mv utility ./src/ +cd .. +find . -name "*.DS_Store" -type f -delete +zip -r Firmata.zip ./Firmata/ +cd .. +mv ./temp/Firmata.zip Firmata-2.5.8.zip +rm -r ./temp diff --git a/libraries/Firmata/test/firmata_test/firmata_test.ino b/libraries/Firmata/test/firmata_test/firmata_test.ino new file mode 100644 index 0000000..db05853 --- /dev/null +++ b/libraries/Firmata/test/firmata_test/firmata_test.ino @@ -0,0 +1,172 @@ +/* + * To run this test suite, you must first install the ArduinoUnit library + * to your Arduino/libraries/ directory. + * You can get ArduinoUnit here: https://github.com/mmurdoch/arduinounit + * Download version 2.0 or greater or install it via the Arduino library manager. + */ + +#include +#include + +void setup() +{ + Serial.begin(9600); +} + +void loop() +{ + Test::run(); +} + +test(beginPrintsVersion) +{ + FakeStream stream; + + Firmata.begin(stream); + + char expected[] = { + REPORT_VERSION, + FIRMATA_PROTOCOL_MAJOR_VERSION, + FIRMATA_PROTOCOL_MINOR_VERSION, + 0 + }; + assertEqual(expected, stream.bytesWritten()); +} + +void processMessage(const byte *message, size_t length) +{ + FakeStream stream; + Firmata.begin(stream); + + for (size_t i = 0; i < length; i++) { + stream.nextByte(message[i]); + Firmata.processInput(); + } +} + +byte _digitalPort; +int _digitalPortValue; +void writeToDigitalPort(byte port, int value) +{ + _digitalPort = port; + _digitalPortValue = value; +} + +void setupDigitalPort() +{ + _digitalPort = 0; + _digitalPortValue = 0; +} + +char * _receivedString; +void handleStringCallback(char *str) +{ + _receivedString = str; +} + +test(processWriteDigital_0) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0, 0 }; + processMessage(message, 3); + + assertEqual(0, _digitalPortValue); +} + +test(processWriteDigital_127) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 127, 0 }; + processMessage(message, 3); + + assertEqual(127, _digitalPortValue); +} + +test(processWriteDigital_128) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0, 1 }; + processMessage(message, 3); + + assertEqual(128, _digitalPortValue); +} + +test(processWriteLargestDigitalValue) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0x7F, 0x7F }; + processMessage(message, 3); + + // Maximum of 14 bits can be set (B0011111111111111) + assertEqual(0x3FFF, _digitalPortValue); +} + +test(defaultDigitalWritePortIsZero) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0, 0 }; + processMessage(message, 3); + + assertEqual(0, _digitalPort); +} + +test(specifiedDigitalWritePort) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE + 1, 0, 0 }; + processMessage(message, 3); + + assertEqual(1, _digitalPort); +} + +test(setFirmwareVersionDoesNotLeakMemory) +{ + Firmata.setFirmwareVersion(1, 0); + int initialMemory = freeMemory(); + + Firmata.setFirmwareVersion(1, 0); + + assertEqual(0, initialMemory - freeMemory()); +} + +test(sendStringShouldEncode2BytesPerChar) +{ + FakeStream stream; + Firmata.begin(stream); + // reset the buffer because the firmware name string will be sent on Firmata.begin + stream.reset(); + + char testString[] = "hi!"; + Firmata.sendString(testString); + + byte expected[] = { START_SYSEX, STRING_DATA, 'h', 0, 'i', 0, '!', 0, END_SYSEX }; + + int len = stream.bytesWritten().length(); + assertEqual(sizeof(expected), len); + for (byte i = 0; i < len; i++) { + assertEqual(expected[i], (byte)stream.bytesWritten().charAt(i)); + } +} + +test(receivedStringShouldDecodeFrom2BytesPerChar) +{ + Firmata.attach(STRING_DATA, handleStringCallback); + + byte message[] = { START_SYSEX, STRING_DATA, 'b', 0, 'y', 0, 'e', 0, '!', 0, END_SYSEX }; + processMessage(message, 11); + + assertEqual("bye!", _receivedString); +} + diff --git a/libraries/Firmata/test/readme.md b/libraries/Firmata/test/readme.md new file mode 100644 index 0000000..ab8f8c3 --- /dev/null +++ b/libraries/Firmata/test/readme.md @@ -0,0 +1,13 @@ +# Testing Firmata + +Tests tests are written using the [ArduinoUnit](https://github.com/mmurdoch/arduinounit) library (version 2.0). + +Follow the instructions in the [ArduinoUnit readme](https://github.com/mmurdoch/arduinounit/blob/master/readme.md) to install the library. + +Compile and upload the test sketch as you would any other sketch. Then open the +Serial Monitor to view the test results. + +If you make changes to Firmata.cpp, run the tests in /test/ to ensure +that your changes have not produced any unexpected errors. + +You should also perform manual tests against actual hardware. diff --git a/libraries/Firmata/utility/BLEStream.cpp b/libraries/Firmata/utility/BLEStream.cpp new file mode 100644 index 0000000..ea50840 --- /dev/null +++ b/libraries/Firmata/utility/BLEStream.cpp @@ -0,0 +1,3 @@ +/* + * Implementation is in BLEStream.h to avoid linker issues. + */ diff --git a/libraries/Firmata/utility/BLEStream.h b/libraries/Firmata/utility/BLEStream.h new file mode 100644 index 0000000..56b3648 --- /dev/null +++ b/libraries/Firmata/utility/BLEStream.h @@ -0,0 +1,243 @@ +/* + BLEStream.h + + Based on BLESerial.cpp by Voita Molda + https://github.com/sandeepmistry/arduino-BLEPeripheral/blob/master/examples/serial/BLESerial.h + + Last updated April 4th, 2016 + */ + +#ifndef _BLE_STREAM_H_ +#define _BLE_STREAM_H_ + +#include +#if defined(_VARIANT_ARDUINO_101_X_) +#include +#define _MAX_ATTR_DATA_LEN_ BLE_MAX_ATTR_DATA_LEN +#else +#include +#define _MAX_ATTR_DATA_LEN_ BLE_ATTRIBUTE_MAX_VALUE_LENGTH +#endif + +#define BLESTREAM_TXBUFFER_FLUSH_INTERVAL 80 +#define BLESTREAM_MIN_FLUSH_INTERVAL 8 // minimum interval for flushing the TX buffer + +// #define BLE_SERIAL_DEBUG + +class BLEStream : public BLEPeripheral, public Stream +{ + public: + BLEStream(unsigned char req = 0, unsigned char rdy = 0, unsigned char rst = 0); + + void begin(...); + bool poll(); + void end(); + void setFlushInterval(int); + + virtual int available(void); + virtual int peek(void); + virtual int read(void); + virtual void flush(void); + virtual size_t write(uint8_t byte); + using Print::write; + virtual operator bool(); + + private: + bool _connected; + unsigned long _flushed; + int _flushInterval; + static BLEStream* _instance; + + size_t _rxHead; + size_t _rxTail; + size_t _rxCount() const; + unsigned char _rxBuffer[256]; + size_t _txCount; + unsigned char _txBuffer[_MAX_ATTR_DATA_LEN_]; + + BLEService _uartService = BLEService("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); + BLEDescriptor _uartNameDescriptor = BLEDescriptor("2901", "UART"); + BLECharacteristic _rxCharacteristic = BLECharacteristic("6E400002-B5A3-F393-E0A9-E50E24DCCA9E", BLEWriteWithoutResponse, _MAX_ATTR_DATA_LEN_); + BLEDescriptor _rxNameDescriptor = BLEDescriptor("2901", "RX - Receive Data (Write)"); + BLECharacteristic _txCharacteristic = BLECharacteristic("6E400003-B5A3-F393-E0A9-E50E24DCCA9E", BLENotify, _MAX_ATTR_DATA_LEN_); + BLEDescriptor _txNameDescriptor = BLEDescriptor("2901", "TX - Transfer Data (Notify)"); + + void _received(const unsigned char* data, size_t size); + static void _received(BLECentral& /*central*/, BLECharacteristic& rxCharacteristic); +}; + + +/* + * BLEStream.cpp + * Copied here as a hack to avoid having to install the BLEPeripheral libarary even if it's + * not needed. + */ + +BLEStream* BLEStream::_instance = NULL; + +BLEStream::BLEStream(unsigned char req, unsigned char rdy, unsigned char rst) : +#if defined(_VARIANT_ARDUINO_101_X_) + BLEPeripheral() +#else + BLEPeripheral(req, rdy, rst) +#endif +{ + this->_txCount = 0; + this->_rxHead = this->_rxTail = 0; + this->_flushed = 0; + this->_flushInterval = BLESTREAM_TXBUFFER_FLUSH_INTERVAL; + BLEStream::_instance = this; + + addAttribute(this->_uartService); + addAttribute(this->_uartNameDescriptor); + setAdvertisedServiceUuid(this->_uartService.uuid()); + addAttribute(this->_rxCharacteristic); + addAttribute(this->_rxNameDescriptor); + this->_rxCharacteristic.setEventHandler(BLEWritten, BLEStream::_received); + addAttribute(this->_txCharacteristic); + addAttribute(this->_txNameDescriptor); +} + +void BLEStream::begin(...) +{ + BLEPeripheral::begin(); +#ifdef BLE_SERIAL_DEBUG + Serial.println(F("BLEStream::begin()")); +#endif +} + +bool BLEStream::poll() +{ + // BLEPeripheral::poll is called each time connected() is called + this->_connected = BLEPeripheral::connected(); + if (millis() > this->_flushed + this->_flushInterval) { + flush(); + } + return this->_connected; +} + +void BLEStream::end() +{ + this->_rxCharacteristic.setEventHandler(BLEWritten, (void(*)(BLECentral&, BLECharacteristic&))NULL); + this->_rxHead = this->_rxTail = 0; + flush(); + BLEPeripheral::disconnect(); +} + +int BLEStream::available(void) +{ +// BLEPeripheral::poll only calls delay(1) in CurieBLE so skipping it here to avoid the delay +#ifndef _VARIANT_ARDUINO_101_X_ + // TODO Need to do more testing to determine if all of these calls to BLEPeripheral::poll are + // actually necessary. Seems to run fine without them, but only minimal testing so far. + BLEPeripheral::poll(); +#endif + int retval = (this->_rxHead - this->_rxTail + sizeof(this->_rxBuffer)) % sizeof(this->_rxBuffer); +#ifdef BLE_SERIAL_DEBUG + if (retval > 0) { + Serial.print(F("BLEStream::available() = ")); + Serial.println(retval); + } +#endif + return retval; +} + +int BLEStream::peek(void) +{ +#ifndef _VARIANT_ARDUINO_101_X_ + BLEPeripheral::poll(); +#endif + if (this->_rxTail == this->_rxHead) return -1; + uint8_t byte = this->_rxBuffer[this->_rxTail]; +#ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLEStream::peek() = 0x")); + Serial.println(byte, HEX); +#endif + return byte; +} + +int BLEStream::read(void) +{ +#ifndef _VARIANT_ARDUINO_101_X_ + BLEPeripheral::poll(); +#endif + if (this->_rxTail == this->_rxHead) return -1; + this->_rxTail = (this->_rxTail + 1) % sizeof(this->_rxBuffer); + uint8_t byte = this->_rxBuffer[this->_rxTail]; +#ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLEStream::read() = 0x")); + Serial.println(byte, HEX); +#endif + return byte; +} + +void BLEStream::flush(void) +{ + if (this->_txCount == 0) return; +#ifndef _VARIANT_ARDUINO_101_X_ + // ensure there are available packets before sending + while(!this->_txCharacteristic.canNotify()) { + BLEPeripheral::poll(); + } +#endif + this->_txCharacteristic.setValue(this->_txBuffer, this->_txCount); + this->_flushed = millis(); + this->_txCount = 0; +#ifdef BLE_SERIAL_DEBUG + Serial.println(F("BLEStream::flush()")); +#endif +} + +size_t BLEStream::write(uint8_t byte) +{ +#ifndef _VARIANT_ARDUINO_101_X_ + BLEPeripheral::poll(); +#endif + if (this->_txCharacteristic.subscribed() == false) return 0; + this->_txBuffer[this->_txCount++] = byte; + if (this->_txCount == sizeof(this->_txBuffer)) flush(); +#ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLEStream::write( 0x")); + Serial.print(byte, HEX); + Serial.println(F(") = 1")); +#endif + return 1; +} + +BLEStream::operator bool() +{ + bool retval = this->_connected = BLEPeripheral::connected(); +#ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLEStream::operator bool() = ")); + Serial.println(retval); +#endif + return retval; +} + +void BLEStream::setFlushInterval(int interval) +{ + if (interval > BLESTREAM_MIN_FLUSH_INTERVAL) { + this->_flushInterval = interval; + } +} + +void BLEStream::_received(const unsigned char* data, size_t size) +{ + for (size_t i = 0; i < size; i++) { + this->_rxHead = (this->_rxHead + 1) % sizeof(this->_rxBuffer); + this->_rxBuffer[this->_rxHead] = data[i]; + } +#ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLEStream::received(")); + for (int i = 0; i < size; i++) Serial.print(data[i], HEX); + Serial.println(F(")")); +#endif +} + +void BLEStream::_received(BLECentral& /*central*/, BLECharacteristic& rxCharacteristic) +{ + BLEStream::_instance->_received(rxCharacteristic.value(), rxCharacteristic.valueLength()); +} + + +#endif // _BLE_STREAM_H_ diff --git a/libraries/Firmata/utility/BluefruitLE_SPI_Stream.cpp b/libraries/Firmata/utility/BluefruitLE_SPI_Stream.cpp new file mode 100644 index 0000000..93953e9 --- /dev/null +++ b/libraries/Firmata/utility/BluefruitLE_SPI_Stream.cpp @@ -0,0 +1,3 @@ +/* + * Implementation is in BluefruitLE_SPI_Stream.h to avoid linker issues. + */ diff --git a/libraries/Firmata/utility/BluefruitLE_SPI_Stream.h b/libraries/Firmata/utility/BluefruitLE_SPI_Stream.h new file mode 100644 index 0000000..372e5aa --- /dev/null +++ b/libraries/Firmata/utility/BluefruitLE_SPI_Stream.h @@ -0,0 +1,157 @@ +/* + BluefruitLE_SPI_Stream.h + + Documentation for the various AT commands used below is available at + https://learn.adafruit.com/adafruit-feather-m0-bluefruit-le/at-commands + */ + +#ifndef _BLUEFRUIT_LE_SPI_STREAM_H_ +#define _BLUEFRUIT_LE_SPI_STREAM_H_ + +#include + + +class BluefruitLE_SPI_Stream : public Stream +{ + public: + BluefruitLE_SPI_Stream(int8_t csPin, int8_t irqPin, int8_t rstPin); + + void setLocalName(const char *localName); + void setConnectionInterval(unsigned short minConnInterval, unsigned short maxConnInterval); + void setFlushInterval(int flushInterval); + + void begin(); + bool poll(); + void end(); + + // Print overrides + size_t write(uint8_t byte); + using Print::write; // Expose other write variants + + // Stream overrides + int available(); + int read(); + int peek(); + void flush(); + + private: + Adafruit_BluefruitLE_SPI ble; + + String localName; + unsigned short minConnInterval; + unsigned short maxConnInterval; + + uint8_t txBuffer[SDEP_MAX_PACKETSIZE]; + size_t txCount; +}; + + +BluefruitLE_SPI_Stream::BluefruitLE_SPI_Stream(int8_t csPin, int8_t irqPin, int8_t rstPin) : + ble(csPin, irqPin, rstPin), + minConnInterval(0), + maxConnInterval(0), + txCount(0) +{ } + +void BluefruitLE_SPI_Stream::setLocalName(const char *localName) +{ + this->localName = localName; +} + +void BluefruitLE_SPI_Stream::setConnectionInterval(unsigned short minConnInterval, unsigned short maxConnInterval) +{ + this->minConnInterval = minConnInterval; + this->maxConnInterval = maxConnInterval; +} + +void BluefruitLE_SPI_Stream::setFlushInterval(int flushInterval) +{ + // Not used +} + +void BluefruitLE_SPI_Stream::begin() +{ + // Initialize the SPI interface + ble.begin(); + + // Perform a factory reset to make sure everything is in a known state + ble.factoryReset(); + + // Disable command echo from Bluefruit + ble.echo(false); + + // Change the MODE LED to indicate BLE UART activity + ble.println("AT+HWMODELED=BLEUART"); + + // Set local name + if (localName.length() > 0) { + ble.print("AT+GAPDEVNAME="); + ble.println(localName); + } + + // Set connection interval + if (minConnInterval > 0 && maxConnInterval > 0) { + ble.print("AT+GAPINTERVALS="); + ble.print(minConnInterval); + ble.print(","); + ble.print(maxConnInterval); + ble.println(",,,"); + } + + // Disable real and simulated mode switch (i.e. "+++") command + ble.println("AT+MODESWITCHEN=local,0"); + ble.enableModeSwitchCommand(false); + + // Switch to data mode + ble.setMode(BLUEFRUIT_MODE_DATA); +} + +bool BluefruitLE_SPI_Stream::poll() +{ + // If there's outgoing data in the buffer, just send it. The firmware on + // the nRF51822 will decide when to transmit the data in its TX FIFO. + if (txCount) flush(); + + // In order to check for a connection, we would need to switch from data to + // command mode and back again. However, due to the internal workings of + // Adafruit_BluefruitLE_SPI, this can lead to unread incoming data being + // lost. Therefore, we always return true. + return true; +} + +void BluefruitLE_SPI_Stream::end() +{ + flush(); + ble.end(); +} + +size_t BluefruitLE_SPI_Stream::write(uint8_t byte) +{ + txBuffer[txCount++] = byte; + if (txCount == sizeof(txBuffer)) flush(); + return 1; +} + +int BluefruitLE_SPI_Stream::available() +{ + return ble.available(); +} + +int BluefruitLE_SPI_Stream::read() +{ + return ble.read(); +} + +int BluefruitLE_SPI_Stream::peek() +{ + return ble.peek(); +} + +void BluefruitLE_SPI_Stream::flush() +{ + ble.write(txBuffer, txCount); + txCount = 0; +} + + +#endif // _BLUEFRUIT_LE_SPI_STREAM_H_ diff --git a/libraries/Firmata/utility/EthernetClientStream.cpp b/libraries/Firmata/utility/EthernetClientStream.cpp new file mode 100644 index 0000000..f4f8968 --- /dev/null +++ b/libraries/Firmata/utility/EthernetClientStream.cpp @@ -0,0 +1,3 @@ +/* + * Implementation is in EthernetClientStream.h to avoid linker issues. + */ diff --git a/libraries/Firmata/utility/EthernetClientStream.h b/libraries/Firmata/utility/EthernetClientStream.h new file mode 100644 index 0000000..1b7d2e2 --- /dev/null +++ b/libraries/Firmata/utility/EthernetClientStream.h @@ -0,0 +1,141 @@ +/* + EthernetClientStream.h + An Arduino-Stream that wraps an instance of Client reconnecting to + the remote-ip in a transparent way. A disconnected client may be + recognized by the returnvalues -1 from calls to peek or read and + a 0 from calls to write. + + Copyright (C) 2013 Norbert Truchsess. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated June 18th, 2016 + */ + +#ifndef ETHERNETCLIENTSTREAM_H +#define ETHERNETCLIENTSTREAM_H + +#include +#include + +//#define SERIAL_DEBUG +#include "firmataDebug.h" + +#define MILLIS_RECONNECT 5000 + +class EthernetClientStream : public Stream +{ + public: + EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port); + int available(); + int read(); + int peek(); + void flush(); + size_t write(uint8_t); + void maintain(IPAddress localip); + + private: + Client &client; + IPAddress localip; + IPAddress ip; + const char* host; + uint16_t port; + bool connected; + uint32_t time_connect; + bool maintain(); + void stop(); +}; + + +/* + * EthernetClientStream.cpp + * Copied here as a hack to linker issues with 3rd party board packages that don't properly + * implement the Arduino network APIs. + */ +EthernetClientStream::EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port) + : client(client), + localip(localip), + ip(ip), + host(host), + port(port), + connected(false) +{ +} + +int +EthernetClientStream::available() +{ + return maintain() ? client.available() : 0; +} + +int +EthernetClientStream::read() +{ + return maintain() ? client.read() : -1; +} + +int +EthernetClientStream::peek() +{ + return maintain() ? client.peek() : -1; +} + +void EthernetClientStream::flush() +{ + if (maintain()) + client.flush(); +} + +size_t +EthernetClientStream::write(uint8_t c) +{ + return maintain() ? client.write(c) : 0; +} + +void +EthernetClientStream::maintain(IPAddress localip) +{ + // ensure the local IP is updated in the case that it is changed by the DHCP server + if (this->localip != localip) { + this->localip = localip; + if (connected) + stop(); + } +} + +void +EthernetClientStream::stop() +{ + client.stop(); + connected = false; + time_connect = millis(); +} + +bool +EthernetClientStream::maintain() +{ + if (client && client.connected()) + return true; + + if (connected) { + stop(); + } + // if the client is disconnected, attempt to reconnect every 5 seconds + else if (millis() - time_connect >= MILLIS_RECONNECT) { + connected = host ? client.connect(host, port) : client.connect(ip, port); + if (!connected) { + time_connect = millis(); + DEBUG_PRINTLN("Connection failed. Attempting to reconnect..."); + } else { + DEBUG_PRINTLN("Connected"); + } + } + return connected; +} + +#endif /* ETHERNETCLIENTSTREAM_H */ diff --git a/libraries/Firmata/utility/EthernetServerStream.cpp b/libraries/Firmata/utility/EthernetServerStream.cpp new file mode 100644 index 0000000..de466f5 --- /dev/null +++ b/libraries/Firmata/utility/EthernetServerStream.cpp @@ -0,0 +1,3 @@ +/* + * Implementation is in EthernetServerStream.h to avoid linker issues. + */ diff --git a/libraries/Firmata/utility/EthernetServerStream.h b/libraries/Firmata/utility/EthernetServerStream.h new file mode 100644 index 0000000..56f541e --- /dev/null +++ b/libraries/Firmata/utility/EthernetServerStream.h @@ -0,0 +1,147 @@ +/* + EthernetServerStream.h + + Copyright (C) 2017 Marc Josef Pees. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated July 10th, 2017 + */ + +#ifndef ETHERNETSERVERSTREAM_H +#define ETHERNETSERVERSTREAM_H + +#include +#include +#include + +//#define SERIAL_DEBUG +#include "firmataDebug.h" + +class EthernetServerStream : public Stream +{ + public: + EthernetServerStream(IPAddress localip, uint16_t port); + int available(); + int read(); + int peek(); + void flush(); + size_t write(uint8_t); + void maintain(IPAddress localip); + + private: + EthernetClient client; + IPAddress localip; + uint16_t port; + bool connected; + bool maintain(); + void stop(); + + protected: + EthernetServer server = EthernetServer(3030); + bool listening = false; + bool connect_client(); +}; + + +/* + * EthernetServerStream.cpp + * Copied here as a hack to linker issues with 3rd party board packages that don't properly + * implement the Arduino network APIs. + */ +EthernetServerStream::EthernetServerStream(IPAddress localip, uint16_t port) + : localip(localip), + port(port), + connected(false) +{ +} + +bool EthernetServerStream::connect_client() + { + if ( connected ) + { + if ( client && client.connected() ) return true; + stop(); + } + + EthernetClient newClient = server.available(); + if ( !newClient ) return false; + client = newClient; + connected = true; + DEBUG_PRINTLN("Connected"); + return true; + } + +int +EthernetServerStream::available() +{ + return maintain() ? client.available() : 0; +} + +int +EthernetServerStream::read() +{ + return maintain() ? client.read() : -1; +} + +int +EthernetServerStream::peek() +{ + return maintain() ? client.peek() : -1; +} + +void EthernetServerStream::flush() +{ + if (maintain()) + client.flush(); +} + +size_t +EthernetServerStream::write(uint8_t c) +{ + return maintain() ? client.write(c) : 0; +} + +void +EthernetServerStream::maintain(IPAddress localip) +{ + // ensure the local IP is updated in the case that it is changed by the DHCP server + if (this->localip != localip) { + this->localip = localip; + if (connected) + stop(); + } +} + +void +EthernetServerStream::stop() +{ + if(client) + { + client.stop(); + } + connected = false; +} + +bool +EthernetServerStream::maintain() +{ + if (connect_client()) return true; + + stop(); + + if(!listening) + { + server = EthernetServer(port); + server.begin(); + listening = true; + } + return false; +} + +#endif /* ETHERNETSERVERSTREAM_H */ diff --git a/libraries/Firmata/utility/FirmataFeature.h b/libraries/Firmata/utility/FirmataFeature.h new file mode 100644 index 0000000..d5e229d --- /dev/null +++ b/libraries/Firmata/utility/FirmataFeature.h @@ -0,0 +1,38 @@ +/* + FirmataFeature.h + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2013 Norbert Truchsess. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + Interface for Firmata feature classes. + + This version of FirmataFeature.h differs from the ConfigurableFirmata + version in the following ways: + + - Imports Firmata.h rather than ConfigurableFirmata.h + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataFeature_h +#define FirmataFeature_h + +#include + +class FirmataFeature +{ + public: + virtual void handleCapability(byte pin) = 0; + virtual boolean handlePinMode(byte pin, int mode) = 0; + virtual boolean handleSysex(byte command, byte argc, byte* argv) = 0; + virtual void reset() = 0; +}; + +#endif diff --git a/libraries/Firmata/utility/SerialFirmata.cpp b/libraries/Firmata/utility/SerialFirmata.cpp new file mode 100644 index 0000000..8b703e1 --- /dev/null +++ b/libraries/Firmata/utility/SerialFirmata.cpp @@ -0,0 +1,342 @@ +/* + SerialFirmata.cpp + Copyright (C) 2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + This version of SerialFirmata.cpp differs from the ConfigurableFirmata + version in the following ways: + + - handlePinMode calls Firmata::setPinMode + + Last updated October 16th, 2016 +*/ + +#include "SerialFirmata.h" + +SerialFirmata::SerialFirmata() +{ +#if defined(SoftwareSerial_h) + swSerial0 = NULL; + swSerial1 = NULL; + swSerial2 = NULL; + swSerial3 = NULL; +#endif + + serialIndex = -1; +} + +boolean SerialFirmata::handlePinMode(byte pin, int mode) +{ + // used for both HW and SW serial + if (mode == PIN_MODE_SERIAL) { + Firmata.setPinMode(pin, PIN_MODE_SERIAL); + return true; + } + return false; +} + +void SerialFirmata::handleCapability(byte pin) +{ + if (IS_PIN_SERIAL(pin)) { + Firmata.write(PIN_MODE_SERIAL); + Firmata.write(getSerialPinType(pin)); + } +} + +boolean SerialFirmata::handleSysex(byte command, byte argc, byte *argv) +{ + if (command == SERIAL_MESSAGE) { + + Stream *serialPort; + byte mode = argv[0] & SERIAL_MODE_MASK; + byte portId = argv[0] & SERIAL_PORT_ID_MASK; + + switch (mode) { + case SERIAL_CONFIG: + { + long baud = (long)argv[1] | ((long)argv[2] << 7) | ((long)argv[3] << 14); + serial_pins pins; + + if (portId < 8) { + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + pins = getSerialPinNumbers(portId); + if (pins.rx != 0 && pins.tx != 0) { + Firmata.setPinMode(pins.rx, PIN_MODE_SERIAL); + Firmata.setPinMode(pins.tx, PIN_MODE_SERIAL); + // Fixes an issue where some serial devices would not work properly with Arduino Due + // because all Arduino pins are set to OUTPUT by default in StandardFirmata. + pinMode(pins.rx, INPUT); + } + ((HardwareSerial*)serialPort)->begin(baud); + } + } else { +#if defined(SoftwareSerial_h) + byte swTxPin, swRxPin; + if (argc > 4) { + swRxPin = argv[4]; + swTxPin = argv[5]; + } else { + // RX and TX pins must be specified when using SW serial + Firmata.sendString("Specify serial RX and TX pins"); + return false; + } + switch (portId) { + case SW_SERIAL0: + if (swSerial0 == NULL) { + swSerial0 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + case SW_SERIAL1: + if (swSerial1 == NULL) { + swSerial1 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + case SW_SERIAL2: + if (swSerial2 == NULL) { + swSerial2 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + case SW_SERIAL3: + if (swSerial3 == NULL) { + swSerial3 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + } + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + Firmata.setPinMode(swRxPin, PIN_MODE_SERIAL); + Firmata.setPinMode(swTxPin, PIN_MODE_SERIAL); + ((SoftwareSerial*)serialPort)->begin(baud); + } +#endif + } + break; // SERIAL_CONFIG + } + case SERIAL_WRITE: + { + byte data; + serialPort = getPortFromId(portId); + if (serialPort == NULL) { + break; + } + for (byte i = 1; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + serialPort->write(data); + } + break; // SERIAL_WRITE + } + case SERIAL_READ: + if (argv[1] == SERIAL_READ_CONTINUOUSLY) { + if (serialIndex + 1 >= MAX_SERIAL_PORTS) { + break; + } + + if (argc > 2) { + // maximum number of bytes to read from buffer per iteration of loop() + serialBytesToRead[portId] = (int)argv[2] | ((int)argv[3] << 7); + } else { + // read all available bytes per iteration of loop() + serialBytesToRead[portId] = 0; + } + serialIndex++; + reportSerial[serialIndex] = portId; + } else if (argv[1] == SERIAL_STOP_READING) { + byte serialIndexToSkip = 0; + if (serialIndex <= 0) { + serialIndex = -1; + } else { + for (byte i = 0; i < serialIndex + 1; i++) { + if (reportSerial[i] == portId) { + serialIndexToSkip = i; + break; + } + } + // shift elements over to fill space left by removed element + for (byte i = serialIndexToSkip; i < serialIndex + 1; i++) { + if (i < MAX_SERIAL_PORTS) { + reportSerial[i] = reportSerial[i + 1]; + } + } + serialIndex--; + } + } + break; // SERIAL_READ + case SERIAL_CLOSE: + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + if (portId < 8) { + ((HardwareSerial*)serialPort)->end(); + } else { +#if defined(SoftwareSerial_h) + ((SoftwareSerial*)serialPort)->end(); + if (serialPort != NULL) { + free(serialPort); + serialPort = NULL; + } +#endif + } + } + break; // SERIAL_CLOSE + case SERIAL_FLUSH: + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + getPortFromId(portId)->flush(); + } + break; // SERIAL_FLUSH +#if defined(SoftwareSerial_h) + case SERIAL_LISTEN: + // can only call listen() on software serial ports + if (portId > 7) { + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + ((SoftwareSerial*)serialPort)->listen(); + } + } + break; // SERIAL_LISTEN +#endif + } // end switch + return true; + } + return false; +} + +void SerialFirmata::update() +{ + checkSerial(); +} + +void SerialFirmata::reset() +{ +#if defined(SoftwareSerial_h) + Stream *serialPort; + // free memory allocated for SoftwareSerial ports + for (byte i = SW_SERIAL0; i < SW_SERIAL3 + 1; i++) { + serialPort = getPortFromId(i); + if (serialPort != NULL) { + free(serialPort); + serialPort = NULL; + } + } +#endif + + serialIndex = -1; + for (byte i = 0; i < SERIAL_READ_ARR_LEN; i++) { + serialBytesToRead[i] = 0; + } +} + +// get a pointer to the serial port associated with the specified port id +Stream* SerialFirmata::getPortFromId(byte portId) +{ + switch (portId) { + case HW_SERIAL0: + // block use of Serial (typically pins 0 and 1) until ability to reclaim Serial is implemented + //return &Serial; + return NULL; +#if defined(PIN_SERIAL1_RX) + case HW_SERIAL1: + return &Serial1; +#endif +#if defined(PIN_SERIAL2_RX) + case HW_SERIAL2: + return &Serial2; +#endif +#if defined(PIN_SERIAL3_RX) + case HW_SERIAL3: + return &Serial3; +#endif +#if defined(PIN_SERIAL4_RX) + case HW_SERIAL4: + return &Serial4; +#endif +#if defined(PIN_SERIAL5_RX) + case HW_SERIAL5: + return &Serial5; +#endif +#if defined(PIN_SERIAL6_RX) + case HW_SERIAL6: + return &Serial6; +#endif +#if defined(SoftwareSerial_h) + case SW_SERIAL0: + if (swSerial0 != NULL) { + // instances of SoftwareSerial are already pointers so simply return the instance + return swSerial0; + } + break; + case SW_SERIAL1: + if (swSerial1 != NULL) { + return swSerial1; + } + break; + case SW_SERIAL2: + if (swSerial2 != NULL) { + return swSerial2; + } + break; + case SW_SERIAL3: + if (swSerial3 != NULL) { + return swSerial3; + } + break; +#endif + } + return NULL; +} + +// Check serial ports that have READ_CONTINUOUS mode set and relay any data +// for each port to the device attached to that port. +void SerialFirmata::checkSerial() +{ + byte portId, serialData; + int bytesToRead = 0; + int numBytesToRead = 0; + Stream* serialPort; + + if (serialIndex > -1) { + + // loop through all reporting (READ_CONTINUOUS) serial ports + for (byte i = 0; i < serialIndex + 1; i++) { + portId = reportSerial[i]; + bytesToRead = serialBytesToRead[portId]; + serialPort = getPortFromId(portId); + if (serialPort == NULL) { + continue; + } +#if defined(SoftwareSerial_h) + // only the SoftwareSerial port that is "listening" can read data + if (portId > 7 && !((SoftwareSerial*)serialPort)->isListening()) { + continue; + } +#endif + if (serialPort->available() > 0) { + Firmata.write(START_SYSEX); + Firmata.write(SERIAL_MESSAGE); + Firmata.write(SERIAL_REPLY | portId); + + if (bytesToRead == 0 || (serialPort->available() <= bytesToRead)) { + numBytesToRead = serialPort->available(); + } else { + numBytesToRead = bytesToRead; + } + + // relay serial data to the serial device + while (numBytesToRead > 0) { + serialData = serialPort->read(); + Firmata.write(serialData & 0x7F); + Firmata.write((serialData >> 7) & 0x7F); + numBytesToRead--; + } + Firmata.write(END_SYSEX); + } + + } + } +} diff --git a/libraries/Firmata/utility/SerialFirmata.h b/libraries/Firmata/utility/SerialFirmata.h new file mode 100644 index 0000000..2319951 --- /dev/null +++ b/libraries/Firmata/utility/SerialFirmata.h @@ -0,0 +1,208 @@ +/* + SerialFirmata.h + Copyright (C) 2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + This version of SerialFirmata.h differs from the ConfigurableFirmata + version in the following ways: + + - Defines FIRMATA_SERIAL_FEATURE (could add to Configurable version as well) + - Imports Firmata.h rather than ConfigurableFirmata.h + + Last updated October 16th, 2016 +*/ + +#ifndef SerialFirmata_h +#define SerialFirmata_h + +#include +#include "FirmataFeature.h" +// SoftwareSerial is currently only supported for AVR-based boards and the Arduino 101. +// Limited to Arduino 1.6.6 or higher because Arduino builder cannot find SoftwareSerial +// prior to this release. +#if (ARDUINO > 10605) && (defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ARC32)) +#include +#endif + +#define FIRMATA_SERIAL_FEATURE + +// Serial port Ids +#define HW_SERIAL0 0x00 +#define HW_SERIAL1 0x01 +#define HW_SERIAL2 0x02 +#define HW_SERIAL3 0x03 +#define HW_SERIAL4 0x04 +#define HW_SERIAL5 0x05 +#define HW_SERIAL6 0x06 +// extensible up to 0x07 + +#define SW_SERIAL0 0x08 +#define SW_SERIAL1 0x09 +#define SW_SERIAL2 0x0A +#define SW_SERIAL3 0x0B +// extensible up to 0x0F + +#define SERIAL_PORT_ID_MASK 0x0F +#define MAX_SERIAL_PORTS 8 +#define SERIAL_READ_ARR_LEN 12 + +// map configuration query response resolution value to serial pin type +#define RES_RX1 0x02 +#define RES_TX1 0x03 +#define RES_RX2 0x04 +#define RES_TX2 0x05 +#define RES_RX3 0x06 +#define RES_TX3 0x07 +#define RES_RX4 0x08 +#define RES_TX4 0x09 +#define RES_RX5 0x0a +#define RES_TX5 0x0b +#define RES_RX6 0x0c +#define RES_TX6 0x0d + +// Serial command bytes +#define SERIAL_CONFIG 0x10 +#define SERIAL_WRITE 0x20 +#define SERIAL_READ 0x30 +#define SERIAL_REPLY 0x40 +#define SERIAL_CLOSE 0x50 +#define SERIAL_FLUSH 0x60 +#define SERIAL_LISTEN 0x70 + +// Serial read modes +#define SERIAL_READ_CONTINUOUSLY 0x00 +#define SERIAL_STOP_READING 0x01 +#define SERIAL_MODE_MASK 0xF0 + +namespace { + + struct serial_pins { + uint8_t rx; + uint8_t tx; + }; + + /* + * Get the serial serial pin type (RX1, TX1, RX2, TX2, etc) for the specified pin. + */ + inline uint8_t getSerialPinType(uint8_t pin) { + #if defined(PIN_SERIAL_RX) + // TODO when use of HW_SERIAL0 is enabled + #endif + #if defined(PIN_SERIAL1_RX) + if (pin == PIN_SERIAL1_RX) return RES_RX1; + if (pin == PIN_SERIAL1_TX) return RES_TX1; + #endif + #if defined(PIN_SERIAL2_RX) + if (pin == PIN_SERIAL2_RX) return RES_RX2; + if (pin == PIN_SERIAL2_TX) return RES_TX2; + #endif + #if defined(PIN_SERIAL3_RX) + if (pin == PIN_SERIAL3_RX) return RES_RX3; + if (pin == PIN_SERIAL3_TX) return RES_TX3; + #endif + #if defined(PIN_SERIAL4_RX) + if (pin == PIN_SERIAL4_RX) return RES_RX4; + if (pin == PIN_SERIAL4_TX) return RES_TX4; + #endif + #if defined(PIN_SERIAL5_RX) + if (pin == PIN_SERIAL5_RX) return RES_RX5; + if (pin == PIN_SERIAL5_TX) return RES_TX5; + #endif + #if defined(PIN_SERIAL6_RX) + if (pin == PIN_SERIAL6_RX) return RES_RX6; + if (pin == PIN_SERIAL6_TX) return RES_TX6; + #endif + return 0; + } + + /* + * Get the RX and TX pins numbers for the specified HW serial port. + */ + inline serial_pins getSerialPinNumbers(uint8_t portId) { + serial_pins pins; + switch (portId) { + #if defined(PIN_SERIAL_RX) + // case HW_SERIAL0: + // // TODO when use of HW_SERIAL0 is enabled + // break; + #endif + #if defined(PIN_SERIAL1_RX) + case HW_SERIAL1: + pins.rx = PIN_SERIAL1_RX; + pins.tx = PIN_SERIAL1_TX; + break; + #endif + #if defined(PIN_SERIAL2_RX) + case HW_SERIAL2: + pins.rx = PIN_SERIAL2_RX; + pins.tx = PIN_SERIAL2_TX; + break; + #endif + #if defined(PIN_SERIAL3_RX) + case HW_SERIAL3: + pins.rx = PIN_SERIAL3_RX; + pins.tx = PIN_SERIAL3_TX; + break; + #endif + #if defined(PIN_SERIAL4_RX) + case HW_SERIAL4: + pins.rx = PIN_SERIAL4_RX; + pins.tx = PIN_SERIAL4_TX; + break; + #endif + #if defined(PIN_SERIAL5_RX) + case HW_SERIAL5: + pins.rx = PIN_SERIAL5_RX; + pins.tx = PIN_SERIAL5_TX; + break; + #endif + #if defined(PIN_SERIAL6_RX) + case HW_SERIAL6: + pins.rx = PIN_SERIAL6_RX; + pins.tx = PIN_SERIAL6_TX; + break; + #endif + default: + pins.rx = 0; + pins.tx = 0; + } + return pins; + } + +} // end namespace + + +class SerialFirmata: public FirmataFeature +{ + public: + SerialFirmata(); + boolean handlePinMode(byte pin, int mode); + void handleCapability(byte pin); + boolean handleSysex(byte command, byte argc, byte* argv); + void update(); + void reset(); + void checkSerial(); + + private: + byte reportSerial[MAX_SERIAL_PORTS]; + int serialBytesToRead[SERIAL_READ_ARR_LEN]; + signed char serialIndex; + +#if defined(SoftwareSerial_h) + Stream *swSerial0; + Stream *swSerial1; + Stream *swSerial2; + Stream *swSerial3; +#endif + + Stream* getPortFromId(byte portId); + +}; + +#endif /* SerialFirmata_h */ diff --git a/libraries/Firmata/utility/WiFiClientStream.h b/libraries/Firmata/utility/WiFiClientStream.h new file mode 100644 index 0000000..7fd30af --- /dev/null +++ b/libraries/Firmata/utility/WiFiClientStream.h @@ -0,0 +1,105 @@ +/* + WiFiClientStream.h + + An Arduino Stream that wraps an instance of a WiFiClient. For use + with legacy Arduino WiFi shield and other boards and shields that + are compatible with the Arduino WiFi library. + + Copyright (C) 2016 Jens B. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Parts of this class are based on + + - EthernetClientStream - Copyright (C) 2013 Norbert Truchsess. All rights reserved. + + published under the same license. + + Last updated April 23rd, 2016 + */ + +#ifndef WIFI_CLIENT_STREAM_H +#define WIFI_CLIENT_STREAM_H + +#include "WiFiStream.h" + +#define MILLIS_RECONNECT 5000 + +class WiFiClientStream : public WiFiStream +{ +protected: + uint32_t _time_connect = 0; + + /** + * check if TCP client is connected + * @return true if connected + */ + virtual inline bool connect_client() + { + if ( _connected ) + { + if ( _client && _client.connected() ) return true; + stop(); + } + + // active TCP connect + if ( WiFi.status() == WL_CONNECTED ) + { + // if the client is disconnected, try to reconnect every 5 seconds + if ( millis() - _time_connect >= MILLIS_RECONNECT ) + { + _connected = _client.connect( _remote_ip, _port ); + if ( !_connected ) + { + _time_connect = millis(); + } + else if ( _currentHostConnectionCallback ) + { + (*_currentHostConnectionCallback)(HOST_CONNECTION_CONNECTED); + } + } + } + + return _connected; + } + +public: + /** + * create a WiFi stream with a TCP client + */ + WiFiClientStream(IPAddress server_ip, uint16_t server_port) : WiFiStream(server_ip, server_port) {} + + /** + * maintain WiFi and TCP connection + * @return true if WiFi and TCP connection are established + */ + virtual inline bool maintain() + { + return connect_client(); + } + + /** + * stop client connection + */ + virtual inline void stop() + { + if ( _client) + { + _client.stop(); + if ( _currentHostConnectionCallback ) + { + (*_currentHostConnectionCallback)(HOST_CONNECTION_DISCONNECTED); + } + } + _connected = false; + _time_connect = millis(); + } + +}; + +#endif //WIFI_CLIENT_STREAM_H diff --git a/libraries/Firmata/utility/WiFiServerStream.h b/libraries/Firmata/utility/WiFiServerStream.h new file mode 100644 index 0000000..1404b05 --- /dev/null +++ b/libraries/Firmata/utility/WiFiServerStream.h @@ -0,0 +1,107 @@ +/* + WiFiServerStream.h + + An Arduino Stream extension for a WiFiClient or WiFiServer to be used + with legacy Arduino WiFi shield and other boards and shields that + are compatible with the Arduino WiFi library. + + Copyright (C) 2016 Jens B. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Parts of this class are based on + + - WiFiStream - Copyright (C) 2015-2016 Jesse Frush. All rights reserved. + + published under the same license. + + Last updated April 23rd, 2016 + */ + +#ifndef WIFI_SERVER_STREAM_H +#define WIFI_SERVER_STREAM_H + +#include "WiFiStream.h" + +class WiFiServerStream : public WiFiStream +{ +protected: + WiFiServer _server = WiFiServer(3030); + bool _listening = false; + + /** + * check if TCP client is connected + * @return true if connected + */ + virtual inline bool connect_client() + { + if ( _connected ) + { + if ( _client && _client.connected() ) return true; + stop(); + } + + // passive TCP connect (accept) + WiFiClient newClient = _server.available(); + if ( !newClient ) return false; + _client = newClient; + _connected = true; + if ( _currentHostConnectionCallback ) + { + (*_currentHostConnectionCallback)(HOST_CONNECTION_CONNECTED); + } + + return true; + } + +public: + /** + * create a WiFi stream with a TCP server + */ + WiFiServerStream(uint16_t server_port) : WiFiStream(server_port) {} + + /** + * maintain WiFi and TCP connection + * @return true if WiFi and TCP connection are established + */ + virtual inline bool maintain() + { + if ( connect_client() ) return true; + + stop(); + + if ( !_listening && WiFi.status() == WL_CONNECTED ) + { + // start TCP server after first WiFi connect + _server = WiFiServer(_port); + _server.begin(); + _listening = true; + } + + return false; + } + + /** + * stop client connection + */ + virtual inline void stop() + { + if ( _client) + { + _client.stop(); + if ( _currentHostConnectionCallback ) + { + (*_currentHostConnectionCallback)(HOST_CONNECTION_DISCONNECTED); + } + } + _connected = false; + } + +}; + +#endif //WIFI_SERVER_STREAM_H diff --git a/libraries/Firmata/utility/WiFiStream.cpp b/libraries/Firmata/utility/WiFiStream.cpp new file mode 100644 index 0000000..9b54a5a --- /dev/null +++ b/libraries/Firmata/utility/WiFiStream.cpp @@ -0,0 +1,4 @@ +/* + * Implementation is in WiFiStream.h to avoid linker issues. Legacy WiFi and modern WiFi101 both define WiFiClass which + * will cause linker errors whenever Firmata.h is included. + */ diff --git a/libraries/Firmata/utility/WiFiStream.h b/libraries/Firmata/utility/WiFiStream.h new file mode 100644 index 0000000..1ad44bb --- /dev/null +++ b/libraries/Firmata/utility/WiFiStream.h @@ -0,0 +1,226 @@ +/* + WiFiStream.h + + An Arduino Stream extension for a WiFiClient or WiFiServer to be used + with legacy Arduino WiFi shield and other boards and shields that + are compatible with the Arduino WiFi library. + + Copyright (C) 2015-2016 Jesse Frush. All rights reserved. + Copyright (C) 2016 Jens B. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated April 23rd, 2016 + */ + +#ifndef WIFI_STREAM_H +#define WIFI_STREAM_H + +#include +#include + +#define HOST_CONNECTION_DISCONNECTED 0 +#define HOST_CONNECTION_CONNECTED 1 + +extern "C" { + // callback function types + typedef void (*hostConnectionCallbackFunction)(byte); +} + +class WiFiStream : public Stream +{ +protected: + WiFiClient _client; + bool _connected = false; + hostConnectionCallbackFunction _currentHostConnectionCallback; + + //configuration members + IPAddress _local_ip; // DHCP + IPAddress _subnet; + IPAddress _gateway; + IPAddress _remote_ip; + uint16_t _port; + uint8_t _key_idx; //WEP + const char *_key = nullptr; //WEP + const char *_passphrase = nullptr; //WPA + char *_ssid = nullptr; + + /** + * check if TCP client is connected + * @return true if connected + */ + virtual bool connect_client() = 0; + +public: + /** constructor for TCP server */ + WiFiStream(uint16_t server_port) : _port(server_port) {} + + /** constructor for TCP client */ + WiFiStream(IPAddress server_ip, uint16_t server_port) : _remote_ip(server_ip), _port(server_port) {} + + inline void attach( hostConnectionCallbackFunction newFunction ) { _currentHostConnectionCallback = newFunction; } + +/****************************************************************************** + * network configuration + ******************************************************************************/ + +#ifndef ESP8266 + /** + * configure a static local IP address without defining the local network + * DHCP will be used as long as local IP address is not defined + */ + inline void config(IPAddress local_ip) + { + _local_ip = local_ip; + WiFi.config( local_ip ); + } +#endif + + /** + * configure a static local IP address + * DHCP will be used as long as local IP address is not defined + */ + inline void config(IPAddress local_ip, IPAddress gateway, IPAddress subnet) + { + _local_ip = local_ip; + _subnet = subnet; + _gateway = gateway; +#ifndef ESP8266 + WiFi.config( local_ip, IPAddress(0, 0, 0, 0), gateway, subnet ); +#else + WiFi.config( local_ip, gateway, subnet ); +#endif + } + + /** + * @return local IP address + */ + inline IPAddress getLocalIP() + { + return WiFi.localIP(); + } + +/****************************************************************************** + * network functions + ******************************************************************************/ + + /** + * maintain WiFi and TCP connection + * @return true if WiFi and TCP connection are established + */ + virtual bool maintain() = 0; + +#ifdef ESP8266 + /** + * get status of TCP connection + * @return status of TCP connection + * CLOSED = 0 (typical) + * LISTEN = 1 (not used) + * SYN_SENT = 2 + * SYN_RCVD = 3 + * ESTABLISHED = 4 (typical) + * FIN_WAIT_1 = 5 + * FIN_WAIT_2 = 6 + * CLOSE_WAIT = 7 + * CLOSING = 8 + * LAST_ACK = 9 + * TIME_WAIT = 10 + */ + inline uint8_t status() + { + return _client.status(); + } +#endif + + /** + * close TCP client connection + */ + virtual void stop() = 0; + +/****************************************************************************** + * WiFi configuration + ******************************************************************************/ + + /** + * initialize WiFi without security (open) and initiate client connection + * if WiFi connection is already established + * @return WL_CONNECTED if WiFi connection is established + */ + inline int begin(char *ssid) + { + _ssid = ssid; + + WiFi.begin(ssid); + int result = WiFi.status(); + return WiFi.status(); + } + +#ifndef ESP8266 + /** + * initialize WiFi with WEP security and initiate client connection + * if WiFi connection is already established + * @return WL_CONNECTED if WiFi connection is established + */ + inline int begin(char *ssid, uint8_t key_idx, const char *key) + { + _ssid = ssid; + _key_idx = key_idx; + _key = key; + + WiFi.begin( ssid, key_idx, key ); + return WiFi.status(); + } +#endif + + /** + * initialize WiFi with WPA-PSK security and initiate client connection + * if WiFi connection is already established + * @return WL_CONNECTED if WiFi connection is established + */ + inline int begin(char *ssid, const char *passphrase) + { + _ssid = ssid; + _passphrase = passphrase; + + WiFi.begin(ssid, passphrase); + return WiFi.status(); + } + + +/****************************************************************************** + * stream functions + ******************************************************************************/ + + inline int available() + { + return connect_client() ? _client.available() : 0; + } + + inline void flush() + { + if( _client ) _client.flush(); + } + + inline int peek() + { + return connect_client() ? _client.peek(): 0; + } + + inline int read() + { + return connect_client() ? _client.read() : -1; + } + + inline size_t write(uint8_t byte) + { + return connect_client() ? _client.write( byte ) : 0; + } + +}; + +#endif //WIFI_STREAM_H diff --git a/libraries/Firmata/utility/firmataDebug.h b/libraries/Firmata/utility/firmataDebug.h new file mode 100644 index 0000000..dce0f80 --- /dev/null +++ b/libraries/Firmata/utility/firmataDebug.h @@ -0,0 +1,14 @@ +#ifndef FIRMATA_DEBUG_H +#define FIRMATA_DEBUG_H + +#ifdef SERIAL_DEBUG + #define DEBUG_BEGIN(baud) Serial.begin(baud); while(!Serial) {;} + #define DEBUG_PRINTLN(x) Serial.println (x); Serial.flush() + #define DEBUG_PRINT(x) Serial.print (x) +#else + #define DEBUG_BEGIN(baud) + #define DEBUG_PRINTLN(x) + #define DEBUG_PRINT(x) +#endif + +#endif /* FIRMATA_DEBUG_H */ diff --git a/libraries/GyverButton/LICENSE b/libraries/GyverButton/LICENSE new file mode 100644 index 0000000..353b7ee --- /dev/null +++ b/libraries/GyverButton/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Alex + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/libraries/GyverButton/README.md b/libraries/GyverButton/README.md new file mode 100644 index 0000000..5a6eec3 --- /dev/null +++ b/libraries/GyverButton/README.md @@ -0,0 +1,171 @@ +![License: MIT](https://img.shields.io/badge/License-MIT-green.svg) +![author](https://img.shields.io/badge/author-AlexGyver-informational.svg) +# GyverButton +Библиотека для многофункциональной отработки нажатия кнопки +**ВНИМАНИЕ, БИБЛИОТЕКА УСТАРЕЛА! ИСПОЛЬЗУЙ БИБЛИОТЕКУ [EncButton](https://github.com/GyverLibs/EncButton)** +- Работа с нормально замкнутыми и нормально разомкнутыми кнопками +- Работа с подключением PULL_UP и PULL_DOWN +- Опрос кнопки с программным антидребезгом контактов (настраиваемое время) +- Отработка нажатия, удерживания, отпускания, клика по кнопке (+ настройка таймаутов) +- Отработка одиночного, двойного и тройного нажатия (вынесено отдельно) +- Отработка любого количества нажатий кнопки (функция возвращает количество нажатий) +- Функция изменения значения переменной с заданным шагом и заданным интервалом по времени +- Возможность работы с "виртуальными" кнопками (все возможности библиотеки используются для матричных и резистивных клавиатур) + +### Совместимость +Совместима со всеми Arduino платформами (используются Arduino-функции) + +### Документация +К библиотеке есть [расширенная документация](https://alexgyver.ru/GyverButton/) + +## Содержание +- [Установка](#install) +- [Инициализация](#init) +- [Использование](#usage) +- [Пример](#example) +- [Версии](#versions) +- [Баги и обратная связь](#feedback) + +
+## Установка +- Библиотеку можно найти по названию **GyverButton** и установить через менеджер библиотек в: + - Arduino IDE + - Arduino IDE v2 + - PlatformIO +- [Скачать библиотеку](https://github.com/GyverLibs/GyverButton/archive/refs/heads/main.zip) .zip архивом для ручной установки: + - Распаковать и положить в *C:\Program Files (x86)\Arduino\libraries* (Windows x64) + - Распаковать и положить в *C:\Program Files\Arduino\libraries* (Windows x32) + - Распаковать и положить в *Документы/Arduino/libraries/* + - (Arduino IDE) автоматическая установка из .zip: *Скетч/Подключить библиотеку/Добавить .ZIP библиотеку…* и указать скачанный архив +- Читай более подробную инструкцию по установке библиотек [здесь](https://alexgyver.ru/arduino-first/#%D0%A3%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0_%D0%B1%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA) + + +## Инициализация +```cpp +GButton btn; // без привязки к пину (виртуальная кнопка) и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) +GButton btn(пин); // с привязкой к пину и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) +GButton btn(пин, тип подключ.); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и без указания типа кнопки (по умолч. NORM_OPEN) +GButton btn(пин, тип подключ., тип кнопки); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) +GButton btn(BTN_NO_PIN, тип подключ., тип кнопки); // без привязки к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) +``` + + +## Использование +```cpp +void setDebounce(uint16_t debounce); // установка времени антидребезга (по умолчанию 80 мс) +void setTimeout(uint16_t timeout); // установка таймаута удержания (по умолчанию 300 мс) +void setClickTimeout(uint16_t timeout); // установка таймаута между кликами (по умолчанию 500 мс) +void setStepTimeout(uint16_t step_timeout); // установка таймаута между инкрементами (по умолчанию 400 мс) +void setType(uint8_t type); // установка типа кнопки (HIGH_PULL - подтянута к питанию, LOW_PULL - к gnd) +void setDirection(uint8_t dir); // установка направления (разомкнута/замкнута по умолчанию - NORM_OPEN, NORM_CLOSE) + +void setTickMode(uint8_t tickMode); // (MANUAL / AUTO) ручной или автоматический опрос кнопки функцией tick() +// MANUAL - нужно вызывать функцию tick() вручную +// AUTO - tick() входит во все остальные функции и опрашивается сама + +void tick(); // опрос кнопки +void tick(boolean state); // опрос внешнего значения (0 нажато, 1 не нажато) (для матричных, резистивных клавиатур и джойстиков) + +boolean isPress(); // возвращает true при нажатии на кнопку. Сбрасывается после вызова +boolean isRelease(); // возвращает true при отпускании кнопки. Сбрасывается после вызова +boolean isClick(); // возвращает true при клике. Сбрасывается после вызова +boolean isHolded(); // возвращает true при удержании дольше timeout. Сбрасывается после вызова +boolean isHold(); // возвращает true при нажатой кнопке, не сбрасывается +boolean state(); // возвращает состояние кнопки +boolean isSingle(); // возвращает true при одиночном клике. Сбрасывается после вызова +boolean isDouble(); // возвращает true при двойном клике. Сбрасывается после вызова +boolean isTriple(); // возвращает true при тройном клике. Сбрасывается после вызова + +boolean hasClicks(); // проверка на наличие кликов. Сбрасывается после вызова +uint8_t getClicks(); // вернуть количество кликов +uint8_t getHoldClicks();// вернуть количество кликов, предшествующее удерживанию + +boolean isStep(); // возвращает true по таймеру setStepTimeout, смотри пример +void resetStates(); // сбрасывает все is-флаги и счётчики +``` + + +## Пример +Остальные примеры смотри в **examples**! +```cpp +// Пример использования библиотеки GyverButton, все возможности в одном скетче. + +#define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +GButton butt1(BTN_PIN); + +// Варианты инициализации: +// GButton btn; // без привязки к пину (виртуальная кнопка) и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) +// GButton btn(пин); // с привязкой к пину и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) +// GButton btn(пин, тип подключ.); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и без указания типа кнопки (по умолч. NORM_OPEN) +// GButton btn(пин, тип подключ., тип кнопки); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) +// GButton btn(BTN_NO_BTN_PIN, тип подключ., тип кнопки); // без привязки к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) + +int value = 0; + +void setup() { + Serial.begin(9600); + + butt1.setDebounce(50); // настройка антидребезга (по умолчанию 80 мс) + butt1.setTimeout(300); // настройка таймаута на удержание (по умолчанию 500 мс) + butt1.setClickTimeout(600); // настройка таймаута между кликами (по умолчанию 300 мс) + + // HIGH_PULL - кнопка подключена к GND, пин подтянут к VCC (BTN_PIN --- КНОПКА --- GND) + // LOW_PULL - кнопка подключена к VCC, пин подтянут к GND + // по умолчанию стоит HIGH_PULL + butt1.setType(HIGH_PULL); + + // NORM_OPEN - нормально-разомкнутая кнопка + // NORM_CLOSE - нормально-замкнутая кнопка + // по умолчанию стоит NORM_OPEN + butt1.setDirection(NORM_OPEN); +} + +void loop() { + butt1.tick(); // обязательная функция отработки. Должна постоянно опрашиваться + + if (butt1.isClick()) Serial.println("Click"); // проверка на один клик + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик + + if (butt1.hasClicks()) // проверка на наличие нажатий + Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий + + if (butt1.isPress()) Serial.println("Press"); // нажатие на кнопку (+ дебаунс) + if (butt1.isRelease()) Serial.println("Release"); // отпускание кнопки (+ дебаунс) + if (butt1.isHold()) { // если кнопка удерживается + Serial.print("Holding "); // выводим пока удерживается + Serial.println(butt1.getHoldClicks()); // можно вывести количество кликов перед удержанием! + } + if (butt1.isHold()) Serial.println("Holding"); // проверка на удержание + //if (butt1.state()) Serial.println("Hold"); // возвращает состояние кнопки + + if (butt1.isStep()) { // если кнопка была удержана (это для инкремента) + value++; // увеличивать/уменьшать переменную value с шагом и интервалом + Serial.println(value); // для примера выведем в порт + } +} +``` + + +## Версии +- v2.15: Добавлена возможность объявить кнопку без привязки к пину +- v3.0: Ускорен и оптимизирован код, переделана инициализация, дополнены примеры +- v3.1: isStep может принимать количество кликов, сделанных перед ним (см. пример clicks_step) +- v3.2: Добавлен метод getHoldClicks() - вернуть количество кликов, предшествующее удерживанию +- v3.3: Мелкие исправления +- v3.4: Добавлен метод resetStates(), сбрасывающий состояния и счётчики +- v3.5: увелична производительность для AVR Arduino +- v3.6: добавлен отдельный класс для работы с аналоговыми клавиатурами, см пример analogKeyboardG +- v3.7: исправления от Dryundel: + - Любой таймаут удержания + - Single, Double и Triple теперь не мешают hasClicks и getClicks и работают совместно + - isStep() тоже теперь ничего не мешает и он работает более корректно +- v3.8: исправления от Dryundel + + +## Баги и обратная связь +При нахождении багов создавайте **Issue**, а лучше сразу пишите на почту [alex@alexgyver.ru](mailto:alex@alexgyver.ru) +Библиотека открыта для доработки и ваших **Pull Request**'ов! \ No newline at end of file diff --git a/libraries/GyverButton/examples/Gbutton_demo/Gbutton_demo.ino b/libraries/GyverButton/examples/Gbutton_demo/Gbutton_demo.ino new file mode 100644 index 0000000..30fc505 --- /dev/null +++ b/libraries/GyverButton/examples/Gbutton_demo/Gbutton_demo.ino @@ -0,0 +1,59 @@ +// Пример использования библиотеки GyverButton, все возможности в одном скетче. + +#define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +GButton butt1(BTN_PIN); + +// Варианты инициализации: +// GButton btn; // без привязки к пину (виртуальная кнопка) и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) +// GButton btn(пин); // с привязкой к пину и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) +// GButton btn(пин, тип подключ.); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и без указания типа кнопки (по умолч. NORM_OPEN) +// GButton btn(пин, тип подключ., тип кнопки); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) +// GButton btn(BTN_NO_BTN_PIN, тип подключ., тип кнопки); // без привязки к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) + +int value = 0; + +void setup() { + Serial.begin(9600); + + butt1.setDebounce(50); // настройка антидребезга (по умолчанию 80 мс) + butt1.setTimeout(300); // настройка таймаута на удержание (по умолчанию 500 мс) + butt1.setClickTimeout(600); // настройка таймаута между кликами (по умолчанию 300 мс) + + // HIGH_PULL - кнопка подключена к GND, пин подтянут к VCC (BTN_PIN --- КНОПКА --- GND) + // LOW_PULL - кнопка подключена к VCC, пин подтянут к GND + // по умолчанию стоит HIGH_PULL + butt1.setType(HIGH_PULL); + + // NORM_OPEN - нормально-разомкнутая кнопка + // NORM_CLOSE - нормально-замкнутая кнопка + // по умолчанию стоит NORM_OPEN + butt1.setDirection(NORM_OPEN); +} + +void loop() { + butt1.tick(); // обязательная функция отработки. Должна постоянно опрашиваться + + if (butt1.isClick()) Serial.println("Click"); // проверка на один клик + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик + + if (butt1.hasClicks()) // проверка на наличие нажатий + Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий + + if (butt1.isPress()) Serial.println("Press"); // нажатие на кнопку (+ дебаунс) + if (butt1.isRelease()) Serial.println("Release"); // отпускание кнопки (+ дебаунс) + if (butt1.isHold()) { // если кнопка удерживается + Serial.print("Holding "); // выводим пока удерживается + Serial.println(butt1.getHoldClicks()); // можно вывести количество кликов перед удержанием! + } + if (butt1.isHold()) Serial.println("Holding"); // проверка на удержание + //if (butt1.state()) Serial.println("Hold"); // возвращает состояние кнопки + + if (butt1.isStep()) { // если кнопка была удержана (это для инкремента) + value++; // увеличивать/уменьшать переменную value с шагом и интервалом + Serial.println(value); // для примера выведем в порт + } +} diff --git a/libraries/GyverButton/examples/Gbutton_example/Gbutton_example.ino b/libraries/GyverButton/examples/Gbutton_example/Gbutton_example.ino new file mode 100644 index 0000000..d1aefa4 --- /dev/null +++ b/libraries/GyverButton/examples/Gbutton_example/Gbutton_example.ino @@ -0,0 +1,50 @@ +/* + Пример использования библиотеки GyverButton, все возможности в одном скетче. +*/ + +#define PIN 3 // кнопка подключена сюда (PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +GButton butt1(PIN); +// GButton butt1(PIN, HIGH_PULL, NORM_OPEN); // можно инициализировать так + +int value = 0; + +void setup() { + Serial.begin(9600); + + butt1.setDebounce(50); // настройка антидребезга (по умолчанию 80 мс) + butt1.setTimeout(300); // настройка таймаута на удержание (по умолчанию 500 мс) + butt1.setClickTimeout(600); // настройка таймаута между кликами (по умолчанию 300 мс) + + // HIGH_PULL - кнопка подключена к GND, пин подтянут к VCC (PIN --- КНОПКА --- GND) + // LOW_PULL - кнопка подключена к VCC, пин подтянут к GND + butt1.setType(HIGH_PULL); + + // NORM_OPEN - нормально-разомкнутая кнопка + // NORM_CLOSE - нормально-замкнутая кнопка + butt1.setDirection(NORM_OPEN); +} + +void loop() { + butt1.tick(); // обязательная функция отработки. Должна постоянно опрашиваться + + if (butt1.isClick()) Serial.println("Click"); // проверка на один клик + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик + + if (butt1.hasClicks()) // проверка на наличие нажатий + Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий + + if (butt1.isPress()) Serial.println("Press"); // нажатие на кнопку (+ дебаунс) + if (butt1.isRelease()) Serial.println("Release"); // отпускание кнопки (+ дебаунс) + if (butt1.isHolded()) Serial.println("Holded"); // проверка на удержание + if (butt1.isHold()) Serial.println("Holding"); // проверка на удержание + //if (butt1.state()) Serial.println("Hold"); // возвращает состояние кнопки + + if (butt1.isStep()) { // если кнопка была удержана (это для инкремента) + value++; // увеличивать/уменьшать переменную value с шагом и интервалом + Serial.println(value); // для примера выведем в порт + } +} diff --git a/libraries/GyverButton/examples/Gbutton_example_auto/Gbutton_example_auto.ino b/libraries/GyverButton/examples/Gbutton_example_auto/Gbutton_example_auto.ino new file mode 100644 index 0000000..2d816b3 --- /dev/null +++ b/libraries/GyverButton/examples/Gbutton_example_auto/Gbutton_example_auto.ino @@ -0,0 +1,54 @@ +// Пример использования библиотеки GyverButton, все возможности в одном скетче. +// автоматический тик + +#define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +GButton butt1(BTN_PIN); +// GButton butt1(BTN_PIN, HIGH_PULL, NORM_OPEN); // можно инициализировать так + +int value = 0; + +void setup() { + Serial.begin(9600); + + butt1.setDebounce(90); // настройка антидребезга (по умолчанию 80 мс) + butt1.setTimeout(300); // настройка таймаута на удержание (по умолчанию 500 мс) + + // HIGH_PULL - кнопка подключена к GND, пин подтянут к VCC (BTN_PIN --- КНОПКА --- GND) + // LOW_PULL - кнопка подключена к VCC, пин подтянут к GND + // по умолчанию стоит HIGH_PULL + butt1.setType(HIGH_PULL); + + // NORM_OPEN - нормально-разомкнутая кнопка + // NORM_CLOSE - нормально-замкнутая кнопка + // по умолчанию стоит NORM_OPEN + butt1.setDirection(NORM_OPEN); + + // MANUAL - нужно вызывать функцию tick() вручную + // AUTO - tick() входит во все остальные функции и опрашивается сама! + butt1.setTickMode(AUTO); +} + +void loop() { + // butt1.tick(); // НЕ НУЖНА, в этом режиме (AUTO) она входит в каждую функцию + + if (butt1.isClick()) Serial.println("Click"); // проверка на один клик + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик + + if (butt1.hasClicks()) // проверка на наличие нажатий + Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий + + if (butt1.isPress()) Serial.println("Press"); // нажатие на кнопку (+ дебаунс) + if (butt1.isRelease()) Serial.println("Release"); // отпускание кнопки (+ дебаунс) + if (butt1.isHolded()) Serial.println("Holded"); // проверка на удержание + if (butt1.isHold()) Serial.println("Holding"); // проверка на удержание + //if (butt1.state()) Serial.println("Hold"); // возвращает состояние кнопки + + if (butt1.isStep()) { // если кнопка была удержана (это для инкремента) + value++; // увеличивать/уменьшать переменную value с шагом и интервалом + Serial.println(value); // для примера выведем в порт + } +} diff --git a/libraries/GyverButton/examples/Gbutton_interrupt/Gbutton_interrupt.ino b/libraries/GyverButton/examples/Gbutton_interrupt/Gbutton_interrupt.ino new file mode 100644 index 0000000..ef00ab9 --- /dev/null +++ b/libraries/GyverButton/examples/Gbutton_interrupt/Gbutton_interrupt.ino @@ -0,0 +1,42 @@ +// Пример использования библиотеки GyverButton, все возможности в одном скетче. +// Дополнительный опрос по аппаратному прерыванию + +#define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +GButton butt1(BTN_PIN); +int value = 0; + +void setup() { + Serial.begin(9600); + attachInterrupt(1, isr, CHANGE); + + butt1.setDebounce(80); // настройка антидребезга (по умолчанию 80 мс) + butt1.setTimeout(300); // настройка таймаута на удержание (по умолчанию 500 мс) +} + +void isr() { + butt1.tick(); // опрашиваем в прерывании, чтобы поймать нажатие в любом случае +} + +void loop() { + butt1.tick(); // опрашиваем в скетче, иначе не будут работать проверки по времени! + + if (butt1.isClick()) Serial.println("Click"); // проверка на один клик + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик + + if (butt1.hasClicks()) // проверка на наличие нажатий + Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий + + if (butt1.isPress()) Serial.println("Press"); // нажатие на кнопку (+ дебаунс) + if (butt1.isRelease()) Serial.println("Release"); // отпускание кнопки (+ дебаунс) + if (butt1.isHolded()) Serial.println("Holded"); // проверка на удержание + //if (butt1.isHold()) Serial.println("Hold"); // возвращает состояние кнопки + + if (butt1.isStep()) { // если кнопка была удержана (это для инкремента) + value++; // увеличивать/уменьшать переменную value с шагом и интервалом + Serial.println(value); // для примера выведем в порт + } +} diff --git a/libraries/GyverButton/examples/Gbutton_timer_interrupt/Gbutton_timer_interrupt.ino b/libraries/GyverButton/examples/Gbutton_timer_interrupt/Gbutton_timer_interrupt.ino new file mode 100644 index 0000000..b1e1eb6 --- /dev/null +++ b/libraries/GyverButton/examples/Gbutton_timer_interrupt/Gbutton_timer_interrupt.ino @@ -0,0 +1,44 @@ +/* + Пример использования библиотеки GyverButton, все возможности в одном скетче + Данный скетч показывает, как быть в сложном "не сквозном" коде с кучей delay и замкнутых циклов + Здесь кнопка опрашивается каждые 10 миллисекунд независимо от того, что происходит у вас в коде + Используется библиотека TimerOne https://github.com/PaulStoffregen/TimerOne +*/ + +#define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +#include "TimerOne.h" +GButton butt1(BTN_PIN); +int value = 0; + +void setup() { + Serial.begin(9600); + + Timer1.initialize(10000); // установка таймера на каждые 10000 микросекунд (== 10 мс) + Timer1.attachInterrupt(timerIsr); // запуск таймера +} + +void timerIsr() { // прерывание таймера + butt1.tick(); // отработка теперь находится здесь +} + +void loop() { + if (butt1.isClick()) Serial.println("Click"); // проверка на один клик + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик + + if (butt1.hasClicks()) // проверка на наличие нажатий + Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий + + if (butt1.isPress()) Serial.println("Press"); // нажатие на кнопку (+ дебаунс) + if (butt1.isRelease()) Serial.println("Release"); // отпускание кнопки (+ дебаунс) + if (butt1.isHolded()) Serial.println("Holded"); // проверка на удержание + //if (butt1.isHold()) Serial.println("Hold"); // возвращает состояние кнопки + + if (butt1.isStep()) { // если кнопка была удержана (это для инкремента) + value++; // увеличивать/уменьшать переменную value с шагом и интервалом + Serial.println(value); // для примера выведем в порт + } +} diff --git a/libraries/GyverButton/examples/_1-2-3-click/_1-2-3-click.ino b/libraries/GyverButton/examples/_1-2-3-click/_1-2-3-click.ino new file mode 100644 index 0000000..ce84361 --- /dev/null +++ b/libraries/GyverButton/examples/_1-2-3-click/_1-2-3-click.ino @@ -0,0 +1,18 @@ +// Пример использования библиотеки GyverButton, 1- 2- 3- нажатие + +#define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +GButton butt1(BTN_PIN); + +void setup() { + Serial.begin(9600); +} + +void loop() { + butt1.tick(); // обязательная функция отработки. Должна постоянно опрашиваться + + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик +} diff --git a/libraries/GyverButton/examples/_5_buttons/_5_buttons.ino b/libraries/GyverButton/examples/_5_buttons/_5_buttons.ino new file mode 100644 index 0000000..70c099f --- /dev/null +++ b/libraries/GyverButton/examples/_5_buttons/_5_buttons.ino @@ -0,0 +1,36 @@ +// Пример использования библиотеки GyverButton +// опрос 5 кнопок в ручном режиме + +// кнопки подключены к земле (PIN --- КНОПКА --- GND) +#define BTN1 3 +#define BTN2 4 +#define BTN3 5 +#define BTN4 6 +#define BTN5 7 + +#include "GyverButton.h" +GButton butt1(BTN1); +GButton butt2(BTN2); +GButton butt3(BTN3); +GButton butt4(BTN4); +GButton butt5(BTN5); + +void setup() { + Serial.begin(9600); +} + +void loop() { + // тик в ручном режиме + butt1.tick(); + butt2.tick(); + butt3.tick(); + butt4.tick(); + butt5.tick(); + + // проверяем одиночный клик + if (butt1.isClick()) Serial.println("Button 1"); + if (butt2.isClick()) Serial.println("Button 2"); + if (butt3.isClick()) Serial.println("Button 3"); + if (butt4.isClick()) Serial.println("Button 4"); + if (butt5.isClick()) Serial.println("Button 5"); +} diff --git a/libraries/GyverButton/examples/_5_buttons_auto/_5_buttons_auto.ino b/libraries/GyverButton/examples/_5_buttons_auto/_5_buttons_auto.ino new file mode 100644 index 0000000..fbc5ae5 --- /dev/null +++ b/libraries/GyverButton/examples/_5_buttons_auto/_5_buttons_auto.ino @@ -0,0 +1,37 @@ +// Пример использования библиотеки GyverButton +// опрос 5 кнопок в автоматическом режиме + +// кнопки подключены к земле (PIN --- КНОПКА --- GND) +#define BTN1 3 +#define BTN2 4 +#define BTN3 5 +#define BTN4 6 +#define BTN5 7 + +#include "GyverButton.h" +GButton butt1(BTN1); +GButton butt2(BTN2); +GButton butt3(BTN3); +GButton butt4(BTN4); +GButton butt5(BTN5); + +void setup() { + Serial.begin(9600); + + // устанавливаем опрос на автоматический + butt1.setTickMode(AUTO); + butt2.setTickMode(AUTO); + butt3.setTickMode(AUTO); + butt4.setTickMode(AUTO); + butt5.setTickMode(AUTO); +} + +void loop() { + // проверяем одиночный клик + // tick уже сидит внутри опроса + if (butt1.isClick()) Serial.println("Button 1"); + if (butt2.isClick()) Serial.println("Button 2"); + if (butt3.isClick()) Serial.println("Button 3"); + if (butt4.isClick()) Serial.println("Button 4"); + if (butt5.isClick()) Serial.println("Button 5"); +} diff --git a/libraries/GyverButton/examples/analogKeyboard/analogBtns.jpg b/libraries/GyverButton/examples/analogKeyboard/analogBtns.jpg new file mode 100644 index 0000000000000000000000000000000000000000..406c54f2a5dd2906c9fcf83def875e6f0e836cad GIT binary patch literal 94388 zcmbq*1zeR+(>5yIB_%DTgf!C9C5<2=*C7))t#DRG!<*RH|nfPXNT6EGq$H?CiY{DL1?@C%0s z2L}rahm3##kBEwlii(1af`W#QjfsYig^q%PiHC`WgM0JlO;ikg0z6y-Y}}i;5FyuY zfHtsjNN{jSxM(P7xc}>)%SIS1#OsIGyKY>ggt?A&?FQDh%Vro7m}@ZC;2^L2^XEFu zwHxpVh;Xn-p!gOjxPIf0QW#MC1}yw_gv)Ul)El4>^9Ck(wipKF za7Z$JuTFsll6u$ou~^28p{H?4J?!O|b+8W|Gzg%lNCNK~5u8URl)MbTDy&1Qzq1&s z{8Lga5QvD^HLE(>XKWhi_x{{V&CGFcj{b7)l|MLSsvU87LpL+r}Xn?Fm@L4io@+K}W|_m9C# z)$U}XL7wy9?yA!K>a~yluF!MjKOXc8JxA2K9urXB`2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% z($9>~j}-fR|0kdWm0{%QQ4}sAr~BBed7p998S9kz!t=_PSCKbOXmi;NC>5n&MoRx* z^Q8U7{o}i@XmaArrhoYQ7~M~)PyXNbSTd-#T*wBM5N3Nup+M6ZVWtR_mFN1%S(+b2+`kdMF|llHZWT|snaO1({YPJec(H>l=l$I}Ih$dOcC0nlsxc7a~w zT!IaczV}d|qDXWZC&~-jeBC^g1zHS28AQt&%ucOUyy3a;;5c`u(XMH<6Ub;7JFQnE z=;b(P_<#~9CTp+hLHHVN9o1p%6ux>N9-msPbak7FfF(D{X^m7~cAB6XENv)|zAlM7 zjGff0UQ?hX+VhM5>bdvd8pnU7tok2mYP)Yu1}OahU7&wIW0r%b#KWJ`bB1oh%bp#| z=^p-g6>17Ly%Th7uuk{9?YHksKX|$fQmX?$FCWy*>21vD^dI2mgbF&1&j>mTQG&ip zGfp=(i+dYG%eS7+C~*`VMz`Jb0D)4@zU}mX7G-z&# 820); + myButt2.tick(analog < 740 && analog > 700); + myButt3.tick(analog < 650 && analog > 600); + + // проверка на удержание, например + if (myButt1.isHolded()) { + Serial.println("hold 1"); + } + if (myButt2.isHolded()) { + Serial.println("hold 2"); + } + if (myButt3.isHolded()) { + Serial.println("hold 3"); + } + + delay(10); // задержка тут не нужна, чисто для вывода +} diff --git a/libraries/GyverButton/examples/analogKeyboardG/analogKeyboardG.ino b/libraries/GyverButton/examples/analogKeyboardG/analogKeyboardG.ino new file mode 100644 index 0000000..77fc168 --- /dev/null +++ b/libraries/GyverButton/examples/analogKeyboardG/analogKeyboardG.ino @@ -0,0 +1,49 @@ +// новый пример работы с аналоговой клавиатурой +/* + Сигналы кнопок + 1023 + 927 + 856 + 783 + 671 + 632 + 590 + 560 + 504 + 480 + 455 + 440 + 399 + 319 + 255 + 230 +*/ +#include "AnalogKey.h" +// указываем пин и количество кнопок +AnalogKey keys; + +#include +GButton btn1, btn2, btn3; + +void setup() { + Serial.begin(9600); + // указываем сигналы кнопок аналоговой клавы + keys.attach(0, 1023); + keys.attach(1, 927); + keys.attach(2, 856); +} + +void loop() { + // тикаем кнопки как статусы аналоговых + btn1.tick(keys.status(0)); + btn2.tick(keys.status(1)); + btn3.tick(keys.status(2)); + + if (btn1.isClick()) Serial.println("click 0"); + if (btn2.isClick()) Serial.println("click 1"); + if (btn3.isClick()) Serial.println("click 2"); + + if (btn1.isHolded()) Serial.println("click 0"); + if (btn2.isHolded()) Serial.println("hold 1"); + if (btn3.isHolded()) Serial.println("hold 2"); +} diff --git a/libraries/GyverButton/examples/btn_pinChangeInt/btn_pinChangeInt.ino b/libraries/GyverButton/examples/btn_pinChangeInt/btn_pinChangeInt.ino new file mode 100644 index 0000000..47f67d1 --- /dev/null +++ b/libraries/GyverButton/examples/btn_pinChangeInt/btn_pinChangeInt.ino @@ -0,0 +1,57 @@ +// пример с прерываниями pinChangeInterrupt (прерывания на любом пине) +// только для ATmega328 (UNO, Nano, Pro Mini) + +#define BTN_PIN 3 + +#include "GyverButton.h" +GButton butt1(BTN_PIN); + +void setup() { + Serial.begin(9600); + + // настроить PCINT + attachPCINT(BTN_PIN); +} + +void loop() { + butt1.tick(); // обязательно нужен отработчик ещё и в loop, чтобы работали таймауты + + if (butt1.isClick()) Serial.println("Click"); // проверка на один клик + if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик + if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик + if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик +} + +// функция для настройки PCINT для ATmega328 (UNO, Nano, Pro Mini) +uint8_t attachPCINT(uint8_t pin) { + if (pin < 8) { // D0-D7 // PCINT2 + PCICR |= (1 << PCIE2); + PCMSK2 |= (1 << pin); + return 2; + } + else if (pin > 13) { //A0-A5 // PCINT1 + PCICR |= (1 << PCIE1); + PCMSK1 |= (1 << pin - 14); + return 1; + } + else { // D8-D13 // PCINT0 + PCICR |= (1 << PCIE0); + PCMSK0 |= (1 << pin - 8); + return 0; + } +} + +// Векторы PCINT, нужно кинуть сюда тики +// не обязательно в каждый вектор, достаточно в тот, который задействован +// пины 0-7: PCINT2 +// пины 8-13: PCINT0 +// пины A0-A5: PCINT1 +ISR(PCINT0_vect) { + //butt1.tick(); +} +ISR(PCINT1_vect) { + //butt1.tick(); +} +ISR(PCINT2_vect) { + butt1.tick(); +} diff --git a/libraries/GyverButton/examples/clicks_step/clicks_step.ino b/libraries/GyverButton/examples/clicks_step/clicks_step.ino new file mode 100644 index 0000000..cb3aa92 --- /dev/null +++ b/libraries/GyverButton/examples/clicks_step/clicks_step.ino @@ -0,0 +1,27 @@ +// ловим степ с накликиванием +#define BTN_PIN 0 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) +#include "GyverButton.h" +GButton butt1(BTN_PIN); + +void setup() { + Serial.begin(9600); +} + +void loop() { + butt1.tick(); + + // удержание + if (butt1.isStep()) { + Serial.println("0x"); + } + + // один клик + удержание + if (butt1.isStep(1)) { + Serial.println("1x"); + } + + // два клика + удержание + if (butt1.isStep(2)) { + Serial.println("2x"); + } +} diff --git a/libraries/GyverButton/examples/increment/increment.ino b/libraries/GyverButton/examples/increment/increment.ino new file mode 100644 index 0000000..7eb234d --- /dev/null +++ b/libraries/GyverButton/examples/increment/increment.ino @@ -0,0 +1,41 @@ +/* + Пример использования библиотеки GyverButton, управляем переменной value при помощи двух кнопок + Конструкция с isIncr делает увеличение/уменьшение переменной при нажатой кнопке с шагом по времени +*/ + +#define BTN1 2 // кнопка подключена сюда (PIN --- КНОПКА --- GND) +#define BTN2 3 // кнопка подключена сюда (PIN --- КНОПКА --- GND) + +#include "GyverButton.h" +GButton butt1(BTN1); +GButton butt2(BTN2); +int value = 0; + +void setup() { + Serial.begin(9600); +} + +void loop() { + butt1.tick(); // обязательная функция отработки. Должна постоянно опрашиваться + butt2.tick(); // обязательная функция отработки. Должна постоянно опрашиваться + + if (butt1.isClick()) { // одиночное нажатие + value++; // инкремент + Serial.println(value); // для примера выведем в порт + } + + if (butt2.isClick()) { // одиночное нажатие + value--; // декремент + Serial.println(value); // для примера выведем в порт + } + + if (butt1.isStep()) { // обработчик удержания с шагами + value++; // увеличивать/уменьшать переменную value с шагом и интервалом! + Serial.println(value); // для примера выведем в порт + } + + if (butt2.isStep()) { // обработчик удержания с шагами + value--; // увеличивать/уменьшать переменную value с шагом и интервалом! + Serial.println(value); // для примера выведем в порт + } +} diff --git a/libraries/GyverButton/examples/many_clicks/many_clicks.ino b/libraries/GyverButton/examples/many_clicks/many_clicks.ino new file mode 100644 index 0000000..19d0d0b --- /dev/null +++ b/libraries/GyverButton/examples/many_clicks/many_clicks.ino @@ -0,0 +1,19 @@ +/* + Пример использования библиотеки GyverButton, отработка любого количества нажатий +*/ + +#define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) +#include "GyverButton.h" +GButton butt1(BTN_PIN); + +void setup() { + Serial.begin(9600); + butt1.setTimeout(400); // настройка таймаута на удержание и второй клик (по умолчанию 500 мс) +} + +void loop() { + butt1.tick(); // обязательная функция отработки. Должна постоянно опрашиваться + + if (butt1.hasClicks()) // проверка на наличие нажатий + Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий +} diff --git a/libraries/GyverButton/keywords.txt b/libraries/GyverButton/keywords.txt new file mode 100644 index 0000000..ad73cf2 --- /dev/null +++ b/libraries/GyverButton/keywords.txt @@ -0,0 +1,51 @@ +####################################### +# Syntax Coloring Map For GyverButton +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +GButton KEYWORD1 +GyverButton KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +setDebounce KEYWORD2 +setTimeout KEYWORD2 +setStepTimeout KEYWORD2 +setClickTimeout KEYWORD2 +setType KEYWORD2 +setDirection KEYWORD2 +setTickMode KEYWORD2 + +tick KEYWORD2 +isPress KEYWORD2 +isRelease KEYWORD2 +isClick KEYWORD2 +isHolded KEYWORD2 +isHold KEYWORD2 +state KEYWORD2 + +hasClicks KEYWORD2 +getClicks KEYWORD2 +getHoldClicks KEYWORD2 +isSingle KEYWORD2 +isDouble KEYWORD2 +isTriple KEYWORD2 +isStep KEYWORD2 + +resetStates KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +HIGH_PULL LITERAL1 +LOW_PULL LITERAL1 +NORM_OPEN LITERAL1 +NORM_CLOSE LITERAL1 +MANUAL LITERAL1 +AUTO LITERAL1 \ No newline at end of file diff --git a/libraries/GyverButton/library.properties b/libraries/GyverButton/library.properties new file mode 100644 index 0000000..fc5c00a --- /dev/null +++ b/libraries/GyverButton/library.properties @@ -0,0 +1,9 @@ +name=GyverButton +version=3.8 +author=AlexGyver +maintainer=AlexGyver +sentence=Advanced button control library +paragraph=Advanced button control library +category=Sensors +url=https://github.com/GyverLibs/GyverButton +architectures=* \ No newline at end of file diff --git a/libraries/GyverButton/src/AnalogKey.h b/libraries/GyverButton/src/AnalogKey.h new file mode 100644 index 0000000..69f70ad --- /dev/null +++ b/libraries/GyverButton/src/AnalogKey.h @@ -0,0 +1,64 @@ +#ifndef AnalogKey_h +#define AnalogKey_h +/* + Мини класс для работы с аналоговой клавиатурой + GitHub: https://github.com/GyverLibs/AnalogKey + - Встроенный простенький дебаунс + - Оптимальный опрос пина по таймеру + - Проверка конкретной кнопки или вывод номера нажатой + + AlexGyver, alex@alexgyver.ru + https://alexgyver.ru/ + MIT License +*/ + +#define _AKEY_PERIOD 50 // период опроса в мс + +template +class AnalogKey { +public: + // подключает кнопку на указанное значение + void attach(byte num, int value) { + if (num >= AMOUNT) return; + signals[num] = value; + } + + // устанавливает окно сигнала (умолч. 20) + void setWindow(int window) { + _window = window; + } + + // возвращает статус указанной кнопки + bool status(byte num) { + if (millis() - tmr > _AKEY_PERIOD) { + tmr = millis(); + int thisRead = analogRead(PIN); + if (abs(thisRead - _lastRead) < _window) _ready = true; + else _ready = false; + _lastRead = thisRead; + } + if (_ready && + _lastRead > signals[num] - _window && + _lastRead < signals[num] + _window) return true; + else return false; + } + + // выводит номер нажатой кнопки или -1, если нажатых кнопок нет + int pressed() { + status(0); // вызываем опрос + for (byte i = 0; i < AMOUNT; i++) { + if (_ready && + _lastRead > signals[i] - _window && + _lastRead < signals[i] + _window) return i; + } + return -1; + } + +private: + int signals[AMOUNT]; + int _lastRead = 0; + int _window = 20; + bool _ready = false; + uint32_t tmr; +}; +#endif \ No newline at end of file diff --git a/libraries/GyverButton/src/GyverButton.cpp b/libraries/GyverButton/src/GyverButton.cpp new file mode 100644 index 0000000..3c0f3ad --- /dev/null +++ b/libraries/GyverButton/src/GyverButton.cpp @@ -0,0 +1,224 @@ +#include "GyverButton.h" + +// ==================== CONSTRUCTOR ==================== +GButton::GButton(int8_t pin, bool type, bool dir) { + if (pin != BTN_NO_PIN) { + _PIN = (uint8_t)pin; + flags.noPin = false; + } else { + flags.noPin = true; + } + setType(type); + flags.mode = false; + flags.tickMode = false; + flags.inv_state = dir; +} + +// ==================== SET ==================== +void GButton::setDebounce(uint16_t debounce) { + _debounce = debounce; +} +void GButton::setTimeout(uint16_t new_timeout) { + _timeout = new_timeout; +} +void GButton::setClickTimeout(uint16_t new_timeout) { + _click_timeout = new_timeout; +} +void GButton::setStepTimeout(uint16_t step_timeout) { + _step_timeout = step_timeout; +} +void GButton::setType(bool type) { + flags.type = type; + if (!flags.noPin) { + if (type) pinMode(_PIN, INPUT); + else pinMode(_PIN, INPUT_PULLUP); +#if defined(__AVR__) + _pin_reg = portInputRegister(digitalPinToPort(_PIN)); + _bit_mask = digitalPinToBitMask(_PIN); +#endif + } +} +void GButton::setDirection(bool dir) { + flags.inv_state = dir; +} +void GButton::setTickMode(bool tickMode) { + flags.tickMode = tickMode; +} + +// ==================== IS ==================== +boolean GButton::isPress() { + if (flags.tickMode) GButton::tick(); + if (flags.isPress_f) { + flags.isPress_f = false; + return true; + } else return false; +} +boolean GButton::isRelease() { + if (flags.tickMode) GButton::tick(); + if (flags.isRelease_f) { + flags.isRelease_f = false; + return true; + } else return false; +} +boolean GButton::isClick() { + if (flags.tickMode) GButton::tick(); + if (flags.isOne_f) { + flags.isOne_f = false; + return true; + } else return false; +} +boolean GButton::isHolded() { + if (flags.tickMode) GButton::tick(); + if (flags.isHolded_f) { + flags.isHolded_f = false; + return true; + } else return false; +} +boolean GButton::isHold() { + if (flags.tickMode) GButton::tick(); + if (flags.step_flag) return true; + else return false; +} +boolean GButton::state() { + if (flags.tickMode) GButton::tick(); + return btn_state; +} +boolean GButton::isSingle() { + if (flags.tickMode) GButton::tick(); + if (flags.counter_flag && last_counter == 1) { + // last_counter = 0; + // flags.counter_flag = false; + flags.counter_reset = true; + return true; + } else return false; +} +boolean GButton::isDouble() { + if (flags.tickMode) GButton::tick(); + if (flags.counter_flag && last_counter == 2) { + // flags.counter_flag = false; + // last_counter = 0; + flags.counter_reset = true; + return true; + } else return false; +} +boolean GButton::isTriple() { + if (flags.tickMode) GButton::tick(); + if (flags.counter_flag && last_counter == 3) { + // flags.counter_flag = false; + // last_counter = 0; + flags.counter_reset = true; + return true; + } else return false; +} +boolean GButton::hasClicks() { + if (flags.tickMode) GButton::tick(); + if (flags.counter_flag) { + // flags.counter_flag = false; + flags.counter_reset = true; + return true; + } else return false; +} +uint8_t GButton::getClicks() { + // byte thisCount = last_counter; // Исключено 14.01.2021 + // last_counter = 0; + flags.counter_reset = true; + return last_counter; // return thisCount; (замена) 14.01.2021 +} +uint8_t GButton::getHoldClicks() { + if (flags.tickMode) GButton::tick(); + return last_hold_counter; //return flags.hold_flag ? last_hold_counter : 0; (Замена) 14.01.2021 +} +boolean GButton::isStep(byte clicks) { + if (flags.tickMode) GButton::tick(); + if (btn_counter == clicks && flags.step_flag && (millis() - btn_timer >= _step_timeout)) { + btn_timer = millis(); + return true; + } + else return false; +} + +void GButton::resetStates() { + flags.isPress_f = false; + flags.isRelease_f = false; + flags.isOne_f = false; + flags.isHolded_f = false; + flags.step_flag = false; + flags.counter_flag = false; + last_hold_counter = 0; + last_counter = 0; +} + +// ==================== TICK ==================== +void GButton::tick(boolean state) { + flags.mode = true; + btn_state = state ^ flags.inv_state; + GButton::tick(); + flags.mode = false; +} + +void GButton::tick() { + // читаем пин + if (!flags.mode && !flags.noPin) btn_state = !_buttonRead() ^ (flags.inv_state ^ flags.type); + + uint32_t thisMls = millis(); + + // нажатие + if (btn_state && !btn_flag) { + if (!flags.btn_deb) { + flags.btn_deb = true; + btn_timer = thisMls; + } else { + if (thisMls - btn_timer >= _debounce) { + btn_flag = true; + flags.isPress_f = true; + flags.oneClick_f = true; + } + } + } else { + flags.btn_deb = false; + } + + // отпускание + if (!btn_state && btn_flag) { + btn_flag = false; + if (!flags.hold_flag) btn_counter++; + flags.hold_flag = false; + flags.isRelease_f = true; + btn_timer = thisMls; + if (flags.step_flag) { + last_counter = 0; + btn_counter = 0; + flags.step_flag = false; + } + if (flags.oneClick_f) { + flags.oneClick_f = false; + flags.isOne_f = true; + } + } + + // кнопка удерживается + if (btn_flag && btn_state && (thisMls - btn_timer >= _timeout) && !flags.hold_flag) { + flags.hold_flag = true; + last_hold_counter = btn_counter; + //btn_counter = 0; + //last_counter = 0; + flags.isHolded_f = true; + flags.step_flag = true; + flags.oneClick_f = false; + btn_timer = thisMls; + } + + // обработка накликивания + if ((thisMls - btn_timer >= _click_timeout) && (btn_counter != 0) && !btn_state) { //И здесь еще добавлен !btn_state + last_counter = btn_counter; + btn_counter = 0; + flags.counter_flag = true; + } + + // сброс накликивания //Добавлено + if (flags.counter_reset) { + last_counter = 0; + flags.counter_flag = false; + flags.counter_reset = false; + } +} \ No newline at end of file diff --git a/libraries/GyverButton/src/GyverButton.h b/libraries/GyverButton/src/GyverButton.h new file mode 100644 index 0000000..4cdf4f1 --- /dev/null +++ b/libraries/GyverButton/src/GyverButton.h @@ -0,0 +1,134 @@ +/* + GyverButton - библиотека для многофункциональной отработки нажатия кнопки + ВНИМАНИЕ, БИБЛИОТЕКА УСТАРЕЛА! ИСПОЛЬЗУЙ БИБЛИОТЕКУ EncButton https://github.com/GyverLibs/EncButton + GitHub: https://github.com/GyverLibs/GyverButton + Документация: https://alexgyver.ru/gyverbutton/ + Возможности: + - Работа с нормально замкнутыми и нормально разомкнутыми кнопками + - Работа с подключением PULL_UP и PULL_DOWN + - Опрос кнопки с программным антидребезгом контактов (настраиваемое время) + - Отработка нажатия, удерживания, отпускания, клика по кнопке (+ настройка таймаутов) + - Отработка одиночного, двойного и тройного нажатия (вынесено отдельно) + - Отработка любого количества нажатий кнопки (функция возвращает количество нажатий) + - Функция изменения значения переменной с заданным шагом и заданным интервалом по времени + - Возможность работы с "виртуальными" кнопками (все возможности библиотеки используются для матричных и резистивных клавиатур) + + Версии: + v2.15: Добавлена возможность объявить кнопку без привязки к пину + v3.0: Ускорен и оптимизирован код, переделана инициализация, дополнены примеры + v3.1: isStep может принимать количество кликов, сделанных перед ним (см. пример clicks_step) + v3.2: Добавлен метод getHoldClicks() - вернуть количество кликов, предшествующее удерживанию + v3.3: Мелкие исправления + v3.4: Добавлен метод resetStates(), сбрасывающий состояния и счётчики + v3.5: увелична производительность для AVR Arduino + v3.6: добавлен отдельный класс для работы с аналоговыми клавиатурами, см пример analogKeyboardG + v3.7: исправления от Dryundel: + - Любой таймаут удержания + - Single, Double и Triple теперь не мешают hasClicks и getClicks и работают совместно + - isStep() тоже теперь ничего не мешает и он работает более корректно + v3.8: исправления от Dryundel: + +*/ +#ifndef GyverButton_h +#define GyverButton_h +#include + +#if defined(__AVR__) +#define _buttonRead() bool(*_pin_reg & _bit_mask) +#else +#define _buttonRead() digitalRead(_PIN) +#endif + +#pragma pack(push,1) +typedef struct { + bool btn_deb: 1; + bool hold_flag: 1; + bool counter_flag: 1; + bool isHolded_f: 1; + bool isRelease_f: 1; + bool isPress_f: 1; + bool step_flag: 1; + bool oneClick_f: 1; + bool isOne_f: 1; + bool inv_state: 1; + bool mode: 1; + bool type: 1; + bool tickMode: 1; + bool noPin: 1; + bool counter_reset: 1; //Добавлен +} GyverButtonFlags; +#pragma pack(pop) + +#define BTN_NO_PIN -1 +#define HIGH_PULL 0 +#define LOW_PULL 1 +#define NORM_OPEN 0 +#define NORM_CLOSE 1 +#define MANUAL 0 +#define AUTO 1 + +// Варианты инициализации: +// GButton btn; // без привязки к пину (виртуальная кнопка) и без указания типа (по умолч. LOW_PULL и NORM_OPEN) +// GButton btn(пин); // с привязкой к пину и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) +// GButton btn(пин, тип подключ.); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и без указания типа кнопки (по умолч. NORM_OPEN) +// GButton btn(пин, тип подключ., тип кнопки); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) +// GButton btn(BTN_NO_PIN, тип подключ., тип кнопки); // без привязки к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) + +class GButton { +public: + GButton(int8_t pin = BTN_NO_PIN, bool type = HIGH_PULL, bool dir = NORM_OPEN); // конструктор кнопки, принимает PIN пин, тип type (HIGH_PULL / LOW_PULL) и направление dir (NORM_OPEN / NORM_CLOSE) + // HIGH_PULL - кнопка подключена к GND, пин подтянут к VCC, pinMode - INPUT_PULLUP (по умолчанию) + // LOW_PULL - кнопка подключена к VCC, пин подтянут к GND, pinMode - INPUT + // NORM_OPEN - кнопка по умолчанию разомкнута (по умолчанию) + // NORM_CLOSE - кнопка по умолчанию замкнута + + void setDebounce(uint16_t debounce); // установка времени антидребезга (по умолчанию 80 мс) + void setTimeout(uint16_t new_timeout); // установка таймаута удержания (по умолчанию 300 мс) + void setClickTimeout(uint16_t new_timeout); // установка таймаута между кликами (по умолчанию 500 мс) + void setStepTimeout(uint16_t step_timeout); // установка таймаута между инкрементами (по умолчанию 400 мс) + void setType(bool type); // установка типа кнопки (HIGH_PULL - подтянута к питанию, LOW_PULL - к gnd) + void setDirection(bool dir); // установка направления (разомкнута/замкнута по умолчанию - NORM_OPEN, NORM_CLOSE) + + void setTickMode(bool tickMode); // (MANUAL / AUTO) ручной или автоматический опрос кнопки функцией tick() + // MANUAL - нужно вызывать функцию tick() вручную + // AUTO - tick() входит во все остальные функции и опрашивается сама + + void tick(); // опрос кнопки + void tick(boolean state); // опрос внешнего значения (1 нажато, 0 не нажато) (для матричных, резистивных клавиатур и джойстиков) + + boolean isPress(); // возвращает true при нажатии на кнопку. Сбрасывается после вызова + boolean isRelease(); // возвращает true при отпускании кнопки. Сбрасывается после вызова + boolean isClick(); // возвращает true при клике. Сбрасывается после вызова + boolean isHolded(); // возвращает true при удержании дольше timeout. Сбрасывается после вызова + boolean isHold(); // возвращает true при нажатой кнопке, не сбрасывается + boolean state(); // возвращает состояние кнопки + + boolean isSingle(); // возвращает true при одиночном клике. Сбрасывается после вызова + boolean isDouble(); // возвращает true при двойном клике. Сбрасывается после вызова + boolean isTriple(); // возвращает true при тройном клике. Сбрасывается после вызова + + boolean hasClicks(); // проверка на наличие кликов. Сбрасывается после вызова + uint8_t getClicks(); // вернуть количество кликов + uint8_t getHoldClicks();// вернуть количество кликов, предшествующее удерживанию + + boolean isStep(byte clicks = 0); // возвращает true по таймеру setStepTimeout, смотри пример + + void resetStates(); // сбрасывает все is-флаги и счётчики + +private: + GyverButtonFlags flags; + uint8_t _PIN = 0; + uint16_t _debounce = 60; + uint16_t _timeout = 500; + uint16_t _click_timeout = 500; + uint16_t _step_timeout = 400; + uint8_t btn_counter = 0, last_counter = 0, last_hold_counter = 0; + uint32_t btn_timer = 0; + bool btn_state = false; + bool btn_flag = false; +#if defined(__AVR__) + volatile uint8_t *_pin_reg; + volatile uint8_t _bit_mask; +#endif +}; +#endif \ No newline at end of file diff --git a/libraries/Keyboard/LICENSE b/libraries/Keyboard/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/libraries/Keyboard/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/libraries/Keyboard/README.adoc b/libraries/Keyboard/README.adoc new file mode 100644 index 0000000..9b5f9ba --- /dev/null +++ b/libraries/Keyboard/README.adoc @@ -0,0 +1,31 @@ +:repository-owner: arduino-libraries +:repository-name: Keyboard + += {repository-name} Library for Arduino = + +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml/badge.svg["Check Arduino status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml"] +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml/badge.svg["Compile Examples status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml"] +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml/badge.svg["Spell Check status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml"] + +This library allows an Arduino board with USB capabilities to act as a keyboard. + +For more information about this library please visit us at +https://www.arduino.cc/reference/en/language/functions/usb/keyboard/ + +== License == + +Copyright (c) Arduino LLC. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/Keyboard/examples/Serial/Serial.ino b/libraries/Keyboard/examples/Serial/Serial.ino new file mode 100644 index 0000000..050bb18 --- /dev/null +++ b/libraries/Keyboard/examples/Serial/Serial.ino @@ -0,0 +1,39 @@ +/* + Keyboard test + + For the Arduino Leonardo, Micro or Due + + Reads a byte from the serial port, sends a keystroke back. + The sent keystroke is one higher than what's received, e.g. if you send a, + you get b, send A you get B, and so forth. + + The circuit: + - none + + created 21 Oct 2011 + modified 27 Mar 2012 + by Tom Igoe + + This example code is in the public domain. + + https://www.arduino.cc/en/Tutorial/BuiltInExamples/KeyboardSerial +*/ + +#include "Keyboard.h" + +void setup() { + // open the serial port: + Serial.begin(9600); + // initialize control over the keyboard: + Keyboard.begin(); +} + +void loop() { + // check for incoming serial data: + if (Serial.available() > 0) { + // read incoming serial data: + char inChar = Serial.read(); + // Type the next ASCII value from what you received: + Keyboard.write(inChar + 1); + } +} diff --git a/libraries/Keyboard/keywords.txt b/libraries/Keyboard/keywords.txt new file mode 100644 index 0000000..2078f03 --- /dev/null +++ b/libraries/Keyboard/keywords.txt @@ -0,0 +1,24 @@ +####################################### +# Syntax Coloring Map For Keyboard +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Keyboard KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +write KEYWORD2 +press KEYWORD2 +release KEYWORD2 +releaseAll KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/libraries/Keyboard/library.properties b/libraries/Keyboard/library.properties new file mode 100644 index 0000000..f0e65a4 --- /dev/null +++ b/libraries/Keyboard/library.properties @@ -0,0 +1,9 @@ +name=Keyboard +version=1.0.3 +author=Arduino +maintainer=Arduino +sentence=Allows an Arduino board with USB capabilities to act as a Keyboard. +paragraph=This library plugs on the HID library. It can be used with or without other HID-based libraries (Mouse, Gamepad etc) +category=Device Control +url=https://www.arduino.cc/reference/en/language/functions/usb/keyboard/ +architectures=* diff --git a/libraries/Keyboard/src/Keyboard.cpp b/libraries/Keyboard/src/Keyboard.cpp new file mode 100644 index 0000000..d9fcbad --- /dev/null +++ b/libraries/Keyboard/src/Keyboard.cpp @@ -0,0 +1,214 @@ +/* + Keyboard.cpp + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "Keyboard.h" +#include "KeyboardLayout.h" + +#if defined(_USING_HID) + +//================================================================================ +//================================================================================ +// Keyboard + +static const uint8_t _hidReportDescriptor[] PROGMEM = { + + // Keyboard + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47 + 0x09, 0x06, // USAGE (Keyboard) + 0xa1, 0x01, // COLLECTION (Application) + 0x85, 0x02, // REPORT_ID (2) + 0x05, 0x07, // USAGE_PAGE (Keyboard) + + 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) + 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x01, // LOGICAL_MAXIMUM (1) + 0x75, 0x01, // REPORT_SIZE (1) + + 0x95, 0x08, // REPORT_COUNT (8) + 0x81, 0x02, // INPUT (Data,Var,Abs) + 0x95, 0x01, // REPORT_COUNT (1) + 0x75, 0x08, // REPORT_SIZE (8) + 0x81, 0x03, // INPUT (Cnst,Var,Abs) + + 0x95, 0x06, // REPORT_COUNT (6) + 0x75, 0x08, // REPORT_SIZE (8) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x73, // LOGICAL_MAXIMUM (115) + 0x05, 0x07, // USAGE_PAGE (Keyboard) + + 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) + 0x29, 0x73, // USAGE_MAXIMUM (Keyboard Application) + 0x81, 0x00, // INPUT (Data,Ary,Abs) + 0xc0, // END_COLLECTION +}; + +Keyboard_::Keyboard_(void) +{ + static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); + HID().AppendDescriptor(&node); + _asciimap = KeyboardLayout_en_US; +} + +void Keyboard_::begin(const uint8_t *layout) +{ + _asciimap = layout; +} + +void Keyboard_::end(void) +{ +} + +void Keyboard_::sendReport(KeyReport* keys) +{ + HID().SendReport(2,keys,sizeof(KeyReport)); +} + +uint8_t USBPutChar(uint8_t c); + +// press() adds the specified key (printing, non-printing, or modifier) +// to the persistent key report and sends the report. Because of the way +// USB HID works, the host acts like the key remains pressed until we +// call release(), releaseAll(), or otherwise clear the report and resend. +size_t Keyboard_::press(uint8_t k) +{ + uint8_t i; + if (k >= 136) { // it's a non-printing key (not a modifier) + k = k - 136; + } else if (k >= 128) { // it's a modifier key + _keyReport.modifiers |= (1<<(k-128)); + k = 0; + } else { // it's a printing key + k = pgm_read_byte(_asciimap + k); + if (!k) { + setWriteError(); + return 0; + } + if ((k & ALT_GR) == ALT_GR) { + _keyReport.modifiers |= 0x40; // AltGr = right Alt + k &= 0x3F; + } else if ((k & SHIFT) == SHIFT) { + _keyReport.modifiers |= 0x02; // the left shift modifier + k &= 0x7F; + } + if (k == ISO_REPLACEMENT) { + k = ISO_KEY; + } + } + + // Add k to the key report only if it's not already present + // and if there is an empty slot. + if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && + _keyReport.keys[2] != k && _keyReport.keys[3] != k && + _keyReport.keys[4] != k && _keyReport.keys[5] != k) { + + for (i=0; i<6; i++) { + if (_keyReport.keys[i] == 0x00) { + _keyReport.keys[i] = k; + break; + } + } + if (i == 6) { + setWriteError(); + return 0; + } + } + sendReport(&_keyReport); + return 1; +} + +// release() takes the specified key out of the persistent key report and +// sends the report. This tells the OS the key is no longer pressed and that +// it shouldn't be repeated any more. +size_t Keyboard_::release(uint8_t k) +{ + uint8_t i; + if (k >= 136) { // it's a non-printing key (not a modifier) + k = k - 136; + } else if (k >= 128) { // it's a modifier key + _keyReport.modifiers &= ~(1<<(k-128)); + k = 0; + } else { // it's a printing key + k = pgm_read_byte(_asciimap + k); + if (!k) { + return 0; + } + if ((k & ALT_GR) == ALT_GR) { + _keyReport.modifiers &= ~(0x40); // AltGr = right Alt + k &= 0x3F; + } else if ((k & SHIFT) == SHIFT) { + _keyReport.modifiers &= ~(0x02); // the left shift modifier + k &= 0x7F; + } + if (k == ISO_REPLACEMENT) { + k = ISO_KEY; + } + } + + // Test the key report to see if k is present. Clear it if it exists. + // Check all positions in case the key is present more than once (which it shouldn't be) + for (i=0; i<6; i++) { + if (0 != k && _keyReport.keys[i] == k) { + _keyReport.keys[i] = 0x00; + } + } + + sendReport(&_keyReport); + return 1; +} + +void Keyboard_::releaseAll(void) +{ + _keyReport.keys[0] = 0; + _keyReport.keys[1] = 0; + _keyReport.keys[2] = 0; + _keyReport.keys[3] = 0; + _keyReport.keys[4] = 0; + _keyReport.keys[5] = 0; + _keyReport.modifiers = 0; + sendReport(&_keyReport); +} + +size_t Keyboard_::write(uint8_t c) +{ + uint8_t p = press(c); // Keydown + release(c); // Keyup + return p; // just return the result of press() since release() almost always returns 1 +} + +size_t Keyboard_::write(const uint8_t *buffer, size_t size) { + size_t n = 0; + while (size--) { + if (*buffer != '\r') { + if (write(*buffer)) { + n++; + } else { + break; + } + } + buffer++; + } + return n; +} + +Keyboard_ Keyboard; + +#endif diff --git a/libraries/Keyboard/src/Keyboard.h b/libraries/Keyboard/src/Keyboard.h new file mode 100644 index 0000000..33570a7 --- /dev/null +++ b/libraries/Keyboard/src/Keyboard.h @@ -0,0 +1,120 @@ +/* + Keyboard.h + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef KEYBOARD_h +#define KEYBOARD_h + +#include "HID.h" + +#if !defined(_USING_HID) + +#warning "Using legacy HID core (non pluggable)" + +#else + +//================================================================================ +//================================================================================ +// Keyboard + +#define KEY_LEFT_CTRL 0x80 +#define KEY_LEFT_SHIFT 0x81 +#define KEY_LEFT_ALT 0x82 +#define KEY_LEFT_GUI 0x83 +#define KEY_RIGHT_CTRL 0x84 +#define KEY_RIGHT_SHIFT 0x85 +#define KEY_RIGHT_ALT 0x86 +#define KEY_RIGHT_GUI 0x87 + +#define KEY_UP_ARROW 0xDA +#define KEY_DOWN_ARROW 0xD9 +#define KEY_LEFT_ARROW 0xD8 +#define KEY_RIGHT_ARROW 0xD7 +#define KEY_BACKSPACE 0xB2 +#define KEY_TAB 0xB3 +#define KEY_RETURN 0xB0 +#define KEY_ESC 0xB1 +#define KEY_INSERT 0xD1 +#define KEY_DELETE 0xD4 +#define KEY_PAGE_UP 0xD3 +#define KEY_PAGE_DOWN 0xD6 +#define KEY_HOME 0xD2 +#define KEY_END 0xD5 +#define KEY_CAPS_LOCK 0xC1 +#define KEY_F1 0xC2 +#define KEY_F2 0xC3 +#define KEY_F3 0xC4 +#define KEY_F4 0xC5 +#define KEY_F5 0xC6 +#define KEY_F6 0xC7 +#define KEY_F7 0xC8 +#define KEY_F8 0xC9 +#define KEY_F9 0xCA +#define KEY_F10 0xCB +#define KEY_F11 0xCC +#define KEY_F12 0xCD +#define KEY_F13 0xF0 +#define KEY_F14 0xF1 +#define KEY_F15 0xF2 +#define KEY_F16 0xF3 +#define KEY_F17 0xF4 +#define KEY_F18 0xF5 +#define KEY_F19 0xF6 +#define KEY_F20 0xF7 +#define KEY_F21 0xF8 +#define KEY_F22 0xF9 +#define KEY_F23 0xFA +#define KEY_F24 0xFB + +// Supported keyboard layouts +extern const uint8_t KeyboardLayout_de_DE[]; +extern const uint8_t KeyboardLayout_en_US[]; +extern const uint8_t KeyboardLayout_es_ES[]; +extern const uint8_t KeyboardLayout_fr_FR[]; +extern const uint8_t KeyboardLayout_it_IT[]; + +// Low level key report: up to 6 keys and shift, ctrl etc at once +typedef struct +{ + uint8_t modifiers; + uint8_t reserved; + uint8_t keys[6]; +} KeyReport; + +class Keyboard_ : public Print +{ +private: + KeyReport _keyReport; + const uint8_t *_asciimap; + void sendReport(KeyReport* keys); +public: + Keyboard_(void); + void begin(const uint8_t *layout = KeyboardLayout_en_US); + void end(void); + size_t write(uint8_t k); + size_t write(const uint8_t *buffer, size_t size); + size_t press(uint8_t k); + size_t release(uint8_t k); + void releaseAll(void); +}; +extern Keyboard_ Keyboard; + +#endif +#endif diff --git a/libraries/Keyboard/src/KeyboardLayout.h b/libraries/Keyboard/src/KeyboardLayout.h new file mode 100644 index 0000000..c8c858d --- /dev/null +++ b/libraries/Keyboard/src/KeyboardLayout.h @@ -0,0 +1,65 @@ +/* + KeyboardLayout.h + + This file is not part of the public API. It is meant to be included + only in Keyboard.cpp and the keyboard layout files. Layout files map + ASCII character codes to keyboard scan codes (technically, to USB HID + Usage codes), possibly altered by the SHIFT or ALT_GR modifiers. + + == Creating your own layout == + + In order to create your own layout file, copy an existing layout that + is similar to yours, then modify it to use the correct keys. The + layout is an array in ASCII order. Each entry contains a scan code, + possibly modified by "|SHIFT" or "|ALT_GR", as in this excerpt from + the Italian layout: + + 0x35, // bslash + 0x30|ALT_GR, // ] + 0x2e|SHIFT, // ^ + + Do not change the control characters (those before scan code 0x2c, + corresponding to space). Do not attempt to grow the table past DEL. Do + not use both SHIFT and ALT_GR on the same character: this is not + supported. Unsupported characters should have 0x00 as scan code. + + For a keyboard with an ISO physical layout, use the scan codes below: + + +---+---+---+---+---+---+---+---+---+---+---+---+---+-------+ + |35 |1e |1f |20 |21 |22 |23 |24 |25 |26 |27 |2d |2e |BackSp | + +---+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-----+ + | Tab |14 |1a |08 |15 |17 |1c |18 |0c |12 |13 |2f |30 | Ret | + +-----++--++--++--++--++--++--++--++--++--++--++--++--++ | + |CapsL |04 |16 |07 |09 |0a |0b |0d |0e |0f |33 |34 |31 | | + +----+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+---+----+ + |Shi.|32 |1d |1b |06 |19 |05 |11 |10 |36 |37 |38 | Shift | + +----+---++--+-+-+---+---+---+---+---+--++---+---++----+----+ + |Ctrl|Win |Alt | |AlGr|Win |Menu|Ctrl| + +----+----+----+------------------------+----+----+----+----+ + + The ANSI layout is identical except that key 0x31 is above (rather + than next to) Return, and there is not key 0x32. + + Give a unique name to the layout array, then declare it in Keyboard.h + with a line of the form: + + extern const uint8_t KeyboardLayout_xx_YY[]; + + == Encoding details == + + All scan codes are less than 0x80, which makes bit 7 available to + signal that a modifier (Shift or AltGr) is needed to generate the + character. With only one exception, keys that are used with modifiers + have scan codes that are less than 0x40. This makes bit 6 available + to signal whether the modifier is Shift or AltGr. The exception is + 0x64, the key next next to Left Shift on the ISO layout (and absent + from the ANSI layout). We handle it by replacing its value by 0x32 in + the layout arrays. +*/ + +#include + +#define SHIFT 0x80 +#define ALT_GR 0xc0 +#define ISO_KEY 0x64 +#define ISO_REPLACEMENT 0x32 diff --git a/libraries/Keyboard/src/KeyboardLayout_de_DE.cpp b/libraries/Keyboard/src/KeyboardLayout_de_DE.cpp new file mode 100644 index 0000000..858d956 --- /dev/null +++ b/libraries/Keyboard/src/KeyboardLayout_de_DE.cpp @@ -0,0 +1,138 @@ +/* + * German keyboard layout. + */ + +#include "KeyboardLayout.h" + +extern const uint8_t KeyboardLayout_de_DE[128] PROGMEM = +{ + 0x00, // NUL + 0x00, // SOH + 0x00, // STX + 0x00, // ETX + 0x00, // EOT + 0x00, // ENQ + 0x00, // ACK + 0x00, // BEL + 0x2a, // BS Backspace + 0x2b, // TAB Tab + 0x28, // LF Enter + 0x00, // VT + 0x00, // FF + 0x00, // CR + 0x00, // SO + 0x00, // SI + 0x00, // DEL + 0x00, // DC1 + 0x00, // DC2 + 0x00, // DC3 + 0x00, // DC4 + 0x00, // NAK + 0x00, // SYN + 0x00, // ETB + 0x00, // CAN + 0x00, // EM + 0x00, // SUB + 0x00, // ESC + 0x00, // FS + 0x00, // GS + 0x00, // RS + 0x00, // US + + 0x2c, // ' ' + 0x1e|SHIFT, // ! + 0x1f|SHIFT, // " + 0x31, // # + 0x21|SHIFT, // $ + 0x22|SHIFT, // % + 0x23|SHIFT, // & + 0x31|SHIFT, // ' + 0x25|SHIFT, // ( + 0x26|SHIFT, // ) + 0x30|SHIFT, // * + 0x30, // + + 0x36, // , + 0x38, // - + 0x37, // . + 0x24|SHIFT, // / + 0x27, // 0 + 0x1e, // 1 + 0x1f, // 2 + 0x20, // 3 + 0x21, // 4 + 0x22, // 5 + 0x23, // 6 + 0x24, // 7 + 0x25, // 8 + 0x26, // 9 + 0x37|SHIFT, // : + 0x36|SHIFT, // ; + 0x32, // < + 0x27|SHIFT, // = + 0x32|SHIFT, // > + 0x2d|SHIFT, // ? + 0x14|ALT_GR, // @ + 0x04|SHIFT, // A + 0x05|SHIFT, // B + 0x06|SHIFT, // C + 0x07|SHIFT, // D + 0x08|SHIFT, // E + 0x09|SHIFT, // F + 0x0a|SHIFT, // G + 0x0b|SHIFT, // H + 0x0c|SHIFT, // I + 0x0d|SHIFT, // J + 0x0e|SHIFT, // K + 0x0f|SHIFT, // L + 0x10|SHIFT, // M + 0x11|SHIFT, // N + 0x12|SHIFT, // O + 0x13|SHIFT, // P + 0x14|SHIFT, // Q + 0x15|SHIFT, // R + 0x16|SHIFT, // S + 0x17|SHIFT, // T + 0x18|SHIFT, // U + 0x19|SHIFT, // V + 0x1a|SHIFT, // W + 0x1b|SHIFT, // X + 0x1d|SHIFT, // Y + 0x1c|SHIFT, // Z + 0x25|ALT_GR, // [ + 0x2d|ALT_GR, // bslash + 0x26|ALT_GR, // ] + 0x00, // ^ not supported (requires dead key + space) + 0x38|SHIFT, // _ + 0x00, // ` not supported (requires dead key + space) + 0x04, // a + 0x05, // b + 0x06, // c + 0x07, // d + 0x08, // e + 0x09, // f + 0x0a, // g + 0x0b, // h + 0x0c, // i + 0x0d, // j + 0x0e, // k + 0x0f, // l + 0x10, // m + 0x11, // n + 0x12, // o + 0x13, // p + 0x14, // q + 0x15, // r + 0x16, // s + 0x17, // t + 0x18, // u + 0x19, // v + 0x1a, // w + 0x1b, // x + 0x1d, // y + 0x1c, // z + 0x24|ALT_GR, // { + 0x32|ALT_GR, // | + 0x27|ALT_GR, // } + 0x30|ALT_GR, // ~ + 0x00 // DEL +}; diff --git a/libraries/Keyboard/src/KeyboardLayout_en_US.cpp b/libraries/Keyboard/src/KeyboardLayout_en_US.cpp new file mode 100644 index 0000000..51d8dd5 --- /dev/null +++ b/libraries/Keyboard/src/KeyboardLayout_en_US.cpp @@ -0,0 +1,138 @@ +/* + * Standard US keyboard layout. + */ + +#include "KeyboardLayout.h" + +extern const uint8_t KeyboardLayout_en_US[128] PROGMEM = +{ + 0x00, // NUL + 0x00, // SOH + 0x00, // STX + 0x00, // ETX + 0x00, // EOT + 0x00, // ENQ + 0x00, // ACK + 0x00, // BEL + 0x2a, // BS Backspace + 0x2b, // TAB Tab + 0x28, // LF Enter + 0x00, // VT + 0x00, // FF + 0x00, // CR + 0x00, // SO + 0x00, // SI + 0x00, // DEL + 0x00, // DC1 + 0x00, // DC2 + 0x00, // DC3 + 0x00, // DC4 + 0x00, // NAK + 0x00, // SYN + 0x00, // ETB + 0x00, // CAN + 0x00, // EM + 0x00, // SUB + 0x00, // ESC + 0x00, // FS + 0x00, // GS + 0x00, // RS + 0x00, // US + + 0x2c, // ' ' + 0x1e|SHIFT, // ! + 0x34|SHIFT, // " + 0x20|SHIFT, // # + 0x21|SHIFT, // $ + 0x22|SHIFT, // % + 0x24|SHIFT, // & + 0x34, // ' + 0x26|SHIFT, // ( + 0x27|SHIFT, // ) + 0x25|SHIFT, // * + 0x2e|SHIFT, // + + 0x36, // , + 0x2d, // - + 0x37, // . + 0x38, // / + 0x27, // 0 + 0x1e, // 1 + 0x1f, // 2 + 0x20, // 3 + 0x21, // 4 + 0x22, // 5 + 0x23, // 6 + 0x24, // 7 + 0x25, // 8 + 0x26, // 9 + 0x33|SHIFT, // : + 0x33, // ; + 0x36|SHIFT, // < + 0x2e, // = + 0x37|SHIFT, // > + 0x38|SHIFT, // ? + 0x1f|SHIFT, // @ + 0x04|SHIFT, // A + 0x05|SHIFT, // B + 0x06|SHIFT, // C + 0x07|SHIFT, // D + 0x08|SHIFT, // E + 0x09|SHIFT, // F + 0x0a|SHIFT, // G + 0x0b|SHIFT, // H + 0x0c|SHIFT, // I + 0x0d|SHIFT, // J + 0x0e|SHIFT, // K + 0x0f|SHIFT, // L + 0x10|SHIFT, // M + 0x11|SHIFT, // N + 0x12|SHIFT, // O + 0x13|SHIFT, // P + 0x14|SHIFT, // Q + 0x15|SHIFT, // R + 0x16|SHIFT, // S + 0x17|SHIFT, // T + 0x18|SHIFT, // U + 0x19|SHIFT, // V + 0x1a|SHIFT, // W + 0x1b|SHIFT, // X + 0x1c|SHIFT, // Y + 0x1d|SHIFT, // Z + 0x2f, // [ + 0x31, // bslash + 0x30, // ] + 0x23|SHIFT, // ^ + 0x2d|SHIFT, // _ + 0x35, // ` + 0x04, // a + 0x05, // b + 0x06, // c + 0x07, // d + 0x08, // e + 0x09, // f + 0x0a, // g + 0x0b, // h + 0x0c, // i + 0x0d, // j + 0x0e, // k + 0x0f, // l + 0x10, // m + 0x11, // n + 0x12, // o + 0x13, // p + 0x14, // q + 0x15, // r + 0x16, // s + 0x17, // t + 0x18, // u + 0x19, // v + 0x1a, // w + 0x1b, // x + 0x1c, // y + 0x1d, // z + 0x2f|SHIFT, // { + 0x31|SHIFT, // | + 0x30|SHIFT, // } + 0x35|SHIFT, // ~ + 0x00 // DEL +}; diff --git a/libraries/Keyboard/src/KeyboardLayout_es_ES.cpp b/libraries/Keyboard/src/KeyboardLayout_es_ES.cpp new file mode 100644 index 0000000..93a89a9 --- /dev/null +++ b/libraries/Keyboard/src/KeyboardLayout_es_ES.cpp @@ -0,0 +1,138 @@ +/* + * Spanish keyboard layout. + */ + +#include "KeyboardLayout.h" + +extern const uint8_t KeyboardLayout_es_ES[128] PROGMEM = +{ + 0x00, // NUL + 0x00, // SOH + 0x00, // STX + 0x00, // ETX + 0x00, // EOT + 0x00, // ENQ + 0x00, // ACK + 0x00, // BEL + 0x2a, // BS Backspace + 0x2b, // TAB Tab + 0x28, // LF Enter + 0x00, // VT + 0x00, // FF + 0x00, // CR + 0x00, // SO + 0x00, // SI + 0x00, // DEL + 0x00, // DC1 + 0x00, // DC2 + 0x00, // DC3 + 0x00, // DC4 + 0x00, // NAK + 0x00, // SYN + 0x00, // ETB + 0x00, // CAN + 0x00, // EM + 0x00, // SUB + 0x00, // ESC + 0x00, // FS + 0x00, // GS + 0x00, // RS + 0x00, // US + + 0x2c, // ' ' + 0x1e|SHIFT, // ! + 0x1f|SHIFT, // " + 0x20|ALT_GR, // # + 0x21|SHIFT, // $ + 0x22|SHIFT, // % + 0x23|SHIFT, // & + 0x2d, // ' + 0x25|SHIFT, // ( + 0x26|SHIFT, // ) + 0x30|SHIFT, // * + 0x30, // + + 0x36, // , + 0x38, // - + 0x37, // . + 0x24|SHIFT, // / + 0x27, // 0 + 0x1e, // 1 + 0x1f, // 2 + 0x20, // 3 + 0x21, // 4 + 0x22, // 5 + 0x23, // 6 + 0x24, // 7 + 0x25, // 8 + 0x26, // 9 + 0x37|SHIFT, // : + 0x36|SHIFT, // ; + 0x32, // < + 0x27|SHIFT, // = + 0x32|SHIFT, // > + 0x2d|SHIFT, // ? + 0x1f|ALT_GR, // @ + 0x04|SHIFT, // A + 0x05|SHIFT, // B + 0x06|SHIFT, // C + 0x07|SHIFT, // D + 0x08|SHIFT, // E + 0x09|SHIFT, // F + 0x0a|SHIFT, // G + 0x0b|SHIFT, // H + 0x0c|SHIFT, // I + 0x0d|SHIFT, // J + 0x0e|SHIFT, // K + 0x0f|SHIFT, // L + 0x10|SHIFT, // M + 0x11|SHIFT, // N + 0x12|SHIFT, // O + 0x13|SHIFT, // P + 0x14|SHIFT, // Q + 0x15|SHIFT, // R + 0x16|SHIFT, // S + 0x17|SHIFT, // T + 0x18|SHIFT, // U + 0x19|SHIFT, // V + 0x1a|SHIFT, // W + 0x1b|SHIFT, // X + 0x1c|SHIFT, // Y + 0x1d|SHIFT, // Z + 0x2f|ALT_GR, // [ + 0x35|ALT_GR, // bslash + 0x30|ALT_GR, // ] + 0x00, // ^ not supported (requires dead key + space) + 0x38|SHIFT, // _ + 0x00, // ` not supported (requires dead key + space) + 0x04, // a + 0x05, // b + 0x06, // c + 0x07, // d + 0x08, // e + 0x09, // f + 0x0a, // g + 0x0b, // h + 0x0c, // i + 0x0d, // j + 0x0e, // k + 0x0f, // l + 0x10, // m + 0x11, // n + 0x12, // o + 0x13, // p + 0x14, // q + 0x15, // r + 0x16, // s + 0x17, // t + 0x18, // u + 0x19, // v + 0x1a, // w + 0x1b, // x + 0x1c, // y + 0x1d, // z + 0x34|ALT_GR, // { + 0x1e|ALT_GR, // | + 0x31|ALT_GR, // } + 0x00, // ~ not supported (requires dead key + space) + 0x00 // DEL +}; diff --git a/libraries/Keyboard/src/KeyboardLayout_fr_FR.cpp b/libraries/Keyboard/src/KeyboardLayout_fr_FR.cpp new file mode 100644 index 0000000..80fa6ce --- /dev/null +++ b/libraries/Keyboard/src/KeyboardLayout_fr_FR.cpp @@ -0,0 +1,138 @@ +/* + * Traditional (not AFNOR) French keyboard layout. + */ + +#include "KeyboardLayout.h" + +extern const uint8_t KeyboardLayout_fr_FR[128] PROGMEM = +{ + 0x00, // NUL + 0x00, // SOH + 0x00, // STX + 0x00, // ETX + 0x00, // EOT + 0x00, // ENQ + 0x00, // ACK + 0x00, // BEL + 0x2a, // BS Backspace + 0x2b, // TAB Tab + 0x28, // LF Enter + 0x00, // VT + 0x00, // FF + 0x00, // CR + 0x00, // SO + 0x00, // SI + 0x00, // DEL + 0x00, // DC1 + 0x00, // DC2 + 0x00, // DC3 + 0x00, // DC4 + 0x00, // NAK + 0x00, // SYN + 0x00, // ETB + 0x00, // CAN + 0x00, // EM + 0x00, // SUB + 0x00, // ESC + 0x00, // FS + 0x00, // GS + 0x00, // RS + 0x00, // US + + 0x2c, // ' ' + 0x38, // ! + 0x20, // " + 0x20|ALT_GR, // # + 0x30, // $ + 0x34|SHIFT, // % + 0x1E, // & + 0x21, // ' + 0x22, // ( + 0x2d, // ) + 0x31, // * + 0x2e|SHIFT, // + + 0x10, // , + 0x23, // - + 0x36|SHIFT, // . + 0x37|SHIFT, // / + 0x27|SHIFT, // 0 + 0x1e|SHIFT, // 1 + 0x1f|SHIFT, // 2 + 0x20|SHIFT, // 3 + 0x21|SHIFT, // 4 + 0x22|SHIFT, // 5 + 0x23|SHIFT, // 6 + 0x24|SHIFT, // 7 + 0x25|SHIFT, // 8 + 0x26|SHIFT, // 9 + 0x37, // : + 0x36, // ; + 0x32, // < + 0x2e, // = + 0x32|SHIFT, // > + 0x10|SHIFT, // ? + 0x27|ALT_GR, // @ + 0x14|SHIFT, // A + 0x05|SHIFT, // B + 0x06|SHIFT, // C + 0x07|SHIFT, // D + 0x08|SHIFT, // E + 0x09|SHIFT, // F + 0x0a|SHIFT, // G + 0x0b|SHIFT, // H + 0x0c|SHIFT, // I + 0x0d|SHIFT, // J + 0x0e|SHIFT, // K + 0x0f|SHIFT, // L + 0x33|SHIFT, // M + 0x11|SHIFT, // N + 0x12|SHIFT, // O + 0x13|SHIFT, // P + 0x04|SHIFT, // Q + 0x15|SHIFT, // R + 0x16|SHIFT, // S + 0x17|SHIFT, // T + 0x18|SHIFT, // U + 0x19|SHIFT, // V + 0x1d|SHIFT, // W + 0x1b|SHIFT, // X + 0x1c|SHIFT, // Y + 0x1a|SHIFT, // Z + 0x22|ALT_GR, // [ + 0x25|ALT_GR, // bslash + 0x2d|ALT_GR, // ] + 0x26|ALT_GR, // ^ + 0x25, // _ + 0x24|ALT_GR, // ` + 0x14, // a + 0x05, // b + 0x06, // c + 0x07, // d + 0x08, // e + 0x09, // f + 0x0a, // g + 0x0b, // h + 0x0c, // i + 0x0d, // j + 0x0e, // k + 0x0f, // l + 0x33, // m + 0x11, // n + 0x12, // o + 0x13, // p + 0x04, // q + 0x15, // r + 0x16, // s + 0x17, // t + 0x18, // u + 0x19, // v + 0x1d, // w + 0x1b, // x + 0x1c, // y + 0x1a, // z + 0x21|ALT_GR, // { + 0x23|ALT_GR, // | + 0x2e|ALT_GR, // } + 0x1f|ALT_GR, // ~ + 0x00 // DEL +}; diff --git a/libraries/Keyboard/src/KeyboardLayout_it_IT.cpp b/libraries/Keyboard/src/KeyboardLayout_it_IT.cpp new file mode 100644 index 0000000..b24588f --- /dev/null +++ b/libraries/Keyboard/src/KeyboardLayout_it_IT.cpp @@ -0,0 +1,138 @@ +/* + * Italian keyboard layout. + */ + +#include "KeyboardLayout.h" + +extern const uint8_t KeyboardLayout_it_IT[128] PROGMEM = +{ + 0x00, // NUL + 0x00, // SOH + 0x00, // STX + 0x00, // ETX + 0x00, // EOT + 0x00, // ENQ + 0x00, // ACK + 0x00, // BEL + 0x2a, // BS Backspace + 0x2b, // TAB Tab + 0x28, // LF Enter + 0x00, // VT + 0x00, // FF + 0x00, // CR + 0x00, // SO + 0x00, // SI + 0x00, // DEL + 0x00, // DC1 + 0x00, // DC2 + 0x00, // DC3 + 0x00, // DC4 + 0x00, // NAK + 0x00, // SYN + 0x00, // ETB + 0x00, // CAN + 0x00, // EM + 0x00, // SUB + 0x00, // ESC + 0x00, // FS + 0x00, // GS + 0x00, // RS + 0x00, // US + + 0x2c, // ' ' + 0x1e|SHIFT, // ! + 0x1f|SHIFT, // " + 0x34|ALT_GR, // # + 0x21|SHIFT, // $ + 0x22|SHIFT, // % + 0x23|SHIFT, // & + 0x2d, // ' + 0x25|SHIFT, // ( + 0x26|SHIFT, // ) + 0x30|SHIFT, // * + 0x30, // + + 0x36, // , + 0x38, // - + 0x37, // . + 0x24|SHIFT, // / + 0x27, // 0 + 0x1e, // 1 + 0x1f, // 2 + 0x20, // 3 + 0x21, // 4 + 0x22, // 5 + 0x23, // 6 + 0x24, // 7 + 0x25, // 8 + 0x26, // 9 + 0x37|SHIFT, // : + 0x36|SHIFT, // ; + 0x32, // < + 0x27|SHIFT, // = + 0x32|SHIFT, // > + 0x2d|SHIFT, // ? + 0x33|ALT_GR, // @ + 0x04|SHIFT, // A + 0x05|SHIFT, // B + 0x06|SHIFT, // C + 0x07|SHIFT, // D + 0x08|SHIFT, // E + 0x09|SHIFT, // F + 0x0a|SHIFT, // G + 0x0b|SHIFT, // H + 0x0c|SHIFT, // I + 0x0d|SHIFT, // J + 0x0e|SHIFT, // K + 0x0f|SHIFT, // L + 0x10|SHIFT, // M + 0x11|SHIFT, // N + 0x12|SHIFT, // O + 0x13|SHIFT, // P + 0x14|SHIFT, // Q + 0x15|SHIFT, // R + 0x16|SHIFT, // S + 0x17|SHIFT, // T + 0x18|SHIFT, // U + 0x19|SHIFT, // V + 0x1a|SHIFT, // W + 0x1b|SHIFT, // X + 0x1c|SHIFT, // Y + 0x1d|SHIFT, // Z + 0x2f|ALT_GR, // [ + 0x35, // bslash + 0x30|ALT_GR, // ] + 0x2e|SHIFT, // ^ + 0x38|SHIFT, // _ + 0x00, // ` not in this layout + 0x04, // a + 0x05, // b + 0x06, // c + 0x07, // d + 0x08, // e + 0x09, // f + 0x0a, // g + 0x0b, // h + 0x0c, // i + 0x0d, // j + 0x0e, // k + 0x0f, // l + 0x10, // m + 0x11, // n + 0x12, // o + 0x13, // p + 0x14, // q + 0x15, // r + 0x16, // s + 0x17, // t + 0x18, // u + 0x19, // v + 0x1a, // w + 0x1b, // x + 0x1c, // y + 0x1d, // z + 0x00, // { not supported (requires AltGr+Shift) + 0x35|SHIFT, // | + 0x00, // } not supported (requires AltGr+Shift) + 0x00, // ~ not in this layout + 0x00 // DEL +}; diff --git a/libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.cpp b/libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.cpp new file mode 100644 index 0000000..f2d37cf --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.cpp @@ -0,0 +1,332 @@ +// Based on the work by DFRobot + +#include "LiquidCrystal_I2C.h" +#include +#if defined(ARDUINO) && ARDUINO >= 100 + +#include "Arduino.h" + +#define printIIC(args) Wire.write(args) +inline size_t LiquidCrystal_I2C::write(uint8_t value) { + send(value, Rs); + return 1; +} + +#else +#include "WProgram.h" + +#define printIIC(args) Wire.send(args) +inline void LiquidCrystal_I2C::write(uint8_t value) { + send(value, Rs); +} + +#endif +#include "Wire.h" + + + +// When the display powers up, it is configured as follows: +// +// 1. Display clear +// 2. Function set: +// DL = 1; 8-bit interface data +// N = 0; 1-line display +// F = 0; 5x8 dot character font +// 3. Display on/off control: +// D = 0; Display off +// C = 0; Cursor off +// B = 0; Blinking off +// 4. Entry mode set: +// I/D = 1; Increment by 1 +// S = 0; No shift +// +// Note, however, that resetting the Arduino doesn't reset the LCD, so we +// can't assume that its in that state when a sketch starts (and the +// LiquidCrystal constructor is called). + +LiquidCrystal_I2C::LiquidCrystal_I2C(uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t lcd_rows) +{ + _Addr = lcd_Addr; + _cols = lcd_cols; + _rows = lcd_rows; + _backlightval = LCD_NOBACKLIGHT; +} + +void LiquidCrystal_I2C::oled_init(){ + _oled = true; + init_priv(); +} + +void LiquidCrystal_I2C::init(){ + init_priv(); +} + +void LiquidCrystal_I2C::init_priv() +{ + Wire.begin(); + _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS; + begin(_cols, _rows); +} + +void LiquidCrystal_I2C::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) { + if (lines > 1) { + _displayfunction |= LCD_2LINE; + } + _numlines = lines; + + // for some 1 line displays you can select a 10 pixel high font + if ((dotsize != 0) && (lines == 1)) { + _displayfunction |= LCD_5x10DOTS; + } + + // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION! + // according to datasheet, we need at least 40ms after power rises above 2.7V + // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50 + delay(50); + + // Now we pull both RS and R/W low to begin commands + expanderWrite(_backlightval); // reset expanderand turn backlight off (Bit 8 =1) + delay(1000); + + //put the LCD into 4 bit mode + // this is according to the hitachi HD44780 datasheet + // figure 24, pg 46 + + // we start in 8bit mode, try to set 4 bit mode + write4bits(0x03 << 4); + delayMicroseconds(4500); // wait min 4.1ms + + // second try + write4bits(0x03 << 4); + delayMicroseconds(4500); // wait min 4.1ms + + // third go! + write4bits(0x03 << 4); + delayMicroseconds(150); + + // finally, set to 4-bit interface + write4bits(0x02 << 4); + + + // set # lines, font size, etc. + command(LCD_FUNCTIONSET | _displayfunction); + + // turn the display on with no cursor or blinking default + _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; + display(); + + // clear it off + clear(); + + // Initialize to default text direction (for roman languages) + _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; + + // set the entry mode + command(LCD_ENTRYMODESET | _displaymode); + + home(); + +} + +/********** high level commands, for the user! */ +void LiquidCrystal_I2C::clear(){ + command(LCD_CLEARDISPLAY);// clear display, set cursor position to zero + delayMicroseconds(2000); // this command takes a long time! + if (_oled) setCursor(0,0); +} + +void LiquidCrystal_I2C::home(){ + command(LCD_RETURNHOME); // set cursor position to zero + delayMicroseconds(2000); // this command takes a long time! +} + +void LiquidCrystal_I2C::setCursor(uint8_t col, uint8_t row){ + int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 }; + if ( row > _numlines ) { + row = _numlines-1; // we count rows starting w/0 + } + command(LCD_SETDDRAMADDR | (col + row_offsets[row])); +} + +// Turn the display on/off (quickly) +void LiquidCrystal_I2C::noDisplay() { + _displaycontrol &= ~LCD_DISPLAYON; + command(LCD_DISPLAYCONTROL | _displaycontrol); +} +void LiquidCrystal_I2C::display() { + _displaycontrol |= LCD_DISPLAYON; + command(LCD_DISPLAYCONTROL | _displaycontrol); +} + +// Turns the underline cursor on/off +void LiquidCrystal_I2C::noCursor() { + _displaycontrol &= ~LCD_CURSORON; + command(LCD_DISPLAYCONTROL | _displaycontrol); +} +void LiquidCrystal_I2C::cursor() { + _displaycontrol |= LCD_CURSORON; + command(LCD_DISPLAYCONTROL | _displaycontrol); +} + +// Turn on and off the blinking cursor +void LiquidCrystal_I2C::noBlink() { + _displaycontrol &= ~LCD_BLINKON; + command(LCD_DISPLAYCONTROL | _displaycontrol); +} +void LiquidCrystal_I2C::blink() { + _displaycontrol |= LCD_BLINKON; + command(LCD_DISPLAYCONTROL | _displaycontrol); +} + +// These commands scroll the display without changing the RAM +void LiquidCrystal_I2C::scrollDisplayLeft(void) { + command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); +} +void LiquidCrystal_I2C::scrollDisplayRight(void) { + command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); +} + +// This is for text that flows Left to Right +void LiquidCrystal_I2C::leftToRight(void) { + _displaymode |= LCD_ENTRYLEFT; + command(LCD_ENTRYMODESET | _displaymode); +} + +// This is for text that flows Right to Left +void LiquidCrystal_I2C::rightToLeft(void) { + _displaymode &= ~LCD_ENTRYLEFT; + command(LCD_ENTRYMODESET | _displaymode); +} + +// This will 'right justify' text from the cursor +void LiquidCrystal_I2C::autoscroll(void) { + _displaymode |= LCD_ENTRYSHIFTINCREMENT; + command(LCD_ENTRYMODESET | _displaymode); +} + +// This will 'left justify' text from the cursor +void LiquidCrystal_I2C::noAutoscroll(void) { + _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; + command(LCD_ENTRYMODESET | _displaymode); +} + +// Allows us to fill the first 8 CGRAM locations +// with custom characters +void LiquidCrystal_I2C::createChar(uint8_t location, uint8_t charmap[]) { + location &= 0x7; // we only have 8 locations 0-7 + command(LCD_SETCGRAMADDR | (location << 3)); + for (int i=0; i<8; i++) { + write(charmap[i]); + } +} + +//createChar with PROGMEM input +void LiquidCrystal_I2C::createChar(uint8_t location, const char *charmap) { + location &= 0x7; // we only have 8 locations 0-7 + command(LCD_SETCGRAMADDR | (location << 3)); + for (int i=0; i<8; i++) { + write(pgm_read_byte_near(charmap++)); + } +} + +// Turn the (optional) backlight off/on +void LiquidCrystal_I2C::noBacklight(void) { + _backlightval=LCD_NOBACKLIGHT; + expanderWrite(0); +} + +void LiquidCrystal_I2C::backlight(void) { + _backlightval=LCD_BACKLIGHT; + expanderWrite(0); +} + + + +/*********** mid level commands, for sending data/cmds */ + +inline void LiquidCrystal_I2C::command(uint8_t value) { + send(value, 0); +} + + +/************ low level data pushing commands **********/ + +// write either command or data +void LiquidCrystal_I2C::send(uint8_t value, uint8_t mode) { + uint8_t highnib=value&0xf0; + uint8_t lownib=(value<<4)&0xf0; + write4bits((highnib)|mode); + write4bits((lownib)|mode); +} + +void LiquidCrystal_I2C::write4bits(uint8_t value) { + expanderWrite(value); + pulseEnable(value); +} + +void LiquidCrystal_I2C::expanderWrite(uint8_t _data){ + Wire.beginTransmission(_Addr); + printIIC((int)(_data) | _backlightval); + Wire.endTransmission(); +} + +void LiquidCrystal_I2C::pulseEnable(uint8_t _data){ + expanderWrite(_data | En); // En high + delayMicroseconds(1); // enable pulse must be >450ns + + expanderWrite(_data & ~En); // En low + delayMicroseconds(50); // commands need > 37us to settle +} + + +// Alias functions + +void LiquidCrystal_I2C::cursor_on(){ + cursor(); +} + +void LiquidCrystal_I2C::cursor_off(){ + noCursor(); +} + +void LiquidCrystal_I2C::blink_on(){ + blink(); +} + +void LiquidCrystal_I2C::blink_off(){ + noBlink(); +} + +void LiquidCrystal_I2C::load_custom_character(uint8_t char_num, uint8_t *rows){ + createChar(char_num, rows); +} + +void LiquidCrystal_I2C::setBacklight(uint8_t new_val){ + if(new_val){ + backlight(); // turn backlight on + }else{ + noBacklight(); // turn backlight off + } +} + +void LiquidCrystal_I2C::printstr(const char c[]){ + //This function is not identical to the function used for "real" I2C displays + //it's here so the user sketch doesn't have to be changed + print(c); +} + + +// unsupported API functions +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" +void LiquidCrystal_I2C::off(){} +void LiquidCrystal_I2C::on(){} +void LiquidCrystal_I2C::setDelay (int cmdDelay,int charDelay) {} +uint8_t LiquidCrystal_I2C::status(){return 0;} +uint8_t LiquidCrystal_I2C::keypad (){return 0;} +uint8_t LiquidCrystal_I2C::init_bargraph(uint8_t graphtype){return 0;} +void LiquidCrystal_I2C::draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end){} +void LiquidCrystal_I2C::draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_row_end){} +void LiquidCrystal_I2C::setContrast(uint8_t new_val){} +#pragma GCC diagnostic pop + diff --git a/libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.h b/libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.h new file mode 100644 index 0000000..6f98fc2 --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/LiquidCrystal_I2C.h @@ -0,0 +1,131 @@ +//YWROBOT +#ifndef LiquidCrystal_I2C_h +#define LiquidCrystal_I2C_h + +#include +#include "Print.h" +#include + +// commands +#define LCD_CLEARDISPLAY 0x01 +#define LCD_RETURNHOME 0x02 +#define LCD_ENTRYMODESET 0x04 +#define LCD_DISPLAYCONTROL 0x08 +#define LCD_CURSORSHIFT 0x10 +#define LCD_FUNCTIONSET 0x20 +#define LCD_SETCGRAMADDR 0x40 +#define LCD_SETDDRAMADDR 0x80 + +// flags for display entry mode +#define LCD_ENTRYRIGHT 0x00 +#define LCD_ENTRYLEFT 0x02 +#define LCD_ENTRYSHIFTINCREMENT 0x01 +#define LCD_ENTRYSHIFTDECREMENT 0x00 + +// flags for display on/off control +#define LCD_DISPLAYON 0x04 +#define LCD_DISPLAYOFF 0x00 +#define LCD_CURSORON 0x02 +#define LCD_CURSOROFF 0x00 +#define LCD_BLINKON 0x01 +#define LCD_BLINKOFF 0x00 + +// flags for display/cursor shift +#define LCD_DISPLAYMOVE 0x08 +#define LCD_CURSORMOVE 0x00 +#define LCD_MOVERIGHT 0x04 +#define LCD_MOVELEFT 0x00 + +// flags for function set +#define LCD_8BITMODE 0x10 +#define LCD_4BITMODE 0x00 +#define LCD_2LINE 0x08 +#define LCD_1LINE 0x00 +#define LCD_5x10DOTS 0x04 +#define LCD_5x8DOTS 0x00 + +// flags for backlight control +#define LCD_BACKLIGHT 0x08 +#define LCD_NOBACKLIGHT 0x00 + +#define En B00000100 // Enable bit +#define Rw B00000010 // Read/Write bit +#define Rs B00000001 // Register select bit + +class LiquidCrystal_I2C : public Print { +public: + LiquidCrystal_I2C(uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t lcd_rows); + void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS ); + void clear(); + void home(); + void noDisplay(); + void display(); + void noBlink(); + void blink(); + void noCursor(); + void cursor(); + void scrollDisplayLeft(); + void scrollDisplayRight(); + void printLeft(); + void printRight(); + void leftToRight(); + void rightToLeft(); + void shiftIncrement(); + void shiftDecrement(); + void noBacklight(); + void backlight(); + void autoscroll(); + void noAutoscroll(); + void createChar(uint8_t, uint8_t[]); + void createChar(uint8_t location, const char *charmap); + // Example: const char bell[8] PROGMEM = {B00100,B01110,B01110,B01110,B11111,B00000,B00100,B00000}; + + void setCursor(uint8_t, uint8_t); +#if defined(ARDUINO) && ARDUINO >= 100 + virtual size_t write(uint8_t); +#else + virtual void write(uint8_t); +#endif + void command(uint8_t); + void init(); + void oled_init(); + +////compatibility API function aliases +void blink_on(); // alias for blink() +void blink_off(); // alias for noBlink() +void cursor_on(); // alias for cursor() +void cursor_off(); // alias for noCursor() +void setBacklight(uint8_t new_val); // alias for backlight() and nobacklight() +void load_custom_character(uint8_t char_num, uint8_t *rows); // alias for createChar() +void printstr(const char[]); + +////Unsupported API functions (not implemented in this library) +uint8_t status(); +void setContrast(uint8_t new_val); +uint8_t keypad(); +void setDelay(int,int); +void on(); +void off(); +uint8_t init_bargraph(uint8_t graphtype); +void draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end); +void draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end); + + +private: + void init_priv(); + void send(uint8_t, uint8_t); + void write4bits(uint8_t); + void expanderWrite(uint8_t); + void pulseEnable(uint8_t); + uint8_t _Addr; + uint8_t _displayfunction; + uint8_t _displaycontrol; + uint8_t _displaymode; + uint8_t _numlines; + bool _oled = false; + uint8_t _cols; + uint8_t _rows; + uint8_t _backlightval; +}; + +#endif diff --git a/libraries/LiquidCrystal_I2C-master/README.md b/libraries/LiquidCrystal_I2C-master/README.md new file mode 100644 index 0000000..574ee3c --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/README.md @@ -0,0 +1,6 @@ +# LiquidCrystal_I2C + +LiquidCrystal Arduino library for I2C LCD displays + +**Status: Archived** +This repository has been transfered to GitLab at https://gitlab.com/tandembyte/LCD_I2C diff --git a/libraries/LiquidCrystal_I2C-master/examples/CustomChars/CustomChars.pde b/libraries/LiquidCrystal_I2C-master/examples/CustomChars/CustomChars.pde new file mode 100644 index 0000000..e341000 --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/examples/CustomChars/CustomChars.pde @@ -0,0 +1,70 @@ +//YWROBOT +//Compatible with the Arduino IDE 1.0 +//Library version:1.1 +#include +#include + +#if defined(ARDUINO) && ARDUINO >= 100 +#define printByte(args) write(args); +#else +#define printByte(args) print(args,BYTE); +#endif + +uint8_t bell[8] = {0x4,0xe,0xe,0xe,0x1f,0x0,0x4}; +uint8_t note[8] = {0x2,0x3,0x2,0xe,0x1e,0xc,0x0}; +uint8_t clock[8] = {0x0,0xe,0x15,0x17,0x11,0xe,0x0}; +uint8_t heart[8] = {0x0,0xa,0x1f,0x1f,0xe,0x4,0x0}; +uint8_t duck[8] = {0x0,0xc,0x1d,0xf,0xf,0x6,0x0}; +uint8_t check[8] = {0x0,0x1,0x3,0x16,0x1c,0x8,0x0}; +uint8_t cross[8] = {0x0,0x1b,0xe,0x4,0xe,0x1b,0x0}; +uint8_t retarrow[8] = { 0x1,0x1,0x5,0x9,0x1f,0x8,0x4}; + +LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display + +void setup() +{ + lcd.init(); // initialize the lcd + lcd.backlight(); + + lcd.createChar(0, bell); + lcd.createChar(1, note); + lcd.createChar(2, clock); + lcd.createChar(3, heart); + lcd.createChar(4, duck); + lcd.createChar(5, check); + lcd.createChar(6, cross); + lcd.createChar(7, retarrow); + lcd.home(); + + lcd.print("Hello world..."); + lcd.setCursor(0, 1); + lcd.print(" i "); + lcd.printByte(3); + lcd.print(" arduinos!"); + delay(5000); + displayKeyCodes(); + +} + +// display all keycodes +void displayKeyCodes(void) { + uint8_t i = 0; + while (1) { + lcd.clear(); + lcd.print("Codes 0x"); lcd.print(i, HEX); + lcd.print("-0x"); lcd.print(i+15, HEX); + lcd.setCursor(0, 1); + for (int j=0; j<16; j++) { + lcd.printByte(i+j); + } + i+=16; + + delay(4000); + } +} + +void loop() +{ + +} + diff --git a/libraries/LiquidCrystal_I2C-master/examples/HelloWorld/HelloWorld.pde b/libraries/LiquidCrystal_I2C-master/examples/HelloWorld/HelloWorld.pde new file mode 100644 index 0000000..a6b4cba --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/examples/HelloWorld/HelloWorld.pde @@ -0,0 +1,26 @@ +//YWROBOT +//Compatible with the Arduino IDE 1.0 +//Library version:1.1 +#include + +LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display + +void setup() +{ + lcd.init(); // initialize the lcd + // Print a message to the LCD. + lcd.backlight(); + lcd.setCursor(3,0); + lcd.print("Hello, world!"); + lcd.setCursor(2,1); + lcd.print("Ywrobot Arduino!"); + lcd.setCursor(0,2); + lcd.print("Arduino LCM IIC 2004"); + lcd.setCursor(2,3); + lcd.print("Power By Ec-yuan!"); +} + + +void loop() +{ +} diff --git a/libraries/LiquidCrystal_I2C-master/examples/SerialDisplay/SerialDisplay.pde b/libraries/LiquidCrystal_I2C-master/examples/SerialDisplay/SerialDisplay.pde new file mode 100644 index 0000000..fdbbc64 --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/examples/SerialDisplay/SerialDisplay.pde @@ -0,0 +1,34 @@ +/* + * Displays text sent over the serial port (e.g. from the Serial Monitor) on + * an attached LCD. + * YWROBOT + *Compatible with the Arduino IDE 1.0 + *Library version:1.1 + */ +#include +#include + +LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display + +void setup() +{ + lcd.init(); // initialize the lcd + lcd.backlight(); + Serial.begin(9600); +} + +void loop() +{ + // when characters arrive over the serial port... + if (Serial.available()) { + // wait a bit for the entire message to arrive + delay(100); + // clear the screen + lcd.clear(); + // read all the available characters + while (Serial.available() > 0) { + // display each character to the LCD + lcd.write(Serial.read()); + } + } +} diff --git a/libraries/LiquidCrystal_I2C-master/keywords.txt b/libraries/LiquidCrystal_I2C-master/keywords.txt new file mode 100644 index 0000000..8c450a9 --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/keywords.txt @@ -0,0 +1,46 @@ +########################################### +# Syntax Coloring Map For LiquidCrystal_I2C +########################################### + +########################################### +# Datatypes (KEYWORD1) +########################################### + +LiquidCrystal_I2C KEYWORD1 + +########################################### +# Methods and Functions (KEYWORD2) +########################################### +init KEYWORD2 +begin KEYWORD2 +clear KEYWORD2 +home KEYWORD2 +noDisplay KEYWORD2 +display KEYWORD2 +noBlink KEYWORD2 +blink KEYWORD2 +noCursor KEYWORD2 +cursor KEYWORD2 +scrollDisplayLeft KEYWORD2 +scrollDisplayRight KEYWORD2 +leftToRight KEYWORD2 +rightToLeft KEYWORD2 +shiftIncrement KEYWORD2 +shiftDecrement KEYWORD2 +noBacklight KEYWORD2 +backlight KEYWORD2 +autoscroll KEYWORD2 +noAutoscroll KEYWORD2 +createChar KEYWORD2 +setCursor KEYWORD2 +print KEYWORD2 +blink_on KEYWORD2 +blink_off KEYWORD2 +cursor_on KEYWORD2 +cursor_off KEYWORD2 +setBacklight KEYWORD2 +load_custom_character KEYWORD2 +printstr KEYWORD2 +########################################### +# Constants (LITERAL1) +########################################### diff --git a/libraries/LiquidCrystal_I2C-master/library.json b/libraries/LiquidCrystal_I2C-master/library.json new file mode 100644 index 0000000..4710920 --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/library.json @@ -0,0 +1,16 @@ +{ + "name": "LiquidCrystal_I2C", + "keywords": "LCD, liquidcrystal, I2C", + "description": "A library for DFRobot I2C LCD displays", + "repository": + { + "type": "git", + "url": "https://github.com/marcoschwartz/LiquidCrystal_I2C.git" + }, + "frameworks": "arduino", + "platforms": + [ + "atmelavr", + "espressif8266" + ] +} diff --git a/libraries/LiquidCrystal_I2C-master/library.properties b/libraries/LiquidCrystal_I2C-master/library.properties new file mode 100644 index 0000000..9764810 --- /dev/null +++ b/libraries/LiquidCrystal_I2C-master/library.properties @@ -0,0 +1,9 @@ +name=LiquidCrystal_I2C +version=1.1.4 +author=Frank de Brabander +maintainer=Marco Schwartz +sentence=A library for I2C LCD displays. +paragraph= The library allows to control I2C displays with functions extremely similar to LiquidCrystal library. THIS LIBRARY MIGHT NOT BE COMPATIBLE WITH EXISTING SKETCHES. +category=Display +url=https://github.com/marcoschwartz/LiquidCrystal_I2C +architectures=avr diff --git a/libraries/Mouse/README.adoc b/libraries/Mouse/README.adoc new file mode 100644 index 0000000..3e61306 --- /dev/null +++ b/libraries/Mouse/README.adoc @@ -0,0 +1,25 @@ += Mouse Library for Arduino = + +This library allows an Arduino board with USB capabilites to act as a Mouse. +Being based on HID library you need to include "HID.h" in your sketch + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/Mouse + +== License == + +Copyright (c) Arduino LLC. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/Mouse/keywords.txt b/libraries/Mouse/keywords.txt new file mode 100644 index 0000000..258c48e --- /dev/null +++ b/libraries/Mouse/keywords.txt @@ -0,0 +1,24 @@ +####################################### +# Syntax Coloring Map For Keyboard +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Mouse KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +click KEYWORD2 +move KEYWORD2 +press KEYWORD2 +release KEYWORD2 +isPressed KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/libraries/Mouse/library.properties b/libraries/Mouse/library.properties new file mode 100644 index 0000000..6e60f01 --- /dev/null +++ b/libraries/Mouse/library.properties @@ -0,0 +1,9 @@ +name=Mouse +version=1.0.1 +author=Arduino +maintainer=Arduino +sentence=Allows an Arduino/Genuino board with USB capabilites to act as a Mouse. +paragraph=This library plugs on the HID library. Can be used with or without other HID-based libraries (Keyboard, Gamepad etc) +category=Device Control +url=http://www.arduino.cc/en/Reference/Mouse +architectures=* diff --git a/libraries/Mouse/src/Mouse.cpp b/libraries/Mouse/src/Mouse.cpp new file mode 100644 index 0000000..b2a2cd7 --- /dev/null +++ b/libraries/Mouse/src/Mouse.cpp @@ -0,0 +1,123 @@ +/* + Mouse.cpp + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "Mouse.h" + +#if defined(_USING_HID) + +static const uint8_t _hidReportDescriptor[] PROGMEM = { + + // Mouse + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54 + 0x09, 0x02, // USAGE (Mouse) + 0xa1, 0x01, // COLLECTION (Application) + 0x09, 0x01, // USAGE (Pointer) + 0xa1, 0x00, // COLLECTION (Physical) + 0x85, 0x01, // REPORT_ID (1) + 0x05, 0x09, // USAGE_PAGE (Button) + 0x19, 0x01, // USAGE_MINIMUM (Button 1) + 0x29, 0x03, // USAGE_MAXIMUM (Button 3) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x01, // LOGICAL_MAXIMUM (1) + 0x95, 0x03, // REPORT_COUNT (3) + 0x75, 0x01, // REPORT_SIZE (1) + 0x81, 0x02, // INPUT (Data,Var,Abs) + 0x95, 0x01, // REPORT_COUNT (1) + 0x75, 0x05, // REPORT_SIZE (5) + 0x81, 0x03, // INPUT (Cnst,Var,Abs) + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) + 0x09, 0x30, // USAGE (X) + 0x09, 0x31, // USAGE (Y) + 0x09, 0x38, // USAGE (Wheel) + 0x15, 0x81, // LOGICAL_MINIMUM (-127) + 0x25, 0x7f, // LOGICAL_MAXIMUM (127) + 0x75, 0x08, // REPORT_SIZE (8) + 0x95, 0x03, // REPORT_COUNT (3) + 0x81, 0x06, // INPUT (Data,Var,Rel) + 0xc0, // END_COLLECTION + 0xc0, // END_COLLECTION +}; + +//================================================================================ +//================================================================================ +// Mouse + +Mouse_::Mouse_(void) : _buttons(0) +{ + static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); + HID().AppendDescriptor(&node); +} + +void Mouse_::begin(void) +{ +} + +void Mouse_::end(void) +{ +} + +void Mouse_::click(uint8_t b) +{ + _buttons = b; + move(0,0,0); + _buttons = 0; + move(0,0,0); +} + +void Mouse_::move(signed char x, signed char y, signed char wheel) +{ + uint8_t m[4]; + m[0] = _buttons; + m[1] = x; + m[2] = y; + m[3] = wheel; + HID().SendReport(1,m,4); +} + +void Mouse_::buttons(uint8_t b) +{ + if (b != _buttons) + { + _buttons = b; + move(0,0,0); + } +} + +void Mouse_::press(uint8_t b) +{ + buttons(_buttons | b); +} + +void Mouse_::release(uint8_t b) +{ + buttons(_buttons & ~b); +} + +bool Mouse_::isPressed(uint8_t b) +{ + if ((b & _buttons) > 0) + return true; + return false; +} + +Mouse_ Mouse; + +#endif diff --git a/libraries/Mouse/src/Mouse.h b/libraries/Mouse/src/Mouse.h new file mode 100644 index 0000000..2672b5c --- /dev/null +++ b/libraries/Mouse/src/Mouse.h @@ -0,0 +1,60 @@ +/* + Mouse.h + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef MOUSE_h +#define MOUSE_h + +#include "HID.h" + +#if !defined(_USING_HID) + +#warning "Using legacy HID core (non pluggable)" + +#else + +//================================================================================ +//================================================================================ +// Mouse + +#define MOUSE_LEFT 1 +#define MOUSE_RIGHT 2 +#define MOUSE_MIDDLE 4 +#define MOUSE_ALL (MOUSE_LEFT | MOUSE_RIGHT | MOUSE_MIDDLE) + +class Mouse_ +{ +private: + uint8_t _buttons; + void buttons(uint8_t b); +public: + Mouse_(void); + void begin(void); + void end(void); + void click(uint8_t b = MOUSE_LEFT); + void move(signed char x, signed char y, signed char wheel = 0); + void press(uint8_t b = MOUSE_LEFT); // press LEFT by default + void release(uint8_t b = MOUSE_LEFT); // release LEFT by default + bool isPressed(uint8_t b = MOUSE_LEFT); // check LEFT by default +}; +extern Mouse_ Mouse; + +#endif +#endif \ No newline at end of file diff --git a/libraries/SD/README.adoc b/libraries/SD/README.adoc new file mode 100644 index 0000000..fb3ed03 --- /dev/null +++ b/libraries/SD/README.adoc @@ -0,0 +1,26 @@ += SD Library for Arduino = + +image:https://travis-ci.org/arduino-libraries/SD.svg?branch=master[Build Status, link=https://travis-ci.org/arduino-libraries/SD] + +The SD library allows for reading from and writing to SD cards. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/SD + +== License == + + Copyright (C) 2009 by William Greiman +Copyright (c) 2010 SparkFun Electronics + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . diff --git a/libraries/SD/examples/CardInfo/CardInfo.ino b/libraries/SD/examples/CardInfo/CardInfo.ino new file mode 100644 index 0000000..97913ef --- /dev/null +++ b/libraries/SD/examples/CardInfo/CardInfo.ino @@ -0,0 +1,116 @@ +/* + SD card test + + This example shows how use the utility libraries on which the' + SD library is based in order to get info about your SD card. + Very useful for testing a card when you're not sure whether its working or not. + + The circuit: + SD card attached to SPI bus as follows: + ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila + ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila + ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila + ** CS - depends on your SD card shield or module. + Pin 4 used here for consistency with other Arduino examples + + + created 28 Mar 2011 + by Limor Fried + modified 9 Apr 2012 + by Tom Igoe +*/ +// include the SD library: +#include +#include + +// set up variables using the SD utility library functions: +Sd2Card card; +SdVolume volume; +SdFile root; + +// change this to match your SD shield or module; +// Arduino Ethernet shield: pin 4 +// Adafruit SD shields and modules: pin 10 +// Sparkfun SD shield: pin 8 +// MKRZero SD: SDCARD_SS_PIN +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("\nInitializing SD card..."); + + // we'll use the initialization code from the utility libraries + // since we're just testing if the card is working! + if (!card.init(SPI_HALF_SPEED, chipSelect)) { + Serial.println("initialization failed. Things to check:"); + Serial.println("* is a card inserted?"); + Serial.println("* is your wiring correct?"); + Serial.println("* did you change the chipSelect pin to match your shield or module?"); + while (1); + } else { + Serial.println("Wiring is correct and a card is present."); + } + + // print the type of card + Serial.println(); + Serial.print("Card type: "); + switch (card.type()) { + case SD_CARD_TYPE_SD1: + Serial.println("SD1"); + break; + case SD_CARD_TYPE_SD2: + Serial.println("SD2"); + break; + case SD_CARD_TYPE_SDHC: + Serial.println("SDHC"); + break; + default: + Serial.println("Unknown"); + } + + // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32 + if (!volume.init(card)) { + Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card"); + while (1); + } + + Serial.print("Clusters: "); + Serial.println(volume.clusterCount()); + Serial.print("Blocks x Cluster: "); + Serial.println(volume.blocksPerCluster()); + + Serial.print("Total Blocks: "); + Serial.println(volume.blocksPerCluster() * volume.clusterCount()); + Serial.println(); + + // print the type and size of the first FAT-type volume + uint32_t volumesize; + Serial.print("Volume type is: FAT"); + Serial.println(volume.fatType(), DEC); + + volumesize = volume.blocksPerCluster(); // clusters are collections of blocks + volumesize *= volume.clusterCount(); // we'll have a lot of clusters + volumesize /= 2; // SD card blocks are always 512 bytes (2 blocks are 1KB) + Serial.print("Volume size (Kb): "); + Serial.println(volumesize); + Serial.print("Volume size (Mb): "); + volumesize /= 1024; + Serial.println(volumesize); + Serial.print("Volume size (Gb): "); + Serial.println((float)volumesize / 1024.0); + + Serial.println("\nFiles found on the card (name, date and size in bytes): "); + root.openRoot(volume); + + // list all files in the card with date and size + root.ls(LS_R | LS_DATE | LS_SIZE); +} + +void loop(void) { +} diff --git a/libraries/SD/examples/Datalogger/Datalogger.ino b/libraries/SD/examples/Datalogger/Datalogger.ino new file mode 100644 index 0000000..c2631c0 --- /dev/null +++ b/libraries/SD/examples/Datalogger/Datalogger.ino @@ -0,0 +1,84 @@ +/* + SD card datalogger + + This example shows how to log data from three analog sensors + to an SD card using the SD library. + + The circuit: + analog sensors on analog ins 0, 1, and 2 + SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created 24 Nov 2010 + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + +*/ + +#include +#include + +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + // see if the card is present and can be initialized: + if (!SD.begin(chipSelect)) { + Serial.println("Card failed, or not present"); + // don't do anything more: + while (1); + } + Serial.println("card initialized."); +} + +void loop() { + // make a string for assembling the data to log: + String dataString = ""; + + // read three sensors and append to the string: + for (int analogPin = 0; analogPin < 3; analogPin++) { + int sensor = analogRead(analogPin); + dataString += String(sensor); + if (analogPin < 2) { + dataString += ","; + } + } + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + File dataFile = SD.open("datalog.txt", FILE_WRITE); + + // if the file is available, write to it: + if (dataFile) { + dataFile.println(dataString); + dataFile.close(); + // print to the serial port too: + Serial.println(dataString); + } + // if the file isn't open, pop up an error: + else { + Serial.println("error opening datalog.txt"); + } +} + + + + + + + + + diff --git a/libraries/SD/examples/DumpFile/DumpFile.ino b/libraries/SD/examples/DumpFile/DumpFile.ino new file mode 100644 index 0000000..7491999 --- /dev/null +++ b/libraries/SD/examples/DumpFile/DumpFile.ino @@ -0,0 +1,65 @@ +/* + SD card file dump + + This example shows how to read a file from the SD card using the + SD library and send it over the serial port. + + The circuit: + SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created 22 December 2010 + by Limor Fried + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + +*/ + +#include +#include + +const int chipSelect = 4; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + // see if the card is present and can be initialized: + if (!SD.begin(chipSelect)) { + Serial.println("Card failed, or not present"); + // don't do anything more: + while (1); + } + Serial.println("card initialized."); + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + File dataFile = SD.open("datalog.txt"); + + // if the file is available, write to it: + if (dataFile) { + while (dataFile.available()) { + Serial.write(dataFile.read()); + } + dataFile.close(); + } + // if the file isn't open, pop up an error: + else { + Serial.println("error opening datalog.txt"); + } +} + +void loop() { +} + diff --git a/libraries/SD/examples/Files/Files.ino b/libraries/SD/examples/Files/Files.ino new file mode 100644 index 0000000..cabebba --- /dev/null +++ b/libraries/SD/examples/Files/Files.ino @@ -0,0 +1,75 @@ +/* + SD card basic file example + + This example shows how to create and destroy an SD card file + The circuit: + SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + +*/ +#include +#include + +File myFile; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + while (1); + } + Serial.println("initialization done."); + + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } + + // open a new file and immediately close it: + Serial.println("Creating example.txt..."); + myFile = SD.open("example.txt", FILE_WRITE); + myFile.close(); + + // Check to see if the file exists: + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } + + // delete the file: + Serial.println("Removing example.txt..."); + SD.remove("example.txt"); + + if (SD.exists("example.txt")) { + Serial.println("example.txt exists."); + } else { + Serial.println("example.txt doesn't exist."); + } +} + +void loop() { + // nothing happens after setup finishes. +} + + + diff --git a/libraries/SD/examples/NonBlockingWrite/NonBlockingWrite.ino b/libraries/SD/examples/NonBlockingWrite/NonBlockingWrite.ino new file mode 100644 index 0000000..29d8ec6 --- /dev/null +++ b/libraries/SD/examples/NonBlockingWrite/NonBlockingWrite.ino @@ -0,0 +1,91 @@ +/* + Non-blocking Write + + This example demonstrates how to perform non-blocking writes + to a file on a SD card. The file will contain the current millis() + value every 10ms. If the SD card is busy, the data will be buffered + in order to not block the sketch. + + NOTE: myFile.availableForWrite() will automatically sync the + file contents as needed. You may lose some unsynced data + still if myFile.sync() or myFile.close() is not called. + + The circuit: + - Arduino MKR Zero board + - micro SD card attached + + This example code is in the public domain. +*/ + +#include + +// file name to use for writing +const char filename[] = "demo.txt"; + +// File object to represent file +File txtFile; + +// string to buffer output +String buffer; + +unsigned long lastMillis = 0; + +void setup() { + Serial.begin(9600); + while (!Serial); + + // reserve 1kB for String used as a buffer + buffer.reserve(1024); + + // set LED pin to output, used to blink when writing + pinMode(LED_BUILTIN, OUTPUT); + + // init the SD card + if (!SD.begin()) { + Serial.println("Card failed, or not present"); + // don't do anything more: + while (1); + } + + // If you want to start from an empty file, + // uncomment the next line: + // SD.remove(filename); + + // try to open the file for writing + txtFile = SD.open(filename, FILE_WRITE); + if (!txtFile) { + Serial.print("error opening "); + Serial.println(filename); + while (1); + } + + // add some new lines to start + txtFile.println(); + txtFile.println("Hello World!"); +} + +void loop() { + // check if it's been over 10 ms since the last line added + unsigned long now = millis(); + if ((now - lastMillis) >= 10) { + // add a new line to the buffer + buffer += "Hello "; + buffer += now; + buffer += "\r\n"; + + lastMillis = now; + } + + // check if the SD card is available to write data without blocking + // and if the buffered data is enough for the full chunk size + unsigned int chunkSize = txtFile.availableForWrite(); + if (chunkSize && buffer.length() >= chunkSize) { + // write to file and blink LED + digitalWrite(LED_BUILTIN, HIGH); + txtFile.write(buffer.c_str(), chunkSize); + digitalWrite(LED_BUILTIN, LOW); + + // remove written data from buffer + buffer.remove(0, chunkSize); + } +} diff --git a/libraries/SD/examples/ReadWrite/ReadWrite.ino b/libraries/SD/examples/ReadWrite/ReadWrite.ino new file mode 100644 index 0000000..d964668 --- /dev/null +++ b/libraries/SD/examples/ReadWrite/ReadWrite.ino @@ -0,0 +1,79 @@ +/* + SD card read/write + + This example shows how to read and write data to and from an SD card file + The circuit: + SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + This example code is in the public domain. + +*/ + +#include +#include + +File myFile; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + while (1); + } + Serial.println("initialization done."); + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + myFile = SD.open("test.txt", FILE_WRITE); + + // if the file opened okay, write to it: + if (myFile) { + Serial.print("Writing to test.txt..."); + myFile.println("testing 1, 2, 3."); + // close the file: + myFile.close(); + Serial.println("done."); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } + + // re-open the file for reading: + myFile = SD.open("test.txt"); + if (myFile) { + Serial.println("test.txt:"); + + // read from the file until there's nothing else in it: + while (myFile.available()) { + Serial.write(myFile.read()); + } + // close the file: + myFile.close(); + } else { + // if the file didn't open, print an error: + Serial.println("error opening test.txt"); + } +} + +void loop() { + // nothing happens after setup +} + + diff --git a/libraries/SD/examples/listfiles/listfiles.ino b/libraries/SD/examples/listfiles/listfiles.ino new file mode 100644 index 0000000..48f84fb --- /dev/null +++ b/libraries/SD/examples/listfiles/listfiles.ino @@ -0,0 +1,80 @@ +/* + Listfiles + + This example shows how print out the files in a + directory on a SD card + + The circuit: + SD card attached to SPI bus as follows: + ** MOSI - pin 11 + ** MISO - pin 12 + ** CLK - pin 13 + ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) + + created Nov 2010 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + modified 2 Feb 2014 + by Scott Fitzgerald + + This example code is in the public domain. + +*/ +#include +#include + +File root; + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Serial.print("Initializing SD card..."); + + if (!SD.begin(4)) { + Serial.println("initialization failed!"); + while (1); + } + Serial.println("initialization done."); + + root = SD.open("/"); + + printDirectory(root, 0); + + Serial.println("done!"); +} + +void loop() { + // nothing happens after setup finishes. +} + +void printDirectory(File dir, int numTabs) { + while (true) { + + File entry = dir.openNextFile(); + if (! entry) { + // no more files + break; + } + for (uint8_t i = 0; i < numTabs; i++) { + Serial.print('\t'); + } + Serial.print(entry.name()); + if (entry.isDirectory()) { + Serial.println("/"); + printDirectory(entry, numTabs + 1); + } else { + // files have sizes, directories do not + Serial.print("\t\t"); + Serial.println(entry.size(), DEC); + } + entry.close(); + } +} + + + diff --git a/libraries/SD/extras/codespell-ignore-words-list.txt b/libraries/SD/extras/codespell-ignore-words-list.txt new file mode 100644 index 0000000..e69de29 diff --git a/libraries/SD/keywords.txt b/libraries/SD/keywords.txt new file mode 100644 index 0000000..91e74b8 --- /dev/null +++ b/libraries/SD/keywords.txt @@ -0,0 +1,31 @@ +####################################### +# Syntax Coloring Map SD +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +SD KEYWORD1 SD +File KEYWORD1 SD +SDFile KEYWORD1 SD + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +begin KEYWORD2 +exists KEYWORD2 +mkdir KEYWORD2 +remove KEYWORD2 +rmdir KEYWORD2 +open KEYWORD2 +close KEYWORD2 +seek KEYWORD2 +position KEYWORD2 +size KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +FILE_READ LITERAL1 +FILE_WRITE LITERAL1 diff --git a/libraries/SD/library.properties b/libraries/SD/library.properties new file mode 100644 index 0000000..60e8859 --- /dev/null +++ b/libraries/SD/library.properties @@ -0,0 +1,9 @@ +name=SD +version=1.2.4 +author=Arduino, SparkFun +maintainer=Arduino +sentence=Enables reading and writing on SD cards. +paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card. +category=Data Storage +url=http://www.arduino.cc/en/Reference/SD +architectures=* diff --git a/libraries/SD/src/File.cpp b/libraries/SD/src/File.cpp new file mode 100644 index 0000000..5e37166 --- /dev/null +++ b/libraries/SD/src/File.cpp @@ -0,0 +1,168 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + +*/ + +#include + +/* for debugging file open/close leaks + uint8_t nfilecount=0; +*/ + +File::File(SdFile f, const char *n) { + // oh man you are kidding me, new() doesn't exist? Ok we do it by hand! + _file = (SdFile *)malloc(sizeof(SdFile)); + if (_file) { + memcpy(_file, &f, sizeof(SdFile)); + + strncpy(_name, n, 12); + _name[12] = 0; + + /* for debugging file open/close leaks + nfilecount++; + Serial.print("Created \""); + Serial.print(n); + Serial.print("\": "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::File(void) { + _file = 0; + _name[0] = 0; + //Serial.print("Created empty file object"); +} + +// returns a pointer to the file name +char *File::name(void) { + return _name; +} + +// a directory is a special type of file +boolean File::isDirectory(void) { + return (_file && _file->isDir()); +} + + +size_t File::write(uint8_t val) { + return write(&val, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + size_t t; + if (!_file) { + setWriteError(); + return 0; + } + _file->clearWriteError(); + t = _file->write(buf, size); + if (_file->getWriteError()) { + setWriteError(); + return 0; + } + return t; +} + +int File::availableForWrite() { + if (_file) { + return _file->availableForWrite(); + } + return 0; +} + +int File::peek() { + if (! _file) { + return 0; + } + + int c = _file->read(); + if (c != -1) { + _file->seekCur(-1); + } + return c; +} + +int File::read() { + if (_file) { + return _file->read(); + } + return -1; +} + +// buffered read for more efficient, high speed reading +int File::read(void *buf, uint16_t nbyte) { + if (_file) { + return _file->read(buf, nbyte); + } + return 0; +} + +int File::available() { + if (! _file) { + return 0; + } + + uint32_t n = size() - position(); + + return n > 0X7FFF ? 0X7FFF : n; +} + +void File::flush() { + if (_file) { + _file->sync(); + } +} + +boolean File::seek(uint32_t pos) { + if (! _file) { + return false; + } + + return _file->seekSet(pos); +} + +uint32_t File::position() { + if (! _file) { + return -1; + } + return _file->curPosition(); +} + +uint32_t File::size() { + if (! _file) { + return 0; + } + return _file->fileSize(); +} + +void File::close() { + if (_file) { + _file->close(); + free(_file); + _file = 0; + + /* for debugging file open/close leaks + nfilecount--; + Serial.print("Deleted "); + Serial.println(nfilecount, DEC); + */ + } +} + +File::operator bool() { + if (_file) { + return _file->isOpen(); + } + return false; +} + diff --git a/libraries/SD/src/README.txt b/libraries/SD/src/README.txt new file mode 100644 index 0000000..495ea4c --- /dev/null +++ b/libraries/SD/src/README.txt @@ -0,0 +1,13 @@ + +** SD - a slightly more friendly wrapper for sdfatlib ** + +This library aims to expose a subset of SD card functionality in the +form of a higher level "wrapper" object. + +License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + +(C) Copyright 2010 SparkFun Electronics + +Now better than ever with optimization, multiple file support, directory handling, etc - ladyada! + diff --git a/libraries/SD/src/SD.cpp b/libraries/SD/src/SD.cpp new file mode 100644 index 0000000..8c9a29e --- /dev/null +++ b/libraries/SD/src/SD.cpp @@ -0,0 +1,637 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + + + This library provides four key benefits: + + Including `SD.h` automatically creates a global + `SD` object which can be interacted with in a similar + manner to other standard global objects like `Serial` and `Ethernet`. + + Boilerplate initialisation code is contained in one method named + `begin` and no further objects need to be created in order to access + the SD card. + + Calls to `open` can supply a full path name including parent + directories which simplifies interacting with files in subdirectories. + + Utility methods are provided to determine whether a file exists + and to create a directory hierarchy. + + + Note however that not all functionality provided by the underlying + sdfatlib library is exposed. + +*/ + +/* + + Implementation Notes + + In order to handle multi-directory path traversal, functionality that + requires this ability is implemented as callback functions. + + Individual methods call the `walkPath` function which performs the actual + directory traversal (swapping between two different directory/file handles + along the way) and at each level calls the supplied callback function. + + Some types of functionality will take an action at each level (e.g. exists + or make directory) which others will only take an action at the bottom + level (e.g. open). + +*/ + +#include "SD.h" + +namespace SDLib { + + // Used by `getNextPathComponent` +#define MAX_COMPONENT_LEN 12 // What is max length? +#define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1 + + bool getNextPathComponent(const char *path, unsigned int *p_offset, + char *buffer) { + /* + + Parse individual path components from a path. + + e.g. after repeated calls '/foo/bar/baz' will be split + into 'foo', 'bar', 'baz'. + + This is similar to `strtok()` but copies the component into the + supplied buffer rather than modifying the original string. + + + `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size. + + `p_offset` needs to point to an integer of the offset at + which the previous path component finished. + + Returns `true` if more components remain. + + Returns `false` if this is the last component. + (This means path ended with 'foo' or 'foo/'.) + + */ + + // TODO: Have buffer local to this function, so we know it's the + // correct length? + + int bufferOffset = 0; + + int offset = *p_offset; + + // Skip root or other separator + if (path[offset] == '/') { + offset++; + } + + // Copy the next next path segment + while (bufferOffset < MAX_COMPONENT_LEN + && (path[offset] != '/') + && (path[offset] != '\0')) { + buffer[bufferOffset++] = path[offset++]; + } + + buffer[bufferOffset] = '\0'; + + // Skip trailing separator so we can determine if this + // is the last component in the path or not. + if (path[offset] == '/') { + offset++; + } + + *p_offset = offset; + + return (path[offset] != '\0'); + } + + + + boolean walkPath(const char *filepath, SdFile& parentDir, + boolean(*callback)(SdFile& parentDir, + const char *filePathComponent, + boolean isLastComponent, + void *object), + void *object = NULL) { + /* + + When given a file path (and parent directory--normally root), + this function traverses the directories in the path and at each + level calls the supplied callback function while also providing + the supplied object for context if required. + + e.g. given the path '/foo/bar/baz' + the callback would be called at the equivalent of + '/foo', '/foo/bar' and '/foo/bar/baz'. + + The implementation swaps between two different directory/file + handles as it traverses the directories and does not use recursion + in an attempt to use memory efficiently. + + If a callback wishes to stop the directory traversal it should + return false--in this case the function will stop the traversal, + tidy up and return false. + + If a directory path doesn't exist at some point this function will + also return false and not subsequently call the callback. + + If a directory path specified is complete, valid and the callback + did not indicate the traversal should be interrupted then this + function will return true. + + */ + + + SdFile subfile1; + SdFile subfile2; + + char buffer[PATH_COMPONENT_BUFFER_LEN]; + + unsigned int offset = 0; + + SdFile *p_parent; + SdFile *p_child; + + SdFile *p_tmp_sdfile; + + p_child = &subfile1; + + p_parent = &parentDir; + + while (true) { + + boolean moreComponents = getNextPathComponent(filepath, &offset, buffer); + + boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object); + + if (!shouldContinue) { + // TODO: Don't repeat this code? + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + return false; + } + + if (!moreComponents) { + break; + } + + boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY); + + // If it's one we've created then we + // don't need the parent handle anymore. + if (p_parent != &parentDir) { + (*p_parent).close(); + } + + // Handle case when it doesn't exist and we can't continue... + if (exists) { + // We alternate between two file handles as we go down + // the path. + if (p_parent == &parentDir) { + p_parent = &subfile2; + } + + p_tmp_sdfile = p_parent; + p_parent = p_child; + p_child = p_tmp_sdfile; + } else { + return false; + } + } + + if (p_parent != &parentDir) { + (*p_parent).close(); // TODO: Return/ handle different? + } + + return true; + } + + + + /* + + The callbacks used to implement various functionality follow. + + Each callback is supplied with a parent directory handle, + character string with the name of the current file path component, + a flag indicating if this component is the last in the path and + a pointer to an arbitrary object used for context. + + */ + + boolean callback_pathExists(SdFile& parentDir, const char *filePathComponent, + boolean /* isLastComponent */, void * /* object */) { + /* + + Callback used to determine if a file/directory exists in parent + directory. + + Returns true if file path exists. + + */ + SdFile child; + + boolean exists = child.open(parentDir, filePathComponent, O_RDONLY); + + if (exists) { + child.close(); + } + + return exists; + } + + + + boolean callback_makeDirPath(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void *object) { + /* + + Callback used to create a directory in the parent directory if + it does not already exist. + + Returns true if a directory was created or it already existed. + + */ + boolean result = false; + SdFile child; + + result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object); + if (!result) { + result = child.makeDir(parentDir, filePathComponent); + } + + return result; + } + + + /* + + boolean callback_openPath(SdFile& parentDir, char *filePathComponent, + boolean isLastComponent, void *object) { + + Callback used to open a file specified by a filepath that may + specify one or more directories above it. + + Expects the context object to be an instance of `SDClass` and + will use the `file` property of the instance to open the requested + file/directory with the associated file open mode property. + + Always returns true if the directory traversal hasn't reached the + bottom of the directory hierarchy. + + Returns false once the file has been opened--to prevent the traversal + from descending further. (This may be unnecessary.) + + if (isLastComponent) { + SDClass *p_SD = static_cast(object); + p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode); + if (p_SD->fileOpenMode == FILE_WRITE) { + p_SD->file.seekSet(p_SD->file.fileSize()); + } + // TODO: Return file open result? + return false; + } + return true; + } + */ + + + + boolean callback_remove(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + return SdFile::remove(parentDir, filePathComponent); + } + return true; + } + + boolean callback_rmdir(SdFile& parentDir, const char *filePathComponent, + boolean isLastComponent, void * /* object */) { + if (isLastComponent) { + SdFile f; + if (!f.open(parentDir, filePathComponent, O_READ)) { + return false; + } + return f.rmDir(); + } + return true; + } + + + + /* Implementation of class used to create `SDCard` object. */ + + + + boolean SDClass::begin(uint8_t csPin) { + if (root.isOpen()) { + root.close(); + } + + /* + + Performs the initialisation required by the sdfatlib library. + + Return true if initialization succeeds, false otherwise. + + */ + return card.init(SPI_HALF_SPEED, csPin) && + volume.init(card) && + root.openRoot(volume); + } + + boolean SDClass::begin(uint32_t clock, uint8_t csPin) { + if (root.isOpen()) { + root.close(); + } + + return card.init(SPI_HALF_SPEED, csPin) && + card.setSpiClock(clock) && + volume.init(card) && + root.openRoot(volume); + } + + //call this when a card is removed. It will allow you to insert and initialise a new card. + void SDClass::end() { + root.close(); + } + + // this little helper is used to traverse paths + SdFile SDClass::getParentDir(const char *filepath, int *index) { + // get parent directory + SdFile d1; + SdFile d2; + + d1.openRoot(volume); // start with the mostparent, root! + + // we'll use the pointers to swap between the two objects + SdFile *parent = &d1; + SdFile *subdir = &d2; + + const char *origpath = filepath; + + while (strchr(filepath, '/')) { + + // get rid of leading /'s + if (filepath[0] == '/') { + filepath++; + continue; + } + + if (! strchr(filepath, '/')) { + // it was in the root directory, so leave now + break; + } + + // extract just the name of the next subdirectory + uint8_t idx = strchr(filepath, '/') - filepath; + if (idx > 12) { + idx = 12; // don't let them specify long names + } + char subdirname[13]; + strncpy(subdirname, filepath, idx); + subdirname[idx] = 0; + + // close the subdir (we reuse them) if open + subdir->close(); + if (! subdir->open(parent, subdirname, O_READ)) { + // failed to open one of the subdirectories + return SdFile(); + } + // move forward to the next subdirectory + filepath += idx; + + // we reuse the objects, close it. + parent->close(); + + // swap the pointers + SdFile *t = parent; + parent = subdir; + subdir = t; + } + + *index = (int)(filepath - origpath); + // parent is now the parent directory of the file! + return *parent; + } + + + File SDClass::open(const char *filepath, uint8_t mode) { + /* + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + */ + + int pathidx; + + // do the interactive search + SdFile parentdir = getParentDir(filepath, &pathidx); + // no more subdirs! + + filepath += pathidx; + + if (! filepath[0]) { + // it was the directory itself! + return File(parentdir, "/"); + } + + // Open the file itself + SdFile file; + + // failed to open a subdir! + if (!parentdir.isOpen()) { + return File(); + } + + if (! file.open(parentdir, filepath, mode)) { + return File(); + } + // close the parent + parentdir.close(); + + if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) { + file.seekSet(file.fileSize()); + } + return File(file, filepath); + } + + + /* + File SDClass::open(char *filepath, uint8_t mode) { + // + + Open the supplied file path for reading or writing. + + The file content can be accessed via the `file` property of + the `SDClass` object--this property is currently + a standard `SdFile` object from `sdfatlib`. + + Defaults to read only. + + If `write` is true, default action (when `append` is true) is to + append data to the end of the file. + + If `append` is false then the file will be truncated first. + + If the file does not exist and it is opened for writing the file + will be created. + + An attempt to open a file for reading that does not exist is an + error. + + // + + // TODO: Allow for read&write? (Possibly not, as it requires seek.) + + fileOpenMode = mode; + walkPath(filepath, root, callback_openPath, this); + + return File(); + + } + */ + + + //boolean SDClass::close() { + // /* + // + // Closes the file opened by the `open` method. + // + // */ + // file.close(); + //} + + + boolean SDClass::exists(const char *filepath) { + /* + + Returns true if the supplied file path exists. + + */ + return walkPath(filepath, root, callback_pathExists); + } + + + //boolean SDClass::exists(char *filepath, SdFile& parentDir) { + // /* + // + // Returns true if the supplied file path rooted at `parentDir` + // exists. + // + // */ + // return walkPath(filepath, parentDir, callback_pathExists); + //} + + + boolean SDClass::mkdir(const char *filepath) { + /* + + Makes a single directory or a hierarchy of directories. + + A rough equivalent to `mkdir -p`. + + */ + return walkPath(filepath, root, callback_makeDirPath); + } + + boolean SDClass::rmdir(const char *filepath) { + /* + + Remove a single directory or a hierarchy of directories. + + A rough equivalent to `rm -rf`. + + */ + return walkPath(filepath, root, callback_rmdir); + } + + boolean SDClass::remove(const char *filepath) { + return walkPath(filepath, root, callback_remove); + } + + + // allows you to recurse into a directory + File File::openNextFile(uint8_t mode) { + dir_t p; + + //Serial.print("\t\treading dir..."); + while (_file->readDir(&p) > 0) { + + // done if past last used entry + if (p.name[0] == DIR_NAME_FREE) { + //Serial.println("end"); + return File(); + } + + // skip deleted entry and entries for . and .. + if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') { + //Serial.println("dots"); + continue; + } + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(&p)) { + //Serial.println("notafile"); + continue; + } + + // print file name with possible blank fill + SdFile f; + char name[13]; + _file->dirName(p, name); + //Serial.print("try to open file "); + //Serial.println(name); + + if (f.open(_file, name, mode)) { + //Serial.println("OK!"); + return File(f, name); + } else { + //Serial.println("ugh"); + return File(); + } + } + + //Serial.println("nothing"); + return File(); + } + + void File::rewindDirectory(void) { + if (isDirectory()) { + _file->rewind(); + } + } + + SDClass SD; + +}; diff --git a/libraries/SD/src/SD.h b/libraries/SD/src/SD.h new file mode 100644 index 0000000..fa34ccd --- /dev/null +++ b/libraries/SD/src/SD.h @@ -0,0 +1,138 @@ +/* + + SD - a slightly more friendly wrapper for sdfatlib + + This library aims to expose a subset of SD card functionality + in the form of a higher level "wrapper" object. + + License: GNU General Public License V3 + (Because sdfatlib is licensed with this.) + + (C) Copyright 2010 SparkFun Electronics + +*/ + +#ifndef __SD_H__ +#define __SD_H__ + +#include + +#include "utility/SdFat.h" +#include "utility/SdFatUtil.h" + +#define FILE_READ O_READ +#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND) + +namespace SDLib { + + class File : public Stream { + private: + char _name[13]; // our name + SdFile *_file; // underlying file pointer + + public: + File(SdFile f, const char *name); // wraps an underlying SdFile + File(void); // 'empty' constructor + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int availableForWrite(); + virtual int read(); + virtual int peek(); + virtual int available(); + virtual void flush(); + int read(void *buf, uint16_t nbyte); + boolean seek(uint32_t pos); + uint32_t position(); + uint32_t size(); + void close(); + operator bool(); + char * name(); + + boolean isDirectory(void); + File openNextFile(uint8_t mode = O_RDONLY); + void rewindDirectory(void); + + using Print::write; + }; + + class SDClass { + + private: + // These are required for initialisation and use of sdfatlib + Sd2Card card; + SdVolume volume; + SdFile root; + + // my quick&dirty iterator, should be replaced + SdFile getParentDir(const char *filepath, int *indx); + public: + // This needs to be called to set up the connection to the SD card + // before other methods are used. + boolean begin(uint8_t csPin = SD_CHIP_SELECT_PIN); + boolean begin(uint32_t clock, uint8_t csPin); + + //call this when a card is removed. It will allow you to insert and initialise a new card. + void end(); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + File open(const char *filename, uint8_t mode = FILE_READ); + File open(const String &filename, uint8_t mode = FILE_READ) { + return open(filename.c_str(), mode); + } + + // Methods to determine if the requested file path exists. + boolean exists(const char *filepath); + boolean exists(const String &filepath) { + return exists(filepath.c_str()); + } + + // Create the requested directory heirarchy--if intermediate directories + // do not exist they will be created. + boolean mkdir(const char *filepath); + boolean mkdir(const String &filepath) { + return mkdir(filepath.c_str()); + } + + // Delete the file. + boolean remove(const char *filepath); + boolean remove(const String &filepath) { + return remove(filepath.c_str()); + } + + boolean rmdir(const char *filepath); + boolean rmdir(const String &filepath) { + return rmdir(filepath.c_str()); + } + + private: + + // This is used to determine the mode used to open a file + // it's here because it's the easiest place to pass the + // information through the directory walking function. But + // it's probably not the best place for it. + // It shouldn't be set directly--it is set via the parameters to `open`. + int fileOpenMode; + + friend class File; + friend boolean callback_openPath(SdFile&, const char *, boolean, void *); + }; + + extern SDClass SD; + +}; + +// We enclose File and SD classes in namespace SDLib to avoid conflicts +// with others legacy libraries that redefines File class. + +// This ensure compatibility with sketches that uses only SD library +using namespace SDLib; + +// This allows sketches to use SDLib::File with other libraries (in the +// sketch you must use SDFile instead of File to disambiguate) +typedef SDLib::File SDFile; +typedef SDLib::SDClass SDFileSystemClass; +#define SDFileSystem SDLib::SD + +#endif diff --git a/libraries/SD/src/utility/FatStructs.h b/libraries/SD/src/utility/FatStructs.h new file mode 100644 index 0000000..8cb0980 --- /dev/null +++ b/libraries/SD/src/utility/FatStructs.h @@ -0,0 +1,418 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#ifndef FatStructs_h +#define FatStructs_h +/** + \file + FAT file structures +*/ +/* + mostly from Microsoft document fatgen103.doc + http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx +*/ +//------------------------------------------------------------------------------ +/** Value for byte 510 of boot block or MBR */ +uint8_t const BOOTSIG0 = 0X55; +/** Value for byte 511 of boot block or MBR */ +uint8_t const BOOTSIG1 = 0XAA; +//------------------------------------------------------------------------------ +/** + \struct partitionTable + \brief MBR partition table entry + + A partition table entry for a MBR formatted storage device. + The MBR partition table has four entries. +*/ +struct partitionTable { + /** + Boot Indicator . Indicates whether the volume is the active + partition. Legal values include: 0X00. Do not use for booting. + 0X80 Active partition. + */ + uint8_t boot; + /** + Head part of Cylinder-head-sector address of the first block in + the partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t beginHead; + /** + Sector part of Cylinder-head-sector address of the first block in + the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned beginSector : 6; + /** High bits cylinder for first block in partition. */ + unsigned beginCylinderHigh : 2; + /** + Combine beginCylinderLow with beginCylinderHigh. Legal values + are 0-1023. Only used in old PC BIOS. + */ + uint8_t beginCylinderLow; + /** + Partition type. See defines that begin with PART_TYPE_ for + some Microsoft partition types. + */ + uint8_t type; + /** + head part of cylinder-head-sector address of the last sector in the + partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t endHead; + /** + Sector part of cylinder-head-sector address of the last sector in + the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned endSector : 6; + /** High bits of end cylinder */ + unsigned endCylinderHigh : 2; + /** + Combine endCylinderLow with endCylinderHigh. Legal values + are 0-1023. Only used in old PC BIOS. + */ + uint8_t endCylinderLow; + /** Logical block address of the first block in the partition. */ + uint32_t firstSector; + /** Length of the partition, in blocks. */ + uint32_t totalSectors; +} __attribute__((packed)); +/** Type name for partitionTable */ +typedef struct partitionTable part_t; +//------------------------------------------------------------------------------ +/** + \struct masterBootRecord + + \brief Master Boot Record + + The first block of a storage device that is formatted with a MBR. +*/ +struct masterBootRecord { + /** Code Area for master boot program. */ + uint8_t codeArea[440]; + /** Optional WindowsNT disk signature. May contain more boot code. */ + uint32_t diskSignature; + /** Usually zero but may be more boot code. */ + uint16_t usuallyZero; + /** Partition tables. */ + part_t part[4]; + /** First MBR signature byte. Must be 0X55 */ + uint8_t mbrSig0; + /** Second MBR signature byte. Must be 0XAA */ + uint8_t mbrSig1; +} __attribute__((packed)); +/** Type name for masterBootRecord */ +typedef struct masterBootRecord mbr_t; +//------------------------------------------------------------------------------ +/** + \struct biosParmBlock + + \brief BIOS parameter block + + The BIOS parameter block describes the physical layout of a FAT volume. +*/ +struct biosParmBlock { + /** + Count of bytes per sector. This value may take on only the + following values: 512, 1024, 2048 or 4096 + */ + uint16_t bytesPerSector; + /** + Number of sectors per allocation unit. This value must be a + power of 2 that is greater than 0. The legal values are + 1, 2, 4, 8, 16, 32, 64, and 128. + */ + uint8_t sectorsPerCluster; + /** + Number of sectors before the first FAT. + This value must not be zero. + */ + uint16_t reservedSectorCount; + /** The count of FAT data structures on the volume. This field should + always contain the value 2 for any FAT volume of any type. + */ + uint8_t fatCount; + /** + For FAT12 and FAT16 volumes, this field contains the count of + 32-byte directory entries in the root directory. For FAT32 volumes, + this field must be set to 0. For FAT12 and FAT16 volumes, this + value should always specify a count that when multiplied by 32 + results in a multiple of bytesPerSector. FAT16 volumes should + use the value 512. + */ + uint16_t rootDirEntryCount; + /** + This field is the old 16-bit total count of sectors on the volume. + This count includes the count of all sectors in all four regions + of the volume. This field can be 0; if it is 0, then totalSectors32 + must be non-zero. For FAT32 volumes, this field must be 0. For + FAT12 and FAT16 volumes, this field contains the sector count, and + totalSectors32 is 0 if the total sector count fits + (is less than 0x10000). + */ + uint16_t totalSectors16; + /** + This dates back to the old MS-DOS 1.x media determination and is + no longer usually used for anything. 0xF8 is the standard value + for fixed (non-removable) media. For removable media, 0xF0 is + frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + Count of sectors occupied by one FAT on FAT12/FAT16 volumes. + On FAT32 volumes this field must be 0, and sectorsPerFat32 + contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrtack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + Count of hidden sectors preceding the partition that contains this + FAT volume. This field is generally only relevant for media + visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + This field is the new 32-bit total count of sectors on the volume. + This count includes the count of all sectors in all four regions + of the volume. This field can be 0; if it is 0, then + totalSectors16 must be non-zero. + */ + uint32_t totalSectors32; + /** + Count of sectors occupied by one FAT on FAT32 volumes. + */ + uint32_t sectorsPerFat32; + /** + This field is only defined for FAT32 media and does not exist on + FAT12 and FAT16 media. + Bits 0-3 -- Zero-based number of active FAT. + Only valid if mirroring is disabled. + Bits 4-6 -- Reserved. + Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. + -- 1 means only one FAT is active; it is the one referenced in bits 0-3. + Bits 8-15 -- Reserved. + */ + uint16_t fat32Flags; + /** + FAT32 version. High byte is major revision number. + Low byte is minor revision number. Only 0.0 define. + */ + uint16_t fat32Version; + /** + Cluster number of the first cluster of the root directory for FAT32. + This usually 2 but not required to be 2. + */ + uint32_t fat32RootCluster; + /** + Sector number of FSINFO structure in the reserved area of the + FAT32 volume. Usually 1. + */ + uint16_t fat32FSInfo; + /** + If non-zero, indicates the sector number in the reserved area + of the volume of a copy of the boot record. Usually 6. + No value other than 6 is recommended. + */ + uint16_t fat32BackBootBlock; + /** + Reserved for future expansion. Code that formats FAT32 volumes + should always set all of the bytes of this field to 0. + */ + uint8_t fat32Reserved[12]; +} __attribute__((packed)); +/** Type name for biosParmBlock */ +typedef struct biosParmBlock bpb_t; +//------------------------------------------------------------------------------ +/** + \struct fat32BootSector + + \brief Boot sector for a FAT16 or FAT32 volume. + +*/ +struct fat32BootSector { + /** X86 jmp to boot program */ + uint8_t jmpToBootCode[3]; + /** informational only - don't depend on it */ + char oemName[8]; + /** BIOS Parameter Block */ + bpb_t bpb; + /** for int0x13 use value 0X80 for hard drive */ + uint8_t driveNumber; + /** used by Windows NT - should be zero for FAT */ + uint8_t reserved1; + /** 0X29 if next three fields are valid */ + uint8_t bootSignature; + /** usually generated by combining date and time */ + uint32_t volumeSerialNumber; + /** should match volume label in root dir */ + char volumeLabel[11]; + /** informational only - don't depend on it */ + char fileSystemType[8]; + /** X86 boot code */ + uint8_t bootCode[420]; + /** must be 0X55 */ + uint8_t bootSectorSig0; + /** must be 0XAA */ + uint8_t bootSectorSig1; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// End Of Chain values for FAT entries +/** FAT16 end of chain value used by Microsoft. */ +uint16_t const FAT16EOC = 0XFFFF; +/** Minimum value for FAT16 EOC. Use to test for EOC. */ +uint16_t const FAT16EOC_MIN = 0XFFF8; +/** FAT32 end of chain value used by Microsoft. */ +uint32_t const FAT32EOC = 0X0FFFFFFF; +/** Minimum value for FAT32 EOC. Use to test for EOC. */ +uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; +/** Mask a for FAT32 entry. Entries are 28 bits. */ +uint32_t const FAT32MASK = 0X0FFFFFFF; + +/** Type name for fat32BootSector */ +typedef struct fat32BootSector fbs_t; +//------------------------------------------------------------------------------ +/** + \struct directoryEntry + \brief FAT short directory entry + + Short means short 8.3 name, not the entry size. + + Date Format. A FAT directory entry date stamp is a 16-bit field that is + basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the + format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the + 16-bit word): + + Bits 9-15: Count of years from 1980, valid value range 0-127 + inclusive (1980-2107). + + Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. + + Bits 0-4: Day of month, valid value range 1-31 inclusive. + + Time Format. A FAT directory entry time stamp is a 16-bit field that has + a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the + 16-bit word, bit 15 is the MSB of the 16-bit word). + + Bits 11-15: Hours, valid value range 0-23 inclusive. + + Bits 5-10: Minutes, valid value range 0-59 inclusive. + + Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). + + The valid time range is from Midnight 00:00:00 to 23:59:58. +*/ +struct directoryEntry { + /** + Short 8.3 name. + The first eight bytes contain the file name with blank fill. + The last three bytes contain the file extension with blank fill. + */ + uint8_t name[11]; + /** Entry attributes. + + The upper two bits of the attribute byte are reserved and should + always be set to 0 when a file is created and never modified or + looked at after that. See defines that begin with DIR_ATT_. + */ + uint8_t attributes; + /** + Reserved for use by Windows NT. Set value to 0 when a file is + created and never modify or look at it after that. + */ + uint8_t reservedNT; + /** + The granularity of the seconds part of creationTime is 2 seconds + so this field is a count of tenths of a second and its valid + value range is 0-199 inclusive. (WHG note - seems to be hundredths) + */ + uint8_t creationTimeTenths; + /** Time file was created. */ + uint16_t creationTime; + /** Date file was created. */ + uint16_t creationDate; + /** + Last access date. Note that there is no last access time, only + a date. This is the date of last read or write. In the case of + a write, this should be set to the same date as lastWriteDate. + */ + uint16_t lastAccessDate; + /** + High word of this entry's first cluster number (always 0 for a + FAT12 or FAT16 volume). + */ + uint16_t firstClusterHigh; + /** Time of last write. File creation is considered a write. */ + uint16_t lastWriteTime; + /** Date of last write. File creation is considered a write. */ + uint16_t lastWriteDate; + /** Low word of this entry's first cluster number. */ + uint16_t firstClusterLow; + /** 32-bit unsigned holding this file's size in bytes. */ + uint32_t fileSize; +} __attribute__((packed)); +//------------------------------------------------------------------------------ +// Definitions for directory entries +// +/** Type name for directoryEntry */ +typedef struct directoryEntry dir_t; +/** escape for name[0] = 0XE5 */ +uint8_t const DIR_NAME_0XE5 = 0X05; +/** name[0] value for entry that is free after being "deleted" */ +uint8_t const DIR_NAME_DELETED = 0XE5; +/** name[0] value for entry that is free and no allocated entries follow */ +uint8_t const DIR_NAME_FREE = 0X00; +/** file is read-only */ +uint8_t const DIR_ATT_READ_ONLY = 0X01; +/** File should hidden in directory listings */ +uint8_t const DIR_ATT_HIDDEN = 0X02; +/** Entry is for a system file */ +uint8_t const DIR_ATT_SYSTEM = 0X04; +/** Directory entry contains the volume label */ +uint8_t const DIR_ATT_VOLUME_ID = 0X08; +/** Entry is for a directory */ +uint8_t const DIR_ATT_DIRECTORY = 0X10; +/** Old DOS archive bit for backup support */ +uint8_t const DIR_ATT_ARCHIVE = 0X20; +/** Test value for long name entry. Test is + (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ +uint8_t const DIR_ATT_LONG_NAME = 0X0F; +/** Test mask for long name entry */ +uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; +/** defined attribute bits */ +uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; +/** Directory entry is part of a long name */ +static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { + return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; +} +/** Mask for file/subdirectory tests */ +uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); +/** Directory entry is for a file */ +static inline uint8_t DIR_IS_FILE(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; +} +/** Directory entry is for a subdirectory */ +static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; +} +/** Directory entry is for a file or subdirectory */ +static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; +} +#endif // FatStructs_h diff --git a/libraries/SD/src/utility/Sd2Card.cpp b/libraries/SD/src/utility/Sd2Card.cpp new file mode 100644 index 0000000..fc3d857 --- /dev/null +++ b/libraries/SD/src/utility/Sd2Card.cpp @@ -0,0 +1,777 @@ +/* Arduino Sd2Card Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino Sd2Card Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino Sd2Card Library. If not, see + . +*/ +#define USE_SPI_LIB +#include +#include "Sd2Card.h" +//------------------------------------------------------------------------------ +#ifndef SOFTWARE_SPI +#ifdef USE_SPI_LIB + + #ifndef SDCARD_SPI + #define SDCARD_SPI SPI + #endif + + #include + static SPISettings settings; +#endif +// functions for hardware SPI +/** Send a byte to the card */ +static void spiSend(uint8_t b) { + #ifndef USE_SPI_LIB + SPDR = b; + while (!(SPSR & (1 << SPIF))) + ; + #else + SDCARD_SPI.transfer(b); + #endif +} +/** Receive a byte from the card */ +static uint8_t spiRec(void) { + #ifndef USE_SPI_LIB + spiSend(0XFF); + return SPDR; + #else + return SDCARD_SPI.transfer(0xFF); + #endif +} +#else // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** nop to tune soft SPI timing */ +#define nop asm volatile ("nop\n\t") +//------------------------------------------------------------------------------ +/** Soft SPI receive */ +uint8_t spiRec(void) { + uint8_t data = 0; + // no interrupts during byte receive - about 8 us + cli(); + // output pin high - like sending 0XFF + fastDigitalWrite(SPI_MOSI_PIN, HIGH); + + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, HIGH); + + // adjust so SCK is nice + nop; + nop; + + data <<= 1; + + if (fastDigitalRead(SPI_MISO_PIN)) { + data |= 1; + } + + fastDigitalWrite(SPI_SCK_PIN, LOW); + } + // enable interrupts + sei(); + return data; +} +//------------------------------------------------------------------------------ +/** Soft SPI send */ +void spiSend(uint8_t data) { + // no interrupts during byte send - about 8 us + cli(); + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, LOW); + + fastDigitalWrite(SPI_MOSI_PIN, data & 0X80); + + data <<= 1; + + fastDigitalWrite(SPI_SCK_PIN, HIGH); + } + // hold SCK high for a few ns + nop; + nop; + nop; + nop; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + // enable interrupts + sei(); +} +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +// send command and return error code. Return zero for OK +uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) { + // end read if in partialBlockRead mode + readEnd(); + + // select card + chipSelectLow(); + + // wait up to 300 ms if busy + waitNotBusy(300); + + // send command + spiSend(cmd | 0x40); + + // send argument + for (int8_t s = 24; s >= 0; s -= 8) { + spiSend(arg >> s); + } + + // send CRC + uint8_t crc = 0XFF; + if (cmd == CMD0) { + crc = 0X95; // correct crc for CMD0 with arg 0 + } + if (cmd == CMD8) { + crc = 0X87; // correct crc for CMD8 with arg 0X1AA + } + spiSend(crc); + + // wait for response + for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++) + ; + return status_; +} +//------------------------------------------------------------------------------ +/** + Determine the size of an SD flash memory card. + + \return The number of 512 byte data blocks in the card + or zero if an error occurs. +*/ +uint32_t Sd2Card::cardSize(void) { + csd_t csd; + if (!readCSD(&csd)) { + return 0; + } + if (csd.v1.csd_ver == 0) { + uint8_t read_bl_len = csd.v1.read_bl_len; + uint16_t c_size = (csd.v1.c_size_high << 10) + | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low; + uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1) + | csd.v1.c_size_mult_low; + return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); + } else if (csd.v2.csd_ver == 1) { + uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16) + | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low; + return (c_size + 1) << 10; + } else { + error(SD_CARD_ERROR_BAD_CSD); + return 0; + } +} +//------------------------------------------------------------------------------ +static uint8_t chip_select_asserted = 0; + +void Sd2Card::chipSelectHigh(void) { + digitalWrite(chipSelectPin_, HIGH); + #ifdef USE_SPI_LIB + if (chip_select_asserted) { + chip_select_asserted = 0; + SDCARD_SPI.endTransaction(); + } + #endif +} +//------------------------------------------------------------------------------ +void Sd2Card::chipSelectLow(void) { + #ifdef USE_SPI_LIB + if (!chip_select_asserted) { + chip_select_asserted = 1; + SDCARD_SPI.beginTransaction(settings); + } + #endif + digitalWrite(chipSelectPin_, LOW); +} +//------------------------------------------------------------------------------ +/** Erase a range of blocks. + + \param[in] firstBlock The address of the first block in the range. + \param[in] lastBlock The address of the last block in the range. + + \note This function requests the SD card to do a flash erase for a + range of blocks. The data on the card after an erase operation is + either 0 or 1, depends on the card vendor. The card must support + single block erase. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) { + if (!eraseSingleBlockEnable()) { + error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); + goto fail; + } + if (type_ != SD_CARD_TYPE_SDHC) { + firstBlock <<= 9; + lastBlock <<= 9; + } + if (cardCommand(CMD32, firstBlock) + || cardCommand(CMD33, lastBlock) + || cardCommand(CMD38, 0)) { + error(SD_CARD_ERROR_ERASE); + goto fail; + } + if (!waitNotBusy(SD_ERASE_TIMEOUT)) { + error(SD_CARD_ERROR_ERASE_TIMEOUT); + goto fail; + } + chipSelectHigh(); + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Determine if card supports single block erase. + + \return The value one, true, is returned if single block erase is supported. + The value zero, false, is returned if single block erase is not supported. +*/ +uint8_t Sd2Card::eraseSingleBlockEnable(void) { + csd_t csd; + return readCSD(&csd) ? csd.v1.erase_blk_en : 0; +} +//------------------------------------------------------------------------------ +/** + Initialize an SD flash memory card. + + \param[in] sckRateID SPI clock rate selector. See setSckRate(). + \param[in] chipSelectPin SD chip select pin number. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. The reason for failure + can be determined by calling errorCode() and errorData(). +*/ +uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) { + errorCode_ = inBlock_ = partialBlockRead_ = type_ = 0; + chipSelectPin_ = chipSelectPin; + // 16-bit init start time allows over a minute + unsigned int t0 = millis(); + uint32_t arg; + + // set pin modes + pinMode(chipSelectPin_, OUTPUT); + digitalWrite(chipSelectPin_, HIGH); + #ifndef USE_SPI_LIB + pinMode(SPI_MISO_PIN, INPUT); + pinMode(SPI_MOSI_PIN, OUTPUT); + pinMode(SPI_SCK_PIN, OUTPUT); + #endif + + #ifndef SOFTWARE_SPI + #ifndef USE_SPI_LIB + // SS must be in output mode even it is not chip select + pinMode(SS_PIN, OUTPUT); + digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin + // Enable SPI, Master, clock rate f_osc/128 + SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); + // clear double speed + SPSR &= ~(1 << SPI2X); + #else // USE_SPI_LIB + SDCARD_SPI.begin(); + settings = SPISettings(250000, MSBFIRST, SPI_MODE0); + #endif // USE_SPI_LIB + #endif // SOFTWARE_SPI + + // must supply min of 74 clock cycles with CS high. + #ifdef USE_SPI_LIB + SDCARD_SPI.beginTransaction(settings); + #endif + for (uint8_t i = 0; i < 10; i++) { + spiSend(0XFF); + } + #ifdef USE_SPI_LIB + SDCARD_SPI.endTransaction(); + #endif + + chipSelectLow(); + + // command to go idle in SPI mode + while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { + unsigned int d = millis() - t0; + if (d > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_CMD0); + goto fail; + } + } + // check SD version + if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) { + type(SD_CARD_TYPE_SD1); + } else { + // only need last byte of r7 response + for (uint8_t i = 0; i < 4; i++) { + status_ = spiRec(); + } + if (status_ != 0XAA) { + error(SD_CARD_ERROR_CMD8); + goto fail; + } + type(SD_CARD_TYPE_SD2); + } + // initialize card and send host supports SDHC if SD2 + arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; + + while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) { + // check for timeout + unsigned int d = millis() - t0; + if (d > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_ACMD41); + goto fail; + } + } + // if SD2 read OCR register to check for SDHC card + if (type() == SD_CARD_TYPE_SD2) { + if (cardCommand(CMD58, 0)) { + error(SD_CARD_ERROR_CMD58); + goto fail; + } + if ((spiRec() & 0XC0) == 0XC0) { + type(SD_CARD_TYPE_SDHC); + } + // discard rest of ocr - contains allowed voltage range + for (uint8_t i = 0; i < 3; i++) { + spiRec(); + } + } + chipSelectHigh(); + + #ifndef SOFTWARE_SPI + return setSckRate(sckRateID); + #else // SOFTWARE_SPI + return true; + #endif // SOFTWARE_SPI + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + Enable or disable partial block reads. + + Enabling partial block reads improves performance by allowing a block + to be read over the SPI bus as several sub-blocks. Errors may occur + if the time between reads is too long since the SD card may timeout. + The SPI SS line will be held low until the entire block is read or + readEnd() is called. + + Use this for applications like the Adafruit Wave Shield. + + \param[in] value The value TRUE (non-zero) or FALSE (zero).) +*/ +void Sd2Card::partialBlockRead(uint8_t value) { + readEnd(); + partialBlockRead_ = value; +} +//------------------------------------------------------------------------------ +/** + Read a 512 byte block from an SD card device. + + \param[in] block Logical block to be read. + \param[out] dst Pointer to the location that will receive the data. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::readBlock(uint32_t block, uint8_t* dst) { + return readData(block, 0, 512, dst); +} +//------------------------------------------------------------------------------ +/** + Read part of a 512 byte block from an SD card. + + \param[in] block Logical block to be read. + \param[in] offset Number of bytes to skip at start of block + \param[out] dst Pointer to the location that will receive the data. + \param[in] count Number of bytes to read + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst) { + if (count == 0) { + return true; + } + if ((count + offset) > 512) { + goto fail; + } + if (!inBlock_ || block != block_ || offset < offset_) { + block_ = block; + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + block <<= 9; + } + if (cardCommand(CMD17, block)) { + error(SD_CARD_ERROR_CMD17); + goto fail; + } + if (!waitStartBlock()) { + goto fail; + } + offset_ = 0; + inBlock_ = 1; + } + + #ifdef OPTIMIZE_HARDWARE_SPI + // start first spi transfer + SPDR = 0XFF; + + // skip data before offset + for (; offset_ < offset; offset_++) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // transfer data + n = count - 1; + for (uint16_t i = 0; i < n; i++) { + while (!(SPSR & (1 << SPIF))) + ; + dst[i] = SPDR; + SPDR = 0XFF; + } + // wait for last byte + while (!(SPSR & (1 << SPIF))) + ; + dst[n] = SPDR; + + #else // OPTIMIZE_HARDWARE_SPI + + // skip data before offset + for (; offset_ < offset; offset_++) { + spiRec(); + } + // transfer data + for (uint16_t i = 0; i < count; i++) { + dst[i] = spiRec(); + } + #endif // OPTIMIZE_HARDWARE_SPI + + offset_ += count; + if (!partialBlockRead_ || offset_ >= 512) { + // read rest of data, checksum and set chip select high + readEnd(); + } + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Skip remaining data in a block when in partial block read mode. */ +void Sd2Card::readEnd(void) { + if (inBlock_) { + // skip data and crc + #ifdef OPTIMIZE_HARDWARE_SPI + // optimize skip for hardware + SPDR = 0XFF; + while (offset_++ < 513) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = 0XFF; + } + // wait for last crc byte + while (!(SPSR & (1 << SPIF))) + ; + #else // OPTIMIZE_HARDWARE_SPI + while (offset_++ < 514) { + spiRec(); + } + #endif // OPTIMIZE_HARDWARE_SPI + chipSelectHigh(); + inBlock_ = 0; + } +} +//------------------------------------------------------------------------------ +/** read CID or CSR register */ +uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) { + uint8_t* dst = reinterpret_cast(buf); + if (cardCommand(cmd, 0)) { + error(SD_CARD_ERROR_READ_REG); + goto fail; + } + if (!waitStartBlock()) { + goto fail; + } + // transfer data + for (uint16_t i = 0; i < 16; i++) { + dst[i] = spiRec(); + } + spiRec(); // get first crc byte + spiRec(); // get second crc byte + chipSelectHigh(); + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + Set the SPI clock rate. + + \param[in] sckRateID A value in the range [0, 6]. + + The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum + SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128 + for \a scsRateID = 6. + + \return The value one, true, is returned for success and the value zero, + false, is returned for an invalid value of \a sckRateID. +*/ +uint8_t Sd2Card::setSckRate(uint8_t sckRateID) { + if (sckRateID > 6) { + error(SD_CARD_ERROR_SCK_RATE); + return false; + } + #ifndef USE_SPI_LIB + // see avr processor datasheet for SPI register bit definitions + if ((sckRateID & 1) || sckRateID == 6) { + SPSR &= ~(1 << SPI2X); + } else { + SPSR |= (1 << SPI2X); + } + SPCR &= ~((1 << SPR1) | (1 << SPR0)); + SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0) + | (sckRateID & 2 ? (1 << SPR0) : 0); + #else // USE_SPI_LIB + switch (sckRateID) { + case 0: settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break; + case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break; + case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break; + case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break; + case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break; + case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break; + default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0); + } + #endif // USE_SPI_LIB + return true; +} +#ifdef USE_SPI_LIB +//------------------------------------------------------------------------------ +// set the SPI clock frequency +uint8_t Sd2Card::setSpiClock(uint32_t clock) { + settings = SPISettings(clock, MSBFIRST, SPI_MODE0); + return true; +} +#endif +//------------------------------------------------------------------------------ +// wait for card to go not busy +uint8_t Sd2Card::waitNotBusy(unsigned int timeoutMillis) { + unsigned int t0 = millis(); + unsigned int d; + do { + if (spiRec() == 0XFF) { + return true; + } + d = millis() - t0; + } while (d < timeoutMillis); + return false; +} +//------------------------------------------------------------------------------ +/** Wait for start block token */ +uint8_t Sd2Card::waitStartBlock(void) { + unsigned int t0 = millis(); + while ((status_ = spiRec()) == 0XFF) { + unsigned int d = millis() - t0; + if (d > SD_READ_TIMEOUT) { + error(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + if (status_ != DATA_START_BLOCK) { + error(SD_CARD_ERROR_READ); + goto fail; + } + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + Writes a 512 byte block to an SD card. + + \param[in] blockNumber Logical block to be written. + \param[in] src Pointer to the location of the data to be written. + \param[in] blocking If the write should be blocking. + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src, uint8_t blocking) { + #if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } + #endif // SD_PROTECT_BLOCK_ZERO + + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD24, blockNumber)) { + error(SD_CARD_ERROR_CMD24); + goto fail; + } + if (!writeData(DATA_START_BLOCK, src)) { + goto fail; + } + if (blocking) { + // wait for flash programming to complete + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_TIMEOUT); + goto fail; + } + // response is r2 so get and check two bytes for nonzero + if (cardCommand(CMD13, 0) || spiRec()) { + error(SD_CARD_ERROR_WRITE_PROGRAMMING); + goto fail; + } + } + chipSelectHigh(); + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Write one data block in a multiple block write sequence */ +uint8_t Sd2Card::writeData(const uint8_t* src) { + // wait for previous write to finish + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_MULTIPLE); + chipSelectHigh(); + return false; + } + return writeData(WRITE_MULTIPLE_TOKEN, src); +} +//------------------------------------------------------------------------------ +// send one block of data for write block or write multiple blocks +uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) { + #ifdef OPTIMIZE_HARDWARE_SPI + + // send data - optimized loop + SPDR = token; + + // send two byte per iteration + for (uint16_t i = 0; i < 512; i += 2) { + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i]; + while (!(SPSR & (1 << SPIF))) + ; + SPDR = src[i + 1]; + } + + // wait for last data byte + while (!(SPSR & (1 << SPIF))) + ; + + #else // OPTIMIZE_HARDWARE_SPI + spiSend(token); + for (uint16_t i = 0; i < 512; i++) { + spiSend(src[i]); + } + #endif // OPTIMIZE_HARDWARE_SPI + spiSend(0xff); // dummy crc + spiSend(0xff); // dummy crc + + status_ = spiRec(); + if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { + error(SD_CARD_ERROR_WRITE); + chipSelectHigh(); + return false; + } + return true; +} +//------------------------------------------------------------------------------ +/** Start a write multiple blocks sequence. + + \param[in] blockNumber Address of first block in sequence. + \param[in] eraseCount The number of blocks to be pre-erased. + + \note This function is used with writeData() and writeStop() + for optimized multiple block writes. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) { + #if SD_PROTECT_BLOCK_ZERO + // don't allow write to first block + if (blockNumber == 0) { + error(SD_CARD_ERROR_WRITE_BLOCK_ZERO); + goto fail; + } + #endif // SD_PROTECT_BLOCK_ZERO + // send pre-erase count + if (cardAcmd(ACMD23, eraseCount)) { + error(SD_CARD_ERROR_ACMD23); + goto fail; + } + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) { + blockNumber <<= 9; + } + if (cardCommand(CMD25, blockNumber)) { + error(SD_CARD_ERROR_CMD25); + goto fail; + } + return true; + +fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** End a write multiple blocks sequence. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t Sd2Card::writeStop(void) { + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + goto fail; + } + spiSend(STOP_TRAN_TOKEN); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + goto fail; + } + chipSelectHigh(); + return true; + +fail: + error(SD_CARD_ERROR_STOP_TRAN); + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Check if the SD card is busy + + \return The value one, true, is returned when is busy and + the value zero, false, is returned for when is NOT busy. +*/ +uint8_t Sd2Card::isBusy(void) { + chipSelectLow(); + byte b = spiRec(); + chipSelectHigh(); + + return (b != 0XFF); +} diff --git a/libraries/SD/src/utility/Sd2Card.h b/libraries/SD/src/utility/Sd2Card.h new file mode 100644 index 0000000..59ec95b --- /dev/null +++ b/libraries/SD/src/utility/Sd2Card.h @@ -0,0 +1,273 @@ +/* Arduino Sd2Card Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino Sd2Card Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino Sd2Card Library. If not, see + . +*/ +#ifndef Sd2Card_h +#define Sd2Card_h +/** + \file + Sd2Card class +*/ +#include "Sd2PinMap.h" +#include "SdInfo.h" +/** Set SCK to max rate of F_CPU/2. See Sd2Card::setSckRate(). */ +uint8_t const SPI_FULL_SPEED = 0; +/** Set SCK rate to F_CPU/4. See Sd2Card::setSckRate(). */ +uint8_t const SPI_HALF_SPEED = 1; +/** Set SCK rate to F_CPU/8. Sd2Card::setSckRate(). */ +uint8_t const SPI_QUARTER_SPEED = 2; +/** + USE_SPI_LIB: if set, use the SPI library bundled with Arduino IDE, otherwise + run with a standalone driver for AVR. +*/ +#define USE_SPI_LIB +/** + Define MEGA_SOFT_SPI non-zero to use software SPI on Mega Arduinos. + Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. + + MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used + on Mega Arduinos. Software SPI works well with GPS Shield V1.1 + but many SD cards will fail with GPS Shield V1.0. +*/ +#define MEGA_SOFT_SPI 0 +//------------------------------------------------------------------------------ +#if MEGA_SOFT_SPI && (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__)) + #define SOFTWARE_SPI +#endif // MEGA_SOFT_SPI +//------------------------------------------------------------------------------ +// SPI pin definitions +// +#ifndef SOFTWARE_SPI + // hardware pin defs + + // include pins_arduino.h or variant.h depending on architecture, via Arduino.h + #include + + /** + SD Chip Select pin + + Warning if this pin is redefined the hardware SS will pin will be enabled + as an output by init(). An avr processor will not function as an SPI + master unless SS is set to output mode. + */ + #ifndef SDCARD_SS_PIN + /** The default chip select pin for the SD card is SS. */ + uint8_t const SD_CHIP_SELECT_PIN = SS; + #else + uint8_t const SD_CHIP_SELECT_PIN = SDCARD_SS_PIN; + #endif + + // The following three pins must not be redefined for hardware SPI, + // so ensure that they are taken from pins_arduino.h or variant.h, depending on architecture. + #ifndef SDCARD_MOSI_PIN + /** SPI Master Out Slave In pin */ + uint8_t const SPI_MOSI_PIN = MOSI; + /** SPI Master In Slave Out pin */ + uint8_t const SPI_MISO_PIN = MISO; + /** SPI Clock pin */ + uint8_t const SPI_SCK_PIN = SCK; + #else + uint8_t const SPI_MOSI_PIN = SDCARD_MOSI_PIN; + uint8_t const SPI_MISO_PIN = SDCARD_MISO_PIN; + uint8_t const SPI_SCK_PIN = SDCARD_SCK_PIN; + #endif + + /** optimize loops for hardware SPI */ + #ifndef USE_SPI_LIB + #define OPTIMIZE_HARDWARE_SPI + #endif + +#else // SOFTWARE_SPI + // define software SPI pins so Mega can use unmodified GPS Shield + /** SPI chip select pin */ + uint8_t const SD_CHIP_SELECT_PIN = 10; + /** SPI Master Out Slave In pin */ + uint8_t const SPI_MOSI_PIN = 11; + /** SPI Master In Slave Out pin */ + uint8_t const SPI_MISO_PIN = 12; + /** SPI Clock pin */ + uint8_t const SPI_SCK_PIN = 13; +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** Protect block zero from write if nonzero */ +#define SD_PROTECT_BLOCK_ZERO 1 +/** init timeout ms */ +unsigned int const SD_INIT_TIMEOUT = 2000; +/** erase timeout ms */ +unsigned int const SD_ERASE_TIMEOUT = 10000; +/** read timeout ms */ +unsigned int const SD_READ_TIMEOUT = 300; +/** write time out ms */ +unsigned int const SD_WRITE_TIMEOUT = 600; +//------------------------------------------------------------------------------ +// SD card errors +/** timeout error for command CMD0 */ +uint8_t const SD_CARD_ERROR_CMD0 = 0X1; +/** CMD8 was not accepted - not a valid SD card*/ +uint8_t const SD_CARD_ERROR_CMD8 = 0X2; +/** card returned an error response for CMD17 (read block) */ +uint8_t const SD_CARD_ERROR_CMD17 = 0X3; +/** card returned an error response for CMD24 (write block) */ +uint8_t const SD_CARD_ERROR_CMD24 = 0X4; +/** WRITE_MULTIPLE_BLOCKS command failed */ +uint8_t const SD_CARD_ERROR_CMD25 = 0X05; +/** card returned an error response for CMD58 (read OCR) */ +uint8_t const SD_CARD_ERROR_CMD58 = 0X06; +/** SET_WR_BLK_ERASE_COUNT failed */ +uint8_t const SD_CARD_ERROR_ACMD23 = 0X07; +/** card's ACMD41 initialization process timeout */ +uint8_t const SD_CARD_ERROR_ACMD41 = 0X08; +/** card returned a bad CSR version field */ +uint8_t const SD_CARD_ERROR_BAD_CSD = 0X09; +/** erase block group command failed */ +uint8_t const SD_CARD_ERROR_ERASE = 0X0A; +/** card not capable of single block erase */ +uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0X0B; +/** Erase sequence timed out */ +uint8_t const SD_CARD_ERROR_ERASE_TIMEOUT = 0X0C; +/** card returned an error token instead of read data */ +uint8_t const SD_CARD_ERROR_READ = 0X0D; +/** read CID or CSD failed */ +uint8_t const SD_CARD_ERROR_READ_REG = 0X0E; +/** timeout while waiting for start of read data */ +uint8_t const SD_CARD_ERROR_READ_TIMEOUT = 0X0F; +/** card did not accept STOP_TRAN_TOKEN */ +uint8_t const SD_CARD_ERROR_STOP_TRAN = 0X10; +/** card returned an error token as a response to a write operation */ +uint8_t const SD_CARD_ERROR_WRITE = 0X11; +/** attempt to write protected block zero */ +uint8_t const SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0X12; +/** card did not go ready for a multiple block write */ +uint8_t const SD_CARD_ERROR_WRITE_MULTIPLE = 0X13; +/** card returned an error to a CMD13 status check after a write */ +uint8_t const SD_CARD_ERROR_WRITE_PROGRAMMING = 0X14; +/** timeout occurred during write programming */ +uint8_t const SD_CARD_ERROR_WRITE_TIMEOUT = 0X15; +/** incorrect rate selected */ +uint8_t const SD_CARD_ERROR_SCK_RATE = 0X16; +//------------------------------------------------------------------------------ +// card types +/** Standard capacity V1 SD card */ +uint8_t const SD_CARD_TYPE_SD1 = 1; +/** Standard capacity V2 SD card */ +uint8_t const SD_CARD_TYPE_SD2 = 2; +/** High Capacity SD card */ +uint8_t const SD_CARD_TYPE_SDHC = 3; +//------------------------------------------------------------------------------ +/** + \class Sd2Card + \brief Raw access to SD and SDHC flash memory cards. +*/ +class Sd2Card { + public: + /** Construct an instance of Sd2Card. */ + Sd2Card(void) : errorCode_(0), inBlock_(0), partialBlockRead_(0), type_(0) {} + uint32_t cardSize(void); + uint8_t erase(uint32_t firstBlock, uint32_t lastBlock); + uint8_t eraseSingleBlockEnable(void); + /** + \return error code for last error. See Sd2Card.h for a list of error codes. + */ + uint8_t errorCode(void) const { + return errorCode_; + } + /** \return error data for last error. */ + uint8_t errorData(void) const { + return status_; + } + /** + Initialize an SD flash memory card with default clock rate and chip + select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(void) { + return init(SPI_FULL_SPEED, SD_CHIP_SELECT_PIN); + } + /** + Initialize an SD flash memory card with the selected SPI clock rate + and the default SD chip select pin. + See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + */ + uint8_t init(uint8_t sckRateID) { + return init(sckRateID, SD_CHIP_SELECT_PIN); + } + uint8_t init(uint8_t sckRateID, uint8_t chipSelectPin); + void partialBlockRead(uint8_t value); + /** Returns the current value, true or false, for partial block read. */ + uint8_t partialBlockRead(void) const { + return partialBlockRead_; + } + uint8_t readBlock(uint32_t block, uint8_t* dst); + uint8_t readData(uint32_t block, + uint16_t offset, uint16_t count, uint8_t* dst); + /** + Read a cards CID register. The CID contains card identification + information such as Manufacturer ID, Product name, Product serial + number and Manufacturing date. */ + uint8_t readCID(cid_t* cid) { + return readRegister(CMD10, cid); + } + /** + Read a cards CSD register. The CSD contains Card-Specific Data that + provides information regarding access to the card's contents. */ + uint8_t readCSD(csd_t* csd) { + return readRegister(CMD9, csd); + } + void readEnd(void); + uint8_t setSckRate(uint8_t sckRateID); + #ifdef USE_SPI_LIB + uint8_t setSpiClock(uint32_t clock); + #endif + /** Return the card type: SD V1, SD V2 or SDHC */ + uint8_t type(void) const { + return type_; + } + uint8_t writeBlock(uint32_t blockNumber, const uint8_t* src, uint8_t blocking = 1); + uint8_t writeData(const uint8_t* src); + uint8_t writeStart(uint32_t blockNumber, uint32_t eraseCount); + uint8_t writeStop(void); + uint8_t isBusy(void); + private: + uint32_t block_; + uint8_t chipSelectPin_; + uint8_t errorCode_; + uint8_t inBlock_; + uint16_t offset_; + uint8_t partialBlockRead_; + uint8_t status_; + uint8_t type_; + // private functions + uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { + cardCommand(CMD55, 0); + return cardCommand(cmd, arg); + } + uint8_t cardCommand(uint8_t cmd, uint32_t arg); + void error(uint8_t code) { + errorCode_ = code; + } + uint8_t readRegister(uint8_t cmd, void* buf); + uint8_t sendWriteCommand(uint32_t blockNumber, uint32_t eraseCount); + void chipSelectHigh(void); + void chipSelectLow(void); + void type(uint8_t value) { + type_ = value; + } + uint8_t waitNotBusy(unsigned int timeoutMillis); + uint8_t writeData(uint8_t token, const uint8_t* src); + uint8_t waitStartBlock(void); +}; +#endif // Sd2Card_h diff --git a/libraries/SD/src/utility/Sd2PinMap.h b/libraries/SD/src/utility/Sd2PinMap.h new file mode 100644 index 0000000..a07fcca --- /dev/null +++ b/libraries/SD/src/utility/Sd2PinMap.h @@ -0,0 +1,525 @@ +/* Arduino SdFat Library + Copyright (C) 2010 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#if defined(__arm__) // Arduino Due Board follows + +#ifndef Sd2PinMap_h + #define Sd2PinMap_h + + #include + + uint8_t const SS_PIN = SS; + uint8_t const MOSI_PIN = MOSI; + uint8_t const MISO_PIN = MISO; + uint8_t const SCK_PIN = SCK; + +#endif // Sd2PinMap_h + +#elif defined(__AVR_ATmega4809__) // Arduino UNO WiFI Rev2 follows + +#ifndef Sd2PinMap_h + #define Sd2PinMap_h + + #include + + uint8_t const SS_PIN = SS; + uint8_t const MOSI_PIN = MOSI; + uint8_t const MISO_PIN = MISO; + uint8_t const SCK_PIN = SCK; + +#endif // Sd2PinMap_h + +#elif defined(__AVR__) // Other AVR based Boards follows + +// Warning this file was generated by a program. +#ifndef Sd2PinMap_h +#define Sd2PinMap_h +#include + +//------------------------------------------------------------------------------ +/** struct for mapping digital pins */ +struct pin_map_t { + volatile uint8_t* ddr; + volatile uint8_t* pin; + volatile uint8_t* port; + uint8_t bit; +}; +//------------------------------------------------------------------------------ +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// Mega + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 53; +uint8_t const MOSI_PIN = 51; +uint8_t const MISO_PIN = 50; +uint8_t const SCK_PIN = 52; + +static const pin_map_t digitalPinMap[] = { + {&DDRE, &PINE, &PORTE, 0}, // E0 0 + {&DDRE, &PINE, &PORTE, 1}, // E1 1 + {&DDRE, &PINE, &PORTE, 4}, // E4 2 + {&DDRE, &PINE, &PORTE, 5}, // E5 3 + {&DDRG, &PING, &PORTG, 5}, // G5 4 + {&DDRE, &PINE, &PORTE, 3}, // E3 5 + {&DDRH, &PINH, &PORTH, 3}, // H3 6 + {&DDRH, &PINH, &PORTH, 4}, // H4 7 + {&DDRH, &PINH, &PORTH, 5}, // H5 8 + {&DDRH, &PINH, &PORTH, 6}, // H6 9 + {&DDRB, &PINB, &PORTB, 4}, // B4 10 + {&DDRB, &PINB, &PORTB, 5}, // B5 11 + {&DDRB, &PINB, &PORTB, 6}, // B6 12 + {&DDRB, &PINB, &PORTB, 7}, // B7 13 + {&DDRJ, &PINJ, &PORTJ, 1}, // J1 14 + {&DDRJ, &PINJ, &PORTJ, 0}, // J0 15 + {&DDRH, &PINH, &PORTH, 1}, // H1 16 + {&DDRH, &PINH, &PORTH, 0}, // H0 17 + {&DDRD, &PIND, &PORTD, 3}, // D3 18 + {&DDRD, &PIND, &PORTD, 2}, // D2 19 + {&DDRD, &PIND, &PORTD, 1}, // D1 20 + {&DDRD, &PIND, &PORTD, 0}, // D0 21 + {&DDRA, &PINA, &PORTA, 0}, // A0 22 + {&DDRA, &PINA, &PORTA, 1}, // A1 23 + {&DDRA, &PINA, &PORTA, 2}, // A2 24 + {&DDRA, &PINA, &PORTA, 3}, // A3 25 + {&DDRA, &PINA, &PORTA, 4}, // A4 26 + {&DDRA, &PINA, &PORTA, 5}, // A5 27 + {&DDRA, &PINA, &PORTA, 6}, // A6 28 + {&DDRA, &PINA, &PORTA, 7}, // A7 29 + {&DDRC, &PINC, &PORTC, 7}, // C7 30 + {&DDRC, &PINC, &PORTC, 6}, // C6 31 + {&DDRC, &PINC, &PORTC, 5}, // C5 32 + {&DDRC, &PINC, &PORTC, 4}, // C4 33 + {&DDRC, &PINC, &PORTC, 3}, // C3 34 + {&DDRC, &PINC, &PORTC, 2}, // C2 35 + {&DDRC, &PINC, &PORTC, 1}, // C1 36 + {&DDRC, &PINC, &PORTC, 0}, // C0 37 + {&DDRD, &PIND, &PORTD, 7}, // D7 38 + {&DDRG, &PING, &PORTG, 2}, // G2 39 + {&DDRG, &PING, &PORTG, 1}, // G1 40 + {&DDRG, &PING, &PORTG, 0}, // G0 41 + {&DDRL, &PINL, &PORTL, 7}, // L7 42 + {&DDRL, &PINL, &PORTL, 6}, // L6 43 + {&DDRL, &PINL, &PORTL, 5}, // L5 44 + {&DDRL, &PINL, &PORTL, 4}, // L4 45 + {&DDRL, &PINL, &PORTL, 3}, // L3 46 + {&DDRL, &PINL, &PORTL, 2}, // L2 47 + {&DDRL, &PINL, &PORTL, 1}, // L1 48 + {&DDRL, &PINL, &PORTL, 0}, // L0 49 + {&DDRB, &PINB, &PORTB, 3}, // B3 50 + {&DDRB, &PINB, &PORTB, 2}, // B2 51 + {&DDRB, &PINB, &PORTB, 1}, // B1 52 + {&DDRB, &PINB, &PORTB, 0}, // B0 53 + {&DDRF, &PINF, &PORTF, 0}, // F0 54 + {&DDRF, &PINF, &PORTF, 1}, // F1 55 + {&DDRF, &PINF, &PORTF, 2}, // F2 56 + {&DDRF, &PINF, &PORTF, 3}, // F3 57 + {&DDRF, &PINF, &PORTF, 4}, // F4 58 + {&DDRF, &PINF, &PORTF, 5}, // F5 59 + {&DDRF, &PINF, &PORTF, 6}, // F6 60 + {&DDRF, &PINF, &PORTF, 7}, // F7 61 + {&DDRK, &PINK, &PORTK, 0}, // K0 62 + {&DDRK, &PINK, &PORTK, 1}, // K1 63 + {&DDRK, &PINK, &PORTK, 2}, // K2 64 + {&DDRK, &PINK, &PORTK, 3}, // K3 65 + {&DDRK, &PINK, &PORTK, 4}, // K4 66 + {&DDRK, &PINK, &PORTK, 5}, // K5 67 + {&DDRK, &PINK, &PORTK, 6}, // K6 68 + {&DDRK, &PINK, &PORTK, 7} // K7 69 +}; +//------------------------------------------------------------------------------ +#elif (defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)) && defined(CORE_MICRODUINO) +// Microduino Core+ + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; +uint8_t const SCL_PIN = 21; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 PD0 + {&DDRD, &PIND, &PORTD, 1}, // D1 PD1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINB, &PORTB, 0}, // D4 PB0 + {&DDRB, &PINB, &PORTB, 1}, // D5 PB1 + {&DDRB, &PINB, &PORTB, 2}, // D6 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D7 PB3 + {&DDRD, &PIND, &PORTD, 6}, // D8 PD6 + {&DDRD, &PIND, &PORTD, 5}, // D9 PD5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 5}, // D11 PB5 + {&DDRB, &PINB, &PORTB, 6}, // D12 PB6 + {&DDRB, &PINB, &PORTB, 7}, // D13 PB7 + {&DDRC, &PINC, &PORTC, 7}, // D14 PC7 + {&DDRC, &PINC, &PORTC, 6}, // D15 PC6 + {&DDRC, &PINC, &PORTC, 5}, // D16 PC5 + {&DDRC, &PINC, &PORTC, 4}, // D17 PC4 + {&DDRC, &PINC, &PORTC, 3}, // D18 PC3 + {&DDRC, &PINC, &PORTC, 2}, // D19 PC2 + {&DDRC, &PINC, &PORTC, 1}, // D20 PC1 + {&DDRC, &PINC, &PORTC, 0}, // D21 PC0 + {&DDRD, &PIND, &PORTD, 4}, // D22 PD4 + {&DDRD, &PIND, &PORTD, 7}, // D23 PD7 + {&DDRA, &PINA, &PORTA, 7}, // D24 PA7 + {&DDRA, &PINA, &PORTA, 6}, // D25 PA6 + {&DDRA, &PINA, &PORTA, 5}, // D26 PA5 + {&DDRA, &PINA, &PORTA, 4}, // D27 PA4 + {&DDRA, &PINA, &PORTA, 3}, // D28 PA3 + {&DDRA, &PINA, &PORTA, 2}, // D29 PA2 + {&DDRA, &PINA, &PORTA, 1}, // D30 PA1 + {&DDRA, &PINA, &PORTA, 0} // D31 PA0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega128RFA1__) && defined(CORE_MICRODUINO) +// Microduino Core RF + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PINE, &PORTE, 0}, // D0 PE0 + {&DDRD, &PINE, &PORTE, 1}, // D1 PE1 + {&DDRD, &PIND, &PORTD, 2}, // D2 PD2 + {&DDRD, &PIND, &PORTD, 3}, // D3 PD3 + {&DDRB, &PINE, &PORTE, 3}, // D4 PE3 + {&DDRB, &PINE, &PORTE, 4}, // D5 PE4 + {&DDRB, &PINE, &PORTE, 5}, // D6 PE5 + {&DDRB, &PINB, &PORTB, 7}, // D7 PB7 + {&DDRD, &PINB, &PORTB, 6}, // D8 PB6 + {&DDRD, &PINB, &PORTB, 5}, // D9 PB5 + {&DDRB, &PINB, &PORTB, 4}, // D10 PB4 + {&DDRB, &PINB, &PORTB, 2}, // D11 PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 PD0 + {&DDRF, &PINF, &PORTF, 3}, // D20 PF3 + {&DDRF, &PINF, &PORTF, 2}, // D21 PF2 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) && defined(CORE_MICRODUINO) +// Microduino Core USB + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D0 - PD2 + {&DDRD, &PIND, &PORTD, 3}, // D1 - PD3 + {&DDRE, &PINE, &PORTE, 6}, // D2 - PE6 + {&DDRD, &PIND, &PORTD, 6}, // D3 - PD6 + {&DDRD, &PIND, &PORTD, 7}, // D4 - PD7 + {&DDRC, &PINC, &PORTC, 6}, // D5 - PC6 + {&DDRC, &PINC, &PORTC, 7}, // D6 - PC7 + {&DDRE, &PINE, &PORTE, 7}, // D7 - PE7 + {&DDRB, &PINB, &PORTB, 6}, // D8 - PB6 + {&DDRB, &PINB, &PORTB, 5}, // D9 - PB5 + {&DDRB, &PINB, &PORTB, 0}, // D10 - PB0 + {&DDRB, &PINB, &PORTB, 2}, // D11 - MOSI - PB2 + {&DDRB, &PINB, &PORTB, 3}, // D12 -MISO - PB3 + {&DDRB, &PINB, &PORTB, 1}, // D13 -SCK - PB1 + {&DDRF, &PINF, &PORTF, 7}, // D14 - A0 - PF7 + {&DDRF, &PINF, &PORTF, 6}, // D15 - A1 - PF6 + {&DDRF, &PINF, &PORTF, 5}, // D16 - A2 - PF5 + {&DDRF, &PINF, &PORTF, 4}, // D17 - A3 - PF4 + {&DDRD, &PIND, &PORTD, 1}, // D18 - PD1 + {&DDRD, &PIND, &PORTD, 0}, // D19 - PD0 + {&DDRF, &PINF, &PORTF, 1}, // D20 - A6 - PF1 + {&DDRF, &PINF, &PORTF, 0}, // D21 - A7 - PF0 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +// Sanguino + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 17; +uint8_t const SCL_PIN = 18; + +// SPI port +uint8_t const SS_PIN = 4; +uint8_t const MOSI_PIN = 5; +uint8_t const MISO_PIN = 6; +uint8_t const SCK_PIN = 7; + +static const pin_map_t digitalPinMap[] = { + {&DDRB, &PINB, &PORTB, 0}, // B0 0 + {&DDRB, &PINB, &PORTB, 1}, // B1 1 + {&DDRB, &PINB, &PORTB, 2}, // B2 2 + {&DDRB, &PINB, &PORTB, 3}, // B3 3 + {&DDRB, &PINB, &PORTB, 4}, // B4 4 + {&DDRB, &PINB, &PORTB, 5}, // B5 5 + {&DDRB, &PINB, &PORTB, 6}, // B6 6 + {&DDRB, &PINB, &PORTB, 7}, // B7 7 + {&DDRD, &PIND, &PORTD, 0}, // D0 8 + {&DDRD, &PIND, &PORTD, 1}, // D1 9 + {&DDRD, &PIND, &PORTD, 2}, // D2 10 + {&DDRD, &PIND, &PORTD, 3}, // D3 11 + {&DDRD, &PIND, &PORTD, 4}, // D4 12 + {&DDRD, &PIND, &PORTD, 5}, // D5 13 + {&DDRD, &PIND, &PORTD, 6}, // D6 14 + {&DDRD, &PIND, &PORTD, 7}, // D7 15 + {&DDRC, &PINC, &PORTC, 0}, // C0 16 + {&DDRC, &PINC, &PORTC, 1}, // C1 17 + {&DDRC, &PINC, &PORTC, 2}, // C2 18 + {&DDRC, &PINC, &PORTC, 3}, // C3 19 + {&DDRC, &PINC, &PORTC, 4}, // C4 20 + {&DDRC, &PINC, &PORTC, 5}, // C5 21 + {&DDRC, &PINC, &PORTC, 6}, // C6 22 + {&DDRC, &PINC, &PORTC, 7}, // C7 23 + {&DDRA, &PINA, &PORTA, 7}, // A7 24 + {&DDRA, &PINA, &PORTA, 6}, // A6 25 + {&DDRA, &PINA, &PORTA, 5}, // A5 26 + {&DDRA, &PINA, &PORTA, 4}, // A4 27 + {&DDRA, &PINA, &PORTA, 3}, // A3 28 + {&DDRA, &PINA, &PORTA, 2}, // A2 29 + {&DDRA, &PINA, &PORTA, 1}, // A1 30 + {&DDRA, &PINA, &PORTA, 0} // A0 31 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) +// Leonardo + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 2; +uint8_t const SCL_PIN = 3; + +// SPI port +uint8_t const SS_PIN = 17; +uint8_t const MOSI_PIN = 16; +uint8_t const MISO_PIN = 14; +uint8_t const SCK_PIN = 15; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 2}, // D2 0 + {&DDRD, &PIND, &PORTD, 3}, // D3 1 + {&DDRD, &PIND, &PORTD, 1}, // D1 2 + {&DDRD, &PIND, &PORTD, 0}, // D0 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRC, &PINC, &PORTC, 6}, // C6 5 + {&DDRD, &PIND, &PORTD, 7}, // D7 6 + {&DDRE, &PINE, &PORTE, 6}, // E6 7 + {&DDRB, &PINB, &PORTB, 4}, // B4 8 + {&DDRB, &PINB, &PORTB, 5}, // B5 9 + {&DDRB, &PINB, &PORTB, 6}, // B6 10 + {&DDRB, &PINB, &PORTB, 7}, // B7 11 + {&DDRD, &PIND, &PORTD, 6}, // D6 12 + {&DDRC, &PINC, &PORTC, 7}, // C7 13 + {&DDRB, &PINB, &PORTB, 3}, // B3 14 + {&DDRB, &PINB, &PORTB, 1}, // B1 15 + {&DDRB, &PINB, &PORTB, 2}, // B2 16 + {&DDRB, &PINB, &PORTB, 0}, // B0 17 + {&DDRF, &PINF, &PORTF, 7}, // F7 18 + {&DDRF, &PINF, &PORTF, 6}, // F6 19 + {&DDRF, &PINF, &PORTF, 5}, // F5 20 + {&DDRF, &PINF, &PORTF, 4}, // F4 21 + {&DDRF, &PINF, &PORTF, 1}, // F1 22 + {&DDRF, &PINF, &PORTF, 0}, // F0 23 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +// Teensy++ 1.0 & 2.0 + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 1; +uint8_t const SCL_PIN = 0; + +// SPI port +uint8_t const SS_PIN = 20; +uint8_t const MOSI_PIN = 22; +uint8_t const MISO_PIN = 23; +uint8_t const SCK_PIN = 21; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRE, &PINE, &PORTE, 0}, // E0 8 + {&DDRE, &PINE, &PORTE, 1}, // E1 9 + {&DDRC, &PINC, &PORTC, 0}, // C0 10 + {&DDRC, &PINC, &PORTC, 1}, // C1 11 + {&DDRC, &PINC, &PORTC, 2}, // C2 12 + {&DDRC, &PINC, &PORTC, 3}, // C3 13 + {&DDRC, &PINC, &PORTC, 4}, // C4 14 + {&DDRC, &PINC, &PORTC, 5}, // C5 15 + {&DDRC, &PINC, &PORTC, 6}, // C6 16 + {&DDRC, &PINC, &PORTC, 7}, // C7 17 + {&DDRE, &PINE, &PORTE, 6}, // E6 18 + {&DDRE, &PINE, &PORTE, 7}, // E7 19 + {&DDRB, &PINB, &PORTB, 0}, // B0 20 + {&DDRB, &PINB, &PORTB, 1}, // B1 21 + {&DDRB, &PINB, &PORTB, 2}, // B2 22 + {&DDRB, &PINB, &PORTB, 3}, // B3 23 + {&DDRB, &PINB, &PORTB, 4}, // B4 24 + {&DDRB, &PINB, &PORTB, 5}, // B5 25 + {&DDRB, &PINB, &PORTB, 6}, // B6 26 + {&DDRB, &PINB, &PORTB, 7}, // B7 27 + {&DDRA, &PINA, &PORTA, 0}, // A0 28 + {&DDRA, &PINA, &PORTA, 1}, // A1 29 + {&DDRA, &PINA, &PORTA, 2}, // A2 30 + {&DDRA, &PINA, &PORTA, 3}, // A3 31 + {&DDRA, &PINA, &PORTA, 4}, // A4 32 + {&DDRA, &PINA, &PORTA, 5}, // A5 33 + {&DDRA, &PINA, &PORTA, 6}, // A6 34 + {&DDRA, &PINA, &PORTA, 7}, // A7 35 + {&DDRE, &PINE, &PORTE, 4}, // E4 36 + {&DDRE, &PINE, &PORTE, 5}, // E5 37 + {&DDRF, &PINF, &PORTF, 0}, // F0 38 + {&DDRF, &PINF, &PORTF, 1}, // F1 39 + {&DDRF, &PINF, &PORTF, 2}, // F2 40 + {&DDRF, &PINF, &PORTF, 3}, // F3 41 + {&DDRF, &PINF, &PORTF, 4}, // F4 42 + {&DDRF, &PINF, &PORTF, 5}, // F5 43 + {&DDRF, &PINF, &PORTF, 6}, // F6 44 + {&DDRF, &PINF, &PORTF, 7} // F7 45 +}; +//------------------------------------------------------------------------------ +#else // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +// 168 and 328 Arduinos + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; +uint8_t const SCL_PIN = 19; + +// SPI port +uint8_t const SS_PIN = 10; +uint8_t const MOSI_PIN = 11; +uint8_t const MISO_PIN = 12; +uint8_t const SCK_PIN = 13; + +static const pin_map_t digitalPinMap[] = { + {&DDRD, &PIND, &PORTD, 0}, // D0 0 + {&DDRD, &PIND, &PORTD, 1}, // D1 1 + {&DDRD, &PIND, &PORTD, 2}, // D2 2 + {&DDRD, &PIND, &PORTD, 3}, // D3 3 + {&DDRD, &PIND, &PORTD, 4}, // D4 4 + {&DDRD, &PIND, &PORTD, 5}, // D5 5 + {&DDRD, &PIND, &PORTD, 6}, // D6 6 + {&DDRD, &PIND, &PORTD, 7}, // D7 7 + {&DDRB, &PINB, &PORTB, 0}, // B0 8 + {&DDRB, &PINB, &PORTB, 1}, // B1 9 + {&DDRB, &PINB, &PORTB, 2}, // B2 10 + {&DDRB, &PINB, &PORTB, 3}, // B3 11 + {&DDRB, &PINB, &PORTB, 4}, // B4 12 + {&DDRB, &PINB, &PORTB, 5}, // B5 13 + {&DDRC, &PINC, &PORTC, 0}, // C0 14 + {&DDRC, &PINC, &PORTC, 1}, // C1 15 + {&DDRC, &PINC, &PORTC, 2}, // C2 16 + {&DDRC, &PINC, &PORTC, 3}, // C3 17 + {&DDRC, &PINC, &PORTC, 4}, // C4 18 + {&DDRC, &PINC, &PORTC, 5} // C5 19 +}; +#endif // defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +//------------------------------------------------------------------------------ +static const uint8_t digitalPinCount = sizeof(digitalPinMap) / sizeof(pin_map_t); + +uint8_t badPinNumber(void) +__attribute__((error("Pin number is too large or not a constant"))); + +static inline __attribute__((always_inline)) +uint8_t getPinMode(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) +void setPinMode(uint8_t pin, uint8_t mode) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (mode) { + *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +static inline __attribute__((always_inline)) +uint8_t fastDigitalRead(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) +void fastDigitalWrite(uint8_t pin, uint8_t value) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (value) { + *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit; + } else { + *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +#endif // Sd2PinMap_h + +#elif defined (__CPU_ARC__) + +#if defined (__ARDUINO_ARC__) + // Two Wire (aka I2C) ports + uint8_t const SDA_PIN = 18; + uint8_t const SCL_PIN = 19; + + // SPI port + uint8_t const SS_PIN = 10; + uint8_t const MOSI_PIN = 11; + uint8_t const MISO_PIN = 12; + uint8_t const SCK_PIN = 13; + +#endif // Arduino ARC + +#else +#error Architecture or board not supported. +#endif diff --git a/libraries/SD/src/utility/SdFat.h b/libraries/SD/src/utility/SdFat.h new file mode 100644 index 0000000..a17458d --- /dev/null +++ b/libraries/SD/src/utility/SdFat.h @@ -0,0 +1,641 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#ifndef SdFat_h +#define SdFat_h +/** + \file + SdFile and SdVolume classes +*/ +#if defined (__AVR__) || defined (__CPU_ARC__) + #include +#endif +#include "Sd2Card.h" +#include "FatStructs.h" +#include +//------------------------------------------------------------------------------ +/** + Allow use of deprecated functions if non-zero +*/ +#define ALLOW_DEPRECATED_FUNCTIONS 1 +//------------------------------------------------------------------------------ +// forward declaration since SdVolume is used in SdFile +class SdVolume; +//============================================================================== +// SdFile class + +#ifdef O_RDONLY //ARDUINO_ARCH_MBED +#undef O_READ +#undef O_RDONLY +#undef O_WRITE +#undef O_WRONLY +#undef O_RDWR +#undef O_ACCMODE +#undef O_APPEND +#undef O_SYNC +#undef O_CREAT +#undef O_EXCL +#undef O_TRUNC +#endif + +// flags for ls() +/** ls() flag to print modify date */ +uint8_t const LS_DATE = 1; +/** ls() flag to print file size */ +uint8_t const LS_SIZE = 2; +/** ls() flag for recursive list of subdirectories */ +uint8_t const LS_R = 4; + +// use the gnu style oflag in open() +/** open() oflag for reading */ +uint8_t const O_READ = 0X01; +/** open() oflag - same as O_READ */ +uint8_t const O_RDONLY = O_READ; +/** open() oflag for write */ +uint8_t const O_WRITE = 0X02; +/** open() oflag - same as O_WRITE */ +uint8_t const O_WRONLY = O_WRITE; +/** open() oflag for reading and writing */ +uint8_t const O_RDWR = (O_READ | O_WRITE); +/** open() oflag mask for access modes */ +uint8_t const O_ACCMODE = (O_READ | O_WRITE); +/** The file offset shall be set to the end of the file prior to each write. */ +uint8_t const O_APPEND = 0X04; +/** synchronous writes - call sync() after each write */ +uint8_t const O_SYNC = 0X08; +/** create the file if nonexistent */ +uint8_t const O_CREAT = 0X10; +/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */ +uint8_t const O_EXCL = 0X20; +/** truncate the file to zero length */ +uint8_t const O_TRUNC = 0X40; + +// flags for timestamp +/** set the file's last access date */ +uint8_t const T_ACCESS = 1; +/** set the file's creation date and time */ +uint8_t const T_CREATE = 2; +/** Set the file's write date and time */ +uint8_t const T_WRITE = 4; +// values for type_ +/** This SdFile has not been opened. */ +uint8_t const FAT_FILE_TYPE_CLOSED = 0; +/** SdFile for a file */ +uint8_t const FAT_FILE_TYPE_NORMAL = 1; +/** SdFile for a FAT16 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT16 = 2; +/** SdFile for a FAT32 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT32 = 3; +/** SdFile for a subdirectory */ +uint8_t const FAT_FILE_TYPE_SUBDIR = 4; +/** Test value for directory type */ +uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16; + +/** date field for FAT directory entry */ +static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { + return (year - 1980) << 9 | month << 5 | day; +} +/** year part of FAT directory date field */ +static inline uint16_t FAT_YEAR(uint16_t fatDate) { + return 1980 + (fatDate >> 9); +} +/** month part of FAT directory date field */ +static inline uint8_t FAT_MONTH(uint16_t fatDate) { + return (fatDate >> 5) & 0XF; +} +/** day part of FAT directory date field */ +static inline uint8_t FAT_DAY(uint16_t fatDate) { + return fatDate & 0X1F; +} +/** time field for FAT directory entry */ +static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { + return hour << 11 | minute << 5 | second >> 1; +} +/** hour part of FAT directory time field */ +static inline uint8_t FAT_HOUR(uint16_t fatTime) { + return fatTime >> 11; +} +/** minute part of FAT directory time field */ +static inline uint8_t FAT_MINUTE(uint16_t fatTime) { + return (fatTime >> 5) & 0X3F; +} +/** second part of FAT directory time field */ +static inline uint8_t FAT_SECOND(uint16_t fatTime) { + return 2 * (fatTime & 0X1F); +} +/** Default date for file timestamps is 1 Jan 2000 */ +uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; +/** Default time for file timestamp is 1 am */ +uint16_t const FAT_DEFAULT_TIME = (1 << 11); +//------------------------------------------------------------------------------ +/** + \class SdFile + \brief Access FAT16 and FAT32 files on SD and SDHC cards. +*/ +class SdFile : public Print { + public: + /** Create an instance of SdFile. */ + SdFile(void) : type_(FAT_FILE_TYPE_CLOSED) {} + /** + writeError is set to true if an error occurs during a write(). + Set writeError to false before calling print() and/or write() and check + for true after calls to print() and/or write(). + */ + //bool writeError; + /** + Cancel unbuffered reads for this file. + See setUnbufferedRead() + */ + void clearUnbufferedRead(void) { + flags_ &= ~F_FILE_UNBUFFERED_READ; + } + uint8_t close(void); + uint8_t contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + uint8_t createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size); + /** \return The current cluster number for a file or directory. */ + uint32_t curCluster(void) const { + return curCluster_; + } + /** \return The current position for a file or directory. */ + uint32_t curPosition(void) const { + return curPosition_; + } + /** + Set the date/time callback function + + \param[in] dateTime The user's call back function. The callback + function is of the form: + + \code + void dateTime(uint16_t* date, uint16_t* time) { + uint16_t year; + uint8_t month, day, hour, minute, second; + + // User gets date and time from GPS or real-time clock here + + // return date using FAT_DATE macro to format fields + * *date = FAT_DATE(year, month, day); + + // return time using FAT_TIME macro to format fields + * *time = FAT_TIME(hour, minute, second); + } + \endcode + + Sets the function that is called when a file is created or when + a file's directory entry is modified by sync(). All timestamps, + access, creation, and modify, are set when a file is created. + sync() maintains the last access date and last modify date/time. + + See the timestamp() function. + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t* date, uint16_t* time)) { + dateTime_ = dateTime; + } + /** + Cancel the date/time callback function. + */ + static void dateTimeCallbackCancel(void) { + // use explicit zero since NULL is not defined for Sanguino + dateTime_ = 0; + } + /** \return Address of the block that contains this file's directory. */ + uint32_t dirBlock(void) const { + return dirBlock_; + } + uint8_t dirEntry(dir_t* dir); + /** \return Index of this file's directory in the block dirBlock. */ + uint8_t dirIndex(void) const { + return dirIndex_; + } + static void dirName(const dir_t& dir, char* name); + /** \return The total number of bytes in a file or directory. */ + uint32_t fileSize(void) const { + return fileSize_; + } + /** \return The first cluster number for a file or directory. */ + uint32_t firstCluster(void) const { + return firstCluster_; + } + /** \return True if this is a SdFile for a directory else false. */ + uint8_t isDir(void) const { + return type_ >= FAT_FILE_TYPE_MIN_DIR; + } + /** \return True if this is a SdFile for a file else false. */ + uint8_t isFile(void) const { + return type_ == FAT_FILE_TYPE_NORMAL; + } + /** \return True if this is a SdFile for an open file/directory else false. */ + uint8_t isOpen(void) const { + return type_ != FAT_FILE_TYPE_CLOSED; + } + /** \return True if this is a SdFile for a subdirectory else false. */ + uint8_t isSubDir(void) const { + return type_ == FAT_FILE_TYPE_SUBDIR; + } + /** \return True if this is a SdFile for the root directory. */ + uint8_t isRoot(void) const { + return type_ == FAT_FILE_TYPE_ROOT16 || type_ == FAT_FILE_TYPE_ROOT32; + } + void ls(uint8_t flags = 0, uint8_t indent = 0); + uint8_t makeDir(SdFile* dir, const char* dirName); + uint8_t open(SdFile* dirFile, uint16_t index, uint8_t oflag); + uint8_t open(SdFile* dirFile, const char* fileName, uint8_t oflag); + + uint8_t openRoot(SdVolume* vol); + static void printDirName(const dir_t& dir, uint8_t width); + static void printFatDate(uint16_t fatDate); + static void printFatTime(uint16_t fatTime); + static void printTwoDigits(uint8_t v); + /** + Read the next byte from a file. + + \return For success read returns the next byte in the file as an int. + If an error occurs or end of file is reached -1 is returned. + */ + int16_t read(void) { + uint8_t b; + return read(&b, 1) == 1 ? b : -1; + } + int16_t read(void* buf, uint16_t nbyte); + int8_t readDir(dir_t* dir); + static uint8_t remove(SdFile* dirFile, const char* fileName); + uint8_t remove(void); + /** Set the file's current position to zero. */ + void rewind(void) { + curPosition_ = curCluster_ = 0; + } + uint8_t rmDir(void); + uint8_t rmRfStar(void); + /** Set the files position to current position + \a pos. See seekSet(). */ + uint8_t seekCur(uint32_t pos) { + return seekSet(curPosition_ + pos); + } + /** + Set the files current position to end of file. Useful to position + a file for append. See seekSet(). + */ + uint8_t seekEnd(void) { + return seekSet(fileSize_); + } + uint8_t seekSet(uint32_t pos); + /** + Use unbuffered reads to access this file. Used with Wave + Shield ISR. Used with Sd2Card::partialBlockRead() in WaveRP. + + Not recommended for normal applications. + */ + void setUnbufferedRead(void) { + if (isFile()) { + flags_ |= F_FILE_UNBUFFERED_READ; + } + } + uint8_t timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, + uint8_t hour, uint8_t minute, uint8_t second); + uint8_t sync(uint8_t blocking = 1); + /** Type of this SdFile. You should use isFile() or isDir() instead of type() + if possible. + + \return The file or directory type. + */ + uint8_t type(void) const { + return type_; + } + uint8_t truncate(uint32_t size); + /** \return Unbuffered read flag. */ + uint8_t unbufferedRead(void) const { + return flags_ & F_FILE_UNBUFFERED_READ; + } + /** \return SdVolume that contains this file. */ + SdVolume* volume(void) const { + return vol_; + } + size_t write(uint8_t b); + size_t write(const void* buf, uint16_t nbyte); + size_t write(const char* str); + #ifdef __AVR__ + void write_P(PGM_P str); + void writeln_P(PGM_P str); + #endif + int availableForWrite(void); + //------------------------------------------------------------------------------ + #if ALLOW_DEPRECATED_FUNCTIONS + // Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: + uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + */ + uint8_t contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) { // NOLINT + return contiguousRange(&bgnBlock, &endBlock); + } + /** \deprecated Use: + uint8_t SdFile::createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size) + */ + uint8_t createContiguous(SdFile& dirFile, // NOLINT + const char* fileName, uint32_t size) { + return createContiguous(&dirFile, fileName, size); + } + + /** + \deprecated Use: + static void SdFile::dateTimeCallback( + void (*dateTime)(uint16_t* date, uint16_t* time)); + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t& date, uint16_t& time)) { // NOLINT + oldDateTime_ = dateTime; + dateTime_ = dateTime ? oldToNew : 0; + } + /** \deprecated Use: uint8_t SdFile::dirEntry(dir_t* dir); */ + uint8_t dirEntry(dir_t& dir) { + return dirEntry(&dir); // NOLINT + } + /** \deprecated Use: + uint8_t SdFile::makeDir(SdFile* dir, const char* dirName); + */ + uint8_t makeDir(SdFile& dir, const char* dirName) { // NOLINT + return makeDir(&dir, dirName); + } + /** \deprecated Use: + uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, // NOLINT + const char* fileName, uint8_t oflag) { + return open(&dirFile, fileName, oflag); + } + /** \deprecated Do not use in new apps */ + uint8_t open(SdFile& dirFile, const char* fileName) { // NOLINT + return open(dirFile, fileName, O_RDWR); + } + /** \deprecated Use: + uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag); + */ + uint8_t open(SdFile& dirFile, uint16_t index, uint8_t oflag) { // NOLINT + return open(&dirFile, index, oflag); + } + /** \deprecated Use: uint8_t SdFile::openRoot(SdVolume* vol); */ + uint8_t openRoot(SdVolume& vol) { + return openRoot(&vol); // NOLINT + } + + /** \deprecated Use: int8_t SdFile::readDir(dir_t* dir); */ + int8_t readDir(dir_t& dir) { + return readDir(&dir); // NOLINT + } + /** \deprecated Use: + static uint8_t SdFile::remove(SdFile* dirFile, const char* fileName); + */ + static uint8_t remove(SdFile& dirFile, const char* fileName) { // NOLINT + return remove(&dirFile, fileName); + } + //------------------------------------------------------------------------------ + // rest are private + private: + static void (*oldDateTime_)(uint16_t& date, uint16_t& time); // NOLINT + static void oldToNew(uint16_t* date, uint16_t* time) { + uint16_t d; + uint16_t t; + oldDateTime_(d, t); + *date = d; + *time = t; + } + #endif // ALLOW_DEPRECATED_FUNCTIONS + private: + // bits defined in flags_ + // should be 0XF + static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC); + // available bits + static uint8_t const F_FILE_NON_BLOCKING_WRITE = 0X10; + // a new cluster was added to the file + static uint8_t const F_FILE_CLUSTER_ADDED = 0X20; + // use unbuffered SD read + static uint8_t const F_FILE_UNBUFFERED_READ = 0X40; + // sync of directory entry required + static uint8_t const F_FILE_DIR_DIRTY = 0X80; + + // make sure F_OFLAG is ok + #if ((F_FILE_NON_BLOCKING_WRITE | F_FILE_CLUSTER_ADDED | F_FILE_UNBUFFERED_READ | F_FILE_DIR_DIRTY) & F_OFLAG) +#error flags_ bits conflict + #endif // flags_ bits + + // private data + uint8_t flags_; // See above for definition of flags_ bits + uint8_t type_; // type of file see above for values + uint32_t curCluster_; // cluster for current file position + uint32_t curPosition_; // current file position in bytes from beginning + uint32_t dirBlock_; // SD block that contains directory entry for file + uint8_t dirIndex_; // index of entry in dirBlock 0 <= dirIndex_ <= 0XF + uint32_t fileSize_; // file size in bytes + uint32_t firstCluster_; // first cluster of file + SdVolume* vol_; // volume where file is located + + // private functions + uint8_t addCluster(void); + uint8_t addDirCluster(void); + dir_t* cacheDirEntry(uint8_t action); + static void (*dateTime_)(uint16_t* date, uint16_t* time); + static uint8_t make83Name(const char* str, uint8_t* name); + uint8_t openCachedEntry(uint8_t cacheIndex, uint8_t oflags); + dir_t* readDirCache(void); +}; +//============================================================================== +// SdVolume class +/** + \brief Cache for an SD data block +*/ +union cache_t { + /** Used to access cached file data blocks. */ + uint8_t data[512]; + /** Used to access cached FAT16 entries. */ + uint16_t fat16[256]; + /** Used to access cached FAT32 entries. */ + uint32_t fat32[128]; + /** Used to access cached directory entries. */ + dir_t dir[16]; + /** Used to access a cached MasterBoot Record. */ + mbr_t mbr; + /** Used to access to a cached FAT boot sector. */ + fbs_t fbs; +}; +//------------------------------------------------------------------------------ +/** + \class SdVolume + \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. +*/ +class SdVolume { + public: + /** Create an instance of SdVolume */ + SdVolume(void) : allocSearchStart_(2), fatType_(0) {} + /** Clear the cache and returns a pointer to the cache. Used by the WaveRP + recorder to do raw write to the SD card. Not for normal apps. + */ + static uint8_t* cacheClear(void) { + cacheFlush(); + cacheBlockNumber_ = 0XFFFFFFFF; + return cacheBuffer_.data; + } + /** + Initialize a FAT volume. Try partition one first then try super + floppy format. + + \param[in] dev The Sd2Card where the volume is located. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. Reasons for + failure include not finding a valid partition, not finding a valid + FAT file system or an I/O error. + */ + uint8_t init(Sd2Card* dev) { + return init(dev, 1) ? true : init(dev, 0); + } + uint8_t init(Sd2Card* dev, uint8_t part); + + // inline functions that return volume info + /** \return The volume's cluster size in blocks. */ + uint8_t blocksPerCluster(void) const { + return blocksPerCluster_; + } + /** \return The number of blocks in one FAT. */ + uint32_t blocksPerFat(void) const { + return blocksPerFat_; + } + /** \return The total number of clusters in the volume. */ + uint32_t clusterCount(void) const { + return clusterCount_; + } + /** \return The shift count required to multiply by blocksPerCluster. */ + uint8_t clusterSizeShift(void) const { + return clusterSizeShift_; + } + /** \return The logical block number for the start of file data. */ + uint32_t dataStartBlock(void) const { + return dataStartBlock_; + } + /** \return The number of FAT structures on the volume. */ + uint8_t fatCount(void) const { + return fatCount_; + } + /** \return The logical block number for the start of the first FAT. */ + uint32_t fatStartBlock(void) const { + return fatStartBlock_; + } + /** \return The FAT type of the volume. Values are 12, 16 or 32. */ + uint8_t fatType(void) const { + return fatType_; + } + /** \return The number of entries in the root directory for FAT16 volumes. */ + uint32_t rootDirEntryCount(void) const { + return rootDirEntryCount_; + } + /** \return The logical block number for the start of the root directory + on FAT16 volumes or the first cluster number on FAT32 volumes. */ + uint32_t rootDirStart(void) const { + return rootDirStart_; + } + /** return a pointer to the Sd2Card object for this volume */ + static Sd2Card* sdCard(void) { + return sdCard_; + } + //------------------------------------------------------------------------------ + #if ALLOW_DEPRECATED_FUNCTIONS + // Deprecated functions - suppress cpplint warnings with NOLINT comment + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev); */ + uint8_t init(Sd2Card& dev) { + return init(&dev); // NOLINT + } + + /** \deprecated Use: uint8_t SdVolume::init(Sd2Card* dev, uint8_t vol); */ + uint8_t init(Sd2Card& dev, uint8_t part) { // NOLINT + return init(&dev, part); + } + #endif // ALLOW_DEPRECATED_FUNCTIONS + //------------------------------------------------------------------------------ + private: + // Allow SdFile access to SdVolume private data. + friend class SdFile; + + // value for action argument in cacheRawBlock to indicate read from cache + static uint8_t const CACHE_FOR_READ = 0; + // value for action argument in cacheRawBlock to indicate cache dirty + static uint8_t const CACHE_FOR_WRITE = 1; + + static cache_t cacheBuffer_; // 512 byte cache for device blocks + static uint32_t cacheBlockNumber_; // Logical number of block in the cache + static Sd2Card* sdCard_; // Sd2Card object for cache + static uint8_t cacheDirty_; // cacheFlush() will write block if true + static uint32_t cacheMirrorBlock_; // block number for mirror FAT + // + uint32_t allocSearchStart_; // start cluster for alloc search + uint8_t blocksPerCluster_; // cluster size in blocks + uint32_t blocksPerFat_; // FAT size in blocks + uint32_t clusterCount_; // clusters in one FAT + uint8_t clusterSizeShift_; // shift to convert cluster count to block count + uint32_t dataStartBlock_; // first data block number + uint8_t fatCount_; // number of FATs on volume + uint32_t fatStartBlock_; // start block for first FAT + uint8_t fatType_; // volume type (12, 16, OR 32) + uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir + uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 + //---------------------------------------------------------------------------- + uint8_t allocContiguous(uint32_t count, uint32_t* curCluster); + uint8_t blockOfCluster(uint32_t position) const { + return (position >> 9) & (blocksPerCluster_ - 1); + } + uint32_t clusterStartBlock(uint32_t cluster) const { + return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_); + } + uint32_t blockNumber(uint32_t cluster, uint32_t position) const { + return clusterStartBlock(cluster) + blockOfCluster(position); + } + static uint8_t cacheFlush(uint8_t blocking = 1); + static uint8_t cacheMirrorBlockFlush(uint8_t blocking); + static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action); + static void cacheSetDirty(void) { + cacheDirty_ |= CACHE_FOR_WRITE; + } + static uint8_t cacheZeroBlock(uint32_t blockNumber); + uint8_t chainSize(uint32_t beginCluster, uint32_t* size) const; + uint8_t fatGet(uint32_t cluster, uint32_t* value) const; + uint8_t fatPut(uint32_t cluster, uint32_t value); + uint8_t fatPutEOC(uint32_t cluster) { + return fatPut(cluster, 0x0FFFFFFF); + } + uint8_t freeChain(uint32_t cluster); + uint8_t isEOC(uint32_t cluster) const { + return cluster >= (fatType_ == 16 ? FAT16EOC_MIN : FAT32EOC_MIN); + } + uint8_t readBlock(uint32_t block, uint8_t* dst) { + return sdCard_->readBlock(block, dst); + } + uint8_t readData(uint32_t block, uint16_t offset, + uint16_t count, uint8_t* dst) { + return sdCard_->readData(block, offset, count, dst); + } + uint8_t writeBlock(uint32_t block, const uint8_t* dst, uint8_t blocking = 1) { + return sdCard_->writeBlock(block, dst, blocking); + } + uint8_t isBusy(void) { + return sdCard_->isBusy(); + } + uint8_t isCacheMirrorBlockDirty(void) { + return (cacheMirrorBlock_ != 0); + } +}; +#endif // SdFat_h diff --git a/libraries/SD/src/utility/SdFatUtil.h b/libraries/SD/src/utility/SdFatUtil.h new file mode 100644 index 0000000..2fb6289 --- /dev/null +++ b/libraries/SD/src/utility/SdFatUtil.h @@ -0,0 +1,77 @@ +/* Arduino SdFat Library + Copyright (C) 2008 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#ifndef SdFatUtil_h +#define SdFatUtil_h +/** + \file + Useful utility functions. +*/ +#include +#ifdef __AVR__ + #include + /** Store and print a string in flash memory.*/ + #define PgmPrint(x) SerialPrint_P(PSTR(x)) + /** Store and print a string in flash memory followed by a CR/LF.*/ + #define PgmPrintln(x) SerialPrintln_P(PSTR(x)) + /** Defined so doxygen works for function definitions. */ +#endif +#define NOINLINE __attribute__((noinline,unused)) +#define UNUSEDOK __attribute__((unused)) +//------------------------------------------------------------------------------ +/** Return the number of bytes currently free in RAM. */ +static UNUSEDOK int FreeRam(void) { + extern int __bss_end; + extern int* __brkval; + int free_memory; + if (reinterpret_cast(__brkval) == 0) { + // if no heap use from end of bss section + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(&__bss_end); + } else { + // use from top of stack to heap + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(__brkval); + } + return free_memory; +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + %Print a string in flash memory to the serial port. + + \param[in] str Pointer to string stored in flash memory. +*/ +static NOINLINE void SerialPrint_P(PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) { + Serial.write(c); + } +} +//------------------------------------------------------------------------------ +/** + %Print a string in flash memory followed by a CR/LF. + + \param[in] str Pointer to string stored in flash memory. +*/ +static NOINLINE void SerialPrintln_P(PGM_P str) { + SerialPrint_P(str); + Serial.println(); +} +#endif // __AVR__ +#endif // #define SdFatUtil_h diff --git a/libraries/SD/src/utility/SdFatmainpage.h b/libraries/SD/src/utility/SdFatmainpage.h new file mode 100644 index 0000000..0a42e85 --- /dev/null +++ b/libraries/SD/src/utility/SdFatmainpage.h @@ -0,0 +1,202 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ + +/** + \mainpage Arduino SdFat Library +

Copyright © 2009 by William Greiman +
+ + \section Intro Introduction + The Arduino SdFat Library is a minimal implementation of FAT16 and FAT32 + file systems on SD flash memory cards. Standard SD and high capacity + SDHC cards are supported. + + The SdFat only supports short 8.3 names. + + The main classes in SdFat are Sd2Card, SdVolume, and SdFile. + + The Sd2Card class supports access to standard SD cards and SDHC cards. Most + applications will only need to call the Sd2Card::init() member function. + + The SdVolume class supports FAT16 and FAT32 partitions. Most applications + will only need to call the SdVolume::init() member function. + + The SdFile class provides file access functions such as open(), read(), + remove(), write(), close() and sync(). This class supports access to the root + directory and subdirectories. + + A number of example are provided in the SdFat/examples folder. These were + developed to test SdFat and illustrate its use. + + SdFat was developed for high speed data recording. SdFat was used to implement + an audio record/play class, WaveRP, for the Adafruit Wave Shield. This + application uses special Sd2Card calls to write to contiguous files in raw mode. + These functions reduce write latency so that audio can be recorded with the + small amount of RAM in the Arduino. + + \section SDcard SD\SDHC Cards + + Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and + most consumer devices use the 4-bit parallel SD protocol. A card that + functions well on A PC or Mac may not work well on the Arduino. + + Most cards have good SPI read performance but cards vary widely in SPI + write performance. Write performance is limited by how efficiently the + card manages internal erase/remapping operations. The Arduino cannot + optimize writes to reduce erase operations because of its limit RAM. + + SanDisk cards generally have good write performance. They seem to have + more internal RAM buffering than other cards and therefore can limit + the number of flash erase operations that the Arduino forces due to its + limited RAM. + + \section Hardware Hardware Configuration + + SdFat was developed using an + Adafruit Industries + Wave Shield. + + The hardware interface to the SD card should not use a resistor based level + shifter. SdFat sets the SPI bus frequency to 8 MHz which results in signal + rise times that are too slow for the edge detectors in many newer SD card + controllers when resistor voltage dividers are used. + + The 5 to 3.3 V level shifter for 5 V Arduinos should be IC based like the + 74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield + uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the + 74LCX245. + + If you are using a resistor based level shifter and are having problems try + setting the SPI bus frequency to 4 MHz. This can be done by using + card.init(SPI_HALF_SPEED) to initialize the SD card. + + \section comment Bugs and Comments + + If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. + + \section SdFatClass SdFat Usage + + SdFat uses a slightly restricted form of short names. + Only printable ASCII characters are supported. No characters with code point + values greater than 127 are allowed. Space is not allowed even though space + was allowed in the API of early versions of DOS. + + Short names are limited to 8 characters followed by an optional period (.) + and extension of up to 3 characters. The characters may be any combination + of letters and digits. The following special characters are also allowed: + + $ % ' - _ @ ~ ` ! ( ) { } ^ # & + + Short names are always converted to upper case and their original case + value is lost. + + \note + The Arduino Print class uses character + at a time writes so it was necessary to use a \link SdFile::sync() sync() \endlink + function to control when data is written to the SD card. + + \par + An application which writes to a file using \link Print::print() print()\endlink, + \link Print::println() println() \endlink + or \link SdFile::write write() \endlink must call \link SdFile::sync() sync() \endlink + at the appropriate time to force data and directory information to be written + to the SD Card. Data and directory information are also written to the SD card + when \link SdFile::close() close() \endlink is called. + + \par + Applications must use care calling \link SdFile::sync() sync() \endlink + since 2048 bytes of I/O is required to update file and + directory information. This includes writing the current data block, reading + the block that contains the directory entry for update, writing the directory + block back and reading back the current data block. + + It is possible to open a file with two or more instances of SdFile. A file may + be corrupted if data is written to the file by more than one instance of SdFile. + + \section HowTo How to format SD Cards as FAT Volumes + + You should use a freshly formatted SD card for best performance. FAT + file systems become slower if many files have been created and deleted. + This is because the directory entry for a deleted file is marked as deleted, + but is not deleted. When a new file is created, these entries must be scanned + before creating the file, a flaw in the FAT design. Also files can become + fragmented which causes reads and writes to be slower. + + Microsoft operating systems support removable media formatted with a + Master Boot Record, MBR, or formatted as a super floppy with a FAT Boot Sector + in block zero. + + Microsoft operating systems expect MBR formatted removable media + to have only one partition. The first partition should be used. + + Microsoft operating systems do not support partitioning SD flash cards. + If you erase an SD card with a program like KillDisk, Most versions of + Windows will format the card as a super floppy. + + The best way to restore an SD card's format is to use SDFormatter + which can be downloaded from: + + http://www.sdcard.org/consumers/formatter/ + + SDFormatter aligns flash erase boundaries with file + system structures which reduces write latency and file system overhead. + + SDFormatter does not have an option for FAT type so it may format + small cards as FAT12. + + After the MBR is restored by SDFormatter you may need to reformat small + cards that have been formatted FAT12 to force the volume type to be FAT16. + + If you reformat the SD card with an OS utility, choose a cluster size that + will result in: + + 4084 < CountOfClusters && CountOfClusters < 65525 + + The volume will then be FAT16. + + If you are formatting an SD card on OS X or Linux, be sure to use the first + partition. Format this partition with a cluster count in above range. + + \section References References + + Adafruit Industries: + + http://www.adafruit.com/ + + http://www.ladyada.net/make/waveshield/ + + The Arduino site: + + http://www.arduino.cc/ + + For more information about FAT file systems see: + + http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx + + For information about using SD cards as SPI devices see: + + http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf + + The ATmega328 datasheet: + + http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf + + +*/ diff --git a/libraries/SD/src/utility/SdFile.cpp b/libraries/SD/src/utility/SdFile.cpp new file mode 100644 index 0000000..70be4b5 --- /dev/null +++ b/libraries/SD/src/utility/SdFile.cpp @@ -0,0 +1,1527 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#include "SdFat.h" +#ifdef __AVR__ + #include +#endif +#include +//------------------------------------------------------------------------------ +// callback function for date/time +void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL; + +#if ALLOW_DEPRECATED_FUNCTIONS + // suppress cpplint warnings with NOLINT comment + void (*SdFile::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT +#endif // ALLOW_DEPRECATED_FUNCTIONS +//------------------------------------------------------------------------------ +// add a cluster to a file +uint8_t SdFile::addCluster() { + if (!vol_->allocContiguous(1, &curCluster_)) { + return false; + } + + // if first cluster of file link to directory entry + if (firstCluster_ == 0) { + firstCluster_ = curCluster_; + flags_ |= F_FILE_DIR_DIRTY; + } + flags_ |= F_FILE_CLUSTER_ADDED; + return true; +} +//------------------------------------------------------------------------------ +// Add a cluster to a directory file and zero the cluster. +// return with first block of cluster in the cache +uint8_t SdFile::addDirCluster(void) { + if (!addCluster()) { + return false; + } + + // zero data in cluster insure first cluster is in cache + uint32_t block = vol_->clusterStartBlock(curCluster_); + for (uint8_t i = vol_->blocksPerCluster_; i != 0; i--) { + if (!SdVolume::cacheZeroBlock(block + i - 1)) { + return false; + } + } + // Increase directory file size by cluster size + fileSize_ += 512UL << vol_->clusterSizeShift_; + return true; +} +//------------------------------------------------------------------------------ +// cache a file's directory entry +// return pointer to cached entry or null for failure +dir_t* SdFile::cacheDirEntry(uint8_t action) { + if (!SdVolume::cacheRawBlock(dirBlock_, action)) { + return NULL; + } + return SdVolume::cacheBuffer_.dir + dirIndex_; +} +//------------------------------------------------------------------------------ +/** + Close a file and force cached data and directory information + to be written to the storage device. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include no file is open or an I/O error. +*/ +uint8_t SdFile::close(void) { + if (!sync()) { + return false; + } + type_ = FAT_FILE_TYPE_CLOSED; + return true; +} +//------------------------------------------------------------------------------ +/** + Check for contiguous file and return its raw block range. + + \param[out] bgnBlock the first block address for the file. + \param[out] endBlock the last block address for the file. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include file is not contiguous, file has zero length + or an I/O error occurred. +*/ +uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { + // error if no blocks + if (firstCluster_ == 0) { + return false; + } + + for (uint32_t c = firstCluster_; ; c++) { + uint32_t next; + if (!vol_->fatGet(c, &next)) { + return false; + } + + // check for contiguous + if (next != (c + 1)) { + // error if not end of chain + if (!vol_->isEOC(next)) { + return false; + } + *bgnBlock = vol_->clusterStartBlock(firstCluster_); + *endBlock = vol_->clusterStartBlock(c) + + vol_->blocksPerCluster_ - 1; + return true; + } + } +} +//------------------------------------------------------------------------------ +/** + Create and open a new contiguous file of a specified size. + + \note This function only supports short DOS 8.3 names. + See open() for more information. + + \param[in] dirFile The directory where the file will be created. + \param[in] fileName A valid DOS 8.3 file name. + \param[in] size The desired file size. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include \a fileName contains + an invalid DOS 8.3 file name, the FAT volume has not been initialized, + a file is already open, the file already exists, the root + directory is full or an I/O error. + +*/ +uint8_t SdFile::createContiguous(SdFile* dirFile, + const char* fileName, uint32_t size) { + // don't allow zero length file + if (size == 0) { + return false; + } + if (!open(dirFile, fileName, O_CREAT | O_EXCL | O_RDWR)) { + return false; + } + + // calculate number of clusters needed + uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; + + // allocate clusters + if (!vol_->allocContiguous(count, &firstCluster_)) { + remove(); + return false; + } + fileSize_ = size; + + // insure sync() will update dir entry + flags_ |= F_FILE_DIR_DIRTY; + return sync(); +} +//------------------------------------------------------------------------------ +/** + Return a files directory entry + + \param[out] dir Location for return of the files directory entry. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::dirEntry(dir_t* dir) { + // make sure fields on SD are correct + if (!sync()) { + return false; + } + + // read entry + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ); + if (!p) { + return false; + } + + // copy to caller's struct + memcpy(dir, p, sizeof(dir_t)); + return true; +} +//------------------------------------------------------------------------------ +/** + Format the name field of \a dir into the 13 byte array + \a name in standard 8.3 short name format. + + \param[in] dir The directory structure containing the name. + \param[out] name A 13 byte char array for the formatted name. +*/ +void SdFile::dirName(const dir_t& dir, char* name) { + uint8_t j = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ') { + continue; + } + if (i == 8) { + name[j++] = '.'; + } + name[j++] = dir.name[i]; + } + name[j] = 0; +} +//------------------------------------------------------------------------------ +/** List directory contents to Serial. + + \param[in] flags The inclusive OR of + + LS_DATE - %Print file modification date + + LS_SIZE - %Print file size. + + LS_R - Recursive list of subdirectories. + + \param[in] indent Amount of space before file name. Used for recursive + list to indicate subdirectory level. +*/ +void SdFile::ls(uint8_t flags, uint8_t indent) { + dir_t* p; + + rewind(); + while ((p = readDirCache())) { + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) { + break; + } + + // skip deleted entry and entries for . and .. + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + continue; + } + + // only list subdirectories and files + if (!DIR_IS_FILE_OR_SUBDIR(p)) { + continue; + } + + // print any indent spaces + for (int8_t i = 0; i < indent; i++) { + Serial.print(' '); + } + + // print file name with possible blank fill + printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0); + + // print modify date/time if requested + if (flags & LS_DATE) { + printFatDate(p->lastWriteDate); + Serial.print(' '); + printFatTime(p->lastWriteTime); + } + // print size if requested + if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) { + Serial.print(' '); + Serial.print(p->fileSize); + } + Serial.println(); + + // list subdirectory content if requested + if ((flags & LS_R) && DIR_IS_SUBDIR(p)) { + uint16_t index = curPosition() / 32 - 1; + SdFile s; + if (s.open(this, index, O_READ)) { + s.ls(flags, indent + 2); + } + seekSet(32 * (index + 1)); + } + } +} +//------------------------------------------------------------------------------ +// format directory name field from a 8.3 name string +uint8_t SdFile::make83Name(const char* str, uint8_t* name) { + uint8_t c; + uint8_t n = 7; // max index for part before dot + uint8_t i = 0; + // blank fill name and extension + while (i < 11) { + name[i++] = ' '; + } + i = 0; + while ((c = *str++) != '\0') { + if (c == '.') { + if (n == 10) { + return false; // only one dot allowed + } + n = 10; // max index for full 8.3 name + i = 8; // place for extension + } else { + // illegal FAT characters + uint8_t b; + #if defined(__AVR__) + PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); + while ((b = pgm_read_byte(p++))) if (b == c) { + return false; + } + #elif defined(__arm__) + const uint8_t valid[] = "|<>^+=?/[];,*\"\\"; + const uint8_t *p = valid; + while ((b = *p++)) if (b == c) { + return false; + } + #endif + // check size and only allow ASCII printable characters + if (i > n || c < 0X21 || c > 0X7E) { + return false; + } + // only upper case allowed in 8.3 names - convert lower to upper + name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a'); + } + } + // must have a file name, extension is optional + return name[0] != ' '; +} +//------------------------------------------------------------------------------ +/** Make a new directory. + + \param[in] dir An open SdFat instance for the directory that will containing + the new directory. + + \param[in] dirName A valid 8.3 DOS name for the new directory. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include this SdFile is already open, \a dir is not a + directory, \a dirName is invalid or already exists in \a dir. +*/ +uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) { + dir_t d; + + // create a normal file + if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) { + return false; + } + + // convert SdFile to directory + flags_ = O_READ; + type_ = FAT_FILE_TYPE_SUBDIR; + + // allocate and zero first cluster + if (!addDirCluster()) { + return false; + } + + // force entry to SD + if (!sync()) { + return false; + } + + // cache entry - should already be in cache due to sync() call + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) { + return false; + } + + // change directory entry attribute + p->attributes = DIR_ATT_DIRECTORY; + + // make entry for '.' + memcpy(&d, p, sizeof(d)); + for (uint8_t i = 1; i < 11; i++) { + d.name[i] = ' '; + } + d.name[0] = '.'; + + // cache block for '.' and '..' + uint32_t block = vol_->clusterStartBlock(firstCluster_); + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { + return false; + } + + // copy '.' to block + memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d)); + + // make entry for '..' + d.name[1] = '.'; + if (dir->isRoot()) { + d.firstClusterLow = 0; + d.firstClusterHigh = 0; + } else { + d.firstClusterLow = dir->firstCluster_ & 0XFFFF; + d.firstClusterHigh = dir->firstCluster_ >> 16; + } + // copy '..' to block + memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d)); + + // set position after '..' + curPosition_ = 2 * sizeof(d); + + // write first block + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + Open a file or directory by name. + + \param[in] dirFile An open SdFat instance for the directory containing the + file to be opened. + + \param[in] fileName A valid 8.3 DOS name for a file to be opened. + + \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + OR of flags from the following list + + O_READ - Open for reading. + + O_RDONLY - Same as O_READ. + + O_WRITE - Open for writing. + + O_WRONLY - Same as O_WRITE. + + O_RDWR - Open for reading and writing. + + O_APPEND - If set, the file offset shall be set to the end of the + file prior to each write. + + O_CREAT - If the file exists, this flag has no effect except as noted + under O_EXCL below. Otherwise, the file shall be created + + O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. + + O_SYNC - Call sync() after each write. This flag should not be used with + write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. + These functions do character at a time writes so sync() will be called + after each byte. + + O_TRUNC - If the file exists and is a regular file, and the file is + successfully opened and is not read only, its length shall be truncated to 0. + + \note Directory files must be opened read only. Write and truncation is + not allowed for directory files. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include this SdFile is already open, \a difFile is not + a directory, \a fileName is invalid, the file does not exist + or can't be opened in the access mode specified by oflag. +*/ +uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) { + uint8_t dname[11]; + dir_t* p; + + // error if already open + if (isOpen()) { + return false; + } + + if (!make83Name(fileName, dname)) { + return false; + } + vol_ = dirFile->vol_; + dirFile->rewind(); + + // bool for empty entry found + uint8_t emptyFound = false; + + // search for file + while (dirFile->curPosition_ < dirFile->fileSize_) { + uint8_t index = 0XF & (dirFile->curPosition_ >> 5); + p = dirFile->readDirCache(); + if (p == NULL) { + return false; + } + + if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { + // remember first empty slot + if (!emptyFound) { + emptyFound = true; + dirIndex_ = index; + dirBlock_ = SdVolume::cacheBlockNumber_; + } + // done if no entries follow + if (p->name[0] == DIR_NAME_FREE) { + break; + } + } else if (!memcmp(dname, p->name, 11)) { + // don't open existing file if O_CREAT and O_EXCL + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) { + return false; + } + + // open found file + return openCachedEntry(0XF & index, oflag); + } + } + // only create file if O_CREAT and O_WRITE + if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) { + return false; + } + + // cache found slot or add cluster if end of file + if (emptyFound) { + p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) { + return false; + } + } else { + if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) { + return false; + } + + // add and zero cluster for dirFile - first cluster is in cache for write + if (!dirFile->addDirCluster()) { + return false; + } + + // use first entry in cluster + dirIndex_ = 0; + p = SdVolume::cacheBuffer_.dir; + } + // initialize as empty file + memset(p, 0, sizeof(dir_t)); + memcpy(p->name, dname, 11); + + // set timestamps + if (dateTime_) { + // call user function + dateTime_(&p->creationDate, &p->creationTime); + } else { + // use default date/time + p->creationDate = FAT_DEFAULT_DATE; + p->creationTime = FAT_DEFAULT_TIME; + } + p->lastAccessDate = p->creationDate; + p->lastWriteDate = p->creationDate; + p->lastWriteTime = p->creationTime; + + // force write of entry to SD + if (!SdVolume::cacheFlush()) { + return false; + } + + // open entry in cache + return openCachedEntry(dirIndex_, oflag); +} +//------------------------------------------------------------------------------ +/** + Open a file by index. + + \param[in] dirFile An open SdFat instance for the directory. + + \param[in] index The \a index of the directory entry for the file to be + opened. The value for \a index is (directory file position)/32. + + \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + + See open() by fileName for definition of flags and return values. + +*/ +uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) { + // error if already open + if (isOpen()) { + return false; + } + + // don't open existing file if O_CREAT and O_EXCL - user call error + if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) { + return false; + } + + vol_ = dirFile->vol_; + + // seek to location of entry + if (!dirFile->seekSet(32 * index)) { + return false; + } + + // read entry into cache + dir_t* p = dirFile->readDirCache(); + if (p == NULL) { + return false; + } + + // error if empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_FREE || + p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + return false; + } + // open cached entry + return openCachedEntry(index & 0XF, oflag); +} +//------------------------------------------------------------------------------ +// open a cached directory entry. Assumes vol_ is initializes +uint8_t SdFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) { + // location of entry in cache + dir_t* p = SdVolume::cacheBuffer_.dir + dirIndex; + + // write or truncate is an error for a directory or read-only file + if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { + if (oflag & (O_WRITE | O_TRUNC)) { + return false; + } + } + // remember location of directory entry on SD + dirIndex_ = dirIndex; + dirBlock_ = SdVolume::cacheBlockNumber_; + + // copy first cluster number for directory fields + firstCluster_ = (uint32_t)p->firstClusterHigh << 16; + firstCluster_ |= p->firstClusterLow; + + // make sure it is a normal file or subdirectory + if (DIR_IS_FILE(p)) { + fileSize_ = p->fileSize; + type_ = FAT_FILE_TYPE_NORMAL; + } else if (DIR_IS_SUBDIR(p)) { + if (!vol_->chainSize(firstCluster_, &fileSize_)) { + return false; + } + type_ = FAT_FILE_TYPE_SUBDIR; + } else { + return false; + } + // save open flags for read/write + flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // truncate file to zero length if requested + if (oflag & O_TRUNC) { + return truncate(0); + } + return true; +} +//------------------------------------------------------------------------------ +/** + Open a volume's root directory. + + \param[in] vol The FAT volume containing the root directory to be opened. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the FAT volume has not been initialized + or it a FAT12 volume. +*/ +uint8_t SdFile::openRoot(SdVolume* vol) { + // error if file is already open + if (isOpen()) { + return false; + } + + if (vol->fatType() == 16) { + type_ = FAT_FILE_TYPE_ROOT16; + firstCluster_ = 0; + fileSize_ = 32 * vol->rootDirEntryCount(); + } else if (vol->fatType() == 32) { + type_ = FAT_FILE_TYPE_ROOT32; + firstCluster_ = vol->rootDirStart(); + if (!vol->chainSize(firstCluster_, &fileSize_)) { + return false; + } + } else { + // volume is not initialized or FAT12 + return false; + } + vol_ = vol; + // read only + flags_ = O_READ; + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // root has no directory entry + dirBlock_ = 0; + dirIndex_ = 0; + return true; +} +//------------------------------------------------------------------------------ +/** %Print the name field of a directory entry in 8.3 format to Serial. + + \param[in] dir The directory structure containing the name. + \param[in] width Blank fill name if length is less than \a width. +*/ +void SdFile::printDirName(const dir_t& dir, uint8_t width) { + uint8_t w = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ') { + continue; + } + if (i == 8) { + Serial.print('.'); + w++; + } + Serial.write(dir.name[i]); + w++; + } + if (DIR_IS_SUBDIR(&dir)) { + Serial.print('/'); + w++; + } + while (w < width) { + Serial.print(' '); + w++; + } +} +//------------------------------------------------------------------------------ +/** %Print a directory date field to Serial. + + Format is yyyy-mm-dd. + + \param[in] fatDate The date field from a directory entry. +*/ +void SdFile::printFatDate(uint16_t fatDate) { + Serial.print(FAT_YEAR(fatDate)); + Serial.print('-'); + printTwoDigits(FAT_MONTH(fatDate)); + Serial.print('-'); + printTwoDigits(FAT_DAY(fatDate)); +} +//------------------------------------------------------------------------------ +/** %Print a directory time field to Serial. + + Format is hh:mm:ss. + + \param[in] fatTime The time field from a directory entry. +*/ +void SdFile::printFatTime(uint16_t fatTime) { + printTwoDigits(FAT_HOUR(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_MINUTE(fatTime)); + Serial.print(':'); + printTwoDigits(FAT_SECOND(fatTime)); +} +//------------------------------------------------------------------------------ +/** %Print a value as two digits to Serial. + + \param[in] v Value to be printed, 0 <= \a v <= 99 +*/ +void SdFile::printTwoDigits(uint8_t v) { + char str[3]; + str[0] = '0' + v / 10; + str[1] = '0' + v % 10; + str[2] = 0; + Serial.print(str); +} +//------------------------------------------------------------------------------ +/** + Read data from a file starting at the current position. + + \param[out] buf Pointer to the location that will receive the data. + + \param[in] nbyte Maximum number of bytes to read. + + \return For success read() returns the number of bytes read. + A value less than \a nbyte, including zero, will be returned + if end of file is reached. + If an error occurs, read() returns -1. Possible errors include + read() called before a file has been opened, corrupt file system + or an I/O error occurred. +*/ +int16_t SdFile::read(void* buf, uint16_t nbyte) { + uint8_t* dst = reinterpret_cast(buf); + + // error if not open or write only + if (!isOpen() || !(flags_ & O_READ)) { + return -1; + } + + // max bytes left in file + if (nbyte > (fileSize_ - curPosition_)) { + nbyte = fileSize_ - curPosition_; + } + + // amount left to read + uint16_t toRead = nbyte; + while (toRead > 0) { + uint32_t block; // raw device block number + uint16_t offset = curPosition_ & 0X1FF; // offset in block + if (type_ == FAT_FILE_TYPE_ROOT16) { + block = vol_->rootDirStart() + (curPosition_ >> 9); + } else { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + if (offset == 0 && blockOfCluster == 0) { + // start of new cluster + if (curPosition_ == 0) { + // use first cluster in file + curCluster_ = firstCluster_; + } else { + // get next cluster from FAT + if (!vol_->fatGet(curCluster_, &curCluster_)) { + return -1; + } + } + } + block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + } + uint16_t n = toRead; + + // amount to be read from current block + if (n > (512 - offset)) { + n = 512 - offset; + } + + // no buffering needed if n == 512 or user requests no buffering + if ((unbufferedRead() || n == 512) && + block != SdVolume::cacheBlockNumber_) { + if (!vol_->readData(block, offset, n, dst)) { + return -1; + } + dst += n; + } else { + // read block to cache and copy data to caller + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) { + return -1; + } + uint8_t* src = SdVolume::cacheBuffer_.data + offset; + uint8_t* end = src + n; + while (src != end) { + *dst++ = *src++; + } + } + curPosition_ += n; + toRead -= n; + } + return nbyte; +} +//------------------------------------------------------------------------------ +/** + Read the next directory entry from a directory file. + + \param[out] dir The dir_t struct that will receive the data. + + \return For success readDir() returns the number of bytes read. + A value of zero will be returned if end of file is reached. + If an error occurs, readDir() returns -1. Possible errors include + readDir() called before a directory has been opened, this is not + a directory file or an I/O error occurred. +*/ +int8_t SdFile::readDir(dir_t* dir) { + int8_t n; + // if not a directory file or miss-positioned return an error + if (!isDir() || (0X1F & curPosition_)) { + return -1; + } + + while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) { + // last entry if DIR_NAME_FREE + if (dir->name[0] == DIR_NAME_FREE) { + break; + } + // skip empty entries and entry for . and .. + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { + continue; + } + // return if normal file or subdirectory + if (DIR_IS_FILE_OR_SUBDIR(dir)) { + return n; + } + } + // error, end of file, or past last entry + return n < 0 ? -1 : 0; +} +//------------------------------------------------------------------------------ +// Read next directory entry into the cache +// Assumes file is correctly positioned +dir_t* SdFile::readDirCache(void) { + // error if not directory + if (!isDir()) { + return NULL; + } + + // index of entry in cache + uint8_t i = (curPosition_ >> 5) & 0XF; + + // use read to locate and cache block + if (read() < 0) { + return NULL; + } + + // advance to next entry + curPosition_ += 31; + + // return pointer to entry + return (SdVolume::cacheBuffer_.dir + i); +} +//------------------------------------------------------------------------------ +/** + Remove a file. + + The directory entry and all data for the file are deleted. + + \note This function should not be used to delete the 8.3 version of a + file that has a long name. For example if a file has the long name + "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the file read-only, is a directory, + or an I/O error occurred. +*/ +uint8_t SdFile::remove(void) { + // free any clusters - will fail if read-only or directory + if (!truncate(0)) { + return false; + } + + // cache directory entry + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) { + return false; + } + + // mark entry deleted + d->name[0] = DIR_NAME_DELETED; + + // set this SdFile closed + type_ = FAT_FILE_TYPE_CLOSED; + + // write entry to SD + return SdVolume::cacheFlush(); +} +//------------------------------------------------------------------------------ +/** + Remove a file. + + The directory entry and all data for the file are deleted. + + \param[in] dirFile The directory that contains the file. + \param[in] fileName The name of the file to be removed. + + \note This function should not be used to delete the 8.3 version of a + file that has a long name. For example if a file has the long name + "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the file is a directory, is read only, + \a dirFile is not a directory, \a fileName is not found + or an I/O error occurred. +*/ +uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) { + SdFile file; + if (!file.open(dirFile, fileName, O_WRITE)) { + return false; + } + return file.remove(); +} +//------------------------------------------------------------------------------ +/** Remove a directory file. + + The directory file will be removed only if it is empty and is not the + root directory. rmDir() follows DOS and Windows and ignores the + read-only attribute for the directory. + + \note This function should not be used to delete the 8.3 version of a + directory that has a long name. For example if a directory has the + long name "New folder" you should not delete the 8.3 name "NEWFOL~1". + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include the file is not a directory, is the root + directory, is not empty, or an I/O error occurred. +*/ +uint8_t SdFile::rmDir(void) { + // must be open subdirectory + if (!isSubDir()) { + return false; + } + + rewind(); + + // make sure directory is empty + while (curPosition_ < fileSize_) { + dir_t* p = readDirCache(); + if (p == NULL) { + return false; + } + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) { + break; + } + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + continue; + } + // error not empty + if (DIR_IS_FILE_OR_SUBDIR(p)) { + return false; + } + } + // convert empty directory to normal file for remove + type_ = FAT_FILE_TYPE_NORMAL; + flags_ |= O_WRITE; + return remove(); +} +//------------------------------------------------------------------------------ +/** Recursively delete a directory and all contained files. + + This is like the Unix/Linux 'rm -rf *' if called with the root directory + hence the name. + + Warning - This will remove all contents of the directory including + subdirectories. The directory will then be removed if it is not root. + The read-only attribute for files will be ignored. + + \note This function should not be used to delete the 8.3 version of + a directory that has a long name. See remove() and rmDir(). + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::rmRfStar(void) { + rewind(); + while (curPosition_ < fileSize_) { + SdFile f; + + // remember position + uint16_t index = curPosition_ / 32; + + dir_t* p = readDirCache(); + if (!p) { + return false; + } + + // done if past last entry + if (p->name[0] == DIR_NAME_FREE) { + break; + } + + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + continue; + } + + // skip if part of long file name or volume label in root + if (!DIR_IS_FILE_OR_SUBDIR(p)) { + continue; + } + + if (!f.open(this, index, O_READ)) { + return false; + } + if (f.isSubDir()) { + // recursively delete + if (!f.rmRfStar()) { + return false; + } + } else { + // ignore read-only + f.flags_ |= O_WRITE; + if (!f.remove()) { + return false; + } + } + // position to next entry if required + if (curPosition_ != (32u * (index + 1))) { + if (!seekSet(32u * (index + 1))) { + return false; + } + } + } + // don't try to delete root + if (isRoot()) { + return true; + } + return rmDir(); +} +//------------------------------------------------------------------------------ +/** + Sets a file's position. + + \param[in] pos The new position in bytes from the beginning of the file. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::seekSet(uint32_t pos) { + // error if file not open or seek past end of file + if (!isOpen() || pos > fileSize_) { + return false; + } + + if (type_ == FAT_FILE_TYPE_ROOT16) { + curPosition_ = pos; + return true; + } + if (pos == 0) { + // set position to start of file + curCluster_ = 0; + curPosition_ = 0; + return true; + } + // calculate cluster index for cur and new position + uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); + uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); + + if (nNew < nCur || curPosition_ == 0) { + // must follow chain from first cluster + curCluster_ = firstCluster_; + } else { + // advance from curPosition + nNew -= nCur; + } + while (nNew--) { + if (!vol_->fatGet(curCluster_, &curCluster_)) { + return false; + } + } + curPosition_ = pos; + return true; +} +//------------------------------------------------------------------------------ +/** + The sync() call causes all modified data and directory fields + to be written to the storage device. + + \param[in] blocking If the sync should block until fully complete. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include a call to sync() before a file has been + opened or an I/O error. +*/ +uint8_t SdFile::sync(uint8_t blocking) { + // only allow open files and directories + if (!isOpen()) { + return false; + } + + if (flags_ & F_FILE_DIR_DIRTY) { + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) { + return false; + } + + // do not set filesize for dir files + if (!isDir()) { + d->fileSize = fileSize_; + } + + // update first cluster fields + d->firstClusterLow = firstCluster_ & 0XFFFF; + d->firstClusterHigh = firstCluster_ >> 16; + + // set modify time if user supplied a callback date/time function + if (dateTime_) { + dateTime_(&d->lastWriteDate, &d->lastWriteTime); + d->lastAccessDate = d->lastWriteDate; + } + // clear directory dirty + flags_ &= ~F_FILE_DIR_DIRTY; + } + + if (!blocking) { + flags_ &= ~F_FILE_NON_BLOCKING_WRITE; + } + + return SdVolume::cacheFlush(blocking); +} +//------------------------------------------------------------------------------ +/** + Set a file's timestamps in its directory entry. + + \param[in] flags Values for \a flags are constructed by a bitwise-inclusive + OR of flags from the following list + + T_ACCESS - Set the file's last access date. + + T_CREATE - Set the file's creation date and time. + + T_WRITE - Set the file's last write/modification date and time. + + \param[in] year Valid range 1980 - 2107 inclusive. + + \param[in] month Valid range 1 - 12 inclusive. + + \param[in] day Valid range 1 - 31 inclusive. + + \param[in] hour Valid range 0 - 23 inclusive. + + \param[in] minute Valid range 0 - 59 inclusive. + + \param[in] second Valid range 0 - 59 inclusive + + \note It is possible to set an invalid date since there is no check for + the number of days in a month. + + \note + Modify and access timestamps may be overwritten if a date time callback + function has been set by dateTimeCallback(). + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. +*/ +uint8_t SdFile::timestamp(uint8_t flags, uint16_t year, uint8_t month, + uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { + if (!isOpen() + || year < 1980 + || year > 2107 + || month < 1 + || month > 12 + || day < 1 + || day > 31 + || hour > 23 + || minute > 59 + || second > 59) { + return false; + } + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) { + return false; + } + + uint16_t dirDate = FAT_DATE(year, month, day); + uint16_t dirTime = FAT_TIME(hour, minute, second); + if (flags & T_ACCESS) { + d->lastAccessDate = dirDate; + } + if (flags & T_CREATE) { + d->creationDate = dirDate; + d->creationTime = dirTime; + // seems to be units of 1/100 second not 1/10 as Microsoft states + d->creationTimeTenths = second & 1 ? 100 : 0; + } + if (flags & T_WRITE) { + d->lastWriteDate = dirDate; + d->lastWriteTime = dirTime; + } + SdVolume::cacheSetDirty(); + return sync(); +} +//------------------------------------------------------------------------------ +/** + Truncate a file to a specified length. The current file position + will be maintained if it is less than or equal to \a length otherwise + it will be set to end of file. + + \param[in] length The desired length for the file. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. + Reasons for failure include file is read only, file is a directory, + \a length is greater than the current file size or an I/O error occurs. +*/ +uint8_t SdFile::truncate(uint32_t length) { + // error if not a normal file or read-only + if (!isFile() || !(flags_ & O_WRITE)) { + return false; + } + + // error if length is greater than current size + if (length > fileSize_) { + return false; + } + + // fileSize and length are zero - nothing to do + if (fileSize_ == 0) { + return true; + } + + // remember position for seek after truncation + uint32_t newPos = curPosition_ > length ? length : curPosition_; + + // position to last cluster in truncated file + if (!seekSet(length)) { + return false; + } + + if (length == 0) { + // free all clusters + if (!vol_->freeChain(firstCluster_)) { + return false; + } + firstCluster_ = 0; + } else { + uint32_t toFree; + if (!vol_->fatGet(curCluster_, &toFree)) { + return false; + } + + if (!vol_->isEOC(toFree)) { + // free extra clusters + if (!vol_->freeChain(toFree)) { + return false; + } + + // current cluster is end of chain + if (!vol_->fatPutEOC(curCluster_)) { + return false; + } + } + } + fileSize_ = length; + + // need to update directory entry + flags_ |= F_FILE_DIR_DIRTY; + + if (!sync()) { + return false; + } + + // set file to correct position + return seekSet(newPos); +} +//------------------------------------------------------------------------------ +/** + Write data to an open file. + + \note Data is moved to the cache but may not be written to the + storage device until sync() is called. + + \param[in] buf Pointer to the location of the data to be written. + + \param[in] nbyte Number of bytes to write. + + \return For success write() returns the number of bytes written, always + \a nbyte. If an error occurs, write() returns 0. Possible errors + include write() is called before a file has been opened, write is called + for a read-only file, device is full, a corrupt file system or an I/O error. + +*/ +size_t SdFile::write(const void* buf, uint16_t nbyte) { + // convert void* to uint8_t* - must be before goto statements + const uint8_t* src = reinterpret_cast(buf); + + // number of bytes left to write - must be before goto statements + uint16_t nToWrite = nbyte; + // if blocking writes should be used + uint8_t blocking = (flags_ & F_FILE_NON_BLOCKING_WRITE) == 0x00; + + // error if not a normal file or is read-only + if (!isFile() || !(flags_ & O_WRITE)) { + goto writeErrorReturn; + } + + // seek to end of file if append flag + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) { + goto writeErrorReturn; + } + } + + while (nToWrite > 0) { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + uint16_t blockOffset = curPosition_ & 0X1FF; + if (blockOfCluster == 0 && blockOffset == 0) { + // start of new cluster + if (curCluster_ == 0) { + if (firstCluster_ == 0) { + // allocate first cluster of file + if (!addCluster()) { + goto writeErrorReturn; + } + } else { + curCluster_ = firstCluster_; + } + } else { + uint32_t next; + if (!vol_->fatGet(curCluster_, &next)) { + return false; + } + if (vol_->isEOC(next)) { + // add cluster if at end of chain + if (!addCluster()) { + goto writeErrorReturn; + } + } else { + curCluster_ = next; + } + } + } + // max space in block + uint16_t n = 512 - blockOffset; + + // lesser of space and amount to write + if (n > nToWrite) { + n = nToWrite; + } + + // block for data write + uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + if (n == 512) { + // full block - don't need to use cache + // invalidate cache if block is in cache + if (SdVolume::cacheBlockNumber_ == block) { + SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; + } + if (!vol_->writeBlock(block, src, blocking)) { + goto writeErrorReturn; + } + src += 512; + } else { + if (blockOffset == 0 && curPosition_ >= fileSize_) { + // start of new block don't need to read into cache + if (!SdVolume::cacheFlush()) { + goto writeErrorReturn; + } + SdVolume::cacheBlockNumber_ = block; + SdVolume::cacheSetDirty(); + } else { + // rewrite part of block + if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { + goto writeErrorReturn; + } + } + uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset; + uint8_t* end = dst + n; + while (dst != end) { + *dst++ = *src++; + } + } + nToWrite -= n; + curPosition_ += n; + } + if (curPosition_ > fileSize_) { + // update fileSize and insure sync will update dir entry + fileSize_ = curPosition_; + flags_ |= F_FILE_DIR_DIRTY; + } else if (dateTime_ && nbyte) { + // insure sync will update modified date and time + flags_ |= F_FILE_DIR_DIRTY; + } + + if (flags_ & O_SYNC) { + if (!sync()) { + goto writeErrorReturn; + } + } + return nbyte; + +writeErrorReturn: + // return for write error + //writeError = true; + setWriteError(); + return 0; +} +//------------------------------------------------------------------------------ +/** + Write a byte to a file. Required by the Arduino Print class. + + Use SdFile::writeError to check for errors. +*/ +size_t SdFile::write(uint8_t b) { + return write(&b, 1); +} +//------------------------------------------------------------------------------ +/** + Write a string to a file. Used by the Arduino Print class. + + Use SdFile::writeError to check for errors. +*/ +size_t SdFile::write(const char* str) { + return write(str, strlen(str)); +} +#ifdef __AVR__ +//------------------------------------------------------------------------------ +/** + Write a PROGMEM string to a file. + + Use SdFile::writeError to check for errors. +*/ +void SdFile::write_P(PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) { + write(c); + } +} +//------------------------------------------------------------------------------ +/** + Write a PROGMEM string followed by CR/LF to a file. + + Use SdFile::writeError to check for errors. +*/ +void SdFile::writeln_P(PGM_P str) { + write_P(str); + println(); +} +#endif +//------------------------------------------------------------------------------ +/** + Check how many bytes can be written without blocking. + + \return The number of bytes that can be written without blocking. +*/ +int SdFile::availableForWrite() { + if (!isFile() || !(flags_ & O_WRITE)) { + return 0; + } + + // seek to end of file if append flag + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) { + return 0; + } + } + + if (vol_->isBusy()) { + return 0; + } + + if (flags_ & F_FILE_CLUSTER_ADDED) { + // new cluster added, trigger a non-blocking sync + sync(0); + flags_ &= ~F_FILE_CLUSTER_ADDED; + return 0; + } + + if (vol_->isCacheMirrorBlockDirty()) { + // cache mirror block is dirty, trigger a non-blocking sync + vol_->cacheMirrorBlockFlush(0); + return 0; + } + + flags_ |= F_FILE_NON_BLOCKING_WRITE; + + uint16_t blockOffset = curPosition_ & 0X1FF; + uint16_t n = 512 - blockOffset; + + return n; +} diff --git a/libraries/SD/src/utility/SdInfo.h b/libraries/SD/src/utility/SdInfo.h new file mode 100644 index 0000000..e9c80db --- /dev/null +++ b/libraries/SD/src/utility/SdInfo.h @@ -0,0 +1,232 @@ +/* Arduino Sd2Card Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino Sd2Card Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino Sd2Card Library. If not, see + . +*/ +#ifndef SdInfo_h +#define SdInfo_h +#include +// Based on the document: +// +// SD Specifications +// Part 1 +// Physical Layer +// Simplified Specification +// Version 2.00 +// September 25, 2006 +// +// www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf +//------------------------------------------------------------------------------ +// SD card commands +/** GO_IDLE_STATE - init card in spi mode if CS low */ +uint8_t const CMD0 = 0X00; +/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ +uint8_t const CMD8 = 0X08; +/** SEND_CSD - read the Card Specific Data (CSD register) */ +uint8_t const CMD9 = 0X09; +/** SEND_CID - read the card identification information (CID register) */ +uint8_t const CMD10 = 0X0A; +/** SEND_STATUS - read the card status register */ +uint8_t const CMD13 = 0X0D; +/** READ_BLOCK - read a single data block from the card */ +uint8_t const CMD17 = 0X11; +/** WRITE_BLOCK - write a single data block to the card */ +uint8_t const CMD24 = 0X18; +/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ +uint8_t const CMD25 = 0X19; +/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ +uint8_t const CMD32 = 0X20; +/** ERASE_WR_BLK_END - sets the address of the last block of the continuous + range to be erased*/ +uint8_t const CMD33 = 0X21; +/** ERASE - erase all previously selected blocks */ +uint8_t const CMD38 = 0X26; +/** APP_CMD - escape for application specific command */ +uint8_t const CMD55 = 0X37; +/** READ_OCR - read the OCR register of a card */ +uint8_t const CMD58 = 0X3A; +/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be + pre-erased before writing */ +uint8_t const ACMD23 = 0X17; +/** SD_SEND_OP_COMD - Sends host capacity support information and + activates the card's initialization process */ +uint8_t const ACMD41 = 0X29; +//------------------------------------------------------------------------------ +/** status for card in the ready state */ +uint8_t const R1_READY_STATE = 0X00; +/** status for card in the idle state */ +uint8_t const R1_IDLE_STATE = 0X01; +/** status bit for illegal command */ +uint8_t const R1_ILLEGAL_COMMAND = 0X04; +/** start data token for read or write single block*/ +uint8_t const DATA_START_BLOCK = 0XFE; +/** stop token for write multiple blocks*/ +uint8_t const STOP_TRAN_TOKEN = 0XFD; +/** start data token for write multiple blocks*/ +uint8_t const WRITE_MULTIPLE_TOKEN = 0XFC; +/** mask for data response tokens after a write block operation */ +uint8_t const DATA_RES_MASK = 0X1F; +/** write data accepted token */ +uint8_t const DATA_RES_ACCEPTED = 0X05; +//------------------------------------------------------------------------------ +typedef struct CID { + // byte 0 + uint8_t mid; // Manufacturer ID + // byte 1-2 + char oid[2]; // OEM/Application ID + // byte 3-7 + char pnm[5]; // Product name + // byte 8 + unsigned prv_m : 4; // Product revision n.m + unsigned prv_n : 4; + // byte 9-12 + uint32_t psn; // Product serial number + // byte 13 + unsigned mdt_year_high : 4; // Manufacturing date + unsigned reserved : 4; + // byte 14 + unsigned mdt_month : 4; + unsigned mdt_year_low : 4; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +} cid_t; +//------------------------------------------------------------------------------ +// CSD for version 1.00 cards +typedef struct CSDV1 { + // byte 0 + unsigned reserved1 : 6; + unsigned csd_ver : 2; + // byte 1 + uint8_t taac; + // byte 2 + uint8_t nsac; + // byte 3 + uint8_t tran_speed; + // byte 4 + uint8_t ccc_high; + // byte 5 + unsigned read_bl_len : 4; + unsigned ccc_low : 4; + // byte 6 + unsigned c_size_high : 2; + unsigned reserved2 : 2; + unsigned dsr_imp : 1; + unsigned read_blk_misalign : 1; + unsigned write_blk_misalign : 1; + unsigned read_bl_partial : 1; + // byte 7 + uint8_t c_size_mid; + // byte 8 + unsigned vdd_r_curr_max : 3; + unsigned vdd_r_curr_min : 3; + unsigned c_size_low : 2; + // byte 9 + unsigned c_size_mult_high : 2; + unsigned vdd_w_cur_max : 3; + unsigned vdd_w_curr_min : 3; + // byte 10 + unsigned sector_size_high : 6; + unsigned erase_blk_en : 1; + unsigned c_size_mult_low : 1; + // byte 11 + unsigned wp_grp_size : 7; + unsigned sector_size_low : 1; + // byte 12 + unsigned write_bl_len_high : 2; + unsigned r2w_factor : 3; + unsigned reserved3 : 2; + unsigned wp_grp_enable : 1; + // byte 13 + unsigned reserved4 : 5; + unsigned write_partial : 1; + unsigned write_bl_len_low : 2; + // byte 14 + unsigned reserved5: 2; + unsigned file_format : 2; + unsigned tmp_write_protect : 1; + unsigned perm_write_protect : 1; + unsigned copy : 1; + unsigned file_format_grp : 1; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +} csd1_t; +//------------------------------------------------------------------------------ +// CSD for version 2.00 cards +typedef struct CSDV2 { + // byte 0 + unsigned reserved1 : 6; + unsigned csd_ver : 2; + // byte 1 + uint8_t taac; + // byte 2 + uint8_t nsac; + // byte 3 + uint8_t tran_speed; + // byte 4 + uint8_t ccc_high; + // byte 5 + unsigned read_bl_len : 4; + unsigned ccc_low : 4; + // byte 6 + unsigned reserved2 : 4; + unsigned dsr_imp : 1; + unsigned read_blk_misalign : 1; + unsigned write_blk_misalign : 1; + unsigned read_bl_partial : 1; + // byte 7 + unsigned reserved3 : 2; + unsigned c_size_high : 6; + // byte 8 + uint8_t c_size_mid; + // byte 9 + uint8_t c_size_low; + // byte 10 + unsigned sector_size_high : 6; + unsigned erase_blk_en : 1; + unsigned reserved4 : 1; + // byte 11 + unsigned wp_grp_size : 7; + unsigned sector_size_low : 1; + // byte 12 + unsigned write_bl_len_high : 2; + unsigned r2w_factor : 3; + unsigned reserved5 : 2; + unsigned wp_grp_enable : 1; + // byte 13 + unsigned reserved6 : 5; + unsigned write_partial : 1; + unsigned write_bl_len_low : 2; + // byte 14 + unsigned reserved7: 2; + unsigned file_format : 2; + unsigned tmp_write_protect : 1; + unsigned perm_write_protect : 1; + unsigned copy : 1; + unsigned file_format_grp : 1; + // byte 15 + unsigned always1 : 1; + unsigned crc : 7; +} csd2_t; +//------------------------------------------------------------------------------ +// union of old and new style CSD register +union csd_t { + csd1_t v1; + csd2_t v2; +}; +#endif // SdInfo_h diff --git a/libraries/SD/src/utility/SdVolume.cpp b/libraries/SD/src/utility/SdVolume.cpp new file mode 100644 index 0000000..b8b6025 --- /dev/null +++ b/libraries/SD/src/utility/SdVolume.cpp @@ -0,0 +1,351 @@ +/* Arduino SdFat Library + Copyright (C) 2009 by William Greiman + + This file is part of the Arduino SdFat Library + + This Library is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the Arduino SdFat Library. If not, see + . +*/ +#include "SdFat.h" +//------------------------------------------------------------------------------ +// raw block cache +// init cacheBlockNumber_to invalid SD block number +uint32_t SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; +cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card +Sd2Card* SdVolume::sdCard_; // pointer to SD card object +uint8_t SdVolume::cacheDirty_ = 0; // cacheFlush() will write block if true +uint32_t SdVolume::cacheMirrorBlock_ = 0; // mirror block for second FAT +//------------------------------------------------------------------------------ +// find a contiguous group of clusters +uint8_t SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) { + // start of group + uint32_t bgnCluster; + + // flag to save place to start next search + uint8_t setStart; + + // set search start cluster + if (*curCluster) { + // try to make file contiguous + bgnCluster = *curCluster + 1; + + // don't save new start location + setStart = false; + } else { + // start at likely place for free cluster + bgnCluster = allocSearchStart_; + + // save next search start if one cluster + setStart = 1 == count; + } + // end of group + uint32_t endCluster = bgnCluster; + + // last cluster of FAT + uint32_t fatEnd = clusterCount_ + 1; + + // search the FAT for free clusters + for (uint32_t n = 0;; n++, endCluster++) { + // can't find space checked all clusters + if (n >= clusterCount_) { + return false; + } + + // past end - start from beginning of FAT + if (endCluster > fatEnd) { + bgnCluster = endCluster = 2; + } + uint32_t f; + if (!fatGet(endCluster, &f)) { + return false; + } + + if (f != 0) { + // cluster in use try next cluster as bgnCluster + bgnCluster = endCluster + 1; + } else if ((endCluster - bgnCluster + 1) == count) { + // done - found space + break; + } + } + // mark end of chain + if (!fatPutEOC(endCluster)) { + return false; + } + + // link clusters + while (endCluster > bgnCluster) { + if (!fatPut(endCluster - 1, endCluster)) { + return false; + } + endCluster--; + } + if (*curCluster != 0) { + // connect chains + if (!fatPut(*curCluster, bgnCluster)) { + return false; + } + } + // return first cluster number to caller + *curCluster = bgnCluster; + + // remember possible next free cluster + if (setStart) { + allocSearchStart_ = bgnCluster + 1; + } + + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheFlush(uint8_t blocking) { + if (cacheDirty_) { + if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data, blocking)) { + return false; + } + + if (!blocking) { + return true; + } + + // mirror FAT tables + if (!cacheMirrorBlockFlush(blocking)) { + return false; + } + cacheDirty_ = 0; + } + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheMirrorBlockFlush(uint8_t blocking) { + if (cacheMirrorBlock_) { + if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data, blocking)) { + return false; + } + cacheMirrorBlock_ = 0; + } + return true; +} +//------------------------------------------------------------------------------ +uint8_t SdVolume::cacheRawBlock(uint32_t blockNumber, uint8_t action) { + if (cacheBlockNumber_ != blockNumber) { + if (!cacheFlush()) { + return false; + } + if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) { + return false; + } + cacheBlockNumber_ = blockNumber; + } + cacheDirty_ |= action; + return true; +} +//------------------------------------------------------------------------------ +// cache a zero block for blockNumber +uint8_t SdVolume::cacheZeroBlock(uint32_t blockNumber) { + if (!cacheFlush()) { + return false; + } + + // loop take less flash than memset(cacheBuffer_.data, 0, 512); + for (uint16_t i = 0; i < 512; i++) { + cacheBuffer_.data[i] = 0; + } + cacheBlockNumber_ = blockNumber; + cacheSetDirty(); + return true; +} +//------------------------------------------------------------------------------ +// return the size in bytes of a cluster chain +uint8_t SdVolume::chainSize(uint32_t cluster, uint32_t* size) const { + uint32_t s = 0; + do { + if (!fatGet(cluster, &cluster)) { + return false; + } + s += 512UL << clusterSizeShift_; + } while (!isEOC(cluster)); + *size = s; + return true; +} +//------------------------------------------------------------------------------ +// Fetch a FAT entry +uint8_t SdVolume::fatGet(uint32_t cluster, uint32_t* value) const { + if (cluster > (clusterCount_ + 1)) { + return false; + } + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) { + return false; + } + } + if (fatType_ == 16) { + *value = cacheBuffer_.fat16[cluster & 0XFF]; + } else { + *value = cacheBuffer_.fat32[cluster & 0X7F] & FAT32MASK; + } + return true; +} +//------------------------------------------------------------------------------ +// Store a FAT entry +uint8_t SdVolume::fatPut(uint32_t cluster, uint32_t value) { + // error if reserved cluster + if (cluster < 2) { + return false; + } + + // error if not in FAT + if (cluster > (clusterCount_ + 1)) { + return false; + } + + // calculate block address for entry + uint32_t lba = fatStartBlock_; + lba += fatType_ == 16 ? cluster >> 8 : cluster >> 7; + + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) { + return false; + } + } + // store entry + if (fatType_ == 16) { + cacheBuffer_.fat16[cluster & 0XFF] = value; + } else { + cacheBuffer_.fat32[cluster & 0X7F] = value; + } + cacheSetDirty(); + + // mirror second FAT + if (fatCount_ > 1) { + cacheMirrorBlock_ = lba + blocksPerFat_; + } + return true; +} +//------------------------------------------------------------------------------ +// free a cluster chain +uint8_t SdVolume::freeChain(uint32_t cluster) { + // clear free cluster location + allocSearchStart_ = 2; + + do { + uint32_t next; + if (!fatGet(cluster, &next)) { + return false; + } + + // free cluster + if (!fatPut(cluster, 0)) { + return false; + } + + cluster = next; + } while (!isEOC(cluster)); + + return true; +} +//------------------------------------------------------------------------------ +/** + Initialize a FAT volume. + + \param[in] dev The SD card where the volume is located. + + \param[in] part The partition to be used. Legal values for \a part are + 1-4 to use the corresponding partition on a device formatted with + a MBR, Master Boot Record, or zero if the device is formatted as + a super floppy with the FAT boot sector in block zero. + + \return The value one, true, is returned for success and + the value zero, false, is returned for failure. Reasons for + failure include not finding a valid partition, not finding a valid + FAT file system in the specified partition or an I/O error. +*/ +uint8_t SdVolume::init(Sd2Card* dev, uint8_t part) { + uint32_t volumeStartBlock = 0; + sdCard_ = dev; + // if part == 0 assume super floppy with FAT boot sector in block zero + // if part > 0 assume mbr volume with partition table + if (part) { + if (part > 4) { + return false; + } + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) { + return false; + } + part_t* p = &cacheBuffer_.mbr.part[part - 1]; + if ((p->boot & 0X7F) != 0 || + p->totalSectors < 100 || + p->firstSector == 0) { + // not a valid partition + return false; + } + volumeStartBlock = p->firstSector; + } + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) { + return false; + } + bpb_t* bpb = &cacheBuffer_.fbs.bpb; + if (bpb->bytesPerSector != 512 || + bpb->fatCount == 0 || + bpb->reservedSectorCount == 0 || + bpb->sectorsPerCluster == 0) { + // not valid FAT volume + return false; + } + fatCount_ = bpb->fatCount; + blocksPerCluster_ = bpb->sectorsPerCluster; + + // determine shift that is same as multiply by blocksPerCluster_ + clusterSizeShift_ = 0; + while (blocksPerCluster_ != (1 << clusterSizeShift_)) { + // error if not power of 2 + if (clusterSizeShift_++ > 7) { + return false; + } + } + blocksPerFat_ = bpb->sectorsPerFat16 ? + bpb->sectorsPerFat16 : bpb->sectorsPerFat32; + + fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount; + + // count for FAT16 zero for FAT32 + rootDirEntryCount_ = bpb->rootDirEntryCount; + + // directory start for FAT16 dataStart for FAT32 + rootDirStart_ = fatStartBlock_ + bpb->fatCount * blocksPerFat_; + + // data start for FAT16 and FAT32 + dataStartBlock_ = rootDirStart_ + ((32 * bpb->rootDirEntryCount + 511) / 512); + + // total blocks for FAT16 or FAT32 + uint32_t totalBlocks = bpb->totalSectors16 ? + bpb->totalSectors16 : bpb->totalSectors32; + // total data blocks + clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock); + + // divide by cluster size to get cluster count + clusterCount_ >>= clusterSizeShift_; + + // FAT type is determined by cluster count + if (clusterCount_ < 4085) { + fatType_ = 12; + } else if (clusterCount_ < 65525) { + fatType_ = 16; + } else { + rootDirStart_ = bpb->fat32RootCluster; + fatType_ = 32; + } + return true; +} diff --git a/libraries/Servo/LICENSE.txt b/libraries/Servo/LICENSE.txt new file mode 100644 index 0000000..8000a6f --- /dev/null +++ b/libraries/Servo/LICENSE.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/libraries/Servo/README.adoc b/libraries/Servo/README.adoc new file mode 100644 index 0000000..b16b16b --- /dev/null +++ b/libraries/Servo/README.adoc @@ -0,0 +1,13 @@ +:repository-owner: arduino-libraries +:repository-name: Servo + += {repository-name} Library for Arduino = + +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml/badge.svg["Check Arduino status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml"] +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml/badge.svg["Compile Examples status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml"] +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml/badge.svg["Spell Check status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml"] + +This library allows an Arduino board to control RC (hobby) servo motors. + +For more information about this library please visit us at +https://www.arduino.cc/reference/en/libraries/servo/ diff --git a/libraries/Servo/docs/api.md b/libraries/Servo/docs/api.md new file mode 100644 index 0000000..fc54c9d --- /dev/null +++ b/libraries/Servo/docs/api.md @@ -0,0 +1,181 @@ +# Servo library + +## Methods + +### `attach()` + +Attach the Servo variable to a pin. Note that in Arduino 0016 and earlier, the Servo library supports servos on only two pins: 9 and 10. + +#### Syntax + +``` +servo.attach(pin) +servo.attach(pin, min, max) +``` + +#### Parameters + +* _servo_: a variable of type `Servo` +* _pin_: the number of the pin that the servo is attached to +* _min_ (optional): the pulse width, in microseconds, corresponding to the minimum (0 degree) angle on the servo (defaults to 544) +* _max_ (optional): the pulse width, in microseconds, corresponding to the maximum (180 degree) angle on the servo (defaults to 2400) + +#### Example + +``` +#include + +Servo myservo; + +void setup() +{ + myservo.attach(9); +} + +void loop() {} +``` + +#### See also + +* [attached()](#attached) +* [detach()](#detach) + +### `write()` + +Writes a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement). + +#### Syntax + +``` +servo.write(angle) +``` + +#### Parameters + +* _servo_: a variable of type Servo +* _angle_: the value to write to the servo, from 0 to 180 + +#### Example + +```` +#include + +Servo myservo; + +void setup() +{ + myservo.attach(9); + myservo.write(90); // set servo to mid-point +} + +void loop() {} +```` +#### See also + +* [attach()](#attach) +* [read()](#read) + +### `writeMicroseconds()` + +Writes a value in microseconds (us) to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft. On standard servos a parameter value of 1000 is fully counter-clockwise, 2000 is fully clockwise, and 1500 is in the middle. + +Note that some manufactures do not follow this standard very closely so that servos often respond to values between 700 and 2300. Feel free to increase these endpoints until the servo no longer continues to increase its range. Note however that attempting to drive a servo past its endpoints (often indicated by a growling sound) is a high-current state, and should be avoided. + +Continuous-rotation servos will respond to the writeMicrosecond function in an analogous manner to the write function. + +#### Syntax + +```` +servo.writeMicroseconds(us) +```` + +#### Parameters + +* _servo_: a variable of type Servo +* _us_: the value of the parameter in microseconds (int) + +#### Example + +```` +#include + +Servo myservo; + +void setup() +{ + myservo.attach(9); + myservo.writeMicroseconds(1500); // set servo to mid-point +} + +void loop() {} +```` + +#### See also + +* [attach()](#attach) +* [read()](#read) + + +### `read()` + +Read the current angle of the servo (the value passed to the last call to [write()](#write)). + +#### Syntax + +```` +servo.read() +```` + +#### Parameters + +* _servo_: a variable of type `Servo` + +#### Returns + +The angle of the servo, from 0 to 180 degrees. + +#### See also + +* [write()](#write) + +### `attached()` + +Check whether the Servo variable is attached to a pin. + +#### Syntax + +``` +servo.attached() +``` + +#### Parameters + +* _servo_: a variable of type `Servo` + +#### Returns + +`true` if the servo is attached to pin; `false` otherwise. + +#### See also + +* [attach()](#attach) +* [detach()](#detach) + +### `detach()` + +Detach the Servo variable from its pin. If all Servo variables are detached, then pins 9 and 10 can be used for PWM output with [analogWrite()](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/). + +#### Syntax + +``` +servo.detach() +``` + +#### Parameters + +* _servo_: a variable of type `Servo` + +#### See also + +* [attach()](#attach) +* [attached()](#attached) diff --git a/libraries/Servo/docs/readme.md b/libraries/Servo/docs/readme.md new file mode 100644 index 0000000..b986b14 --- /dev/null +++ b/libraries/Servo/docs/readme.md @@ -0,0 +1,21 @@ +# Servo library + + +This library allows an Arduino board to control RC (hobby) servo motors. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos allow the rotation of the shaft to be set to various speeds. + +The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables `analogWrite()` (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12. + +To use this library: + +``` +#include +``` + +## Circuit + +Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow, orange or white and should be connected to a digital pin on the Arduino board. Note that servos draw considerable power, so if you need to drive more than one or two, you'll probably need to power them from a separate supply (i.e. not the 5V pin on your Arduino). Be sure to connect the grounds of the Arduino and external power supply together. + +## Examples + +* [Knob](https://www.arduino.cc/en/Tutorial/Knob): control the shaft of a servo motor by turning a potentiometer +* [Sweep](https://www.arduino.cc/en/Tutorial/LibraryExamples/Sweep): sweeps the shaft of a servo motor back and forth diff --git a/libraries/Servo/examples/Knob/Knob.ino b/libraries/Servo/examples/Knob/Knob.ino new file mode 100644 index 0000000..0015a46 --- /dev/null +++ b/libraries/Servo/examples/Knob/Knob.ino @@ -0,0 +1,26 @@ +/* + Controlling a servo position using a potentiometer (variable resistor) + by Michal Rinott + + modified on 8 Nov 2013 + by Scott Fitzgerald + http://www.arduino.cc/en/Tutorial/Knob +*/ + +#include + +Servo myservo; // create servo object to control a servo + +int potpin = A0; // analog pin used to connect the potentiometer +int val; // variable to read the value from the analog pin + +void setup() { + myservo.attach(9); // attaches the servo on pin 9 to the servo object +} + +void loop() { + val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) + val = map(val, 0, 1023, 0, 180); // scale it for use with the servo (value between 0 and 180) + myservo.write(val); // sets the servo position according to the scaled value + delay(15); // waits for the servo to get there +} diff --git a/libraries/Servo/examples/Knob/images/knob_BB.png b/libraries/Servo/examples/Knob/images/knob_BB.png new file mode 100644 index 0000000000000000000000000000000000000000..af398f3f1edc92531613c4d9eab0648599a885e7 GIT binary patch literal 20514 zcma&NbzD^6_dPsAH_{EFgtT7?j(-nHIPwuyDXx zqHBEf^*yh`th2!W5mQ59#OB5X>*|}sT=Yj6t?%FWT#BKFZ(gmIzp}_B<2V_0R&Ff( z^L;GvbXD*;z{P6~gzG-ZcMe0@#2wVkBd~Mym$tu)0LA2CO7Su3EFGvaph<;zT>I_J z`{I8z((U!T^{(}4{@+2Yu&U38 z?go4|@jinW{t$kSu^^RZtx?7)NQk^p;<=lqMCM#%;v5aSowN18k7pffUyIsCj>;`^ zGgU9}zIJ4t1*+DqO7zh8U{h2|$~8x4pGVC|ZkYcn*zOAxrzYn=yLv~`L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z94b2<0dK9}t6hkSP4qPDPf&gG}R>3r5IpcnC50!SM?M2oEvN8Ge9}5Wggft(Nin zTl0&l4fKu|=@(~DzD!U&YH#1Q{=|uuIl<;{b n{}6xqpZ?(AdqbI3W0I@#0vuXm0~&~bN5x{TwOOvoj+6fcdam^w literal 0 HcmV?d00001 diff --git a/libraries/Servo/examples/Knob/readme.md b/libraries/Servo/examples/Knob/readme.md new file mode 100644 index 0000000..7dc37dd --- /dev/null +++ b/libraries/Servo/examples/Knob/readme.md @@ -0,0 +1,35 @@ +# Knob + +Control the position of a RC (hobby) [servo motor](http://en.wikipedia.org/wiki/Servo_motor#RC_servos) with your Arduino and a potentiometer. + +This example makes use of the Arduino `Servo` library. + +## Hardware Required + +* an Arduino board +* Servo motor +* 10k ohm potentiometer +* hook-up wires + +## Circuit + +Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the board. The signal pin is typically yellow or orange and should be connected to pin 9 on the board. + +The potentiometer should be wired so that its two outer pins are connected to power (+5V) and ground, and its middle pin is connected to analog input 0 on the board. + +![](images/knob_BB.png) + +(Images developed using Fritzing. For more circuit examples, see the [Fritzing project page](http://fritzing.org/projects/)) + +## Schematic + +![](images/knob_schem.png) + +## See also + +* [attach()](/docs/api.md#attach) +* [write()](/docs/api.md#write) +* [map()](https://www.arduino.cc/en/Reference/Map) +* [analogRead()](https://www.arduino.cc/en/Reference/AnalogRead) +* [Servo library reference](/docs/readme.md) +* [Sweep](../Sweep) - Sweep the shaft of a servo motor back and forth diff --git a/libraries/Servo/examples/Sweep/Sweep.ino b/libraries/Servo/examples/Sweep/Sweep.ino new file mode 100644 index 0000000..e988bbd --- /dev/null +++ b/libraries/Servo/examples/Sweep/Sweep.ino @@ -0,0 +1,31 @@ +/* Sweep + by BARRAGAN + This example code is in the public domain. + + modified 8 Nov 2013 + by Scott Fitzgerald + https://www.arduino.cc/en/Tutorial/LibraryExamples/Sweep +*/ + +#include + +Servo myservo; // create servo object to control a servo +// twelve servo objects can be created on most boards + +int pos = 0; // variable to store the servo position + +void setup() { + myservo.attach(9); // attaches the servo on pin 9 to the servo object +} + +void loop() { + for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees + // in steps of 1 degree + myservo.write(pos); // tell servo to go to position in variable 'pos' + delay(15); // waits 15 ms for the servo to reach the position + } + for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees + myservo.write(pos); // tell servo to go to position in variable 'pos' + delay(15); // waits 15 ms for the servo to reach the position + } +} diff --git a/libraries/Servo/examples/Sweep/images/sweep_bb.png b/libraries/Servo/examples/Sweep/images/sweep_bb.png new file mode 100644 index 0000000000000000000000000000000000000000..336eb11ad9cae3194b13959b3774ead5058488a6 GIT binary patch literal 18442 zcmYhi1yoeu8!ik;NQ%UOv>*yNfTVON-61eTGjvL)bTddd(nw1R(miy8bR*r}@Ev~t zd++*KYu1|CoO5=ZcfavG&kj{mki^9z!$Lwr!j+a1Q$a#Po&i31&ryID8LFFhBqWpr z^Ut4^q(6VAQL_JPVs2%Ogyf1G_+{9VP?YF_+oo`Y_PM4dUZraktu(aQOnid-{w2&3 zXO6l?Jj#eedeVk__uy^y&yatsqfCq9`&k%|K2+{UMyxV{n&J$L#SE}466WJU8@ZaF zJFP=rr;8sCJ-<3HA>rDOai062{=@B7$$n{W_3e|zT?kS{Hl`>iz1rNK!W(o^e}`+2 z&1v@+zFO)X9=9%)F27R7YEm!)?nRa*Q)ZaT4@vB>padu(0!vwp-Hy+f)}~MPB6$_u zT-&N&ycg_*(tZ=+Vjl9AuT>qS9~beL;)y%AQxWFU96QjE%L7&s_~ zW&KdNz>8{1JM&VgS`=!3-H!e0m#{?b_w@7dzrw2qE4dq;L4p*dTxVDM#DB;NuejQY z^zh~1Wq+}oVZl94D!o@fk@2&Q;^{Lo@Nv+TQk;^rxvCFF^L#r+Shnh-uDs$FNocw_ zv2Z9pi&FLhj}nIrCk0nZ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?$vlud$2vMJzJWk{|oYW!Nfe*u3(6?6%Wfc^T6ITxpgB84> zzbC}Pf;i#G)Rc_m-Af?Gjl-nOe$nYxU<4gZ3Km5h_3f0>U5Q$U?xNNn6;J^v z%uD2fuu+D9SjjICr+SlMWM-xePRnYpgK+}5Ohm*)%sbmSHK_IJ0*@S!DtvtjeD(kc zito!^XdfJOgS7&`B>18xKboNC^?WK&F)AS&a+MJ*699HY5P+xwdpQ>1ne(bR7!u(7 zJiube4I=n$@f6MGq}%ztTI}Bf$%plGz7~QSdvg1IvZs%=xk^Y zoEEd(nuDsBv=h*0g<7!6pNN(=I)D^!x(0TOfalNqK`)PvroDBPh)91$m;}Rw2W+wX z5nJlK!p?J%)pMZS36v`vNIs|NHKPb|M``(&q45W~>p{`XaHZR=M$f3IC@vy>K*J{t z3~C}Cg%=!oh3l-pPHtpU!He+l=Z%_kERI7DJs(kBcO7o1!oIR`Ev z`9?*|#^xr&C%-&o`Pg!aB`*C96oqhT6$s|z?YH2EnevO0<6&COy9ZdQPpt&bFJOFu zzP>;)9s|QMRf7~52(C7ZFU`%(0|QZQa7K?8TmqIg$g{O!IoY9HAJceKx&S zkjM3AY4E-|ff6;vJ zM_++if8QuHa{m491sN)w>K`Ns!ibcV)CH`0?ts-OvQKhgZP)p}7p5 zCHz6=d;}TE$bu9Yx91@{7#@844jfLa$j_&QD?pi`0>Sqa;AnJobO|N9DYqHPdHaI!@sb=eN0|Yow>!L+G;5h9SNQp_{GwEw>MKuX}Je>h_Gl2R5 zBD$|7vN3S5qE=HlsT;+^vmU*O)FT6NV0DgN3WVwv fx; +sentence=Allows Arduino boards to control a variety of servo motors. +paragraph=This library can control a great number of servos.
It makes careful use of timers: the library can control 12 servos using only 1 timer.
On the Arduino Due you can control up to 60 servos. +category=Device Control +url=https://www.arduino.cc/reference/en/libraries/servo/ +architectures=avr,megaavr,sam,samd,nrf52,stm32f4,mbed,mbed_nano,mbed_portenta,mbed_rp2040 diff --git a/libraries/Servo/src/Servo.h b/libraries/Servo/src/Servo.h new file mode 100644 index 0000000..1f52912 --- /dev/null +++ b/libraries/Servo/src/Servo.h @@ -0,0 +1,123 @@ +/* + Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 + Copyright (c) 2009 Michael Margolis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + A servo is activated by creating an instance of the Servo class passing + the desired pin to the attach() method. + The servos are pulsed in the background using the value most recently + written using the write() method. + + Note that analogWrite of PWM on pins associated with the timer are + disabled when the first servo is attached. + Timers are seized as needed in groups of 12 servos - 24 servos use two + timers, 48 servos will use four. + The sequence used to seize timers is defined in timers.h + + The methods are: + + Servo - Class for manipulating servo motors connected to Arduino pins. + + attach(pin ) - Attaches a servo motor to an I/O pin. + attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds + default min is 544, max is 2400 + + write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) + writeMicroseconds() - Sets the servo pulse width in microseconds + read() - Gets the last written servo pulse width as an angle between 0 and 180. + readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) + attached() - Returns true if there is a servo attached. + detach() - Stops an attached servos from pulsing its I/O pin. + */ + +#ifndef Servo_h +#define Servo_h + +#include + +/* + * Defines for 16 bit timers used with Servo library + * + * If _useTimerX is defined then TimerX is a 16 bit timer on the current board + * timer16_Sequence_t enumerates the sequence that the timers should be allocated + * _Nbr_16timers indicates how many 16 bit timers are available. + */ + +// Architecture specific include +#if defined(ARDUINO_ARCH_AVR) +#include "avr/ServoTimers.h" +#elif defined(ARDUINO_ARCH_SAM) +#include "sam/ServoTimers.h" +#elif defined(ARDUINO_ARCH_SAMD) +#include "samd/ServoTimers.h" +#elif defined(ARDUINO_ARCH_STM32F4) +#include "stm32f4/ServoTimers.h" +#elif defined(ARDUINO_ARCH_NRF52) +#include "nrf52/ServoTimers.h" +#elif defined(ARDUINO_ARCH_MEGAAVR) +#include "megaavr/ServoTimers.h" +#elif defined(ARDUINO_ARCH_MBED) +#include "mbed/ServoTimers.h" +#else +#error "This library only supports boards with an AVR, SAM, SAMD, NRF52 or STM32F4 processor." +#endif + +#define Servo_VERSION 2 // software version of this library + +#define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo +#define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo +#define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached +#define REFRESH_INTERVAL 20000 // minimum time to refresh servos in microseconds + +#define SERVOS_PER_TIMER 12 // the maximum number of servos controlled by one timer +#define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER) + +#define INVALID_SERVO 255 // flag indicating an invalid servo index + +#if !defined(ARDUINO_ARCH_STM32F4) + +typedef struct { + uint8_t nbr :6 ; // a pin number from 0 to 63 + uint8_t isActive :1 ; // true if this channel is enabled, pin not pulsed if false +} ServoPin_t ; + +typedef struct { + ServoPin_t Pin; + volatile unsigned int ticks; +} servo_t; + +class Servo +{ +public: + Servo(); + uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure + uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes. + void detach(); + void write(int value); // if value is < 200 its treated as an angle, otherwise as pulse width in microseconds + void writeMicroseconds(int value); // Write pulse width in microseconds + int read(); // returns current pulse width as an angle between 0 and 180 degrees + int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release) + bool attached(); // return true if this servo is attached, otherwise false +private: + uint8_t servoIndex; // index into the channel data for this servo + int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH + int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH +}; + +#endif +#endif diff --git a/libraries/Servo/src/avr/Servo.cpp b/libraries/Servo/src/avr/Servo.cpp new file mode 100644 index 0000000..11fecc5 --- /dev/null +++ b/libraries/Servo/src/avr/Servo.cpp @@ -0,0 +1,317 @@ +/* + Servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 + Copyright (c) 2009 Michael Margolis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if defined(ARDUINO_ARCH_AVR) + +#include +#include + +#include "Servo.h" + +#define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8) // converts microseconds to tick (assumes prescale of 8) // 12 Aug 2009 +#define ticksToUs(_ticks) (( (unsigned)_ticks * 8)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds + + +#define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays // 12 August 2009 + +//#define NBR_TIMERS (MAX_SERVOS / SERVOS_PER_TIMER) + +static servo_t servos[MAX_SERVOS]; // static array of servo structures +static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval) + +uint8_t ServoCount = 0; // the total number of attached servos + + +// convenience macros +#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo +#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer +#define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel +#define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel + +#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo +#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo + +/************ static functions common to all instances ***********************/ + +static inline void handle_interrupts(timer16_Sequence_t timer, volatile uint16_t *TCNTn, volatile uint16_t* OCRnA) +{ + if( Channel[timer] < 0 ) + *TCNTn = 0; // channel set to -1 indicated that refresh interval completed so reset the timer + else{ + if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true ) + digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,LOW); // pulse this channel low if activated + } + + Channel[timer]++; // increment to the next channel + if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) { + *OCRnA = *TCNTn + SERVO(timer,Channel[timer]).ticks; + if(SERVO(timer,Channel[timer]).Pin.isActive == true) // check if activated + digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // its an active channel so pulse it high + } + else { + // finished all channels so wait for the refresh period to expire before starting over + if( ((unsigned)*TCNTn) + 4 < usToTicks(REFRESH_INTERVAL) ) // allow a few ticks to ensure the next OCR1A not missed + *OCRnA = (unsigned int)usToTicks(REFRESH_INTERVAL); + else + *OCRnA = *TCNTn + 4; // at least REFRESH_INTERVAL has elapsed + Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel + } +} + +#ifndef WIRING // Wiring pre-defines signal handlers so don't define any if compiling for the Wiring platform +// Interrupt handlers for Arduino +#if defined(_useTimer1) +SIGNAL (TIMER1_COMPA_vect) +{ + handle_interrupts(_timer1, &TCNT1, &OCR1A); +} +#endif + +#if defined(_useTimer3) +SIGNAL (TIMER3_COMPA_vect) +{ + handle_interrupts(_timer3, &TCNT3, &OCR3A); +} +#endif + +#if defined(_useTimer4) +SIGNAL (TIMER4_COMPA_vect) +{ + handle_interrupts(_timer4, &TCNT4, &OCR4A); +} +#endif + +#if defined(_useTimer5) +SIGNAL (TIMER5_COMPA_vect) +{ + handle_interrupts(_timer5, &TCNT5, &OCR5A); +} +#endif + +#elif defined WIRING +// Interrupt handlers for Wiring +#if defined(_useTimer1) +void Timer1Service() +{ + handle_interrupts(_timer1, &TCNT1, &OCR1A); +} +#endif +#if defined(_useTimer3) +void Timer3Service() +{ + handle_interrupts(_timer3, &TCNT3, &OCR3A); +} +#endif +#endif + + +static void initISR(timer16_Sequence_t timer) +{ +#if defined (_useTimer1) + if(timer == _timer1) { + TCCR1A = 0; // normal counting mode + TCCR1B = _BV(CS11); // set prescaler of 8 + TCNT1 = 0; // clear the timer count +#if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__) + TIFR |= _BV(OCF1A); // clear any pending interrupts + TIMSK |= _BV(OCIE1A) ; // enable the output compare interrupt +#else + // here if not ATmega8 or ATmega128 + TIFR1 |= _BV(OCF1A); // clear any pending interrupts + TIMSK1 |= _BV(OCIE1A) ; // enable the output compare interrupt +#endif +#if defined(WIRING) + timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service); +#endif + } +#endif + +#if defined (_useTimer3) + if(timer == _timer3) { + TCCR3A = 0; // normal counting mode + TCCR3B = _BV(CS31); // set prescaler of 8 + TCNT3 = 0; // clear the timer count +#if defined(__AVR_ATmega128__) + TIFR |= _BV(OCF3A); // clear any pending interrupts + ETIMSK |= _BV(OCIE3A); // enable the output compare interrupt +#else + TIFR3 = _BV(OCF3A); // clear any pending interrupts + TIMSK3 = _BV(OCIE3A) ; // enable the output compare interrupt +#endif +#if defined(WIRING) + timerAttach(TIMER3OUTCOMPAREA_INT, Timer3Service); // for Wiring platform only +#endif + } +#endif + +#if defined (_useTimer4) + if(timer == _timer4) { + TCCR4A = 0; // normal counting mode + TCCR4B = _BV(CS41); // set prescaler of 8 + TCNT4 = 0; // clear the timer count + TIFR4 = _BV(OCF4A); // clear any pending interrupts + TIMSK4 = _BV(OCIE4A) ; // enable the output compare interrupt + } +#endif + +#if defined (_useTimer5) + if(timer == _timer5) { + TCCR5A = 0; // normal counting mode + TCCR5B = _BV(CS51); // set prescaler of 8 + TCNT5 = 0; // clear the timer count + TIFR5 = _BV(OCF5A); // clear any pending interrupts + TIMSK5 = _BV(OCIE5A) ; // enable the output compare interrupt + } +#endif +} + +static void finISR(timer16_Sequence_t timer) +{ + //disable use of the given timer +#if defined WIRING // Wiring + if(timer == _timer1) { + #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) + TIMSK1 &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt + #else + TIMSK &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt + #endif + timerDetach(TIMER1OUTCOMPAREA_INT); + } + else if(timer == _timer3) { + #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) + TIMSK3 &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt + #else + ETIMSK &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt + #endif + timerDetach(TIMER3OUTCOMPAREA_INT); + } +#else + //For Arduino - in future: call here to a currently undefined function to reset the timer + (void) timer; // squash "unused parameter 'timer' [-Wunused-parameter]" warning +#endif +} + +static boolean isTimerActive(timer16_Sequence_t timer) +{ + // returns true if any servo is active on this timer + for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { + if(SERVO(timer,channel).Pin.isActive == true) + return true; + } + return false; +} + + +/****************** end of static functions ******************************/ + +Servo::Servo() +{ + if( ServoCount < MAX_SERVOS) { + this->servoIndex = ServoCount++; // assign a servo index to this instance + servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values - 12 Aug 2009 + } + else + this->servoIndex = INVALID_SERVO ; // too many servos +} + +uint8_t Servo::attach(int pin) +{ + return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); +} + +uint8_t Servo::attach(int pin, int min, int max) +{ + if(this->servoIndex < MAX_SERVOS ) { + pinMode( pin, OUTPUT) ; // set servo pin to output + servos[this->servoIndex].Pin.nbr = pin; + // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 + this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us + this->max = (MAX_PULSE_WIDTH - max)/4; + // initialize the timer if it has not already been initialized + timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); + if(isTimerActive(timer) == false) + initISR(timer); + servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive + } + return this->servoIndex ; +} + +void Servo::detach() +{ + servos[this->servoIndex].Pin.isActive = false; + timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); + if(isTimerActive(timer) == false) { + finISR(timer); + } +} + +void Servo::write(int value) +{ + if(value < MIN_PULSE_WIDTH) + { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) + if(value < 0) value = 0; + if(value > 180) value = 180; + value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); + } + this->writeMicroseconds(value); +} + +void Servo::writeMicroseconds(int value) +{ + // calculate and store the values for the given channel + byte channel = this->servoIndex; + if( (channel < MAX_SERVOS) ) // ensure channel is valid + { + if( value < SERVO_MIN() ) // ensure pulse width is valid + value = SERVO_MIN(); + else if( value > SERVO_MAX() ) + value = SERVO_MAX(); + + value = value - TRIM_DURATION; + value = usToTicks(value); // convert to ticks after compensating for interrupt overhead - 12 Aug 2009 + + uint8_t oldSREG = SREG; + cli(); + servos[channel].ticks = value; + SREG = oldSREG; + } +} + +int Servo::read() // return the value as degrees +{ + return map( this->readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); +} + +int Servo::readMicroseconds() +{ + unsigned int pulsewidth; + if( this->servoIndex != INVALID_SERVO ) + pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION ; // 12 aug 2009 + else + pulsewidth = 0; + + return pulsewidth; +} + +bool Servo::attached() +{ + return servos[this->servoIndex].Pin.isActive ; +} + +#endif // ARDUINO_ARCH_AVR diff --git a/libraries/Servo/src/avr/ServoTimers.h b/libraries/Servo/src/avr/ServoTimers.h new file mode 100644 index 0000000..8a35c59 --- /dev/null +++ b/libraries/Servo/src/avr/ServoTimers.h @@ -0,0 +1,58 @@ +/* + Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 + Copyright (c) 2009 Michael Margolis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + * Defines for 16 bit timers used with Servo library + * + * If _useTimerX is defined then TimerX is a 16 bit timer on the current board + * timer16_Sequence_t enumerates the sequence that the timers should be allocated + * _Nbr_16timers indicates how many 16 bit timers are available. + */ + +/** + * AVR Only definitions + * -------------------- + */ + +// Say which 16 bit timers can be used and in what order +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define _useTimer5 +#define _useTimer1 +#define _useTimer3 +#define _useTimer4 +typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t; + +#elif defined(__AVR_ATmega32U4__) +#define _useTimer1 +typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t; + +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +#define _useTimer3 +#define _useTimer1 +typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t; + +#elif defined(__AVR_ATmega128__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega2561__) +#define _useTimer3 +#define _useTimer1 +typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t; + +#else // everything else +#define _useTimer1 +typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t; +#endif diff --git a/libraries/Servo/src/mbed/Servo.cpp b/libraries/Servo/src/mbed/Servo.cpp new file mode 100644 index 0000000..efb67f9 --- /dev/null +++ b/libraries/Servo/src/mbed/Servo.cpp @@ -0,0 +1,139 @@ +#if defined(ARDUINO_ARCH_MBED) + +#include +#include +#include + +#if defined __has_include +# if __has_include ("pinDefinitions.h") +# include "pinDefinitions.h" +# endif +#endif + +class ServoImpl { + mbed::DigitalOut *pin; + mbed::Timeout timeout; // calls a callback once when a timeout expires + mbed::Ticker ticker; // calls a callback repeatedly with a timeout + +public: + ServoImpl(PinName _pin) { + pin = new mbed::DigitalOut(_pin); + } + + ~ServoImpl() { + ticker.detach(); + timeout.detach(); + delete pin; + } + + void start(uint32_t duration_us) { + duration = duration_us; + ticker.attach(mbed::callback(this, &ServoImpl::call), 0.02f); + } + + void call() { + timeout.attach(mbed::callback(this, &ServoImpl::toggle), duration / 1e6); + toggle(); + } + + void toggle() { + *pin = !*pin; + } + + int32_t duration = -1; +}; + +static ServoImpl* servos[MAX_SERVOS]; // static array of servo structures +uint8_t ServoCount = 0; // the total number of attached servos + +#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min) // minimum value in us for this servo +#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max) // maximum value in us for this servo + +#define TRIM_DURATION 15 //callback overhead (35 us) -> 15 us if toggle() is called after starting the timeout + +Servo::Servo() +{ + if (ServoCount < MAX_SERVOS) { + this->servoIndex = ServoCount++; + } else { + this->servoIndex = INVALID_SERVO; // too many servos + } +} + +uint8_t Servo::attach(int pin) +{ + return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); +} + +uint8_t Servo::attach(int pin, int min, int max) +{ + pinMode(pin, OUTPUT); // set servo pin to output + servos[this->servoIndex] = new ServoImpl(digitalPinToPinName(pin)); + + this->min = (MIN_PULSE_WIDTH - min); + this->max = (MAX_PULSE_WIDTH - max); + return this->servoIndex; +} + +void Servo::detach() +{ + delete servos[this->servoIndex]; + servos[this->servoIndex] = NULL; +} + +void Servo::write(int value) +{ + // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) + if (value < MIN_PULSE_WIDTH) + { + if (value < 0) + value = 0; + else if (value > 180) + value = 180; + + value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); + } + writeMicroseconds(value); +} + +void Servo::writeMicroseconds(int value) +{ + if (!servos[this->servoIndex]) { + return; + } + // calculate and store the values for the given channel + byte channel = this->servoIndex; + if( (channel < MAX_SERVOS) ) // ensure channel is valid + { + if (value < SERVO_MIN()) // ensure pulse width is valid + value = SERVO_MIN(); + else if (value > SERVO_MAX()) + value = SERVO_MAX(); + + value = value - TRIM_DURATION; + if (servos[this->servoIndex]->duration == -1) { + servos[this->servoIndex]->start(value); + } + servos[this->servoIndex]->duration = value; + } +} + +int Servo::read() // return the value as degrees +{ + return map(readMicroseconds(), SERVO_MIN(), SERVO_MAX(), 0, 180); +} + +int Servo::readMicroseconds() +{ + if (!servos[this->servoIndex]) { + return 0; + } + return servos[this->servoIndex]->duration; +} + +bool Servo::attached() +{ + return servos[this->servoIndex] != NULL; +} + +#endif diff --git a/libraries/Servo/src/mbed/ServoTimers.h b/libraries/Servo/src/mbed/ServoTimers.h new file mode 100644 index 0000000..47f226f --- /dev/null +++ b/libraries/Servo/src/mbed/ServoTimers.h @@ -0,0 +1 @@ +#define _Nbr_16timers 32 diff --git a/libraries/Servo/src/megaavr/Servo.cpp b/libraries/Servo/src/megaavr/Servo.cpp new file mode 100644 index 0000000..59b3e44 --- /dev/null +++ b/libraries/Servo/src/megaavr/Servo.cpp @@ -0,0 +1,214 @@ +#if defined(ARDUINO_ARCH_MEGAAVR) + +#include +#include + +#define usToTicks(_us) ((clockCyclesPerMicrosecond() / 16 * _us) / 4) // converts microseconds to tick +#define ticksToUs(_ticks) (((unsigned) _ticks * 16) / (clockCyclesPerMicrosecond() / 4)) // converts from ticks back to microseconds + +#define TRIM_DURATION 5 // compensation ticks to trim adjust for digitalWrite delays + +static servo_t servos[MAX_SERVOS]; // static array of servo structures + +uint8_t ServoCount = 0; // the total number of attached servos + +static volatile int8_t currentServoIndex[_Nbr_16timers]; // index for the servo being pulsed for each timer (or -1 if refresh interval) + +// convenience macros +#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo +#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer +#define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel +#define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel + +#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo +#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo + +#undef REFRESH_INTERVAL +#define REFRESH_INTERVAL 16000 + +void ServoHandler(int timer) +{ + if (currentServoIndex[timer] < 0) { + // Write compare register + _timer->CCMP = 0; + } else { + if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { + digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, LOW); // pulse this channel low if activated + } + } + + // Select the next servo controlled by this timer + currentServoIndex[timer]++; + + if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && currentServoIndex[timer] < SERVOS_PER_TIMER) { + if (SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { // check if activated + digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, HIGH); // it's an active channel so pulse it high + } + + // Get the counter value + uint16_t tcCounterValue = 0; //_timer->CCMP; + _timer->CCMP = (uint16_t) (tcCounterValue + SERVO(timer, currentServoIndex[timer]).ticks); + } + else { + // finished all channels so wait for the refresh period to expire before starting over + + // Get the counter value + uint16_t tcCounterValue = _timer->CCMP; + + if (tcCounterValue + 4UL < usToTicks(REFRESH_INTERVAL)) { // allow a few ticks to ensure the next OCR1A not missed + _timer->CCMP = (uint16_t) usToTicks(REFRESH_INTERVAL); + } + else { + _timer->CCMP = (uint16_t) (tcCounterValue + 4UL); // at least REFRESH_INTERVAL has elapsed + } + + currentServoIndex[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel + } + + /* Clear flag */ + _timer->INTFLAGS = TCB_CAPT_bm; +} + +#if defined USE_TIMERB0 +ISR(TCB0_INT_vect) +#elif defined USE_TIMERB1 +ISR(TCB1_INT_vect) +#elif defined USE_TIMERB2 +ISR(TCB2_INT_vect) +#endif +{ + ServoHandler(0); +} + +static void initISR(timer16_Sequence_t timer) +{ + //TCA0.SINGLE.CTRLA = (TCA_SINGLE_CLKSEL_DIV16_gc) | (TCA_SINGLE_ENABLE_bm); + + _timer->CTRLA = TCB_CLKSEL_CLKTCA_gc; + // Timer to Periodic interrupt mode + // This write will also disable any active PWM outputs + _timer->CTRLB = TCB_CNTMODE_INT_gc; + // Enable interrupt + _timer->INTCTRL = TCB_CAPTEI_bm; + // Enable timer + _timer->CTRLA |= TCB_ENABLE_bm; +} + +static void finISR(timer16_Sequence_t timer) +{ + // Disable interrupt + _timer->INTCTRL = 0; +} + +static boolean isTimerActive(timer16_Sequence_t timer) +{ + // returns true if any servo is active on this timer + for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { + if(SERVO(timer,channel).Pin.isActive == true) + return true; + } + return false; +} + +/****************** end of static functions ******************************/ + +Servo::Servo() +{ + if (ServoCount < MAX_SERVOS) { + this->servoIndex = ServoCount++; // assign a servo index to this instance + servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values + } else { + this->servoIndex = INVALID_SERVO; // too many servos + } +} + +uint8_t Servo::attach(int pin) +{ + return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); +} + +uint8_t Servo::attach(int pin, int min, int max) +{ + timer16_Sequence_t timer; + + if (this->servoIndex < MAX_SERVOS) { + pinMode(pin, OUTPUT); // set servo pin to output + servos[this->servoIndex].Pin.nbr = pin; + // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 + this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us + this->max = (MAX_PULSE_WIDTH - max)/4; + // initialize the timer if it has not already been initialized + timer = SERVO_INDEX_TO_TIMER(servoIndex); + if (isTimerActive(timer) == false) { + initISR(timer); + } + servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive + } + return this->servoIndex; +} + +void Servo::detach() +{ + timer16_Sequence_t timer; + + servos[this->servoIndex].Pin.isActive = false; + timer = SERVO_INDEX_TO_TIMER(servoIndex); + if(isTimerActive(timer) == false) { + finISR(timer); + } +} + +void Servo::write(int value) +{ + // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) + if (value < MIN_PULSE_WIDTH) + { + if (value < 0) + value = 0; + else if (value > 180) + value = 180; + + value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); + } + writeMicroseconds(value); +} + +void Servo::writeMicroseconds(int value) +{ + // calculate and store the values for the given channel + byte channel = this->servoIndex; + if( (channel < MAX_SERVOS) ) // ensure channel is valid + { + if (value < SERVO_MIN()) // ensure pulse width is valid + value = SERVO_MIN(); + else if (value > SERVO_MAX()) + value = SERVO_MAX(); + + value = value - TRIM_DURATION; + value = usToTicks(value); // convert to ticks after compensating for interrupt overhead + servos[channel].ticks = value; + } +} + +int Servo::read() // return the value as degrees +{ + return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); +} + +int Servo::readMicroseconds() +{ + unsigned int pulsewidth; + if (this->servoIndex != INVALID_SERVO) + pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION; + else + pulsewidth = 0; + + return pulsewidth; +} + +bool Servo::attached() +{ + return servos[this->servoIndex].Pin.isActive; +} + +#endif diff --git a/libraries/Servo/src/megaavr/ServoTimers.h b/libraries/Servo/src/megaavr/ServoTimers.h new file mode 100644 index 0000000..56746dc --- /dev/null +++ b/libraries/Servo/src/megaavr/ServoTimers.h @@ -0,0 +1,54 @@ +/* + Copyright (c) 2018 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + * Defines for 16 bit timers used with Servo library + * + */ + +#ifndef __SERVO_TIMERS_H__ +#define __SERVO_TIMERS_H__ + +#include + +//#define USE_TIMERB1 // interferes with PWM on pin 3 +#define USE_TIMERB2 // interferes with PWM on pin 11 +//#define USE_TIMERB0 // interferes with PWM on pin 6 + +#if !defined(USE_TIMERB1) && !defined(USE_TIMERB2) && !defined(USE_TIMERB0) + # error "No timers allowed for Servo" + /* Please uncomment a timer above and rebuild */ +#endif + +static volatile TCB_t* _timer = +#if defined(USE_TIMERB0) +&TCB0; +#endif +#if defined(USE_TIMERB1) +&TCB1; +#endif +#if defined(USE_TIMERB2) +&TCB2; +#endif + +typedef enum { + timer0, + _Nbr_16timers } timer16_Sequence_t; + + +#endif /* __SERVO_TIMERS_H__ */ diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp new file mode 100644 index 0000000..72bd504 --- /dev/null +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -0,0 +1,134 @@ +/* + Copyright (c) 2016 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#if defined(ARDUINO_ARCH_NRF52) + +#include +#include + + +static servo_t servos[MAX_SERVOS]; // static array of servo structures + +uint8_t ServoCount = 0; // the total number of attached servos + + + +uint32_t group_pins[3][NRF_PWM_CHANNEL_COUNT]={{NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}, {NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}, {NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}}; +static uint16_t seq_values[3][NRF_PWM_CHANNEL_COUNT]={{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; + +Servo::Servo() +{ + if (ServoCount < MAX_SERVOS) { + this->servoIndex = ServoCount++; // assign a servo index to this instance + } else { + this->servoIndex = INVALID_SERVO; // too many servos + } + +} + +uint8_t Servo::attach(int pin) +{ + + return this->attach(pin, 0, 2500); +} + + +uint8_t Servo::attach(int pin, int min, int max) +{ + int servo_min, servo_max; + if (this->servoIndex < MAX_SERVOS) { + pinMode(pin, OUTPUT); // set servo pin to output + servos[this->servoIndex].Pin.nbr = pin; + + if(min < servo_min) min = servo_min; + if (max > servo_max) max = servo_max; + this->min = min; + this->max = max; + + servos[this->servoIndex].Pin.isActive = true; + + } + return this->servoIndex; +} + +void Servo::detach() +{ + servos[this->servoIndex].Pin.isActive = false; +} + + +void Servo::write(int value) +{ + if (value < 0) + value = 0; + else if (value > 180) + value = 180; + value = map(value, 0, 180, MIN_PULSE, MAX_PULSE); + + writeMicroseconds(value); +} + + +void Servo::writeMicroseconds(int value) +{ + uint8_t channel, instance; + uint8_t pin = servos[this->servoIndex].Pin.nbr; + //instance of PWM module is MSB - look at VWariant.h + instance=(g_APinDescription[pin].ulPWMChannel & 0xF0)/16; + //index of PWM channel is LSB - look at VWariant.h + channel=g_APinDescription[pin].ulPWMChannel & 0x0F; + group_pins[instance][channel]=g_APinDescription[pin].ulPin; + NRF_PWM_Type * PWMInstance = instance == 0 ? NRF_PWM0 : (instance == 1 ? NRF_PWM1 : NRF_PWM2); + //configure PWM instance and enable it + seq_values[instance][channel]= value | 0x8000; + nrf_pwm_sequence_t const seq={ + seq_values[instance], + NRF_PWM_VALUES_LENGTH(seq_values), + 0, + 0 + }; + nrf_pwm_pins_set(PWMInstance, group_pins[instance]); + nrf_pwm_enable(PWMInstance); + nrf_pwm_configure(PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, 2500); // 20ms - 50Hz + nrf_pwm_decoder_set(PWMInstance, NRF_PWM_LOAD_INDIVIDUAL, NRF_PWM_STEP_AUTO); + nrf_pwm_sequence_set(PWMInstance, 0, &seq); + nrf_pwm_loop_set(PWMInstance, 0UL); + nrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_SEQSTART0); +} + +int Servo::read() // return the value as degrees +{ + return map(readMicroseconds(), MIN_PULSE, MAX_PULSE, 0, 180); +} + +int Servo::readMicroseconds() +{ + uint8_t channel, instance; + uint8_t pin=servos[this->servoIndex].Pin.nbr; + instance=(g_APinDescription[pin].ulPWMChannel & 0xF0)/16; + channel=g_APinDescription[pin].ulPWMChannel & 0x0F; + // remove the 16th bit we added before + return seq_values[instance][channel] & 0x7FFF; +} + +bool Servo::attached() +{ + return servos[this->servoIndex].Pin.isActive; +} + +#endif // ARDUINO_ARCH_NRF52 diff --git a/libraries/Servo/src/nrf52/ServoTimers.h b/libraries/Servo/src/nrf52/ServoTimers.h new file mode 100644 index 0000000..f4fc176 --- /dev/null +++ b/libraries/Servo/src/nrf52/ServoTimers.h @@ -0,0 +1,38 @@ +/* + Copyright (c) 2016 Arduino. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + * nRF52 doesn't use timer, but PWM. This file include definitions to keep + * compatibility with the Servo library standards. + */ + +#ifndef __SERVO_TIMERS_H__ +#define __SERVO_TIMERS_H__ + +/** + * nRF52 only definitions + * --------------------- + */ + +#define MIN_PULSE 55 +#define MAX_PULSE 284 + +// define one timer in order to have MAX_SERVOS = 12 +typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t; + +#endif // __SERVO_TIMERS_H__ diff --git a/libraries/Servo/src/sam/Servo.cpp b/libraries/Servo/src/sam/Servo.cpp new file mode 100644 index 0000000..df5058f --- /dev/null +++ b/libraries/Servo/src/sam/Servo.cpp @@ -0,0 +1,282 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#if defined(ARDUINO_ARCH_SAM) + +#include +#include + +#define usToTicks(_us) (( clockCyclesPerMicrosecond() * _us) / 32) // converts microseconds to tick +#define ticksToUs(_ticks) (( (unsigned)_ticks * 32)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds + +#define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays + +static servo_t servos[MAX_SERVOS]; // static array of servo structures + +uint8_t ServoCount = 0; // the total number of attached servos + +static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval) + +// convenience macros +#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo +#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer +#define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel +#define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel + +#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo +#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo + +/************ static functions common to all instances ***********************/ + +//------------------------------------------------------------------------------ +/// Interrupt handler for the TC0 channel 1. +//------------------------------------------------------------------------------ +void Servo_Handler(timer16_Sequence_t timer, Tc *pTc, uint8_t channel); +#if defined (_useTimer1) +void HANDLER_FOR_TIMER1(void) { + Servo_Handler(_timer1, TC_FOR_TIMER1, CHANNEL_FOR_TIMER1); +} +#endif +#if defined (_useTimer2) +void HANDLER_FOR_TIMER2(void) { + Servo_Handler(_timer2, TC_FOR_TIMER2, CHANNEL_FOR_TIMER2); +} +#endif +#if defined (_useTimer3) +void HANDLER_FOR_TIMER3(void) { + Servo_Handler(_timer3, TC_FOR_TIMER3, CHANNEL_FOR_TIMER3); +} +#endif +#if defined (_useTimer4) +void HANDLER_FOR_TIMER4(void) { + Servo_Handler(_timer4, TC_FOR_TIMER4, CHANNEL_FOR_TIMER4); +} +#endif +#if defined (_useTimer5) +void HANDLER_FOR_TIMER5(void) { + Servo_Handler(_timer5, TC_FOR_TIMER5, CHANNEL_FOR_TIMER5); +} +#endif + +void Servo_Handler(timer16_Sequence_t timer, Tc *tc, uint8_t channel) +{ + // clear interrupt + tc->TC_CHANNEL[channel].TC_SR; + if (Channel[timer] < 0) { + tc->TC_CHANNEL[channel].TC_CCR |= TC_CCR_SWTRG; // channel set to -1 indicated that refresh interval completed so reset the timer + } else { + if (SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true) { + digitalWrite(SERVO(timer,Channel[timer]).Pin.nbr, LOW); // pulse this channel low if activated + } + } + + Channel[timer]++; // increment to the next channel + if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) { + tc->TC_CHANNEL[channel].TC_RA = tc->TC_CHANNEL[channel].TC_CV + SERVO(timer,Channel[timer]).ticks; + if(SERVO(timer,Channel[timer]).Pin.isActive == true) { // check if activated + digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // its an active channel so pulse it high + } + } + else { + // finished all channels so wait for the refresh period to expire before starting over + if( (tc->TC_CHANNEL[channel].TC_CV) + 4 < usToTicks(REFRESH_INTERVAL) ) { // allow a few ticks to ensure the next OCR1A not missed + tc->TC_CHANNEL[channel].TC_RA = (unsigned int)usToTicks(REFRESH_INTERVAL); + } + else { + tc->TC_CHANNEL[channel].TC_RA = tc->TC_CHANNEL[channel].TC_CV + 4; // at least REFRESH_INTERVAL has elapsed + } + Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel + } +} + +static void _initISR(Tc *tc, uint32_t channel, uint32_t id, IRQn_Type irqn) +{ + pmc_enable_periph_clk(id); + TC_Configure(tc, channel, + TC_CMR_TCCLKS_TIMER_CLOCK3 | // MCK/32 + TC_CMR_WAVE | // Waveform mode + TC_CMR_WAVSEL_UP_RC ); // Counter running up and reset when equals to RC + + /* 84 MHz, MCK/32, for 1.5 ms: 3937 */ + TC_SetRA(tc, channel, 2625); // 1ms + + /* Configure and enable interrupt */ + NVIC_EnableIRQ(irqn); + // TC_IER_CPAS: RA Compare + tc->TC_CHANNEL[channel].TC_IER = TC_IER_CPAS; + + // Enables the timer clock and performs a software reset to start the counting + TC_Start(tc, channel); +} + +static void initISR(timer16_Sequence_t timer) +{ +#if defined (_useTimer1) + if (timer == _timer1) + _initISR(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, ID_TC_FOR_TIMER1, IRQn_FOR_TIMER1); +#endif +#if defined (_useTimer2) + if (timer == _timer2) + _initISR(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, ID_TC_FOR_TIMER2, IRQn_FOR_TIMER2); +#endif +#if defined (_useTimer3) + if (timer == _timer3) + _initISR(TC_FOR_TIMER3, CHANNEL_FOR_TIMER3, ID_TC_FOR_TIMER3, IRQn_FOR_TIMER3); +#endif +#if defined (_useTimer4) + if (timer == _timer4) + _initISR(TC_FOR_TIMER4, CHANNEL_FOR_TIMER4, ID_TC_FOR_TIMER4, IRQn_FOR_TIMER4); +#endif +#if defined (_useTimer5) + if (timer == _timer5) + _initISR(TC_FOR_TIMER5, CHANNEL_FOR_TIMER5, ID_TC_FOR_TIMER5, IRQn_FOR_TIMER5); +#endif +} + +static void finISR(timer16_Sequence_t timer) +{ +#if defined (_useTimer1) + TC_Stop(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1); +#endif +#if defined (_useTimer2) + TC_Stop(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2); +#endif +#if defined (_useTimer3) + TC_Stop(TC_FOR_TIMER3, CHANNEL_FOR_TIMER3); +#endif +#if defined (_useTimer4) + TC_Stop(TC_FOR_TIMER4, CHANNEL_FOR_TIMER4); +#endif +#if defined (_useTimer5) + TC_Stop(TC_FOR_TIMER5, CHANNEL_FOR_TIMER5); +#endif +} + + +static boolean isTimerActive(timer16_Sequence_t timer) +{ + // returns true if any servo is active on this timer + for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { + if(SERVO(timer,channel).Pin.isActive == true) + return true; + } + return false; +} + +/****************** end of static functions ******************************/ + +Servo::Servo() +{ + if (ServoCount < MAX_SERVOS) { + this->servoIndex = ServoCount++; // assign a servo index to this instance + servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values + } else { + this->servoIndex = INVALID_SERVO; // too many servos + } +} + +uint8_t Servo::attach(int pin) +{ + return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); +} + +uint8_t Servo::attach(int pin, int min, int max) +{ + timer16_Sequence_t timer; + + if (this->servoIndex < MAX_SERVOS) { + pinMode(pin, OUTPUT); // set servo pin to output + servos[this->servoIndex].Pin.nbr = pin; + // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 + this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us + this->max = (MAX_PULSE_WIDTH - max)/4; + // initialize the timer if it has not already been initialized + timer = SERVO_INDEX_TO_TIMER(servoIndex); + if (isTimerActive(timer) == false) { + initISR(timer); + } + servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive + } + return this->servoIndex; +} + +void Servo::detach() +{ + timer16_Sequence_t timer; + + servos[this->servoIndex].Pin.isActive = false; + timer = SERVO_INDEX_TO_TIMER(servoIndex); + if(isTimerActive(timer) == false) { + finISR(timer); + } +} + +void Servo::write(int value) +{ + // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) + if (value < MIN_PULSE_WIDTH) + { + if (value < 0) + value = 0; + else if (value > 180) + value = 180; + + value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); + } + writeMicroseconds(value); +} + +void Servo::writeMicroseconds(int value) +{ + // calculate and store the values for the given channel + byte channel = this->servoIndex; + if( (channel < MAX_SERVOS) ) // ensure channel is valid + { + if (value < SERVO_MIN()) // ensure pulse width is valid + value = SERVO_MIN(); + else if (value > SERVO_MAX()) + value = SERVO_MAX(); + + value = value - TRIM_DURATION; + value = usToTicks(value); // convert to ticks after compensating for interrupt overhead + servos[channel].ticks = value; + } +} + +int Servo::read() // return the value as degrees +{ + return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); +} + +int Servo::readMicroseconds() +{ + unsigned int pulsewidth; + if (this->servoIndex != INVALID_SERVO) + pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION; + else + pulsewidth = 0; + + return pulsewidth; +} + +bool Servo::attached() +{ + return servos[this->servoIndex].Pin.isActive; +} + +#endif // ARDUINO_ARCH_SAM diff --git a/libraries/Servo/src/sam/ServoTimers.h b/libraries/Servo/src/sam/ServoTimers.h new file mode 100644 index 0000000..a7ee258 --- /dev/null +++ b/libraries/Servo/src/sam/ServoTimers.h @@ -0,0 +1,87 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + * Defines for 16 bit timers used with Servo library + * + * If _useTimerX is defined then TimerX is a 16 bit timer on the current board + * timer16_Sequence_t enumerates the sequence that the timers should be allocated + * _Nbr_16timers indicates how many 16 bit timers are available. + */ + +/** + * SAM Only definitions + * -------------------- + */ + +// For SAM3X: +#define _useTimer1 +#define _useTimer2 +#define _useTimer3 +#define _useTimer4 +#define _useTimer5 + +/* + TC0, chan 0 => TC0_Handler + TC0, chan 1 => TC1_Handler + TC0, chan 2 => TC2_Handler + TC1, chan 0 => TC3_Handler + TC1, chan 1 => TC4_Handler + TC1, chan 2 => TC5_Handler + TC2, chan 0 => TC6_Handler + TC2, chan 1 => TC7_Handler + TC2, chan 2 => TC8_Handler + */ + +#if defined (_useTimer1) +#define TC_FOR_TIMER1 TC1 +#define CHANNEL_FOR_TIMER1 0 +#define ID_TC_FOR_TIMER1 ID_TC3 +#define IRQn_FOR_TIMER1 TC3_IRQn +#define HANDLER_FOR_TIMER1 TC3_Handler +#endif +#if defined (_useTimer2) +#define TC_FOR_TIMER2 TC1 +#define CHANNEL_FOR_TIMER2 1 +#define ID_TC_FOR_TIMER2 ID_TC4 +#define IRQn_FOR_TIMER2 TC4_IRQn +#define HANDLER_FOR_TIMER2 TC4_Handler +#endif +#if defined (_useTimer3) +#define TC_FOR_TIMER3 TC1 +#define CHANNEL_FOR_TIMER3 2 +#define ID_TC_FOR_TIMER3 ID_TC5 +#define IRQn_FOR_TIMER3 TC5_IRQn +#define HANDLER_FOR_TIMER3 TC5_Handler +#endif +#if defined (_useTimer4) +#define TC_FOR_TIMER4 TC0 +#define CHANNEL_FOR_TIMER4 2 +#define ID_TC_FOR_TIMER4 ID_TC2 +#define IRQn_FOR_TIMER4 TC2_IRQn +#define HANDLER_FOR_TIMER4 TC2_Handler +#endif +#if defined (_useTimer5) +#define TC_FOR_TIMER5 TC0 +#define CHANNEL_FOR_TIMER5 0 +#define ID_TC_FOR_TIMER5 ID_TC0 +#define IRQn_FOR_TIMER5 TC0_IRQn +#define HANDLER_FOR_TIMER5 TC0_Handler +#endif + +typedef enum { _timer1, _timer2, _timer3, _timer4, _timer5, _Nbr_16timers } timer16_Sequence_t ; diff --git a/libraries/Servo/src/samd/Servo.cpp b/libraries/Servo/src/samd/Servo.cpp new file mode 100644 index 0000000..d8e2ec4 --- /dev/null +++ b/libraries/Servo/src/samd/Servo.cpp @@ -0,0 +1,297 @@ +/* + Copyright (c) 2015 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#if defined(ARDUINO_ARCH_SAMD) + +#include +#include + +#define usToTicks(_us) ((clockCyclesPerMicrosecond() * _us) / 16) // converts microseconds to tick +#define ticksToUs(_ticks) (((unsigned) _ticks * 16) / clockCyclesPerMicrosecond()) // converts from ticks back to microseconds + +#define TRIM_DURATION 5 // compensation ticks to trim adjust for digitalWrite delays + +static servo_t servos[MAX_SERVOS]; // static array of servo structures + +uint8_t ServoCount = 0; // the total number of attached servos + +static volatile int8_t currentServoIndex[_Nbr_16timers]; // index for the servo being pulsed for each timer (or -1 if refresh interval) + +// convenience macros +#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo +#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer +#define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel +#define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel + +#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo +#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo + +#define WAIT_TC16_REGS_SYNC(x) while(x->COUNT16.STATUS.bit.SYNCBUSY); + +/************ static functions common to all instances ***********************/ + +void Servo_Handler(timer16_Sequence_t timer, Tc *pTc, uint8_t channel, uint8_t intFlag); +#if defined (_useTimer1) +void HANDLER_FOR_TIMER1(void) { + Servo_Handler(_timer1, TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, INTFLAG_BIT_FOR_TIMER_1); +} +#endif +#if defined (_useTimer2) +void HANDLER_FOR_TIMER2(void) { + Servo_Handler(_timer2, TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, INTFLAG_BIT_FOR_TIMER_2); +} +#endif + +void Servo_Handler(timer16_Sequence_t timer, Tc *tc, uint8_t channel, uint8_t intFlag) +{ + if (currentServoIndex[timer] < 0) { + tc->COUNT16.COUNT.reg = (uint16_t) 0; + WAIT_TC16_REGS_SYNC(tc) + } else { + if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { + digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, LOW); // pulse this channel low if activated + } + } + + // Select the next servo controlled by this timer + currentServoIndex[timer]++; + + if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && currentServoIndex[timer] < SERVOS_PER_TIMER) { + if (SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { // check if activated + digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, HIGH); // it's an active channel so pulse it high + } + + // Get the counter value + uint16_t tcCounterValue = tc->COUNT16.COUNT.reg; + WAIT_TC16_REGS_SYNC(tc) + + tc->COUNT16.CC[channel].reg = (uint16_t) (tcCounterValue + SERVO(timer, currentServoIndex[timer]).ticks); + WAIT_TC16_REGS_SYNC(tc) + } + else { + // finished all channels so wait for the refresh period to expire before starting over + + // Get the counter value + uint16_t tcCounterValue = tc->COUNT16.COUNT.reg; + WAIT_TC16_REGS_SYNC(tc) + + if (tcCounterValue + 4UL < usToTicks(REFRESH_INTERVAL)) { // allow a few ticks to ensure the next OCR1A not missed + tc->COUNT16.CC[channel].reg = (uint16_t) usToTicks(REFRESH_INTERVAL); + } + else { + tc->COUNT16.CC[channel].reg = (uint16_t) (tcCounterValue + 4UL); // at least REFRESH_INTERVAL has elapsed + } + WAIT_TC16_REGS_SYNC(tc) + + currentServoIndex[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel + } + + // Clear the interrupt + tc->COUNT16.INTFLAG.reg = intFlag; +} + +static inline void resetTC (Tc* TCx) +{ + // Disable TCx + TCx->COUNT16.CTRLA.reg &= ~TC_CTRLA_ENABLE; + WAIT_TC16_REGS_SYNC(TCx) + + // Reset TCx + TCx->COUNT16.CTRLA.reg = TC_CTRLA_SWRST; + WAIT_TC16_REGS_SYNC(TCx) + while (TCx->COUNT16.CTRLA.bit.SWRST); +} + +static void _initISR(Tc *tc, uint8_t channel, uint32_t id, IRQn_Type irqn, uint8_t gcmForTimer, uint8_t intEnableBit) +{ + // Enable GCLK for timer 1 (timer counter input clock) + GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(gcmForTimer)); + while (GCLK->STATUS.bit.SYNCBUSY); + + // Reset the timer + // TODO this is not the right thing to do if more than one channel per timer is used by the Servo library + resetTC(tc); + + // Set timer counter mode to 16 bits + tc->COUNT16.CTRLA.reg |= TC_CTRLA_MODE_COUNT16; + + // Set timer counter mode as normal PWM + tc->COUNT16.CTRLA.reg |= TC_CTRLA_WAVEGEN_NPWM; + + // Set the prescaler factor to GCLK_TC/16. At nominal 48 MHz GCLK_TC this is 3000 ticks per millisecond + tc->COUNT16.CTRLA.reg |= TC_CTRLA_PRESCALER_DIV16; + + // Count up + tc->COUNT16.CTRLBCLR.bit.DIR = 1; + WAIT_TC16_REGS_SYNC(tc) + + // First interrupt request after 1 ms + tc->COUNT16.CC[channel].reg = (uint16_t) usToTicks(1000UL); + WAIT_TC16_REGS_SYNC(tc) + + // Configure interrupt request + // TODO this should be changed if more than one channel per timer is used by the Servo library + NVIC_DisableIRQ(irqn); + NVIC_ClearPendingIRQ(irqn); + NVIC_SetPriority(irqn, 0); + NVIC_EnableIRQ(irqn); + + // Enable the match channel interrupt request + tc->COUNT16.INTENSET.reg = intEnableBit; + + // Enable the timer and start it + tc->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE; + WAIT_TC16_REGS_SYNC(tc) +} + +static void initISR(timer16_Sequence_t timer) +{ +#if defined (_useTimer1) + if (timer == _timer1) + _initISR(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, ID_TC_FOR_TIMER1, IRQn_FOR_TIMER1, GCM_FOR_TIMER_1, INTENSET_BIT_FOR_TIMER_1); +#endif +#if defined (_useTimer2) + if (timer == _timer2) + _initISR(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, ID_TC_FOR_TIMER2, IRQn_FOR_TIMER2, GCM_FOR_TIMER_2, INTENSET_BIT_FOR_TIMER_2); +#endif +} + +static void finISR(timer16_Sequence_t timer) +{ +#if defined (_useTimer1) + // Disable the match channel interrupt request + TC_FOR_TIMER1->COUNT16.INTENCLR.reg = INTENCLR_BIT_FOR_TIMER_1; +#endif +#if defined (_useTimer2) + // Disable the match channel interrupt request + TC_FOR_TIMER2->COUNT16.INTENCLR.reg = INTENCLR_BIT_FOR_TIMER_2; +#endif +} + +static boolean isTimerActive(timer16_Sequence_t timer) +{ + // returns true if any servo is active on this timer + for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { + if(SERVO(timer,channel).Pin.isActive == true) + return true; + } + return false; +} + +/****************** end of static functions ******************************/ + +Servo::Servo() +{ + if (ServoCount < MAX_SERVOS) { + this->servoIndex = ServoCount++; // assign a servo index to this instance + servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values + } else { + this->servoIndex = INVALID_SERVO; // too many servos + } +} + +uint8_t Servo::attach(int pin) +{ + return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); +} + +uint8_t Servo::attach(int pin, int min, int max) +{ + timer16_Sequence_t timer; + + if (this->servoIndex < MAX_SERVOS) { + pinMode(pin, OUTPUT); // set servo pin to output + servos[this->servoIndex].Pin.nbr = pin; + // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 + this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us + this->max = (MAX_PULSE_WIDTH - max)/4; + // initialize the timer if it has not already been initialized + timer = SERVO_INDEX_TO_TIMER(servoIndex); + if (isTimerActive(timer) == false) { + initISR(timer); + } + servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive + } + return this->servoIndex; +} + +void Servo::detach() +{ + timer16_Sequence_t timer; + + servos[this->servoIndex].Pin.isActive = false; + timer = SERVO_INDEX_TO_TIMER(servoIndex); + if(isTimerActive(timer) == false) { + finISR(timer); + } +} + +void Servo::write(int value) +{ + // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) + if (value < MIN_PULSE_WIDTH) + { + if (value < 0) + value = 0; + else if (value > 180) + value = 180; + + value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); + } + writeMicroseconds(value); +} + +void Servo::writeMicroseconds(int value) +{ + // calculate and store the values for the given channel + byte channel = this->servoIndex; + if( (channel < MAX_SERVOS) ) // ensure channel is valid + { + if (value < SERVO_MIN()) // ensure pulse width is valid + value = SERVO_MIN(); + else if (value > SERVO_MAX()) + value = SERVO_MAX(); + + value = value - TRIM_DURATION; + value = usToTicks(value); // convert to ticks after compensating for interrupt overhead + servos[channel].ticks = value; + } +} + +int Servo::read() // return the value as degrees +{ + return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); +} + +int Servo::readMicroseconds() +{ + unsigned int pulsewidth; + if (this->servoIndex != INVALID_SERVO) + pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION; + else + pulsewidth = 0; + + return pulsewidth; +} + +bool Servo::attached() +{ + return servos[this->servoIndex].Pin.isActive; +} + +#endif // ARDUINO_ARCH_SAMD diff --git a/libraries/Servo/src/samd/ServoTimers.h b/libraries/Servo/src/samd/ServoTimers.h new file mode 100644 index 0000000..0b18f60 --- /dev/null +++ b/libraries/Servo/src/samd/ServoTimers.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2015 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + * Defines for 16 bit timers used with Servo library + * + * If _useTimerX is defined then TimerX is a 16 bit timer on the current board + * timer16_Sequence_t enumerates the sequence that the timers should be allocated + * _Nbr_16timers indicates how many 16 bit timers are available. + */ + +#ifndef __SERVO_TIMERS_H__ +#define __SERVO_TIMERS_H__ + +/** + * SAMD Only definitions + * --------------------- + */ + +// For SAMD: +#define _useTimer1 +//#define _useTimer2 // <- TODO do not activate until the code in Servo.cpp has been changed in order + // to manage more than one channel per timer on the SAMD architecture + +#if defined (_useTimer1) +#define TC_FOR_TIMER1 TC4 +#define CHANNEL_FOR_TIMER1 0 +#define INTENSET_BIT_FOR_TIMER_1 TC_INTENSET_MC0 +#define INTENCLR_BIT_FOR_TIMER_1 TC_INTENCLR_MC0 +#define INTFLAG_BIT_FOR_TIMER_1 TC_INTFLAG_MC0 +#define ID_TC_FOR_TIMER1 ID_TC4 +#define IRQn_FOR_TIMER1 TC4_IRQn +#define HANDLER_FOR_TIMER1 TC4_Handler +#define GCM_FOR_TIMER_1 GCM_TC4_TC5 +#endif +#if defined (_useTimer2) +#define TC_FOR_TIMER2 TC4 +#define CHANNEL_FOR_TIMER2 1 +#define INTENSET_BIT_FOR_TIMER_2 TC_INTENSET_MC1 +#define INTENCLR_BIT_FOR_TIMER_2 TC_INTENCLR_MC1 +#define ID_TC_FOR_TIMER2 ID_TC4 +#define IRQn_FOR_TIMER2 TC4_IRQn +#define HANDLER_FOR_TIMER2 TC4_Handler +#define GCM_FOR_TIMER_2 GCM_TC4_TC5 +#endif + +typedef enum { +#if defined (_useTimer1) + _timer1, +#endif +#if defined (_useTimer2) + _timer2, +#endif + _Nbr_16timers } timer16_Sequence_t; + +#endif // __SERVO_TIMERS_H__ diff --git a/libraries/Servo/src/stm32f4/Servo.cpp b/libraries/Servo/src/stm32f4/Servo.cpp new file mode 100644 index 0000000..01d05d9 --- /dev/null +++ b/libraries/Servo/src/stm32f4/Servo.cpp @@ -0,0 +1,194 @@ +/****************************************************************************** + * The MIT License + * + * Copyright (c) 2010, LeafLabs, LLC. + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + *****************************************************************************/ + +#if defined(ARDUINO_ARCH_STM32F4) + +#include "ServoTimers.h" + +#include "boards.h" +#include "io.h" +#include "pwm.h" +#include "math.h" + +// 20 millisecond period config. For a 1-based prescaler, +// +// (prescaler * overflow / CYC_MSEC) msec = 1 timer cycle = 20 msec +// => prescaler * overflow = 20 * CYC_MSEC +// +// This picks the smallest prescaler that allows an overflow < 2^16. +#define MAX_OVERFLOW ((1 << 16) - 1) +#define CYC_MSEC (1000 * CYCLES_PER_MICROSECOND) +#define TAU_MSEC 20 +#define TAU_USEC (TAU_MSEC * 1000) +#define TAU_CYC (TAU_MSEC * CYC_MSEC) +#define SERVO_PRESCALER (TAU_CYC / MAX_OVERFLOW + 1) +#define SERVO_OVERFLOW ((uint16)round((double)TAU_CYC / SERVO_PRESCALER)) + +// Unit conversions +#define US_TO_COMPARE(us) ((uint16)map((us), 0, TAU_USEC, 0, SERVO_OVERFLOW)) +#define COMPARE_TO_US(c) ((uint32)map((c), 0, SERVO_OVERFLOW, 0, TAU_USEC)) +#define ANGLE_TO_US(a) ((uint16)(map((a), this->minAngle, this->maxAngle, \ + this->minPW, this->maxPW))) +#define US_TO_ANGLE(us) ((int16)(map((us), this->minPW, this->maxPW, \ + this->minAngle, this->maxAngle))) + +Servo::Servo() { + this->resetFields(); +} + +bool Servo::attach(uint8 pin, uint16 minPW, uint16 maxPW, int16 minAngle, int16 maxAngle) +{ + // SerialUSB.begin(115200); + // SerialUSB.println(MAX_OVERFLOW); + + + timer_dev *tdev = PIN_MAP[pin].timer_device; + + analogWriteResolution(16); + + int prescaler = 6; + int overflow = 65400; + int minPW_correction = 300; + int maxPW_correction = 300; + + pinMode(pin, OUTPUT); + + + if (tdev == NULL) { + // don't reset any fields or ASSERT(0), to keep driving any + // previously attach()ed servo. + return false; + } + + if ( (tdev == TIMER1) || (tdev == TIMER8) || (tdev == TIMER10) || (tdev == TIMER11)) + { + prescaler = 54; + overflow = 65400; + minPW_correction = 40; + maxPW_correction = 50; + } + + if ( (tdev == TIMER2) || (tdev == TIMER3) || (tdev == TIMER4) || (tdev == TIMER5) ) + { + prescaler = 6; + overflow = 64285; + minPW_correction = 370; + maxPW_correction = 350; + } + + if ( (tdev == TIMER6) || (tdev == TIMER7) ) + { + prescaler = 6; + overflow = 65400; + minPW_correction = 0; + maxPW_correction = 0; + } + + if ( (tdev == TIMER9) || (tdev == TIMER12) || (tdev == TIMER13) || (tdev == TIMER14) ) + { + prescaler = 6; + overflow = 65400; + minPW_correction = 30; + maxPW_correction = 0; + } + + if (this->attached()) { + this->detach(); + } + + this->pin = pin; + this->minPW = (minPW + minPW_correction); + this->maxPW = (maxPW + maxPW_correction); + this->minAngle = minAngle; + this->maxAngle = maxAngle; + + timer_pause(tdev); + timer_set_prescaler(tdev, prescaler); // prescaler is 1-based + timer_set_reload(tdev, overflow); + timer_generate_update(tdev); + timer_resume(tdev); + + return true; +} + +bool Servo::detach() { + if (!this->attached()) { + return false; + } + + timer_dev *tdev = PIN_MAP[this->pin].timer_device; + uint8 tchan = PIN_MAP[this->pin].timer_channel; + timer_set_mode(tdev, tchan, TIMER_DISABLED); + + this->resetFields(); + + return true; +} + +void Servo::write(int degrees) { + degrees = constrain(degrees, this->minAngle, this->maxAngle); + this->writeMicroseconds(ANGLE_TO_US(degrees)); +} + +int Servo::read() const { + int a = US_TO_ANGLE(this->readMicroseconds()); + // map() round-trips in a weird way we mostly correct for here; + // the round-trip is still sometimes off-by-one for write(1) and + // write(179). + return a == this->minAngle || a == this->maxAngle ? a : a + 1; +} + +void Servo::writeMicroseconds(uint16 pulseWidth) { + if (!this->attached()) { + ASSERT(0); + return; + } + pulseWidth = constrain(pulseWidth, this->minPW, this->maxPW); + analogWrite(this->pin, US_TO_COMPARE(pulseWidth)); +} + +uint16 Servo::readMicroseconds() const { + if (!this->attached()) { + ASSERT(0); + return 0; + } + + stm32_pin_info pin_info = PIN_MAP[this->pin]; + uint16 compare = timer_get_compare(pin_info.timer_device, + pin_info.timer_channel); + + return COMPARE_TO_US(compare); +} + +void Servo::resetFields(void) { + this->pin = NOT_ATTACHED; + this->minAngle = MIN_ANGLE; + this->maxAngle = MAX_ANGLE; + this->minPW = MIN_PULSE_WIDTH; + this->maxPW = MAX_PULSE_WIDTH; +} + +#endif diff --git a/libraries/Servo/src/stm32f4/ServoTimers.h b/libraries/Servo/src/stm32f4/ServoTimers.h new file mode 100644 index 0000000..53bd647 --- /dev/null +++ b/libraries/Servo/src/stm32f4/ServoTimers.h @@ -0,0 +1,207 @@ +/****************************************************************************** + * The MIT License + * + * Copyright (c) 2010, LeafLabs, LLC. + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + *****************************************************************************/ + + /* + * Arduino srl - www.arduino.org + * 2017 Feb 23: Edited by Francesco Alessi (alfran) - francesco@arduino.org + */ +#ifndef _SERVO_H_ +#define _SERVO_H_ + +#include "types.h" +#include "timer.h" + +#include "wiring.h" /* hack for IDE compile */ + +/* + * Note on Arduino compatibility: + * + * In the Arduino implementation, PWM is done "by hand" in the sense + * that timer channels are hijacked in groups and an ISR is set which + * toggles Servo::attach()ed pins using digitalWrite(). + * + * While this scheme allows any pin to drive a servo, it chews up + * cycles and complicates the programmer's notion of when a particular + * timer channel will be in use. + * + * This implementation only allows Servo instances to attach() to pins + * that already have a timer channel associated with them, and just + * uses pwmWrite() to drive the wave. + * + * This introduces an incompatibility: while the Arduino + * implementation of attach() returns the affected channel on success + * and 0 on failure, this one returns true on success and false on + * failure. + * + * RC Servos expect a pulse every 20 ms. Since periods are set for + * entire timers, rather than individual channels, attach()ing a Servo + * to a pin can interfere with other pins associated with the same + * timer. As always, your board's pin map is your friend. + */ + +// Pin number of unattached pins +#define NOT_ATTACHED (-1) + +#define _Nbr_16timers 14 // Number of STM32F469 Timers +#define SERVOS_PER_TIMER 4 // Number of timer channels + + +// Default min/max pulse widths (in microseconds) and angles (in +// degrees). Values chosen for Arduino compatibility. These values +// are part of the public API; DO NOT CHANGE THEM. +#define MIN_ANGLE 0 +#define MAX_ANGLE 180 + +#define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo +#define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo + +/** Class for interfacing with RC servomotors. */ +class Servo { +public: + /** + * @brief Construct a new Servo instance. + * + * The new instance will not be attached to any pin. + */ + Servo(); + + /** + * @brief Associate this instance with a servomotor whose input is + * connected to pin. + * + * If this instance is already attached to a pin, it will be + * detached before being attached to the new pin. This function + * doesn't detach any interrupt attached with the pin's timer + * channel. + * + * @param pin Pin connected to the servo pulse wave input. This + * pin must be capable of PWM output. + * + * @param minPulseWidth Minimum pulse width to write to pin, in + * microseconds. This will be associated + * with a minAngle degree angle. Defaults to + * SERVO_DEFAULT_MIN_PW = 544. + * + * @param maxPulseWidth Maximum pulse width to write to pin, in + * microseconds. This will be associated + * with a maxAngle degree angle. Defaults to + * SERVO_DEFAULT_MAX_PW = 2400. + * + * @param minAngle Target angle (in degrees) associated with + * minPulseWidth. Defaults to + * SERVO_DEFAULT_MIN_ANGLE = 0. + * + * @param maxAngle Target angle (in degrees) associated with + * maxPulseWidth. Defaults to + * SERVO_DEFAULT_MAX_ANGLE = 180. + * + * @sideeffect May set pinMode(pin, PWM). + * + * @return true if successful, false when pin doesn't support PWM. + */ + + bool attach(uint8 pin, + uint16 minPulseWidth=MIN_PULSE_WIDTH, + uint16 maxPulseWidth=MAX_PULSE_WIDTH, + int16 minAngle=MIN_ANGLE, + int16 maxAngle=MAX_ANGLE); + /** + * @brief Stop driving the servo pulse train. + * + * If not currently attached to a motor, this function has no effect. + * + * @return true if this call did anything, false otherwise. + */ + bool detach(); + + /** + * @brief Set the servomotor target angle. + * + * @param angle Target angle, in degrees. If the target angle is + * outside the range specified at attach() time, it + * will be clamped to lie in that range. + * + * @see Servo::attach() + */ + void write(int angle); + + /** + * @brief Set the pulse width, in microseconds. + * + * @param pulseWidth Pulse width to send to the servomotor, in + * microseconds. If outside of the range + * specified at attach() time, it is clamped to + * lie in that range. + * + * @see Servo::attach() + */ + void writeMicroseconds(uint16 pulseWidth); + + /** + * Get the servomotor's target angle, in degrees. This will + * lie inside the range specified at attach() time. + * + * @see Servo::attach() + */ + int read() const; + + /** + * Get the current pulse width, in microseconds. This will + * lie within the range specified at attach() time. + * + * @see Servo::attach() + */ + uint16 readMicroseconds() const; + + + /** + * @brief Check if this instance is attached to a servo. + * @return true if this instance is attached to a servo, false otherwise. + * @see Servo::attachedPin() + */ + bool attached() const { return this->pin != NOT_ATTACHED; } + + /** + * @brief Get the pin this instance is attached to. + * @return Pin number if currently attached to a pin, NOT_ATTACHED + * otherwise. + * @see Servo::attach() + */ + int attachedPin() const { return this->pin; } + +private: + int16 pin; + uint16 minPW; + uint16 maxPW; + int16 minAngle; + int16 maxAngle; + + void resetFields(void); +}; + + + +#endif /* _SERVO_H_ */ diff --git a/libraries/Stepper/README.adoc b/libraries/Stepper/README.adoc new file mode 100644 index 0000000..9d4d052 --- /dev/null +++ b/libraries/Stepper/README.adoc @@ -0,0 +1,26 @@ += Stepper Library for Arduino = + +This library allows you to control unipolar or bipolar stepper motors. To use it you will need a stepper motor, and the appropriate hardware to control it. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/Stepper + +== License == + +Copyright (c) Arduino LLC. All right reserved. +Copyright (c) Sebastian Gassner. All right reserved. +Copyright (c) Noah Shibley. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/Stepper/examples/MotorKnob/MotorKnob.ino b/libraries/Stepper/examples/MotorKnob/MotorKnob.ino new file mode 100644 index 0000000..5cf12ec --- /dev/null +++ b/libraries/Stepper/examples/MotorKnob/MotorKnob.ino @@ -0,0 +1,39 @@ +/* + * MotorKnob + * + * A stepper motor follows the turns of a potentiometer + * (or other sensor) on analog input 0. + * + * http://www.arduino.cc/en/Reference/Stepper + * This example code is in the public domain. + */ + +#include + +// change this to the number of steps on your motor +#define STEPS 100 + +// create an instance of the stepper class, specifying +// the number of steps of the motor and the pins it's +// attached to +Stepper stepper(STEPS, 8, 9, 10, 11); + +// the previous reading from the analog input +int previous = 0; + +void setup() { + // set the speed of the motor to 30 RPMs + stepper.setSpeed(30); +} + +void loop() { + // get the sensor value + int val = analogRead(0); + + // move a number of steps equal to the change in the + // sensor reading + stepper.step(val - previous); + + // remember the previous value of the sensor + previous = val; +} \ No newline at end of file diff --git a/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino b/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino new file mode 100644 index 0000000..373eb60 --- /dev/null +++ b/libraries/Stepper/examples/stepper_oneRevolution/stepper_oneRevolution.ino @@ -0,0 +1,44 @@ + +/* + Stepper Motor Control - one revolution + + This program drives a unipolar or bipolar stepper motor. + The motor is attached to digital pins 8 - 11 of the Arduino. + + The motor should revolve one revolution in one direction, then + one revolution in the other direction. + + + Created 11 Mar. 2007 + Modified 30 Nov. 2009 + by Tom Igoe + + */ + +#include + +const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution +// for your motor + +// initialize the stepper library on pins 8 through 11: +Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); + +void setup() { + // set the speed at 60 rpm: + myStepper.setSpeed(60); + // initialize the serial port: + Serial.begin(9600); +} + +void loop() { + // step one revolution in one direction: + Serial.println("clockwise"); + myStepper.step(stepsPerRevolution); + delay(500); + + // step one revolution in the other direction: + Serial.println("counterclockwise"); + myStepper.step(-stepsPerRevolution); + delay(500); +} + diff --git a/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino b/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino new file mode 100644 index 0000000..e6c141f --- /dev/null +++ b/libraries/Stepper/examples/stepper_oneStepAtATime/stepper_oneStepAtATime.ino @@ -0,0 +1,44 @@ + +/* + Stepper Motor Control - one step at a time + + This program drives a unipolar or bipolar stepper motor. + The motor is attached to digital pins 8 - 11 of the Arduino. + + The motor will step one step at a time, very slowly. You can use this to + test that you've got the four wires of your stepper wired to the correct + pins. If wired correctly, all steps should be in the same direction. + + Use this also to count the number of steps per revolution of your motor, + if you don't know it. Then plug that number into the oneRevolution + example to see if you got it right. + + Created 30 Nov. 2009 + by Tom Igoe + + */ + +#include + +const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution +// for your motor + +// initialize the stepper library on pins 8 through 11: +Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); + +int stepCount = 0; // number of steps the motor has taken + +void setup() { + // initialize the serial port: + Serial.begin(9600); +} + +void loop() { + // step one step: + myStepper.step(1); + Serial.print("steps:"); + Serial.println(stepCount); + stepCount++; + delay(500); +} + diff --git a/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino b/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino new file mode 100644 index 0000000..5eb4f6a --- /dev/null +++ b/libraries/Stepper/examples/stepper_speedControl/stepper_speedControl.ino @@ -0,0 +1,48 @@ + +/* + Stepper Motor Control - speed control + + This program drives a unipolar or bipolar stepper motor. + The motor is attached to digital pins 8 - 11 of the Arduino. + A potentiometer is connected to analog input 0. + + The motor will rotate in a clockwise direction. The higher the potentiometer value, + the faster the motor speed. Because setSpeed() sets the delay between steps, + you may notice the motor is less responsive to changes in the sensor value at + low speeds. + + Created 30 Nov. 2009 + Modified 28 Oct 2010 + by Tom Igoe + + */ + +#include + +const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution +// for your motor + + +// initialize the stepper library on pins 8 through 11: +Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); + +int stepCount = 0; // number of steps the motor has taken + +void setup() { + // nothing to do inside the setup +} + +void loop() { + // read the sensor value: + int sensorReading = analogRead(A0); + // map it to a range from 0 to 100: + int motorSpeed = map(sensorReading, 0, 1023, 0, 100); + // set the motor speed: + if (motorSpeed > 0) { + myStepper.setSpeed(motorSpeed); + // step 1/100 of a revolution: + myStepper.step(stepsPerRevolution / 100); + } +} + + diff --git a/libraries/Stepper/keywords.txt b/libraries/Stepper/keywords.txt new file mode 100644 index 0000000..5e58a66 --- /dev/null +++ b/libraries/Stepper/keywords.txt @@ -0,0 +1,28 @@ +####################################### +# Syntax Coloring Map For Test +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Stepper KEYWORD1 Stepper + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +step KEYWORD2 +setSpeed KEYWORD2 +version KEYWORD2 + +###################################### +# Instances (KEYWORD2) +####################################### +direction KEYWORD2 +speed KEYWORD2 + + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/libraries/Stepper/library.properties b/libraries/Stepper/library.properties new file mode 100644 index 0000000..875067a --- /dev/null +++ b/libraries/Stepper/library.properties @@ -0,0 +1,9 @@ +name=Stepper +version=1.1.3 +author=Arduino +maintainer=Arduino +sentence=Allows Arduino boards to control a variety of stepper motors. +paragraph=This library allows you to control unipolar or bipolar stepper motors. To use it you will need a stepper motor, and the appropriate hardware to control it. +category=Device Control +url=http://www.arduino.cc/en/Reference/Stepper +architectures=* diff --git a/libraries/Stepper/src/Stepper.cpp b/libraries/Stepper/src/Stepper.cpp new file mode 100644 index 0000000..1f76295 --- /dev/null +++ b/libraries/Stepper/src/Stepper.cpp @@ -0,0 +1,365 @@ +/* + * Stepper.cpp - Stepper library for Wiring/Arduino - Version 1.1.0 + * + * Original library (0.1) by Tom Igoe. + * Two-wire modifications (0.2) by Sebastian Gassner + * Combination version (0.3) by Tom Igoe and David Mellis + * Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley + * High-speed stepping mod by Eugene Kozlenko + * Timer rollover fix by Eugene Kozlenko + * Five phase five wire (1.1.0) by Ryan Orendorff + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * + * Drives a unipolar, bipolar, or five phase stepper motor. + * + * When wiring multiple stepper motors to a microcontroller, you quickly run + * out of output pins, with each motor requiring 4 connections. + * + * By making use of the fact that at any time two of the four motor coils are + * the inverse of the other two, the number of control connections can be + * reduced from 4 to 2 for the unipolar and bipolar motors. + * + * A slightly modified circuit around a Darlington transistor array or an + * L293 H-bridge connects to only 2 microcontroler pins, inverts the signals + * received, and delivers the 4 (2 plus 2 inverted ones) output signals + * required for driving a stepper motor. Similarly the Arduino motor shields + * 2 direction pins may be used. + * + * The sequence of control signals for 5 phase, 5 control wires is as follows: + * + * Step C0 C1 C2 C3 C4 + * 1 0 1 1 0 1 + * 2 0 1 0 0 1 + * 3 0 1 0 1 1 + * 4 0 1 0 1 0 + * 5 1 1 0 1 0 + * 6 1 0 0 1 0 + * 7 1 0 1 1 0 + * 8 1 0 1 0 0 + * 9 1 0 1 0 1 + * 10 0 0 1 0 1 + * + * The sequence of control signals for 4 control wires is as follows: + * + * Step C0 C1 C2 C3 + * 1 1 0 1 0 + * 2 0 1 1 0 + * 3 0 1 0 1 + * 4 1 0 0 1 + * + * The sequence of controls signals for 2 control wires is as follows + * (columns C1 and C2 from above): + * + * Step C0 C1 + * 1 0 1 + * 2 1 1 + * 3 1 0 + * 4 0 0 + * + * The circuits can be found at + * + * http://www.arduino.cc/en/Tutorial/Stepper + */ + +#include "Arduino.h" +#include "Stepper.h" + +/* + * two-wire constructor. + * Sets which wires should control the motor. + */ +Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2) +{ + this->step_number = 0; // which step the motor is on + this->direction = 0; // motor direction + this->last_step_time = 0; // time stamp in us of the last step taken + this->number_of_steps = number_of_steps; // total number of steps for this motor + + // Arduino pins for the motor control connection: + this->motor_pin_1 = motor_pin_1; + this->motor_pin_2 = motor_pin_2; + + // setup the pins on the microcontroller: + pinMode(this->motor_pin_1, OUTPUT); + pinMode(this->motor_pin_2, OUTPUT); + + // When there are only 2 pins, set the others to 0: + this->motor_pin_3 = 0; + this->motor_pin_4 = 0; + this->motor_pin_5 = 0; + + // pin_count is used by the stepMotor() method: + this->pin_count = 2; +} + + +/* + * constructor for four-pin version + * Sets which wires should control the motor. + */ +Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, + int motor_pin_3, int motor_pin_4) +{ + this->step_number = 0; // which step the motor is on + this->direction = 0; // motor direction + this->last_step_time = 0; // time stamp in us of the last step taken + this->number_of_steps = number_of_steps; // total number of steps for this motor + + // Arduino pins for the motor control connection: + this->motor_pin_1 = motor_pin_1; + this->motor_pin_2 = motor_pin_2; + this->motor_pin_3 = motor_pin_3; + this->motor_pin_4 = motor_pin_4; + + // setup the pins on the microcontroller: + pinMode(this->motor_pin_1, OUTPUT); + pinMode(this->motor_pin_2, OUTPUT); + pinMode(this->motor_pin_3, OUTPUT); + pinMode(this->motor_pin_4, OUTPUT); + + // When there are 4 pins, set the others to 0: + this->motor_pin_5 = 0; + + // pin_count is used by the stepMotor() method: + this->pin_count = 4; +} + +/* + * constructor for five phase motor with five wires + * Sets which wires should control the motor. + */ +Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, + int motor_pin_3, int motor_pin_4, + int motor_pin_5) +{ + this->step_number = 0; // which step the motor is on + this->direction = 0; // motor direction + this->last_step_time = 0; // time stamp in us of the last step taken + this->number_of_steps = number_of_steps; // total number of steps for this motor + + // Arduino pins for the motor control connection: + this->motor_pin_1 = motor_pin_1; + this->motor_pin_2 = motor_pin_2; + this->motor_pin_3 = motor_pin_3; + this->motor_pin_4 = motor_pin_4; + this->motor_pin_5 = motor_pin_5; + + // setup the pins on the microcontroller: + pinMode(this->motor_pin_1, OUTPUT); + pinMode(this->motor_pin_2, OUTPUT); + pinMode(this->motor_pin_3, OUTPUT); + pinMode(this->motor_pin_4, OUTPUT); + pinMode(this->motor_pin_5, OUTPUT); + + // pin_count is used by the stepMotor() method: + this->pin_count = 5; +} + +/* + * Sets the speed in revs per minute + */ +void Stepper::setSpeed(long whatSpeed) +{ + this->step_delay = 60L * 1000L * 1000L / this->number_of_steps / whatSpeed; +} + +/* + * Moves the motor steps_to_move steps. If the number is negative, + * the motor moves in the reverse direction. + */ +void Stepper::step(int steps_to_move) +{ + int steps_left = abs(steps_to_move); // how many steps to take + + // determine direction based on whether steps_to_mode is + or -: + if (steps_to_move > 0) { this->direction = 1; } + if (steps_to_move < 0) { this->direction = 0; } + + + // decrement the number of steps, moving one step each time: + while (steps_left > 0) + { + unsigned long now = micros(); + // move only if the appropriate delay has passed: + if (now - this->last_step_time >= this->step_delay) + { + // get the timeStamp of when you stepped: + this->last_step_time = now; + // increment or decrement the step number, + // depending on direction: + if (this->direction == 1) + { + this->step_number++; + if (this->step_number == this->number_of_steps) { + this->step_number = 0; + } + } + else + { + if (this->step_number == 0) { + this->step_number = this->number_of_steps; + } + this->step_number--; + } + // decrement the steps left: + steps_left--; + // step the motor to step number 0, 1, ..., {3 or 10} + if (this->pin_count == 5) + stepMotor(this->step_number % 10); + else + stepMotor(this->step_number % 4); + } + } +} + +/* + * Moves the motor forward or backwards. + */ +void Stepper::stepMotor(int thisStep) +{ + if (this->pin_count == 2) { + switch (thisStep) { + case 0: // 01 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, HIGH); + break; + case 1: // 11 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, HIGH); + break; + case 2: // 10 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, LOW); + break; + case 3: // 00 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, LOW); + break; + } + } + if (this->pin_count == 4) { + switch (thisStep) { + case 0: // 1010 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, LOW); + digitalWrite(motor_pin_3, HIGH); + digitalWrite(motor_pin_4, LOW); + break; + case 1: // 0110 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, HIGH); + digitalWrite(motor_pin_3, HIGH); + digitalWrite(motor_pin_4, LOW); + break; + case 2: //0101 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, HIGH); + digitalWrite(motor_pin_3, LOW); + digitalWrite(motor_pin_4, HIGH); + break; + case 3: //1001 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, LOW); + digitalWrite(motor_pin_3, LOW); + digitalWrite(motor_pin_4, HIGH); + break; + } + } + + if (this->pin_count == 5) { + switch (thisStep) { + case 0: // 01101 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, HIGH); + digitalWrite(motor_pin_3, HIGH); + digitalWrite(motor_pin_4, LOW); + digitalWrite(motor_pin_5, HIGH); + break; + case 1: // 01001 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, HIGH); + digitalWrite(motor_pin_3, LOW); + digitalWrite(motor_pin_4, LOW); + digitalWrite(motor_pin_5, HIGH); + break; + case 2: // 01011 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, HIGH); + digitalWrite(motor_pin_3, LOW); + digitalWrite(motor_pin_4, HIGH); + digitalWrite(motor_pin_5, HIGH); + break; + case 3: // 01010 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, HIGH); + digitalWrite(motor_pin_3, LOW); + digitalWrite(motor_pin_4, HIGH); + digitalWrite(motor_pin_5, LOW); + break; + case 4: // 11010 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, HIGH); + digitalWrite(motor_pin_3, LOW); + digitalWrite(motor_pin_4, HIGH); + digitalWrite(motor_pin_5, LOW); + break; + case 5: // 10010 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, LOW); + digitalWrite(motor_pin_3, LOW); + digitalWrite(motor_pin_4, HIGH); + digitalWrite(motor_pin_5, LOW); + break; + case 6: // 10110 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, LOW); + digitalWrite(motor_pin_3, HIGH); + digitalWrite(motor_pin_4, HIGH); + digitalWrite(motor_pin_5, LOW); + break; + case 7: // 10100 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, LOW); + digitalWrite(motor_pin_3, HIGH); + digitalWrite(motor_pin_4, LOW); + digitalWrite(motor_pin_5, LOW); + break; + case 8: // 10101 + digitalWrite(motor_pin_1, HIGH); + digitalWrite(motor_pin_2, LOW); + digitalWrite(motor_pin_3, HIGH); + digitalWrite(motor_pin_4, LOW); + digitalWrite(motor_pin_5, HIGH); + break; + case 9: // 00101 + digitalWrite(motor_pin_1, LOW); + digitalWrite(motor_pin_2, LOW); + digitalWrite(motor_pin_3, HIGH); + digitalWrite(motor_pin_4, LOW); + digitalWrite(motor_pin_5, HIGH); + break; + } + } +} + +/* + version() returns the version of the library: +*/ +int Stepper::version(void) +{ + return 5; +} diff --git a/libraries/Stepper/src/Stepper.h b/libraries/Stepper/src/Stepper.h new file mode 100644 index 0000000..2e68979 --- /dev/null +++ b/libraries/Stepper/src/Stepper.h @@ -0,0 +1,121 @@ +/* + * Stepper.h - Stepper library for Wiring/Arduino - Version 1.1.0 + * + * Original library (0.1) by Tom Igoe. + * Two-wire modifications (0.2) by Sebastian Gassner + * Combination version (0.3) by Tom Igoe and David Mellis + * Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley + * High-speed stepping mod by Eugene Kozlenko + * Timer rollover fix by Eugene Kozlenko + * Five phase five wire (1.1.0) by Ryan Orendorff + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * + * Drives a unipolar, bipolar, or five phase stepper motor. + * + * When wiring multiple stepper motors to a microcontroller, you quickly run + * out of output pins, with each motor requiring 4 connections. + * + * By making use of the fact that at any time two of the four motor coils are + * the inverse of the other two, the number of control connections can be + * reduced from 4 to 2 for the unipolar and bipolar motors. + * + * A slightly modified circuit around a Darlington transistor array or an + * L293 H-bridge connects to only 2 microcontroler pins, inverts the signals + * received, and delivers the 4 (2 plus 2 inverted ones) output signals + * required for driving a stepper motor. Similarly the Arduino motor shields + * 2 direction pins may be used. + * + * The sequence of control signals for 5 phase, 5 control wires is as follows: + * + * Step C0 C1 C2 C3 C4 + * 1 0 1 1 0 1 + * 2 0 1 0 0 1 + * 3 0 1 0 1 1 + * 4 0 1 0 1 0 + * 5 1 1 0 1 0 + * 6 1 0 0 1 0 + * 7 1 0 1 1 0 + * 8 1 0 1 0 0 + * 9 1 0 1 0 1 + * 10 0 0 1 0 1 + * + * The sequence of control signals for 4 control wires is as follows: + * + * Step C0 C1 C2 C3 + * 1 1 0 1 0 + * 2 0 1 1 0 + * 3 0 1 0 1 + * 4 1 0 0 1 + * + * The sequence of controls signals for 2 control wires is as follows + * (columns C1 and C2 from above): + * + * Step C0 C1 + * 1 0 1 + * 2 1 1 + * 3 1 0 + * 4 0 0 + * + * The circuits can be found at + * + * http://www.arduino.cc/en/Tutorial/Stepper + */ + +// ensure this library description is only included once +#ifndef Stepper_h +#define Stepper_h + +// library interface description +class Stepper { + public: + // constructors: + Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2); + Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, + int motor_pin_3, int motor_pin_4); + Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, + int motor_pin_3, int motor_pin_4, + int motor_pin_5); + + // speed setter method: + void setSpeed(long whatSpeed); + + // mover method: + void step(int number_of_steps); + + int version(void); + + private: + void stepMotor(int this_step); + + int direction; // Direction of rotation + unsigned long step_delay; // delay between steps, in ms, based on speed + int number_of_steps; // total number of steps this motor can take + int pin_count; // how many pins are in use. + int step_number; // which step the motor is on + + // motor pin numbers: + int motor_pin_1; + int motor_pin_2; + int motor_pin_3; + int motor_pin_4; + int motor_pin_5; // Only 5 phase motor + + unsigned long last_step_time; // time stamp in us of when the last step was taken +}; + +#endif + diff --git a/libraries/TFT/README.adoc b/libraries/TFT/README.adoc new file mode 100644 index 0000000..0550e2d --- /dev/null +++ b/libraries/TFT/README.adoc @@ -0,0 +1,26 @@ += TFT Library for Arduino = + +This library enables an Arduino board to communicate with the Arduino TFT LCD screen. It simplifies the process for drawing shapes, lines, images, and text to the screen. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/TFTLibrary + +== License == + +Copyright (c) Arduino LLC. All right reserved. +Copyright (c) Enrico Gueli. All right reserved. +Copyright (c) 2012, Adafruit Industries. All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino b/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino new file mode 100644 index 0000000..d1b8a73 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTBitmapLogo/TFTBitmapLogo.ino @@ -0,0 +1,108 @@ +/* + + Arduino TFT Bitmap Logo example + + This example reads an image file from a micro-SD card + and draws it on the screen, at random locations. + + In this sketch, the Arduino logo is read from a micro-SD card. + There is a .bmp file included with this sketch. + - open the sketch folder (Ctrl-K or Cmd-K) + - copy the "arduino.bmp" file to a micro-SD + - put the SD into the SD slot of the Arduino TFT module. + + This example code is in the public domain. + + Created 19 April 2013 by Enrico Gueli + + http://www.arduino.cc/en/Tutorial/TFTBitmapLogo + + */ + +// include the necessary libraries +#include +#include +#include // Arduino LCD library + +// pin definition for the Uno +#define sd_cs 4 +#define lcd_cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +//#define sd_cs 8 +//#define lcd_cs 7 +//#define dc 0 +//#define rst 1 + +TFT TFTscreen = TFT(lcd_cs, dc, rst); + +// this variable represents the image to be drawn on screen +PImage logo; + + +void setup() { + // initialize the GLCD and show a message + // asking the user to open the serial line + TFTscreen.begin(); + TFTscreen.background(255, 255, 255); + + TFTscreen.stroke(0, 0, 255); + TFTscreen.println(); + TFTscreen.println(F("Arduino TFT Bitmap Example")); + TFTscreen.stroke(0, 0, 0); + TFTscreen.println(F("Open serial monitor")); + TFTscreen.println(F("to run the sketch")); + + // initialize the serial port: it will be used to + // print some diagnostic info + Serial.begin(9600); + while (!Serial) { + // wait for serial port to connect. Needed for native USB port only + } + + // clear the GLCD screen before starting + TFTscreen.background(255, 255, 255); + + // try to access the SD card. If that fails (e.g. + // no card present), the setup process will stop. + Serial.print(F("Initializing SD card...")); + if (!SD.begin(sd_cs)) { + Serial.println(F("failed!")); + return; + } + Serial.println(F("OK!")); + + // initialize and clear the GLCD screen + TFTscreen.begin(); + TFTscreen.background(255, 255, 255); + + // now that the SD card can be access, try to load the + // image file. + logo = TFTscreen.loadImage("arduino.bmp"); + if (!logo.isValid()) { + Serial.println(F("error while loading arduino.bmp")); + } +} + +void loop() { + // don't do anything if the image wasn't loaded correctly. + if (logo.isValid() == false) { + return; + } + + Serial.println(F("drawing image")); + + // get a random location where to draw the image. + // To avoid the image to be draw outside the screen, + // take into account the image size. + int x = random(TFTscreen.width() - logo.width()); + int y = random(TFTscreen.height() - logo.height()); + + // draw the image to the screen + TFTscreen.image(logo, x, y); + + // wait a little bit before drawing again + delay(1500); +} diff --git a/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp b/libraries/TFT/examples/Arduino/TFTBitmapLogo/arduino.bmp new file mode 100644 index 0000000000000000000000000000000000000000..09c670ab54f01647cd59b35a5b00ab381fcbe2ae GIT binary patch literal 6966 zcmeI0cWm256vv&UfM_Y3Quf}fVwAl%Vj~c=OtBF|Vu+0x5osrBbsX2#ndxUb(${o^pV!eL0cX_iF(IL+J1;Eg zTwmkiNC*u)i-S-*F6u@oz5Y0u{b2voP+(WdSAo7K4iDA!b{7Qr90v=Mn;Jp`eU3*O zWQno2Tdi$EB{cE&JS5ov)QFIa5Rw#s_w@AWj?^uIz9;Oi{58OPBl6klY)|KHUiKRp z4kZVT3^x`Rd|>i8u%_A*8-0w2bP%(3)W#7EzZ?U+!$>syFn5&Dde_e6$V91(J1M(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mb4#og0x>KD1G_0)pu`|Y&jJuN+Sy?Y7D8~Aj7iED!@r8Q6uaz#vcSN(1dhE7 zMulJD+}em|^jS8Zwa{8@QZ!%cu&mzT#^AT?=?|qV(cA^ z%`44s(9>Zdv!AOg%zH;vKc+qmBs=6QnkHj5VB!}BIno52sj)OiuCdZ0=qd69q)=YF zQk^Y?@Pv#Ji11(n0aAnzob=_vfjtBX*H7tUj>Z->>S)1Sfu%~CG*@zmdluI>0Ev#+ zY`d$Hv-Y@Ufo{!>5o*S9N5lK7!mv;%=;q0Z4-i+jxyAQH*=U3`LI_3&kAN*x%975? zxvCCg4H&pJz`eQ^Wt=X_II0?`va?1Ln-}um z;|l4ljMyOnm|?i+?ZY~bpgT}u7*yZ_AMWht=B3&tL{VKCT=R3@L~ZD8bGW7h0}rJ& zI^s(1%UmS?w(VjsNx^M5cH6ZW2)o_a+zZz8OAfz;bhM>%eGupJ(*)IkNE2Tjo=C$+ z-ZnLcaYNza$qaEcG // Arduino LCD library +#include + +TFT TFTscreen = TFT(cs, dc, rst); + +void setup() { + // begin serial communication + Serial.begin(9600); + + // initialize the display + TFTscreen.begin(); + + // set the background to white + TFTscreen.background(255, 255, 255); + +} + +void loop() { + + // read the values from your sensors and scale them to 0-255 + int redVal = map(analogRead(A0), 0, 1023, 0, 255); + int greenVal = map(analogRead(A1), 0, 1023, 0, 255); + int blueVal = map(analogRead(A2), 0, 1023, 0, 255); + + // draw the background based on the mapped values + TFTscreen.background(redVal, greenVal, blueVal); + + // send the values to the serial monitor + Serial.print("background("); + Serial.print(redVal); + Serial.print(" , "); + Serial.print(greenVal); + Serial.print(" , "); + Serial.print(blueVal); + Serial.println(")"); + + // wait for a moment + delay(33); + +} + diff --git a/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino b/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino new file mode 100644 index 0000000..a9c1d86 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino @@ -0,0 +1,74 @@ +/* + Arduino TFT text example + + This example demonstrates how to draw text on the + TFT with an Arduino. The Arduino reads the value + of an analog sensor attached to pin A0, and writes + the value to the LCD screen, updating every + quarter second. + + This example code is in the public domain + + Created 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/TFTDisplayText + + */ + +#include // Arduino LCD library +#include + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +// create an instance of the library +TFT TFTscreen = TFT(cs, dc, rst); + +// char array to print to the screen +char sensorPrintout[4]; + +void setup() { + + // Put this line at the beginning of every sketch that uses the GLCD: + TFTscreen.begin(); + + // clear the screen with a black background + TFTscreen.background(0, 0, 0); + + // write the static text to the screen + // set the font color to white + TFTscreen.stroke(255, 255, 255); + // set the font size + TFTscreen.setTextSize(2); + // write the text to the top left corner of the screen + TFTscreen.text("Sensor Value :\n ", 0, 0); + // ste the font size very large for the loop + TFTscreen.setTextSize(5); +} + +void loop() { + + // Read the value of the sensor on A0 + String sensorVal = String(analogRead(A0)); + + // convert the reading to a char array + sensorVal.toCharArray(sensorPrintout, 4); + + // set the font color + TFTscreen.stroke(255, 255, 255); + // print the sensor value + TFTscreen.text(sensorPrintout, 0, 20); + // wait for a moment + delay(250); + // erase the text you just wrote + TFTscreen.stroke(0, 0, 0); + TFTscreen.text(sensorPrintout, 0, 20); +} + diff --git a/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino b/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino new file mode 100644 index 0000000..4eb75d1 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTEtchASketch/TFTEtchASketch.ino @@ -0,0 +1,83 @@ +/* + + TFT EtchASketch + + This example for the Arduino screen draws a white point + on the GLCD based on the values of 2 potentiometers. + To clear the screen, press a button attached to pin 2. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/TFTEtchASketch + + */ + +#include // Arduino LCD library +#include + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +TFT TFTscreen = TFT(cs, dc, rst); + +// initial position of the cursor +int xPos = TFTscreen.width() / 2; +int yPos = TFTscreen.height() / 2; + +// pin the erase switch is connected to +int erasePin = 2; + +void setup() { + // declare inputs + pinMode(erasePin, INPUT); + // initialize the screen + TFTscreen.begin(); + // make the background black + TFTscreen.background(0, 0, 0); +} + +void loop() { + // read the potentiometers on A0 and A1 + int xValue = analogRead(A0); + int yValue = analogRead(A1); + + // map the values and update the position + xPos = xPos + (map(xValue, 0, 1023, 2, -2)); + yPos = yPos + (map(yValue, 0, 1023, -2, 2)); + + // don't let the point go past the screen edges + if (xPos > 159) { + (xPos = 159); + } + + if (xPos < 0) { + (xPos = 0); + } + if (yPos > 127) { + (yPos = 127); + } + + if (yPos < 0) { + (yPos = 0); + } + + // draw the point + TFTscreen.stroke(255, 255, 255); + TFTscreen.point(xPos, yPos); + + // read the value of the pin, and erase the screen if pressed + if (digitalRead(erasePin) == HIGH) { + TFTscreen.background(0, 0, 0); + } + + delay(33); +} diff --git a/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino b/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino new file mode 100644 index 0000000..3b2f03b --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTGraph/TFTGraph.ino @@ -0,0 +1,70 @@ +/* + + TFT Graph + + This example for an Arduino screen reads + the value of an analog sensor on A0, and + graphs the values on the screen. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/TFTGraph + + */ + +#include // Arduino LCD library +#include + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +TFT TFTscreen = TFT(cs, dc, rst); + +// position of the line on screen +int xPos = 0; + +void setup() { + // initialize the serial port + Serial.begin(9600); + + // initialize the display + TFTscreen.begin(); + + // clear the screen with a pretty color + TFTscreen.background(250, 16, 200); +} + +void loop() { + // read the sensor and map it to the screen height + int sensor = analogRead(A0); + int drawHeight = map(sensor, 0, 1023, 0, TFTscreen.height()); + + // print out the height to the serial monitor + Serial.println(drawHeight); + + // draw a line in a nice color + TFTscreen.stroke(250, 180, 10); + TFTscreen.line(xPos, TFTscreen.height() - drawHeight, xPos, TFTscreen.height()); + + // if the graph has reached the screen edge + // erase the screen and start again + if (xPos >= 160) { + xPos = 0; + TFTscreen.background(250, 16, 200); + } else { + // increment the horizontal position: + xPos++; + } + + delay(16); +} + diff --git a/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino b/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino new file mode 100644 index 0000000..7a61915 --- /dev/null +++ b/libraries/TFT/examples/Arduino/TFTPong/TFTPong.ino @@ -0,0 +1,135 @@ +/* + + TFT Pong + + This example for the Arduino screen reads the values + of 2 potentiometers to move a rectangular platform + on the x and y axes. The platform can intersect + with a ball causing it to bounce. + + This example code is in the public domain. + + Created by Tom Igoe December 2012 + Modified 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/TFTPong + + */ + +#include // Arduino LCD library +#include + +// pin definition for the Uno +#define cs 10 +#define dc 9 +#define rst 8 + +// pin definition for the Leonardo +// #define cs 7 +// #define dc 0 +// #define rst 1 + +TFT TFTscreen = TFT(cs, dc, rst); + +// variables for the position of the ball and paddle +int paddleX = 0; +int paddleY = 0; +int oldPaddleX, oldPaddleY; +int ballDirectionX = 1; +int ballDirectionY = 1; + +int ballSpeed = 10; // lower numbers are faster + +int ballX, ballY, oldBallX, oldBallY; + +void setup() { + // initialize the display + TFTscreen.begin(); + // black background + TFTscreen.background(0, 0, 0); +} + +void loop() { + + // save the width and height of the screen + int myWidth = TFTscreen.width(); + int myHeight = TFTscreen.height(); + + // map the paddle's location to the position of the potentiometers + paddleX = map(analogRead(A0), 512, -512, 0, myWidth) - 20 / 2; + paddleY = map(analogRead(A1), 512, -512, 0, myHeight) - 5 / 2; + + // set the fill color to black and erase the previous + // position of the paddle if different from present + TFTscreen.fill(0, 0, 0); + + if (oldPaddleX != paddleX || oldPaddleY != paddleY) { + TFTscreen.rect(oldPaddleX, oldPaddleY, 20, 5); + } + + // draw the paddle on screen, save the current position + // as the previous. + TFTscreen.fill(255, 255, 255); + + TFTscreen.rect(paddleX, paddleY, 20, 5); + oldPaddleX = paddleX; + oldPaddleY = paddleY; + + // update the ball's position and draw it on screen + if (millis() % ballSpeed < 2) { + moveBall(); + } +} + +// this function determines the ball's position on screen +void moveBall() { + // if the ball goes offscreen, reverse the direction: + if (ballX > TFTscreen.width() || ballX < 0) { + ballDirectionX = -ballDirectionX; + } + + if (ballY > TFTscreen.height() || ballY < 0) { + ballDirectionY = -ballDirectionY; + } + + // check if the ball and the paddle occupy the same space on screen + if (inPaddle(ballX, ballY, paddleX, paddleY, 20, 5)) { + ballDirectionX = -ballDirectionX; + ballDirectionY = -ballDirectionY; + } + + // update the ball's position + ballX += ballDirectionX; + ballY += ballDirectionY; + + // erase the ball's previous position + TFTscreen.fill(0, 0, 0); + + if (oldBallX != ballX || oldBallY != ballY) { + TFTscreen.rect(oldBallX, oldBallY, 5, 5); + } + + + // draw the ball's current position + TFTscreen.fill(255, 255, 255); + TFTscreen.rect(ballX, ballY, 5, 5); + + oldBallX = ballX; + oldBallY = ballY; + +} + +// this function checks the position of the ball +// to see if it intersects with the paddle +boolean inPaddle(int x, int y, int rectX, int rectY, int rectWidth, int rectHeight) { + boolean result = false; + + if ((x >= rectX && x <= (rectX + rectWidth)) && + (y >= rectY && y <= (rectY + rectHeight))) { + result = true; + } + + return result; +} + + diff --git a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino new file mode 100644 index 0000000..8d38519 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/EsploraTFTBitmapLogo.ino @@ -0,0 +1,101 @@ +/* + + Esplora TFT Bitmap Logos + + This example for the Arduino TFT screen is for use + with an Arduino Esplora. + + This example reads an image file from a micro-SD card + and draws it on the screen, at random locations. + + There is a .bmp file included with this sketch. + - open the sketch folder (Ctrl-K or Cmd-K) + - copy the "arduino.bmp" file to a micro-SD + - put the SD into the SD slot of the Arduino LCD module. + + This example code is in the public domain. + + Created 19 April 2013 by Enrico Gueli + + http://www.arduino.cc/en/Tutorial/EsploraTFTBitmapLogo + + */ + +// include the necessary libraries +#include +#include +#include +#include // Arduino LCD library + +// the Esplora pin connected to the chip select line for SD card +#define SD_CS 8 + +// this variable represents the image to be drawn on screen +PImage logo; + +void setup() { + // initialize the GLCD and show a message + // asking the user to open the serial line + EsploraTFT.begin(); + EsploraTFT.background(255, 255, 255); + + EsploraTFT.stroke(0, 0, 255); + EsploraTFT.println(); + EsploraTFT.println(F("Arduino LCD Bitmap Example")); + EsploraTFT.stroke(0, 0, 0); + EsploraTFT.println(F("Open serial monitor")); + EsploraTFT.println(F("to run the sketch")); + + // initialize the serial port: it will be used to + // print some diagnostic info + Serial.begin(9600); + while (!Serial) { + // wait for serial port to connect. Needed for native USB port only + } + + // try to access the SD card. If that fails (e.g. + // no card present), the Esplora's LED will turn red. + Serial.print(F("Initializing SD card...")); + if (!SD.begin(SD_CS)) { + Serial.println(F("failed!")); + Esplora.writeRed(255); + return; + } + Serial.println("OK!"); + + // clear the GLCD screen before starting + EsploraTFT.background(255, 255, 255); + + // now that the SD card can be access, try to load the + // image file. The Esplora LED will turn green or red if + // the loading went OK or not. + Esplora.writeRGB(0, 0, 0); + logo = EsploraTFT.loadImage("arduino.bmp"); + if (logo.isValid()) { + Esplora.writeGreen(255); + } else { + Esplora.writeRed(255); + } + +} + +void loop() { + // don't do anything if the image wasn't loaded correctly. + if (logo.isValid() == false) { + return; + } + + Serial.println(F("drawing image")); + + // get a random location where to draw the image. + // To avoid the image to be draw outside the screen, + // take into account the image size. + int x = random(EsploraTFT.width() - logo.width()); + int y = random(EsploraTFT.height() - logo.height()); + + // draw the image to the screen + EsploraTFT.image(logo, x, y); + + // wait a little bit before drawing again + delay(1500); +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp b/libraries/TFT/examples/Esplora/EsploraTFTBitmapLogo/arduino.bmp new file mode 100644 index 0000000000000000000000000000000000000000..09c670ab54f01647cd59b35a5b00ab381fcbe2ae GIT binary patch literal 6966 zcmeI0cWm256vv&UfM_Y3Quf}fVwAl%Vj~c=OtBF|Vu+0x5osrBbsX2#ndxUb(${o^pV!eL0cX_iF(IL+J1;Eg zTwmkiNC*u)i-S-*F6u@oz5Y0u{b2voP+(WdSAo7K4iDA!b{7Qr90v=Mn;Jp`eU3*O zWQno2Tdi$EB{cE&JS5ov)QFIa5Rw#s_w@AWj?^uIz9;Oi{58OPBl6klY)|KHUiKRp z4kZVT3^x`Rd|>i8u%_A*8-0w2bP%(3)W#7EzZ?U+!$>syFn5&Dde_e6$V91(J1M(UGBy<0`u5A5$q-D+@mL3y4r zk=Klkb;5`~<-5M)ZDHQKsDUqXvtIQv96DgBuv*)L{Z7FO;YU1c@;Iopx^J5~fPTl@UNWkerpZMsT(5JgAhmasbge{!j z+!RRw1b80{0j^;`J>`iYzmqNfWx!={*OiriBlIaQ{K#Udh~0J_n&S&6e70&S&{13C z1%MbhI?}?4JBvOuy6Zr!uEr-X`*n~UuvEs!+=Am+)KnXc`Zc8`UkY$|5?x_I=Wwpr zL?7WVRILuB)d&#Ya3o828dn| zCSlp6P*hjBlT!pOlyJ>VTkC6mVMJP0#m{5}s`mC2veVbM6Bg_uH>amZ$bHyB9x^QA z)#~5BLjd;yGQbjk0A5}BTSHwSrH{%WQ(%82<9CX4Z%{ z^b|VCKD46CWM{mfrH0O^U;cwwf3IUGO0=+*M2%THsN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(1%UmS?w(VjsNx^M5cH6ZW2)o_a+zZz8OAfz;bhM>%eGupJ(*)IkNE2Tjo=C$+ z-ZnLcaYNza$qaEcG +#include // Arduino LCD library +#include + +void setup() { + Serial.begin(9600); + + // initialize the LCD + EsploraTFT.begin(); + + // start out with a white screen + EsploraTFT.background(255, 255, 255); + +} + +void loop() { + + // map the values from sensors + int xValue = map(Esplora.readJoystickX(), -512, 512, 0, 255); // read the joystick's X position + int yValue = map(Esplora.readJoystickY(), -512, 512, 0, 255); // read the joystick's Y position + int slider = map(Esplora.readSlider(), 0, 1023, 0, 255); // read the slider's position + + // change the background color based on the mapped values + EsploraTFT.background(xValue, yValue, slider); + + // print the mapped values to the Serial monitor + Serial.print("background("); + Serial.print(xValue); + Serial.print(" , "); + Serial.print(yValue); + Serial.print(" , "); + Serial.print(slider); + Serial.println(")"); + + delay(33); + +} + diff --git a/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino b/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino new file mode 100644 index 0000000..7d5b567 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTEtchASketch/EsploraTFTEtchASketch.ino @@ -0,0 +1,80 @@ +/* + + Esplora TFT EtchASketch + + This example for the Arduino TFT and Esplora draws + a white line on the screen, based on the position + of the joystick. To clear the screen, shake the + Esplora, using the values from the accelerometer. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/EsploraTFTEtchASketch + + */ + +#include +#include // Arduino LCD library +#include + +// initial position of the cursor +int xPos = EsploraTFT.width() / 2; +int yPos = EsploraTFT.height() / 2; + +void setup() { + // initialize the display + EsploraTFT.begin(); + + // clear the background + EsploraTFT.background(0, 0, 0); +} + +void loop() { + + int xAxis = Esplora.readJoystickX(); // read the X axis + int yAxis = Esplora.readJoystickY(); // read the Y axis + + // update the position of the line + // depending on the position of the joystick + if (xAxis < 10 && xAxis > -10) { + xPos = xPos; + } else { + xPos = xPos + (map(xAxis, -512, 512, 2, -2)); + } + if (yAxis < 10 && yAxis > -10) { + yAxis = yAxis; + } else { + yPos = yPos + (map(yAxis, -512, 512, -2, 2)); + } + + // don't let the point go past the screen edges + if (xPos > 159) { + (xPos = 159); + } + + if (xPos < 0) { + (xPos = 0); + } + if (yPos > 127) { + (yPos = 127); + } + + if (yPos < 0) { + (yPos = 0); + } + + // draw the point + EsploraTFT.stroke(255, 255, 255); + EsploraTFT.point(xPos, yPos); + + // check the accelerometer values and clear + // the screen if it is being shaken + if (abs(Esplora.readAccelerometer(X_AXIS)) > 200 || abs(Esplora.readAccelerometer(Y_AXIS)) > 200) { + EsploraTFT.background(0, 0, 0); + } + + delay(33); +} + diff --git a/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino b/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino new file mode 100644 index 0000000..24e0db6 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTGraph/EsploraTFTGraph.ino @@ -0,0 +1,55 @@ +/* + + Esplora TFT Graph + + This example for the Esplora with an Arduino TFT reads + the value of the light sensor, and graphs the values on + the screen. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/EsploraTFTGraph + + */ + +#include +#include // Arduino LCD library +#include + +// position of the line on screen +int xPos = 0; + +void setup() { + + // initialize the screen + EsploraTFT.begin(); + + // clear the screen with a nice color + EsploraTFT.background(250, 16, 200); +} + +void loop() { + + // read the sensor value + int sensor = Esplora.readLightSensor(); + // map the sensor value to the height of the screen + int graphHeight = map(sensor, 0, 1023, 0, EsploraTFT.height()); + + // draw the line in a pretty color + EsploraTFT.stroke(250, 180, 10); + EsploraTFT.line(xPos, EsploraTFT.height() - graphHeight, xPos, EsploraTFT.height()); + + // if the graph reaches the edge of the screen + // erase it and start over from the other side + if (xPos >= 160) { + xPos = 0; + EsploraTFT.background(250, 16, 200); + } else { + // increment the horizontal position: + xPos++; + } + + delay(16); +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino b/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino new file mode 100644 index 0000000..9a5a454 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTHorizon/EsploraTFTHorizon.ino @@ -0,0 +1,62 @@ +/* + + Esplora TFT Horizon + + This example for the Arduino TFT and Esplora draws + a line on the screen that stays level with the ground + as you tile the Esplora side to side + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/EsploraTFTHorizon + + */ + +#include +#include // Arduino LCD library +#include + +// horizontal start and end positions +int yStart = EsploraTFT.height() / 2; +int yEnd = EsploraTFT.height() / 2; + +// previous start and end positions +int oldEndY; +int oldStartY; + +void setup() { + // initialize the display + EsploraTFT.begin(); + // make the background black + EsploraTFT.background(0, 0, 0); +} + +void loop() { + // read the x-axis of te accelerometer + int tilt = Esplora.readAccelerometer(X_AXIS); + + // the values are 100 when tilted to the left + // and -100 when tilted to the right + // map these values to the start and end points + yStart = map(tilt, -100, 100, EsploraTFT.height(), 0); + yEnd = map(tilt, -100, 100, 0, EsploraTFT.height()); + + // if the previous values are different than the current values + // erase the previous line + if (oldStartY != yStart || oldEndY != yEnd) { + EsploraTFT.stroke(0, 0, 0); + EsploraTFT.line(0, oldStartY, EsploraTFT.width(), oldEndY); + } + + // draw the line in magenta + EsploraTFT.stroke(255, 0, 255); + EsploraTFT.line(0, yStart, EsploraTFT.width(), yEnd); + + // save the current start and end points + // to compare int he next loop + oldStartY = yStart; + oldEndY = yEnd; + delay(10); +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino b/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino new file mode 100644 index 0000000..11b1dff --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTPong/EsploraTFTPong.ino @@ -0,0 +1,126 @@ +/* + + Esplora TFT Pong + + This example for the Esplora with an Arduino TFT screen reads + the value of the joystick to move a rectangular platform + on the x and y axes. The platform can intersect with a ball + causing it to bounce. The Esplora's slider adjusts the speed + of the ball. + + This example code is in the public domain. + + Created by Tom Igoe December 2012 + Modified 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/EsploraTFTPong + + */ + +#include +#include // Arduino LCD library +#include + +// variables for the position of the ball and paddle +int paddleX = 0; +int paddleY = 0; +int oldPaddleX, oldPaddleY; +int ballDirectionX = 1; +int ballDirectionY = 1; + +int ballX, ballY, oldBallX, oldBallY; + +void setup() { + + Serial.begin(9600); + + // initialize the display + EsploraTFT.begin(); + // set the background the black + EsploraTFT.background(0, 0, 0); +} + +void loop() { + // save the width and height of the screen + int myWidth = EsploraTFT.width(); + int myHeight = EsploraTFT.height(); + + // map the paddle's location to the joystick's position + paddleX = map(Esplora.readJoystickX(), 512, -512, 0, myWidth) - 20 / 2; + paddleY = map(Esplora.readJoystickY(), -512, 512, 0, myHeight) - 5 / 2; + Serial.print(paddleX); + Serial.print(" "); + Serial.println(paddleY); + + // set the fill color to black and erase the previous + // position of the paddle if different from present + EsploraTFT.fill(0, 0, 0); + + if (oldPaddleX != paddleX || oldPaddleY != paddleY) { + EsploraTFT.rect(oldPaddleX, oldPaddleY, 20, 5); + } + + // draw the paddle on screen, save the current position + // as the previous. + EsploraTFT.fill(255, 255, 255); + EsploraTFT.rect(paddleX, paddleY, 20, 5); + oldPaddleX = paddleX; + oldPaddleY = paddleY; + + // read the slider to determinde the speed of the ball + int ballSpeed = map(Esplora.readSlider(), 0, 1023, 0, 80) + 1; + if (millis() % ballSpeed < 2) { + moveBall(); + } +} + + +// this function determines the ball's position on screen +void moveBall() { + // if the ball goes offscreen, reverse the direction: + if (ballX > EsploraTFT.width() || ballX < 0) { + ballDirectionX = -ballDirectionX; + } + + if (ballY > EsploraTFT.height() || ballY < 0) { + ballDirectionY = -ballDirectionY; + } + + // check if the ball and the paddle occupy the same space on screen + if (inPaddle(ballX, ballY, paddleX, paddleY, 20, 5)) { + ballDirectionY = -ballDirectionY; + } + + // update the ball's position + ballX += ballDirectionX; + ballY += ballDirectionY; + + // erase the ball's previous position + EsploraTFT.fill(0, 0, 0); + + if (oldBallX != ballX || oldBallY != ballY) { + EsploraTFT.rect(oldBallX, oldBallY, 5, 5); + } + + // draw the ball's current position + EsploraTFT.fill(255, 255, 255); + + EsploraTFT.rect(ballX, ballY, 5, 5); + + oldBallX = ballX; + oldBallY = ballY; + +} + +// this function checks the position of the ball +// to see if it intersects with the paddle +boolean inPaddle(int x, int y, int rectX, int rectY, int rectWidth, int rectHeight) { + boolean result = false; + + if ((x >= rectX && x <= (rectX + rectWidth)) && + (y >= rectY && y <= (rectY + rectHeight))) { + result = true; + } + + return result; +} diff --git a/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino b/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino new file mode 100644 index 0000000..a5c7081 --- /dev/null +++ b/libraries/TFT/examples/Esplora/EsploraTFTTemp/EsploraTFTTemp.ino @@ -0,0 +1,64 @@ +/* + + Esplora TFT Temperature Display + + This example for the Arduino TFT screen is for use + with an Arduino Esplora. + + This example reads the temperature of the Esplora's + on board thermisistor and displays it on an attached + LCD screen, updating every second. + + This example code is in the public domain. + + Created 15 April 2013 by Scott Fitzgerald + + http://www.arduino.cc/en/Tutorial/EsploraTFTTemp + + */ + +// include the necessary libraries +#include +#include // Arduino LCD library +#include + +char tempPrintout[3]; // array to hold the temperature data + +void setup() { + + // Put this line at the beginning of every sketch that uses the GLCD + EsploraTFT.begin(); + + // clear the screen with a black background + EsploraTFT.background(0, 0, 0); + + // set the text color to magenta + EsploraTFT.stroke(200, 20, 180); + // set the text to size 2 + EsploraTFT.setTextSize(2); + // start the text at the top left of the screen + // this text is going to remain static + EsploraTFT.text("Degrees in C :\n ", 0, 0); + + // set the text in the loop to size 5 + EsploraTFT.setTextSize(5); +} + +void loop() { + + // read the temperature in Celcius and store it in a String + String temperature = String(Esplora.readTemperature(DEGREES_C)); + + // convert the string to a char array + temperature.toCharArray(tempPrintout, 3); + + // set the text color to white + EsploraTFT.stroke(255, 255, 255); + // print the temperature one line below the static text + EsploraTFT.text(tempPrintout, 0, 30); + + delay(1000); + // erase the text for the next loop + EsploraTFT.stroke(0, 0, 0); + EsploraTFT.text(tempPrintout, 0, 30); +} diff --git a/libraries/TFT/extras/Adafruit-README.txt b/libraries/TFT/extras/Adafruit-README.txt new file mode 100644 index 0000000..6f3b682 --- /dev/null +++ b/libraries/TFT/extras/Adafruit-README.txt @@ -0,0 +1,21 @@ +This is a library for the Adafruit 1.8" SPI display. +This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 +as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + +Check out the links above for our tutorials and wiring diagrams. +These displays use SPI to communicate, 4 or 5 pins are required +to interface (RST is optional). +Adafruit invests time and resources providing this open source code, +please support Adafruit and open-source hardware by purchasing +products from Adafruit! + +Written by Limor Fried/Ladyada for Adafruit Industries. +MIT license, all text above must be included in any redistribution + +To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_ST7735. Check that the Adafruit_ST7735 folder contains Adafruit_ST7735.cpp and Adafruit_ST7735. + +Place the Adafruit_ST7735 library folder your /libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE + +Also requires the Adafruit_GFX library for Arduino. diff --git a/libraries/TFT/extras/Adafruit-license.txt b/libraries/TFT/extras/Adafruit-license.txt new file mode 100644 index 0000000..4bbfa39 --- /dev/null +++ b/libraries/TFT/extras/Adafruit-license.txt @@ -0,0 +1,25 @@ +Software License Agreement (BSD License) + +Copyright (c) 2012, Adafruit Industries. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holders nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libraries/TFT/extras/README.md b/libraries/TFT/extras/README.md new file mode 100644 index 0000000..6f41794 --- /dev/null +++ b/libraries/TFT/extras/README.md @@ -0,0 +1,18 @@ +TFT Library +============ + +An Arduino library for the Arduino TFT LCD screen. + +This library enables an Arduino board to communicate with an Arduino TFT LCD screen. It simplifies the process for drawing shapes, lines, images, and text to the screen. +The Arduino TFT library extends the Adafruit GFX, and Adafruit ST7735 libraries that it is based on. The GFX library is responsible for the drawing routines, while the ST7735 library is specific to the screen on the Arduino GTFT. The Arduino specific additions were designed to work as similarly to the Processing API as possible. + +Onboard the screen is a SD card slot, which can be used through the SD library. + +The TFT library relies on the SPI library for communication with the screen and SD card, and needs to be included in all sketches. + +https://github.com/adafruit/Adafruit-GFX-Library +https://github.com/adafruit/Adafruit-ST7735-Library +http://www.arduino.cc/en/Reference/SD +http://www.arduino.cc/en/Reference/SPI + +http://www.arduino.cc/en/Reference/TFTLibrary \ No newline at end of file diff --git a/libraries/TFT/keywords.txt b/libraries/TFT/keywords.txt new file mode 100644 index 0000000..c8d33e4 --- /dev/null +++ b/libraries/TFT/keywords.txt @@ -0,0 +1,20 @@ +####################################### +# Syntax Coloring Map For Arduino GLCD +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +TFT KEYWORD1 TFTLibrary + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + + +####################################### +# Constants (LITERAL1) +####################################### + +EsploraTFT LITERAL1 diff --git a/libraries/TFT/library.properties b/libraries/TFT/library.properties new file mode 100644 index 0000000..b89f071 --- /dev/null +++ b/libraries/TFT/library.properties @@ -0,0 +1,9 @@ +name=TFT +version=1.0.6 +author=Arduino, Adafruit +maintainer=Arduino +sentence=Allows drawing text, images, and shapes on the Arduino TFT graphical display. +paragraph=This library is compatible with most of the TFT display based on the ST7735 chipset. +category=Display +url=http://www.arduino.cc/en/Reference/TFTLibrary +architectures=* diff --git a/libraries/TFT/src/TFT.cpp b/libraries/TFT/src/TFT.cpp new file mode 100644 index 0000000..1bdf7ed --- /dev/null +++ b/libraries/TFT/src/TFT.cpp @@ -0,0 +1,51 @@ +/* Copyright (c) 2013, Enrico Gueli All +rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "TFT.h" + +#if ARDUINO_AVR_ESPLORA +TFT EsploraTFT(7, 0, 1); +#endif + +TFT::TFT(uint8_t CS, uint8_t RS, uint8_t RST) + : Adafruit_ST7735(CS, RS, RST) +{ + // as we already know the orientation (landscape, therefore rotated), + // set default width and height without need to call begin() first. + _width = ST7735_TFTHEIGHT; + _height = ST7735_TFTWIDTH; +} + +void TFT::begin() { +//initR(INITR_REDTAB); + initG(); + setRotation(1); +} diff --git a/libraries/TFT/src/TFT.h b/libraries/TFT/src/TFT.h new file mode 100644 index 0000000..16791d6 --- /dev/null +++ b/libraries/TFT/src/TFT.h @@ -0,0 +1,58 @@ +/* Copyright (c) 2013, Enrico Gueli All +rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef _ARDUINO_TFT_H +#define _ARDUINO_TFT_H + +#include "Arduino.h" +#include "utility/Adafruit_GFX.h" +#include "utility/Adafruit_ST7735.h" + +/// The Arduino LCD is a ST7735-based device. +/// By default, it is mounted horizontally. +/// TFT class follows the convention of other +/// Arduino library classes by adding a begin() method +/// to be called in the setup() routine. +/// @author Enrico Gueli +class TFT : public Adafruit_ST7735 { +public: + TFT(uint8_t CS, uint8_t RS, uint8_t RST); + + void begin(); +}; + +/// Esplora boards have hard-wired connections with +/// the Arduino LCD if mounted on the onboard connector. +#if ARDUINO_AVR_ESPLORA // are we building for Esplora? +extern TFT EsploraTFT; +#endif + +#endif // _ARDUINO_TFT_H diff --git a/libraries/TFT/src/utility/Adafruit_GFX.cpp b/libraries/TFT/src/utility/Adafruit_GFX.cpp new file mode 100644 index 0000000..6478c47 --- /dev/null +++ b/libraries/TFT/src/utility/Adafruit_GFX.cpp @@ -0,0 +1,715 @@ +/* +This is the core graphics library for all our displays, providing a common +set of graphics primitives (points, lines, circles, etc.). It needs to be +paired with a hardware-specific library for each display device we carry +(to handle the lower-level functions). + +Adafruit invests time and resources providing this open source code, please +support Adafruit & open-source hardware by purchasing products from Adafruit! + +Copyright (c) 2013 Adafruit Industries. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "Adafruit_GFX.h" +#include "glcdfont.c" +#ifdef __AVR__ + #include +#else + #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) +#endif + +Adafruit_GFX::Adafruit_GFX(int16_t w, int16_t h) : + WIDTH(w), HEIGHT(h) +{ + _width = WIDTH; + _height = HEIGHT; + rotation = 0; + cursor_y = cursor_x = 0; + textsize = 1; + textcolor = textbgcolor = 0xFFFF; + wrap = true; +} + +// draw a circle outline +void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, + uint16_t color) { + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + drawPixel(x0, y0+r, color); + drawPixel(x0, y0-r, color); + drawPixel(x0+r, y0, color); + drawPixel(x0-r, y0, color); + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + + drawPixel(x0 + x, y0 + y, color); + drawPixel(x0 - x, y0 + y, color); + drawPixel(x0 + x, y0 - y, color); + drawPixel(x0 - x, y0 - y, color); + drawPixel(x0 + y, y0 + x, color); + drawPixel(x0 - y, y0 + x, color); + drawPixel(x0 + y, y0 - x, color); + drawPixel(x0 - y, y0 - x, color); + } +} + +void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, + int16_t r, uint8_t cornername, uint16_t color) { + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + if (cornername & 0x4) { + drawPixel(x0 + x, y0 + y, color); + drawPixel(x0 + y, y0 + x, color); + } + if (cornername & 0x2) { + drawPixel(x0 + x, y0 - y, color); + drawPixel(x0 + y, y0 - x, color); + } + if (cornername & 0x8) { + drawPixel(x0 - y, y0 + x, color); + drawPixel(x0 - x, y0 + y, color); + } + if (cornername & 0x1) { + drawPixel(x0 - y, y0 - x, color); + drawPixel(x0 - x, y0 - y, color); + } + } +} + +void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, + uint16_t color) +{ + drawFastVLine(x0, y0-r, 2*r+1, color); + fillCircleHelper(x0, y0, r, 3, 0, color); +} + +// used to do circles and roundrects +void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, + uint8_t cornername, int16_t delta, uint16_t color) +{ + int16_t f = 1 - r; + int16_t ddF_x = 1; + int16_t ddF_y = -2 * r; + int16_t x = 0; + int16_t y = r; + + while (x= 0) { + y--; + ddF_y += 2; + f += ddF_y; + } + x++; + ddF_x += 2; + f += ddF_x; + + if (cornername & 0x1) { + drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); + drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); + } + if (cornername & 0x2) { + drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); + drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); + } + } +} + +// Bresenham's algorithm - thx wikpedia +void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, + int16_t x1, int16_t y1, + uint16_t color) +{ + int16_t steep = abs(y1 - y0) > abs(x1 - x0); + if (steep) { + swap(x0, y0); + swap(x1, y1); + } + + if (x0 > x1) { + swap(x0, x1); + swap(y0, y1); + } + + int16_t dx, dy; + dx = x1 - x0; + dy = abs(y1 - y0); + + int16_t err = dx / 2; + int16_t ystep; + + if (y0 < y1) { + ystep = 1; + } else { + ystep = -1; + } + + for (; x0<=x1; x0++) { + if (steep) { + drawPixel(y0, x0, color); + } else { + drawPixel(x0, y0, color); + } + err -= dy; + if (err < 0) { + y0 += ystep; + err += dx; + } + } +} + + +// Draw a rectangle +void Adafruit_GFX::drawRect(int16_t x, int16_t y, + int16_t w, int16_t h, + uint16_t color) +{ + drawFastHLine(x, y, w, color); + drawFastHLine(x, y+h-1, w, color); + drawFastVLine(x, y, h, color); + drawFastVLine(x+w-1, y, h, color); +} + +void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, + int16_t h, uint16_t color) +{ + // Update in subclasses if desired! + drawLine(x, y, x, y+h-1, color); +} + + +void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, + int16_t w, uint16_t color) +{ + // Update in subclasses if desired! + drawLine(x, y, x+w-1, y, color); +} + +void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color) +{ + // Update in subclasses if desired! + for (int16_t i=x; i= y1 >= y0) + if (y0 > y1) { + swap(y0, y1); swap(x0, x1); + } + if (y1 > y2) { + swap(y2, y1); swap(x2, x1); + } + if (y0 > y1) { + swap(y0, y1); swap(x0, x1); + } + + if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing + a = b = x0; + if(x1 < a) a = x1; + else if(x1 > b) b = x1; + if(x2 < a) a = x2; + else if(x2 > b) b = x2; + drawFastHLine(a, y0, b-a+1, color); + return; + } + + int16_t + dx01 = x1 - x0, + dy01 = y1 - y0, + dx02 = x2 - x0, + dy02 = y2 - y0, + dx12 = x2 - x1, + dy12 = y2 - y1, + sa = 0, + sb = 0; + + // For upper part of triangle, find scanline crossings for segments + // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 + // is included here (and second loop will be skipped, avoiding a /0 + // error there), otherwise scanline y1 is skipped here and handled + // in the second loop...which also avoids a /0 error here if y0=y1 + // (flat-topped triangle). + if(y1 == y2) last = y1; // Include y1 scanline + else last = y1-1; // Skip it + + for(y=y0; y<=last; y++) { + a = x0 + sa / dy01; + b = x0 + sb / dy02; + sa += dx01; + sb += dx02; + /* longhand: + a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); + b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); + */ + if(a > b) swap(a,b); + drawFastHLine(a, y, b-a+1, color); + } + + // For lower part of triangle, find scanline crossings for segments + // 0-2 and 1-2. This loop is skipped if y1=y2. + sa = dx12 * (y - y1); + sb = dx02 * (y - y0); + for(; y<=y2; y++) { + a = x1 + sa / dy12; + b = x0 + sb / dy02; + sa += dx12; + sb += dx02; + /* longhand: + a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); + b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); + */ + if(a > b) swap(a,b); + drawFastHLine(a, y, b-a+1, color); + } +} + +void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, + const uint8_t *bitmap, int16_t w, int16_t h, + uint16_t color) +{ + int16_t i, j, byteWidth = (w + 7) / 8; + + for(j=0; j> (i & 7))) { + drawPixel(x+i, y+j, color); + } + } + } +} + + +#if ARDUINO >= 100 +size_t Adafruit_GFX::write(uint8_t c) { +#else +void Adafruit_GFX::write(uint8_t c) { +#endif + if (c == '\n') { + cursor_y += textsize*8; + cursor_x = 0; + } else if (c == '\r') { + // skip em + } else { + drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); + cursor_x += textsize*6; + if (wrap && (cursor_x > (_width - textsize*6))) { + cursor_y += textsize*8; + cursor_x = 0; + } + } +#if ARDUINO >= 100 + return 1; +#endif +} + +// draw a character +void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, + uint16_t color, uint16_t bg, uint8_t size) +{ + if((x >= _width) || // Clip right + (y >= _height) || // Clip bottom + ((x + 6 * size - 1) < 0) || // Clip left + ((y + 8 * size - 1) < 0)) // Clip top + return; + + for (int8_t i=0; i<6; i++ ) { + uint8_t line; + if (i == 5) + line = 0x0; + else + line = pgm_read_byte(font+(c*5)+i); + for (int8_t j = 0; j<8; j++) { + if (line & 0x1) { + if (size == 1) // default size + drawPixel(x+i, y+j, color); + else { // big size + fillRect(x+(i*size), y+(j*size), size, size, color); + } + } else if (bg != color) { + if (size == 1) // default size + drawPixel(x+i, y+j, bg); + else { // big size + fillRect(x+i*size, y+j*size, size, size, bg); + } + } + line >>= 1; + } + } +} + +void Adafruit_GFX::setCursor(int16_t x, int16_t y) +{ + cursor_x = x; + cursor_y = y; +} + + +void Adafruit_GFX::setTextSize(uint8_t s) +{ + textsize = (s > 0) ? s : 1; +} + + +void Adafruit_GFX::setTextColor(uint16_t c) { + textcolor = c; + textbgcolor = c; + // for 'transparent' background, we'll set the bg + // to the same as fg instead of using a flag +} + + void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) +{ + textcolor = c; + textbgcolor = b; +} + +void Adafruit_GFX::setTextWrap(boolean w) +{ + wrap = w; +} + +uint8_t Adafruit_GFX::getRotation(void) +{ + return rotation; +} + +void Adafruit_GFX::setRotation(uint8_t x) +{ + rotation = (x & 3); + switch (x) { + case 0: + case 2: + _width = WIDTH; + _height = HEIGHT; + break; + case 1: + case 3: + _width = HEIGHT; + _height = WIDTH; + break; + } +} + + + +// return the size of the display (per current rotation) +int16_t Adafruit_GFX::width(void) +{ + return _width; +} + +int16_t Adafruit_GFX::height(void) +{ + return _height; +} + +void Adafruit_GFX::invertDisplay(boolean i) +{ + // Do nothing, must be subclassed if supported +} + + +uint16_t Adafruit_GFX::newColor(uint8_t r, uint8_t g, uint8_t b) +{ + return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); +} + +void Adafruit_GFX::background(uint8_t red, uint8_t green, uint8_t blue) +{ + background(newColor(red, green, blue)); +} + +void Adafruit_GFX::background(color c) { + fillScreen(c); +} + +void Adafruit_GFX::stroke(uint8_t red, uint8_t green, uint8_t blue) +{ + stroke(newColor(red, green, blue)); +} + +void Adafruit_GFX::stroke(color c) +{ + useStroke = true; + strokeColor = c; + setTextColor(c); +} + +void Adafruit_GFX::noStroke() +{ + useStroke = false; +} + +void Adafruit_GFX::noFill() { + useFill = false; +} + +void Adafruit_GFX::fill(uint8_t red, uint8_t green, uint8_t blue) +{ + fill(newColor(red, green, blue)); +} + +void Adafruit_GFX::fill(color c) +{ + useFill = true; + fillColor = c; +} + + +void Adafruit_GFX::text(const char * text, int16_t x, int16_t y) +{ + if (!useStroke) + return; + + setTextWrap(false); + setTextColor(strokeColor); + setCursor(x, y); + print(text); +} + +void Adafruit_GFX::textWrap(const char * text, int16_t x, int16_t y) +{ + if (!useStroke) + return; + + setTextWrap(true); + setTextColor(strokeColor); + setCursor(x, y); + print(text); +} + + +void Adafruit_GFX::textSize(uint8_t size) +{ + setTextSize(size); +} + +void Adafruit_GFX::point(int16_t x, int16_t y) +{ + if (!useStroke) + return; + + drawPixel(x, y, strokeColor); +} + +void Adafruit_GFX::line(int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + if (!useStroke) + return; + + if (x1 == x2) { + if (y1 < y2) + drawFastVLine(x1, y1, y2 - y1, strokeColor); + else + drawFastVLine(x1, y2, y1 - y2, strokeColor); + } + else if (y1 == y2) { + if (x1 < x2) + drawFastHLine(x1, y1, x2 - x1, strokeColor); + else + drawFastHLine(x2, y1, x1 - x2, strokeColor); + } + else { + drawLine(x1, y1, x2, y2, strokeColor); + } +} + +void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height) +{ + if (useFill) { + fillRect(x, y, width, height, fillColor); + } + if (useStroke) { + drawRect(x, y, width, height, strokeColor); + } +} + +void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius) +{ + if (radius == 0) { + rect(x, y, width, height); + } + if (useFill) { + fillRoundRect(x, y, width, height, radius, fillColor); + } + if (useStroke) { + drawRoundRect(x, y, width, height, radius, strokeColor); + } +} + +void Adafruit_GFX::circle(int16_t x, int16_t y, int16_t r) +{ + if (r == 0) + return; + + if (useFill) { + fillCircle(x, y, r, fillColor); + } + if (useStroke) { + drawCircle(x, y, r, strokeColor); + } +} + +void Adafruit_GFX::triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3) +{ + if (useFill) { + fillTriangle(x1, y1, x2, y2, x3, y3, fillColor); + } + if (useStroke) { + drawTriangle(x1, y1, x2, y2, x3, y3, strokeColor); + } +} + +#if defined(__SD_H__) // Arduino SD library + +#define BUFFPIXEL 20 + +void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { + int w, h, row, col; + uint8_t r, g, b; + uint32_t pos = 0; + uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) + uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer + + // Crop area to be loaded + w = img._bmpWidth; + h = img._bmpHeight; + if((x+w-1) >= width()) w = width() - x; + if((y+h-1) >= height()) h = height() - y; + + /* + // Set TFT address window to clipped image bounds + setAddrWindow(x, y, x+w-1, y+h-1); + */ + + for (row=0; row= sizeof(sdbuffer)) { // Indeed + img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); + buffidx = 0; // Set index to beginning + } + + // Convert pixel from BMP to TFT format, push to display + b = sdbuffer[buffidx++]; + g = sdbuffer[buffidx++]; + r = sdbuffer[buffidx++]; + //pushColor(tft.Color565(r,g,b)); + drawPixel(x + col, y + row, newColor(r, g, b)); + + } // end pixel + } // end scanline + +} + +#endif diff --git a/libraries/TFT/src/utility/Adafruit_GFX.h b/libraries/TFT/src/utility/Adafruit_GFX.h new file mode 100644 index 0000000..626e3d7 --- /dev/null +++ b/libraries/TFT/src/utility/Adafruit_GFX.h @@ -0,0 +1,372 @@ +/****************************************************************** + This is the core graphics library for all our displays, providing + basic graphics primitives (points, lines, circles, etc.). It needs + to be paired with a hardware-specific library for each display + device we carry (handling the lower-level functions). + + Adafruit invests time and resources providing this open + source code, please support Adafruit and open-source hardware + by purchasing products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + Processing-like API written by Enrico Gueli for Officine Arduino. + BSD license, check license.txt for more information. + All text above must be included in any redistribution. + ******************************************************************/ + +#ifndef _ADAFRUIT_GFX_H +#define _ADAFRUIT_GFX_H + +#if ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif + +/* + * This library can work with or without the presence of an SD + * reading library (to load images). At the moment, only the + * Arduino SD library is supported; it is included in + * standard Arduino libraries. + * + * The presence of the SD library is detected by looking at the + * __SD_H__ preprocessor variable, defined into + * Arduino SD library to avoid double inclusion. This means + * that in order to use the image-related API of Adafruit_GFX, + * SD.h *must* be included before Adafruit_GFX. + * + * The bottom part of this include file contains the actual image + * loading code; if it was in a separate .cpp file, there were no + * way to check if the SD library was present or not. + * + * A partial solution was to include SD.h anyway, see if that works + * (i.e. it is found in the include search path) and act accordingly. + * But this solution relied on the preprocessor to issue only a + * warning when an include file is not found. Avr-gcc, used for + * Arduino 8-bit MCUs, does that, but the standard gcc-4.4, used for + * Arduino Due, issues a fatal error and stops compilation. + * + * The best solution so far is to put the code here. It works if this + * include is used only in one .cpp file in the build (this is the + * case of most Arduino sketches); if used in multiple .cpp files, + * the linker may complain about duplicate definitions. + * + */ + +#if defined(__SD_H__) // Arduino SD library + #include "PImage.h" +#else + #warning "The SD library was not found. loadImage() and image() won't be supported." +#endif + +#define swap(a, b) { int16_t t = a; a = b; b = t; } + +/* TODO +enum RectMode { + CORNER, + CORNERS, + RADIUS, + CENTER +}; +*/ + +typedef uint16_t color; + +class Adafruit_GFX : public Print { + public: + + Adafruit_GFX(int16_t w, int16_t h); // Constructor + + // This MUST be defined by the subclass + virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0; + + + + // These MAY be overridden by the subclass to provide device-specific + // optimized code. Otherwise 'generic' versions are used. + virtual void + drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + uint16_t color), + drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), + drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), + drawRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color), + fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color), + fillScreen(uint16_t color), + invertDisplay(boolean i); + +// These exist only with Adafruit_GFX (no subclass overrides) + void + drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), + drawCircleHelper(int16_t x0, int16_t y0, + int16_t r, uint8_t cornername, uint16_t color), + fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), + fillCircleHelper(int16_t x0, int16_t y0, int16_t r, + uint8_t cornername, int16_t delta, uint16_t color), + + drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t x2, int16_t y2, uint16_t color), + fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t x2, int16_t y2, uint16_t color), + drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, + int16_t radius, uint16_t color), + fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, + int16_t radius, uint16_t color), + + drawBitmap(int16_t x, int16_t y, + const uint8_t *bitmap, int16_t w, int16_t h, + uint16_t color), + drawChar(int16_t x, int16_t y, unsigned char c, + uint16_t color, uint16_t bg, uint8_t size), + setCursor(int16_t x, int16_t y), + setTextColor(uint16_t c), + setTextColor(uint16_t c, uint16_t bg), + setTextSize(uint8_t s), + setTextWrap(boolean w), + setRotation(uint8_t r); + +#if ARDUINO >= 100 + virtual size_t write(uint8_t); +#else + virtual void write(uint8_t); +#endif + + int16_t + height(void), + width(void); + + + uint8_t getRotation(void); + + + /* + * Processing-like graphics primitives + */ + + /// transforms a color in 16-bit form given the RGB components. + /// The default implementation makes a 5-bit red, a 6-bit + /// green and a 5-bit blue (MSB to LSB). Devices that use + /// different scheme should override this. + virtual uint16_t newColor(uint8_t red, uint8_t green, uint8_t blue); + + + void + // http://processing.org/reference/background_.html + background(uint8_t red, uint8_t green, uint8_t blue), + background(color c), + + // http://processing.org/reference/fill_.html + fill(uint8_t red, uint8_t green, uint8_t blue), + fill(color c), + + // http://processing.org/reference/noFill_.html + noFill(), + + // http://processing.org/reference/stroke_.html + stroke(uint8_t red, uint8_t green, uint8_t blue), + stroke(color c), + + // http://processing.org/reference/noStroke_.html + noStroke(), + + text(const char * text, int16_t x, int16_t y), + textWrap(const char * text, int16_t x, int16_t y), + + textSize(uint8_t size), + + // similar to ellipse() in Processing, but with + // a single radius. + // http://processing.org/reference/ellipse_.html + circle(int16_t x, int16_t y, int16_t r), + point(int16_t x, int16_t y), + line(int16_t x1, int16_t y1, int16_t x2, int16_t y2), + quad(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3, int16_t x4, int16_t y4), +rect(int16_t x, int16_t y, int16_t width, int16_t height), + rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius), + triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3); + + /* TODO + void rectMode(RectMode mode); + + void pushStyle(); + void popStyle(); + */ + +#if defined(__SD_H__) // Arduino SD library + PImage loadImage(const char * fileName) { return PImage::loadImage(fileName); } + + void image(PImage & img, uint16_t x, uint16_t y); +#endif + + protected: + int16_t + WIDTH, HEIGHT; // this is the 'raw' display w/h - never changes + int16_t + _width, _height, // dependent on rotation + cursor_x, cursor_y; + uint16_t + textcolor, textbgcolor; + uint8_t + textsize, + rotation; + boolean + wrap; // If set, 'wrap' text at right edge of display + + /* + * Processing-style graphics state + */ + + color strokeColor; + bool useStroke; + color fillColor; + bool useFill; +}; + +#if defined(__SD_H__) // Arduino SD library + +#define BUFFPIXEL 20 + +void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { + int w, h, row, col; + uint8_t r, g, b; + uint32_t pos = 0; + uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) + uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer + + // Crop area to be loaded + w = img._bmpWidth; + h = img._bmpHeight; + if((x+w-1) >= width()) w = width() - x; + if((y+h-1) >= height()) h = height() - y; + + /* + // Set TFT address window to clipped image bounds + setAddrWindow(x, y, x+w-1, y+h-1); + */ + + for (row=0; row= sizeof(sdbuffer)) { // Indeed + img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); + buffidx = 0; // Set index to beginning + } + + // Convert pixel from BMP to TFT format, push to display + b = sdbuffer[buffidx++]; + g = sdbuffer[buffidx++]; + r = sdbuffer[buffidx++]; + //pushColor(tft.Color565(r,g,b)); + drawPixel(x + col, y + row, newColor(r, g, b)); + + } // end pixel + } // end scanline + +} + + + + +// These read 16- and 32-bit types from the SD card file. +// BMP data is stored little-endian, Arduino is little-endian too. +// May need to reverse subscript order if porting elsewhere. + +uint16_t PImage::read16(File f) { + uint16_t result; + ((uint8_t *)&result)[0] = f.read(); // LSB + ((uint8_t *)&result)[1] = f.read(); // MSB + return result; +} + +uint32_t PImage::read32(File f) { + uint32_t result; + ((uint8_t *)&result)[0] = f.read(); // LSB + ((uint8_t *)&result)[1] = f.read(); + ((uint8_t *)&result)[2] = f.read(); + ((uint8_t *)&result)[3] = f.read(); // MSB + return result; +} + + +PImage PImage::loadImage(const char * fileName) { + File bmpFile; + int bmpWidth, bmpHeight; // W+H in pixels + uint8_t bmpDepth; // Bit depth (currently must be 24) + uint32_t bmpImageoffset; // Start of image data in file + uint32_t rowSize; // Not always = bmpWidth; may have padding + bool flip = true; // BMP is stored bottom-to-top + + + // Open requested file on SD card + if ((bmpFile = SD.open(fileName)) == NULL) { + Serial.print(F("loadImage: file not found: ")); + Serial.println(fileName); + return PImage(); // load error + } + + + + // Parse BMP header + if(read16(bmpFile) != 0x4D42) { // BMP signature + Serial.println(F("loadImage: file doesn't look like a BMP")); + return PImage(); + } + + Serial.print(F("File size: ")); Serial.println(read32(bmpFile)); + (void)read32(bmpFile); // Read & ignore creator bytes + bmpImageoffset = read32(bmpFile); // Start of image data + Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC); + // Read DIB header + Serial.print(F("Header size: ")); Serial.println(read32(bmpFile)); + bmpWidth = read32(bmpFile); + bmpHeight = read32(bmpFile); + if(read16(bmpFile) != 1) { // # planes -- must be '1' + Serial.println(F("loadImage: invalid n. of planes")); + return PImage(); + } + + bmpDepth = read16(bmpFile); // bits per pixel + Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth); + if((bmpDepth != 24) || (read32(bmpFile) != 0)) { // 0 = uncompressed { + Serial.println(F("loadImage: invalid pixel format")); + return PImage(); + } + + Serial.print(F("Image size: ")); + Serial.print(bmpWidth); + Serial.print('x'); + Serial.println(bmpHeight); + + // BMP rows are padded (if needed) to 4-byte boundary + rowSize = (bmpWidth * 3 + 3) & ~3; + + // If bmpHeight is negative, image is in top-down order. + // This is not canon but has been observed in the wild. + if(bmpHeight < 0) { + bmpHeight = -bmpHeight; + flip = false; + } + + return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip); +} + +#endif + +#endif // _ADAFRUIT_GFX_H diff --git a/libraries/TFT/src/utility/Adafruit_ST7735.cpp b/libraries/TFT/src/utility/Adafruit_ST7735.cpp new file mode 100644 index 0000000..c9698a6 --- /dev/null +++ b/libraries/TFT/src/utility/Adafruit_ST7735.cpp @@ -0,0 +1,751 @@ +/*************************************************** + This is a library for the Adafruit 1.8" SPI display. + This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 + as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + + Check out the links above for our tutorials and wiring diagrams + These displays use SPI to communicate, 4 or 5 pins are required to + interface (RST is optional) + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + MIT license, all text above must be included in any redistribution + ****************************************************/ + +#include "Adafruit_ST7735.h" +#include +#include +#include "pins_arduino.h" +#include "wiring_private.h" +#include + +inline uint16_t swapcolor(uint16_t x) { + return (x << 11) | (x & 0x07E0) | (x >> 11); +} + + +// Constructor when using software SPI. All output pins are configurable. +Adafruit_ST7735::Adafruit_ST7735(uint8_t cs, uint8_t rs, uint8_t sid, + uint8_t sclk, uint8_t rst) : Adafruit_GFX(ST7735_TFTWIDTH, ST7735_TFTHEIGHT) +{ + _cs = cs; + _rs = rs; + _sid = sid; + _sclk = sclk; + _rst = rst; + hwSPI = false; +} + + +// Constructor when using hardware SPI. Faster, but must use SPI pins +// specific to each board type (e.g. 11,13 for Uno, 51,52 for Mega, etc.) +Adafruit_ST7735::Adafruit_ST7735(uint8_t cs, uint8_t rs, uint8_t rst) : +Adafruit_GFX(ST7735_TFTWIDTH, ST7735_TFTHEIGHT) +{ + _cs = cs; + _rs = rs; + _rst = rst; + hwSPI = true; + _sid = _sclk = 0; +} + + +inline void Adafruit_ST7735::spiwrite(uint8_t c) { + + //Serial.println(c, HEX); + + if (hwSPI) { + SPI.transfer(c); + } else { + // Fast SPI bitbang swiped from LPD8806 library + for(uint8_t bit = 0x80; bit; bit >>= 1) { + if(c & bit) *dataport |= datapinmask; + else *dataport &= ~datapinmask; + *clkport |= clkpinmask; + *clkport &= ~clkpinmask; + } + } +} + + +void Adafruit_ST7735::writecommand(uint8_t c) { +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.beginTransaction(spisettings); +#endif + +#ifdef __ARDUINO_ARC__ + digitalWrite(_rs, LOW); +#else + *rsport &= ~rspinmask; +#endif + *csport &= ~cspinmask; + + //Serial.print("C "); + spiwrite(c); + + *csport |= cspinmask; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.endTransaction(); +#endif +} + + +void Adafruit_ST7735::writedata(uint8_t c) { +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.beginTransaction(spisettings); +#endif + +#ifdef __ARDUINO_ARC__ + digitalWrite(_rs, HIGH); +#else + *rsport |= rspinmask; +#endif + *csport &= ~cspinmask; + + //Serial.print("D "); + spiwrite(c); + + *csport |= cspinmask; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.endTransaction(); +#endif +} + + +// Rather than a bazillion writecommand() and writedata() calls, screen +// initialization commands and arguments are organized in these tables +// stored in PROGMEM. The table may look bulky, but that's mostly the +// formatting -- storage-wise this is hundreds of bytes more compact +// than the equivalent code. Companion function follows. +#define DELAY 0x80 +PROGMEM const static unsigned char + Bcmd[] = { // Initialization commands for 7735B screens + 18, // 18 commands in list: + ST7735_SWRESET, DELAY, // 1: Software reset, no args, w/delay + 50, // 50 ms delay + ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, no args, w/delay + 255, // 255 = 500 ms delay + ST7735_COLMOD , 1+DELAY, // 3: Set color mode, 1 arg + delay: + 0x05, // 16-bit color + 10, // 10 ms delay + ST7735_FRMCTR1, 3+DELAY, // 4: Frame rate control, 3 args + delay: + 0x00, // fastest refresh + 0x06, // 6 lines front porch + 0x03, // 3 lines back porch + 10, // 10 ms delay + ST7735_MADCTL , 1 , // 5: Memory access ctrl (directions), 1 arg: + 0x08, // Row addr/col addr, bottom to top refresh + ST7735_DISSET5, 2 , // 6: Display settings #5, 2 args, no delay: + 0x15, // 1 clk cycle nonoverlap, 2 cycle gate + // rise, 3 cycle osc equalize + 0x02, // Fix on VTL + ST7735_INVCTR , 1 , // 7: Display inversion control, 1 arg: + 0x0, // Line inversion + ST7735_PWCTR1 , 2+DELAY, // 8: Power control, 2 args + delay: + 0x02, // GVDD = 4.7V + 0x70, // 1.0uA + 10, // 10 ms delay + ST7735_PWCTR2 , 1 , // 9: Power control, 1 arg, no delay: + 0x05, // VGH = 14.7V, VGL = -7.35V + ST7735_PWCTR3 , 2 , // 10: Power control, 2 args, no delay: + 0x01, // Opamp current small + 0x02, // Boost frequency + ST7735_VMCTR1 , 2+DELAY, // 11: Power control, 2 args + delay: + 0x3C, // VCOMH = 4V + 0x38, // VCOML = -1.1V + 10, // 10 ms delay + ST7735_PWCTR6 , 2 , // 12: Power control, 2 args, no delay: + 0x11, 0x15, + ST7735_GMCTRP1,16 , // 13: Magical unicorn dust, 16 args, no delay: + 0x09, 0x16, 0x09, 0x20, // (seriously though, not sure what + 0x21, 0x1B, 0x13, 0x19, // these config values represent) + 0x17, 0x15, 0x1E, 0x2B, + 0x04, 0x05, 0x02, 0x0E, + ST7735_GMCTRN1,16+DELAY, // 14: Sparkles and rainbows, 16 args + delay: + 0x0B, 0x14, 0x08, 0x1E, // (ditto) + 0x22, 0x1D, 0x18, 0x1E, + 0x1B, 0x1A, 0x24, 0x2B, + 0x06, 0x06, 0x02, 0x0F, + 10, // 10 ms delay + ST7735_CASET , 4 , // 15: Column addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 2 + 0x00, 0x81, // XEND = 129 + ST7735_RASET , 4 , // 16: Row addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 1 + 0x00, 0x81, // XEND = 160 + ST7735_NORON , DELAY, // 17: Normal display on, no args, w/delay + 10, // 10 ms delay + ST7735_DISPON , DELAY, // 18: Main screen turn on, no args, w/delay + 255 }, // 255 = 500 ms delay + + Rcmd1[] = { // Init for 7735R, part 1 (red or green tab) + 15, // 15 commands in list: + ST7735_SWRESET, DELAY, // 1: Software reset, 0 args, w/delay + 150, // 150 ms delay + ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, 0 args, w/delay + 255, // 500 ms delay + ST7735_FRMCTR1, 3 , // 3: Frame rate ctrl - normal mode, 3 args: + 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) + ST7735_FRMCTR2, 3 , // 4: Frame rate control - idle mode, 3 args: + 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) + ST7735_FRMCTR3, 6 , // 5: Frame rate ctrl - partial mode, 6 args: + 0x01, 0x2C, 0x2D, // Dot inversion mode + 0x01, 0x2C, 0x2D, // Line inversion mode + ST7735_INVCTR , 1 , // 6: Display inversion ctrl, 1 arg, no delay: + 0x07, // No inversion + ST7735_PWCTR1 , 3 , // 7: Power control, 3 args, no delay: + 0xA2, + 0x02, // -4.6V + 0x84, // AUTO mode + ST7735_PWCTR2 , 1 , // 8: Power control, 1 arg, no delay: + 0xC5, // VGH25 = 2.4C VGSEL = -10 VGH = 3 * AVDD + ST7735_PWCTR3 , 2 , // 9: Power control, 2 args, no delay: + 0x0A, // Opamp current small + 0x00, // Boost frequency + ST7735_PWCTR4 , 2 , // 10: Power control, 2 args, no delay: + 0x8A, // BCLK/2, Opamp current small & Medium low + 0x2A, + ST7735_PWCTR5 , 2 , // 11: Power control, 2 args, no delay: + 0x8A, 0xEE, + ST7735_VMCTR1 , 1 , // 12: Power control, 1 arg, no delay: + 0x0E, + ST7735_INVOFF , 0 , // 13: Don't invert display, no args, no delay + ST7735_MADCTL , 1 , // 14: Memory access control (directions), 1 arg: + 0xC8, // row addr/col addr, bottom to top refresh + ST7735_COLMOD , 1 , // 15: set color mode, 1 arg, no delay: + 0x05 }, // 16-bit color + + Rcmd2green[] = { // Init for 7735R, part 2 (green tab only) + 2, // 2 commands in list: + ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: + 0x00, 0x02, // XSTART = 0 + 0x00, 0x7F+0x02, // XEND = 127 + ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: + 0x00, 0x01, // XSTART = 0 + 0x00, 0x9F+0x01 }, // XEND = 159 + Rcmd2red[] = { // Init for 7735R, part 2 (red tab only) + 2, // 2 commands in list: + ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: + 0x00, 0x00, // XSTART = 0 + 0x00, 0x7F, // XEND = 127 + ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: + 0x00, 0x00, // XSTART = 0 + 0x00, 0x9F }, // XEND = 159 + + Rcmd3[] = { // Init for 7735R, part 3 (red or green tab) + 4, // 4 commands in list: + ST7735_GMCTRP1, 16 , // 1: Magical unicorn dust, 16 args, no delay: + 0x02, 0x1c, 0x07, 0x12, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, + ST7735_GMCTRN1, 16 , // 2: Sparkles and rainbows, 16 args, no delay: + 0x03, 0x1d, 0x07, 0x06, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, + ST7735_NORON , DELAY, // 3: Normal display on, no args, w/delay + 10, // 10 ms delay + ST7735_DISPON , DELAY, // 4: Main screen turn on, no args w/delay + 100 }, // 100 ms delay + Gcmd[] = { // Initialization commands for 7735B screens + 19, // 18 commands in list: + ST7735_SWRESET, DELAY, // 1: Software reset, no args, w/delay + 50, // 50 ms delay + ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, no args, w/delay + 100, // 255 = 500 ms delay + 0x26 , 1, // 3: Set default gamma + 0x04, // 16-bit color + 0xb1, 2, // 4: Frame Rate + 0x0b, + 0x14, + 0xc0, 2, // 5: VRH1[4:0] & VC[2:0] + 0x08, + 0x00, + 0xc1, 1, // 6: BT[2:0] + 0x05, + 0xc5, 2, // 7: VMH[6:0] & VML[6:0] + 0x41, + 0x30, + 0xc7, 1, // 8: LCD Driving control + 0xc1, + 0xEC, 1, // 9: Set pumping color freq + 0x1b, + 0x3a , 1 + DELAY, // 10: Set color format + 0x55, // 16-bit color + 100, + 0x2a, 4, // 11: Set Column Address + 0x00, + 0x00, + 0x00, + 0x7f, + 0x2b, 4, // 12: Set Page Address + 0x00, + 0x00, + 0x00, + 0x9f, + 0x36, 1, // 12+1: Set Scanning Direction + 0xc8, + 0xb7, 1, // 14: Set Source Output Direciton + 0x00, + 0xf2, 1, // 15: Enable Gamma bit + 0x00, + 0xe0, 15 + DELAY, // 16: magic + 0x28, 0x24, 0x22, 0x31, + 0x2b, 0x0e, 0x53, 0xa5, + 0x42, 0x16, 0x18, 0x12, + 0x1a, 0x14, 0x03, + 50, + 0xe1, 15 + DELAY, // 17: more magic + 0x17, 0x1b, 0x1d, 0x0e, + 0x14, 0x11, 0x2c, 0xa5, + 0x3d, 0x09, 0x27, 0x2d, + 0x25, 0x2b, 0x3c, + 50, + ST7735_NORON , DELAY, // 17: Normal display on, no args, w/delay + 10, // 10 ms delay + ST7735_DISPON , DELAY, // 18: Main screen turn on, no args, w/delay + 255 }; // 255 = 500 ms delay + + + +// Companion code to the above tables. Reads and issues +// a series of LCD commands stored in PROGMEM byte array. +void Adafruit_ST7735::commandList(const uint8_t *addr) { + + uint8_t numCommands, numArgs; + uint16_t ms; + + numCommands = pgm_read_byte(addr++); // Number of commands to follow + while(numCommands--) { // For each command... + writecommand(pgm_read_byte(addr++)); // Read, issue command + numArgs = pgm_read_byte(addr++); // Number of args to follow + ms = numArgs & DELAY; // If hibit set, delay follows args + numArgs &= ~DELAY; // Mask out delay bit + while(numArgs--) { // For each argument... + writedata(pgm_read_byte(addr++)); // Read, issue argument + } + + if(ms) { + ms = pgm_read_byte(addr++); // Read post-command delay time (ms) + if(ms == 255) ms = 500; // If 255, delay for 500 ms + delay(ms); + } + } +} + + +// Initialization code common to both 'B' and 'R' type displays +void Adafruit_ST7735::commonInit(const uint8_t *cmdList) { + + colstart = rowstart = 0; // May be overridden in init func + + pinMode(_rs, OUTPUT); + pinMode(_cs, OUTPUT); + csport = portOutputRegister(digitalPinToPort(_cs)); + cspinmask = digitalPinToBitMask(_cs); + rsport = portOutputRegister(digitalPinToPort(_rs)); + rspinmask = digitalPinToBitMask(_rs); + + if(hwSPI) { // Using hardware SPI + SPI.begin(); +#ifdef SPI_HAS_TRANSACTION + spisettings = SPISettings(4000000L, MSBFIRST, SPI_MODE0); +#else +#if defined(ARDUINO_ARCH_SAM) + SPI.setClockDivider(24); // 4 MHz (half speed) +#else + SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHz (half speed) +#endif + SPI.setBitOrder(MSBFIRST); + SPI.setDataMode(SPI_MODE0); +#endif // SPI_HAS_TRANSACTION + } else { + pinMode(_sclk, OUTPUT); + pinMode(_sid , OUTPUT); + clkport = portOutputRegister(digitalPinToPort(_sclk)); + clkpinmask = digitalPinToBitMask(_sclk); + dataport = portOutputRegister(digitalPinToPort(_sid)); + datapinmask = digitalPinToBitMask(_sid); + *clkport &= ~clkpinmask; + *dataport &= ~datapinmask; + } + + // toggle RST low to reset; CS low so it'll listen to us + *csport &= ~cspinmask; + if (_rst) { + pinMode(_rst, OUTPUT); + digitalWrite(_rst, HIGH); + delay(500); + digitalWrite(_rst, LOW); + delay(500); + digitalWrite(_rst, HIGH); + delay(500); + } + + if(cmdList) commandList(cmdList); +} + + +// Initialization for ST7735B screens +void Adafruit_ST7735::initB(void) { + commonInit(Bcmd); +} + + +// Initialization for ST7735B screens +void Adafruit_ST7735::initG(void) { + commonInit(Gcmd); +} + + +// Initialization for ST7735R screens (green or red tabs) +void Adafruit_ST7735::initR(uint8_t options) { + commonInit(Rcmd1); + if(options == INITR_GREENTAB) { + commandList(Rcmd2green); + colstart = 2; + rowstart = 1; + } else { + // colstart, rowstart left at default '0' values + commandList(Rcmd2red); + } + commandList(Rcmd3); + tabcolor = options; +} + + +void Adafruit_ST7735::setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, + uint8_t y1) { + + writecommand(ST7735_CASET); // Column addr set + writedata(0x00); + writedata(x0+colstart); // XSTART + writedata(0x00); + writedata(x1+colstart); // XEND + + writecommand(ST7735_RASET); // Row addr set + writedata(0x00); + writedata(y0+rowstart); // YSTART + writedata(0x00); + writedata(y1+rowstart); // YEND + + writecommand(ST7735_RAMWR); // write to RAM +} + + +void Adafruit_ST7735::pushColor(uint16_t color) { +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.beginTransaction(spisettings); +#endif + +#ifdef __ARDUINO_ARC__ + digitalWrite(_rs, HIGH); +#else + *rsport |= rspinmask; +#endif + *csport &= ~cspinmask; + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + spiwrite(color >> 8); + spiwrite(color); + + *csport |= cspinmask; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.endTransaction(); +#endif +} + +void Adafruit_ST7735::drawPixel(int16_t x, int16_t y, uint16_t color) { + + if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; + + setAddrWindow(x,y,x+1,y+1); + +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.beginTransaction(spisettings); +#endif + +#ifdef __ARDUINO_ARC__ + digitalWrite(_rs, HIGH); +#else + *rsport |= rspinmask; +#endif + *csport &= ~cspinmask; + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + spiwrite(color >> 8); + spiwrite(color); + + *csport |= cspinmask; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.endTransaction(); +#endif +} + + +void Adafruit_ST7735::drawFastVLine(int16_t x, int16_t y, int16_t h, + uint16_t color) { + + // Rudimentary clipping + if((x >= _width) || (y >= _height)) return; + if((y+h-1) >= _height) h = _height-y; + setAddrWindow(x, y, x, y+h-1); + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + uint8_t hi = color >> 8, lo = color; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.beginTransaction(spisettings); +#endif + +#ifdef __ARDUINO_ARC__ + digitalWrite(_rs, HIGH); +#else + *rsport |= rspinmask; +#endif + *csport &= ~cspinmask; + while (h--) { + spiwrite(hi); + spiwrite(lo); + } + *csport |= cspinmask; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.endTransaction(); +#endif +} + + +void Adafruit_ST7735::drawFastHLine(int16_t x, int16_t y, int16_t w, + uint16_t color) { + + // Rudimentary clipping + if((x >= _width) || (y >= _height)) return; + if((x+w-1) >= _width) w = _width-x; + setAddrWindow(x, y, x+w-1, y); + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + uint8_t hi = color >> 8, lo = color; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.beginTransaction(spisettings); +#endif + +#ifdef __ARDUINO_ARC__ + digitalWrite(_rs, HIGH); +#else + *rsport |= rspinmask; +#endif + *csport &= ~cspinmask; + while (w--) { + spiwrite(hi); + spiwrite(lo); + } + *csport |= cspinmask; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.endTransaction(); +#endif +} + + + +void Adafruit_ST7735::fillScreen(uint16_t color) { + fillRect(0, 0, _width, _height, color); +} + + + +// fill a rectangle +void Adafruit_ST7735::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color) { + + // rudimentary clipping (drawChar w/big text requires this) + if((x >= _width) || (y >= _height)) return; + if((x + w - 1) >= _width) w = _width - x; + if((y + h - 1) >= _height) h = _height - y; + + if (tabcolor == INITR_BLACKTAB) color = swapcolor(color); + + setAddrWindow(x, y, x+w-1, y+h-1); + + uint8_t hi = color >> 8, lo = color; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.beginTransaction(spisettings); +#endif + +#ifdef __ARDUINO_ARC__ + digitalWrite(_rs, HIGH); +#else + *rsport |= rspinmask; +#endif + *csport &= ~cspinmask; + for(y=h; y>0; y--) { + for(x=w; x>0; x--) { + spiwrite(hi); + spiwrite(lo); + } + } + + *csport |= cspinmask; +#ifdef SPI_HAS_TRANSACTION + if (hwSPI) SPI.endTransaction(); +#endif +} + + +#define MADCTL_MY 0x80 +#define MADCTL_MX 0x40 +#define MADCTL_MV 0x20 +#define MADCTL_ML 0x10 +#define MADCTL_RGB 0x08 +#define MADCTL_MH 0x04 + +void Adafruit_ST7735::setRotation(uint8_t m) { + + writecommand(ST7735_MADCTL); + rotation = m % 4; // can't be higher than 3 + switch (rotation) { + case 0: + writedata(MADCTL_MX | MADCTL_MY | MADCTL_RGB); + _width = ST7735_TFTWIDTH; + _height = ST7735_TFTHEIGHT; + break; + case 1: + writedata(MADCTL_MY | MADCTL_MV | MADCTL_RGB); + _width = ST7735_TFTHEIGHT; + _height = ST7735_TFTWIDTH; + break; + case 2: + writedata(MADCTL_RGB); + _width = ST7735_TFTWIDTH; + _height = ST7735_TFTHEIGHT; + break; + case 3: + writedata(MADCTL_MX | MADCTL_MV | MADCTL_RGB); + _width = ST7735_TFTHEIGHT; + _height = ST7735_TFTWIDTH; + break; + } +} + + +void Adafruit_ST7735::invertDisplay(boolean i) { + writecommand(i ? ST7735_INVON : ST7735_INVOFF); +} + + +////////// stuff not actively being used, but kept for posterity +/* + + uint8_t Adafruit_ST7735::spiread(void) { + uint8_t r = 0; + if (_sid > 0) { + r = shiftIn(_sid, _sclk, MSBFIRST); + } else { + //SID_DDR &= ~_BV(SID); + //int8_t i; + //for (i=7; i>=0; i--) { + // SCLK_PORT &= ~_BV(SCLK); + // r <<= 1; + // r |= (SID_PIN >> SID) & 0x1; + // SCLK_PORT |= _BV(SCLK); + //} + //SID_DDR |= _BV(SID); + + } + return r; + } + + + void Adafruit_ST7735::dummyclock(void) { + + if (_sid > 0) { + digitalWrite(_sclk, LOW); + digitalWrite(_sclk, HIGH); + } else { + // SCLK_PORT &= ~_BV(SCLK); + //SCLK_PORT |= _BV(SCLK); + } + } + uint8_t Adafruit_ST7735::readdata(void) { + *portOutputRegister(rsport) |= rspin; + + *portOutputRegister(csport) &= ~ cspin; + + uint8_t r = spiread(); + + *portOutputRegister(csport) |= cspin; + + return r; + + } + + uint8_t Adafruit_ST7735::readcommand8(uint8_t c) { + digitalWrite(_rs, LOW); + + *portOutputRegister(csport) &= ~ cspin; + + spiwrite(c); + + digitalWrite(_rs, HIGH); + pinMode(_sid, INPUT); // input! + digitalWrite(_sid, LOW); // low + spiread(); + uint8_t r = spiread(); + + + *portOutputRegister(csport) |= cspin; + + + pinMode(_sid, OUTPUT); // back to output + return r; + } + + + uint16_t Adafruit_ST7735::readcommand16(uint8_t c) { + digitalWrite(_rs, LOW); + if (_cs) + digitalWrite(_cs, LOW); + + spiwrite(c); + pinMode(_sid, INPUT); // input! + uint16_t r = spiread(); + r <<= 8; + r |= spiread(); + if (_cs) + digitalWrite(_cs, HIGH); + + pinMode(_sid, OUTPUT); // back to output + return r; + } + + uint32_t Adafruit_ST7735::readcommand32(uint8_t c) { + digitalWrite(_rs, LOW); + if (_cs) + digitalWrite(_cs, LOW); + spiwrite(c); + pinMode(_sid, INPUT); // input! + + dummyclock(); + dummyclock(); + + uint32_t r = spiread(); + r <<= 8; + r |= spiread(); + r <<= 8; + r |= spiread(); + r <<= 8; + r |= spiread(); + if (_cs) + digitalWrite(_cs, HIGH); + + pinMode(_sid, OUTPUT); // back to output + return r; + } + + */ diff --git a/libraries/TFT/src/utility/Adafruit_ST7735.h b/libraries/TFT/src/utility/Adafruit_ST7735.h new file mode 100644 index 0000000..fbbd6ab --- /dev/null +++ b/libraries/TFT/src/utility/Adafruit_ST7735.h @@ -0,0 +1,156 @@ +/*************************************************** + This is a library for the Adafruit 1.8" SPI display. + This library works with the Adafruit 1.8" TFT Breakout w/SD card + ----> http://www.adafruit.com/products/358 + as well as Adafruit raw 1.8" TFT display + ----> http://www.adafruit.com/products/618 + + Check out the links above for our tutorials and wiring diagrams + These displays use SPI to communicate, 4 or 5 pins are required to + interface (RST is optional) + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + MIT license, all text above must be included in any redistribution + ****************************************************/ + +#ifndef _ADAFRUIT_ST7735H_ +#define _ADAFRUIT_ST7735H_ + +#if ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif +#include "Adafruit_GFX.h" +#include +#include + +// some flags for initR() :( +#define INITR_GREENTAB 0x0 +#define INITR_REDTAB 0x1 +#define INITR_BLACKTAB 0x2 + +#define ST7735_TFTWIDTH 128 +#define ST7735_TFTHEIGHT 160 + +#define ST7735_NOP 0x00 +#define ST7735_SWRESET 0x01 +#define ST7735_RDDID 0x04 +#define ST7735_RDDST 0x09 + +#define ST7735_SLPIN 0x10 +#define ST7735_SLPOUT 0x11 +#define ST7735_PTLON 0x12 +#define ST7735_NORON 0x13 + +#define ST7735_INVOFF 0x20 +#define ST7735_INVON 0x21 +#define ST7735_DISPOFF 0x28 +#define ST7735_DISPON 0x29 +#define ST7735_CASET 0x2A +#define ST7735_RASET 0x2B +#define ST7735_RAMWR 0x2C +#define ST7735_RAMRD 0x2E + +#define ST7735_PTLAR 0x30 +#define ST7735_COLMOD 0x3A +#define ST7735_MADCTL 0x36 + +#define ST7735_FRMCTR1 0xB1 +#define ST7735_FRMCTR2 0xB2 +#define ST7735_FRMCTR3 0xB3 +#define ST7735_INVCTR 0xB4 +#define ST7735_DISSET5 0xB6 + +#define ST7735_PWCTR1 0xC0 +#define ST7735_PWCTR2 0xC1 +#define ST7735_PWCTR3 0xC2 +#define ST7735_PWCTR4 0xC3 +#define ST7735_PWCTR5 0xC4 +#define ST7735_VMCTR1 0xC5 + +#define ST7735_RDID1 0xDA +#define ST7735_RDID2 0xDB +#define ST7735_RDID3 0xDC +#define ST7735_RDID4 0xDD + +#define ST7735_PWCTR6 0xFC + +#define ST7735_GMCTRP1 0xE0 +#define ST7735_GMCTRN1 0xE1 + +// Color definitions +#define ST7735_BLACK 0x0000 +#define ST7735_BLUE 0x001F +#define ST7735_RED 0xF800 +#define ST7735_GREEN 0x07E0 +#define ST7735_CYAN 0x07FF +#define ST7735_MAGENTA 0xF81F +#define ST7735_YELLOW 0xFFE0 +#define ST7735_WHITE 0xFFFF + + +class Adafruit_ST7735 : public Adafruit_GFX { + + public: + + Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t SID, uint8_t SCLK, + uint8_t RST); + Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t RST); + + void initB(void), // for ST7735B displays + initG(void), // for ILI9163C displays + initR(uint8_t options = INITR_GREENTAB), // for ST7735R + setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1), + pushColor(uint16_t color), + fillScreen(uint16_t color), + drawPixel(int16_t x, int16_t y, uint16_t color), + drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), + drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), + fillRect(int16_t x, int16_t y, int16_t w, int16_t h, + uint16_t color), + setRotation(uint8_t r), + invertDisplay(boolean i); + uint16_t Color565(uint8_t r, uint8_t g, uint8_t b) { return newColor(r, g, b);} + + /* These are not for current use, 8-bit protocol only! + uint8_t readdata(void), + readcommand8(uint8_t); + uint16_t readcommand16(uint8_t); + uint32_t readcommand32(uint8_t); + void dummyclock(void); + */ + + private: + uint8_t tabcolor; + + void spiwrite(uint8_t), + writecommand(uint8_t c), + writedata(uint8_t d), + commandList(const uint8_t *addr), + commonInit(const uint8_t *cmdList); +//uint8_t spiread(void); + + boolean hwSPI; +#ifdef SPI_HAS_TRANSACTION + SPISettings spisettings; +#endif +#if defined(ARDUINO_ARCH_SAM) || defined(__ARDUINO_ARC__) || \ + defined(ARDUINO_ARCH_STM32) + volatile uint32_t *dataport, *clkport, *csport, *rsport; + uint32_t _cs, _rs, _rst, _sid, _sclk, + datapinmask, clkpinmask, cspinmask, rspinmask, + colstart, rowstart; // some displays need this changed + #else + volatile uint8_t *dataport, *clkport, *csport, *rsport; + uint8_t _cs, _rs, _rst, _sid, _sclk, + datapinmask, clkpinmask, cspinmask, rspinmask, + colstart, rowstart; // some displays need this changed + #endif +}; + +#endif diff --git a/libraries/TFT/src/utility/PImage.h b/libraries/TFT/src/utility/PImage.h new file mode 100644 index 0000000..ed99db0 --- /dev/null +++ b/libraries/TFT/src/utility/PImage.h @@ -0,0 +1,65 @@ + + +#ifndef _PIMAGE_H +#define _PIMAGE_H + +class Adafruit_GFX; + +#if defined(__SD_H__) // Arduino SD library + + +/// This class mimics Processing's PImage, but with fewer +/// capabilities. It allows an image stored in the SD card to be +/// drawn to the display. +/// @author Enrico Gueli +class PImage { +public: + PImage() : + _valid(false), + _bmpWidth(0), + _bmpHeight(0) { } + + void draw(Adafruit_GFX & glcd, int16_t x, int16_t y); + + static PImage loadImage(const char * fileName); + + void close() { _bmpFile.close(); } + + bool isValid() { return _valid; } + + int width() { return _bmpWidth; } + int height() { return _bmpHeight; } + +private: + friend class Adafruit_GFX; + + File _bmpFile; + int _bmpWidth, _bmpHeight; // W+H in pixels + uint8_t _bmpDepth; // Bit depth (currently must be 24) + uint32_t _bmpImageoffset; // Start of image data in file + uint32_t _rowSize; // Not always = bmpWidth; may have padding + bool _flip; + + bool _valid; + + PImage(File & bmpFile, int bmpWidth, int bmpHeight, uint8_t bmpDepth, uint32_t bmpImageoffset, uint32_t rowSize, bool flip) : + _bmpFile(bmpFile), + _bmpWidth(bmpWidth), + _bmpHeight(bmpHeight), + _bmpDepth(bmpDepth), + _bmpImageoffset(bmpImageoffset), + _rowSize(rowSize), + _flip(flip), + _valid(true) // since Adafruit_GFX is friend, we could just let it write the variables and save some CPU cycles + { } + + static uint16_t read16(File f); + static uint32_t read32(File f); + + // TODO close the file in ~PImage and PImage(const PImage&) + +}; + +#endif + +#endif // _PIMAGE_H diff --git a/libraries/TFT/src/utility/glcdfont.c b/libraries/TFT/src/utility/glcdfont.c new file mode 100644 index 0000000..0bf812e --- /dev/null +++ b/libraries/TFT/src/utility/glcdfont.c @@ -0,0 +1,269 @@ +#if !defined(ARDUINO_ARCH_SAM) && !defined(__ARDUINO_ARC__) && \ + !defined(ARDUINO_ARCH_STM32) +#include +#endif +#include + +#ifndef FONT5X7_H +#define FONT5X7_H + +// standard ascii 5x7 font + +static const unsigned char font[] PROGMEM = { + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, + 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, + 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, + 0x18, 0x3C, 0x7E, 0x3C, 0x18, + 0x1C, 0x57, 0x7D, 0x57, 0x1C, + 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, + 0x00, 0x18, 0x3C, 0x18, 0x00, + 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, + 0x00, 0x18, 0x24, 0x18, 0x00, + 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, + 0x30, 0x48, 0x3A, 0x06, 0x0E, + 0x26, 0x29, 0x79, 0x29, 0x26, + 0x40, 0x7F, 0x05, 0x05, 0x07, + 0x40, 0x7F, 0x05, 0x25, 0x3F, + 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, + 0x7F, 0x3E, 0x1C, 0x1C, 0x08, + 0x08, 0x1C, 0x1C, 0x3E, 0x7F, + 0x14, 0x22, 0x7F, 0x22, 0x14, + 0x5F, 0x5F, 0x00, 0x5F, 0x5F, + 0x06, 0x09, 0x7F, 0x01, 0x7F, + 0x00, 0x66, 0x89, 0x95, 0x6A, + 0x60, 0x60, 0x60, 0x60, 0x60, + 0x94, 0xA2, 0xFF, 0xA2, 0x94, + 0x08, 0x04, 0x7E, 0x04, 0x08, + 0x10, 0x20, 0x7E, 0x20, 0x10, + 0x08, 0x08, 0x2A, 0x1C, 0x08, + 0x08, 0x1C, 0x2A, 0x08, 0x08, + 0x1E, 0x10, 0x10, 0x10, 0x10, + 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, + 0x30, 0x38, 0x3E, 0x38, 0x30, + 0x06, 0x0E, 0x3E, 0x0E, 0x06, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x5F, 0x00, 0x00, + 0x00, 0x07, 0x00, 0x07, 0x00, + 0x14, 0x7F, 0x14, 0x7F, 0x14, + 0x24, 0x2A, 0x7F, 0x2A, 0x12, + 0x23, 0x13, 0x08, 0x64, 0x62, + 0x36, 0x49, 0x56, 0x20, 0x50, + 0x00, 0x08, 0x07, 0x03, 0x00, + 0x00, 0x1C, 0x22, 0x41, 0x00, + 0x00, 0x41, 0x22, 0x1C, 0x00, + 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, + 0x08, 0x08, 0x3E, 0x08, 0x08, + 0x00, 0x80, 0x70, 0x30, 0x00, + 0x08, 0x08, 0x08, 0x08, 0x08, + 0x00, 0x00, 0x60, 0x60, 0x00, + 0x20, 0x10, 0x08, 0x04, 0x02, + 0x3E, 0x51, 0x49, 0x45, 0x3E, + 0x00, 0x42, 0x7F, 0x40, 0x00, + 0x72, 0x49, 0x49, 0x49, 0x46, + 0x21, 0x41, 0x49, 0x4D, 0x33, + 0x18, 0x14, 0x12, 0x7F, 0x10, + 0x27, 0x45, 0x45, 0x45, 0x39, + 0x3C, 0x4A, 0x49, 0x49, 0x31, + 0x41, 0x21, 0x11, 0x09, 0x07, + 0x36, 0x49, 0x49, 0x49, 0x36, + 0x46, 0x49, 0x49, 0x29, 0x1E, + 0x00, 0x00, 0x14, 0x00, 0x00, + 0x00, 0x40, 0x34, 0x00, 0x00, + 0x00, 0x08, 0x14, 0x22, 0x41, + 0x14, 0x14, 0x14, 0x14, 0x14, + 0x00, 0x41, 0x22, 0x14, 0x08, + 0x02, 0x01, 0x59, 0x09, 0x06, + 0x3E, 0x41, 0x5D, 0x59, 0x4E, + 0x7C, 0x12, 0x11, 0x12, 0x7C, + 0x7F, 0x49, 0x49, 0x49, 0x36, + 0x3E, 0x41, 0x41, 0x41, 0x22, + 0x7F, 0x41, 0x41, 0x41, 0x3E, + 0x7F, 0x49, 0x49, 0x49, 0x41, + 0x7F, 0x09, 0x09, 0x09, 0x01, + 0x3E, 0x41, 0x41, 0x51, 0x73, + 0x7F, 0x08, 0x08, 0x08, 0x7F, + 0x00, 0x41, 0x7F, 0x41, 0x00, + 0x20, 0x40, 0x41, 0x3F, 0x01, + 0x7F, 0x08, 0x14, 0x22, 0x41, + 0x7F, 0x40, 0x40, 0x40, 0x40, + 0x7F, 0x02, 0x1C, 0x02, 0x7F, + 0x7F, 0x04, 0x08, 0x10, 0x7F, + 0x3E, 0x41, 0x41, 0x41, 0x3E, + 0x7F, 0x09, 0x09, 0x09, 0x06, + 0x3E, 0x41, 0x51, 0x21, 0x5E, + 0x7F, 0x09, 0x19, 0x29, 0x46, + 0x26, 0x49, 0x49, 0x49, 0x32, + 0x03, 0x01, 0x7F, 0x01, 0x03, + 0x3F, 0x40, 0x40, 0x40, 0x3F, + 0x1F, 0x20, 0x40, 0x20, 0x1F, + 0x3F, 0x40, 0x38, 0x40, 0x3F, + 0x63, 0x14, 0x08, 0x14, 0x63, + 0x03, 0x04, 0x78, 0x04, 0x03, + 0x61, 0x59, 0x49, 0x4D, 0x43, + 0x00, 0x7F, 0x41, 0x41, 0x41, + 0x02, 0x04, 0x08, 0x10, 0x20, + 0x00, 0x41, 0x41, 0x41, 0x7F, + 0x04, 0x02, 0x01, 0x02, 0x04, + 0x40, 0x40, 0x40, 0x40, 0x40, + 0x00, 0x03, 0x07, 0x08, 0x00, + 0x20, 0x54, 0x54, 0x78, 0x40, + 0x7F, 0x28, 0x44, 0x44, 0x38, + 0x38, 0x44, 0x44, 0x44, 0x28, + 0x38, 0x44, 0x44, 0x28, 0x7F, + 0x38, 0x54, 0x54, 0x54, 0x18, + 0x00, 0x08, 0x7E, 0x09, 0x02, + 0x18, 0xA4, 0xA4, 0x9C, 0x78, + 0x7F, 0x08, 0x04, 0x04, 0x78, + 0x00, 0x44, 0x7D, 0x40, 0x00, + 0x20, 0x40, 0x40, 0x3D, 0x00, + 0x7F, 0x10, 0x28, 0x44, 0x00, + 0x00, 0x41, 0x7F, 0x40, 0x00, + 0x7C, 0x04, 0x78, 0x04, 0x78, + 0x7C, 0x08, 0x04, 0x04, 0x78, + 0x38, 0x44, 0x44, 0x44, 0x38, + 0xFC, 0x18, 0x24, 0x24, 0x18, + 0x18, 0x24, 0x24, 0x18, 0xFC, + 0x7C, 0x08, 0x04, 0x04, 0x08, + 0x48, 0x54, 0x54, 0x54, 0x24, + 0x04, 0x04, 0x3F, 0x44, 0x24, + 0x3C, 0x40, 0x40, 0x20, 0x7C, + 0x1C, 0x20, 0x40, 0x20, 0x1C, + 0x3C, 0x40, 0x30, 0x40, 0x3C, + 0x44, 0x28, 0x10, 0x28, 0x44, + 0x4C, 0x90, 0x90, 0x90, 0x7C, + 0x44, 0x64, 0x54, 0x4C, 0x44, + 0x00, 0x08, 0x36, 0x41, 0x00, + 0x00, 0x00, 0x77, 0x00, 0x00, + 0x00, 0x41, 0x36, 0x08, 0x00, + 0x02, 0x01, 0x02, 0x04, 0x02, + 0x3C, 0x26, 0x23, 0x26, 0x3C, + 0x1E, 0xA1, 0xA1, 0x61, 0x12, + 0x3A, 0x40, 0x40, 0x20, 0x7A, + 0x38, 0x54, 0x54, 0x55, 0x59, + 0x21, 0x55, 0x55, 0x79, 0x41, + 0x21, 0x54, 0x54, 0x78, 0x41, + 0x21, 0x55, 0x54, 0x78, 0x40, + 0x20, 0x54, 0x55, 0x79, 0x40, + 0x0C, 0x1E, 0x52, 0x72, 0x12, + 0x39, 0x55, 0x55, 0x55, 0x59, + 0x39, 0x54, 0x54, 0x54, 0x59, + 0x39, 0x55, 0x54, 0x54, 0x58, + 0x00, 0x00, 0x45, 0x7C, 0x41, + 0x00, 0x02, 0x45, 0x7D, 0x42, + 0x00, 0x01, 0x45, 0x7C, 0x40, + 0xF0, 0x29, 0x24, 0x29, 0xF0, + 0xF0, 0x28, 0x25, 0x28, 0xF0, + 0x7C, 0x54, 0x55, 0x45, 0x00, + 0x20, 0x54, 0x54, 0x7C, 0x54, + 0x7C, 0x0A, 0x09, 0x7F, 0x49, + 0x32, 0x49, 0x49, 0x49, 0x32, + 0x32, 0x48, 0x48, 0x48, 0x32, + 0x32, 0x4A, 0x48, 0x48, 0x30, + 0x3A, 0x41, 0x41, 0x21, 0x7A, + 0x3A, 0x42, 0x40, 0x20, 0x78, + 0x00, 0x9D, 0xA0, 0xA0, 0x7D, + 0x39, 0x44, 0x44, 0x44, 0x39, + 0x3D, 0x40, 0x40, 0x40, 0x3D, + 0x3C, 0x24, 0xFF, 0x24, 0x24, + 0x48, 0x7E, 0x49, 0x43, 0x66, + 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, + 0xFF, 0x09, 0x29, 0xF6, 0x20, + 0xC0, 0x88, 0x7E, 0x09, 0x03, + 0x20, 0x54, 0x54, 0x79, 0x41, + 0x00, 0x00, 0x44, 0x7D, 0x41, + 0x30, 0x48, 0x48, 0x4A, 0x32, + 0x38, 0x40, 0x40, 0x22, 0x7A, + 0x00, 0x7A, 0x0A, 0x0A, 0x72, + 0x7D, 0x0D, 0x19, 0x31, 0x7D, + 0x26, 0x29, 0x29, 0x2F, 0x28, + 0x26, 0x29, 0x29, 0x29, 0x26, + 0x30, 0x48, 0x4D, 0x40, 0x20, + 0x38, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x38, + 0x2F, 0x10, 0xC8, 0xAC, 0xBA, + 0x2F, 0x10, 0x28, 0x34, 0xFA, + 0x00, 0x00, 0x7B, 0x00, 0x00, + 0x08, 0x14, 0x2A, 0x14, 0x22, + 0x22, 0x14, 0x2A, 0x14, 0x08, + 0xAA, 0x00, 0x55, 0x00, 0xAA, + 0xAA, 0x55, 0xAA, 0x55, 0xAA, + 0x00, 0x00, 0x00, 0xFF, 0x00, + 0x10, 0x10, 0x10, 0xFF, 0x00, + 0x14, 0x14, 0x14, 0xFF, 0x00, + 0x10, 0x10, 0xFF, 0x00, 0xFF, + 0x10, 0x10, 0xF0, 0x10, 0xF0, + 0x14, 0x14, 0x14, 0xFC, 0x00, + 0x14, 0x14, 0xF7, 0x00, 0xFF, + 0x00, 0x00, 0xFF, 0x00, 0xFF, + 0x14, 0x14, 0xF4, 0x04, 0xFC, + 0x14, 0x14, 0x17, 0x10, 0x1F, + 0x10, 0x10, 0x1F, 0x10, 0x1F, + 0x14, 0x14, 0x14, 0x1F, 0x00, + 0x10, 0x10, 0x10, 0xF0, 0x00, + 0x00, 0x00, 0x00, 0x1F, 0x10, + 0x10, 0x10, 0x10, 0x1F, 0x10, + 0x10, 0x10, 0x10, 0xF0, 0x10, + 0x00, 0x00, 0x00, 0xFF, 0x10, + 0x10, 0x10, 0x10, 0x10, 0x10, + 0x10, 0x10, 0x10, 0xFF, 0x10, + 0x00, 0x00, 0x00, 0xFF, 0x14, + 0x00, 0x00, 0xFF, 0x00, 0xFF, + 0x00, 0x00, 0x1F, 0x10, 0x17, + 0x00, 0x00, 0xFC, 0x04, 0xF4, + 0x14, 0x14, 0x17, 0x10, 0x17, + 0x14, 0x14, 0xF4, 0x04, 0xF4, + 0x00, 0x00, 0xFF, 0x00, 0xF7, + 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0xF7, 0x00, 0xF7, + 0x14, 0x14, 0x14, 0x17, 0x14, + 0x10, 0x10, 0x1F, 0x10, 0x1F, + 0x14, 0x14, 0x14, 0xF4, 0x14, + 0x10, 0x10, 0xF0, 0x10, 0xF0, + 0x00, 0x00, 0x1F, 0x10, 0x1F, + 0x00, 0x00, 0x00, 0x1F, 0x14, + 0x00, 0x00, 0x00, 0xFC, 0x14, + 0x00, 0x00, 0xF0, 0x10, 0xF0, + 0x10, 0x10, 0xFF, 0x10, 0xFF, + 0x14, 0x14, 0x14, 0xFF, 0x14, + 0x10, 0x10, 0x10, 0x1F, 0x00, + 0x00, 0x00, 0x00, 0xF0, 0x10, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, + 0xFF, 0xFF, 0xFF, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xFF, 0xFF, + 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, + 0x38, 0x44, 0x44, 0x38, 0x44, + 0x7C, 0x2A, 0x2A, 0x3E, 0x14, + 0x7E, 0x02, 0x02, 0x06, 0x06, + 0x02, 0x7E, 0x02, 0x7E, 0x02, + 0x63, 0x55, 0x49, 0x41, 0x63, + 0x38, 0x44, 0x44, 0x3C, 0x04, + 0x40, 0x7E, 0x20, 0x1E, 0x20, + 0x06, 0x02, 0x7E, 0x02, 0x02, + 0x99, 0xA5, 0xE7, 0xA5, 0x99, + 0x1C, 0x2A, 0x49, 0x2A, 0x1C, + 0x4C, 0x72, 0x01, 0x72, 0x4C, + 0x30, 0x4A, 0x4D, 0x4D, 0x30, + 0x30, 0x48, 0x78, 0x48, 0x30, + 0xBC, 0x62, 0x5A, 0x46, 0x3D, + 0x3E, 0x49, 0x49, 0x49, 0x00, + 0x7E, 0x01, 0x01, 0x01, 0x7E, + 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, + 0x44, 0x44, 0x5F, 0x44, 0x44, + 0x40, 0x51, 0x4A, 0x44, 0x40, + 0x40, 0x44, 0x4A, 0x51, 0x40, + 0x00, 0x00, 0xFF, 0x01, 0x03, + 0xE0, 0x80, 0xFF, 0x00, 0x00, + 0x08, 0x08, 0x6B, 0x6B, 0x08, + 0x36, 0x12, 0x36, 0x24, 0x36, + 0x06, 0x0F, 0x09, 0x0F, 0x06, + 0x00, 0x00, 0x18, 0x18, 0x00, + 0x00, 0x00, 0x10, 0x10, 0x00, + 0x30, 0x40, 0xFF, 0x01, 0x01, + 0x00, 0x1F, 0x01, 0x01, 0x1E, + 0x00, 0x19, 0x1D, 0x17, 0x12, + 0x00, 0x3C, 0x3C, 0x3C, 0x3C, + 0x00, 0x00, 0x00, 0x00, 0x00, +}; +#endif diff --git a/libraries/TFT/src/utility/keywords.txt b/libraries/TFT/src/utility/keywords.txt new file mode 100644 index 0000000..9614847 --- /dev/null +++ b/libraries/TFT/src/utility/keywords.txt @@ -0,0 +1,70 @@ +####################################### +# Syntax Coloring Map For Adafruit_GFX +# and Adafruit_ST7735 +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Adafruit_GFX KEYWORD1 +Adafruit_ST7735 KEYWORD1 +PImage KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +drawPixel KEYWORD2 +invertDisplay KEYWORD2 +drawLine KEYWORD2 +drawFastVLine KEYWORD2 +drawFastHLine KEYWORD2 +drawRect KEYWORD2 +fillRect KEYWORD2 +fillScreen KEYWORD2 +drawCircle KEYWORD2 +drawCircleHelper KEYWORD2 +fillCircle KEYWORD2 +fillCircleHelper KEYWORD2 +drawTriangle KEYWORD2 +fillTriangle KEYWORD2 +drawRoundRect KEYWORD2 +fillRoundRect KEYWORD2 +drawBitmap KEYWORD2 +drawChar KEYWORD2 +setCursor KEYWORD2 +setTextColor KEYWORD2 +setTextSize KEYWORD2 +setTextWrap KEYWORD2 +height KEYWORD2 +width KEYWORD2 +setRotation KEYWORD2 +getRotation KEYWORD2 + + + +newColor KEYWORD2 +background KEYWORD2 +fill KEYWORD2 +noFill KEYWORD2 +stroke KEYWORD2 +noStroke KEYWORD2 +text KEYWORD2 +textWrap KEYWORD2 +textSize KEYWORD2 +circle KEYWORD2 +point KEYWORD2 +quad KEYWORD2 +rect KEYWORD2 +triangle KEYWORD2 +loadImage KEYWORD2 +image KEYWORD2 + +draw KEYWORD2 +isValid KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +