├── .gitattributes ├── libraries ├── BasicKeyboard │ ├── keywords.txt │ ├── library.properties │ ├── LICENSE.txt │ ├── README.md │ └── src │ │ ├── BasicKeyboard.h │ │ ├── BasicKeyboard.cpp │ │ └── usb_hid_keys.h ├── AbsMouse5 │ ├── keywords.txt │ ├── library.properties │ ├── LICENSE │ ├── README.md │ └── src │ │ ├── AbsMouse5.cpp │ │ └── AbsMouse5.h ├── DFRobotIRPositionEx │ ├── library.properties │ ├── README.md │ ├── DFRobotIRPositionEx.cpp │ └── DFRobotIRPositionEx.h ├── SamcoPositionEnhanced │ ├── library.properties │ ├── SamcoConst.h │ ├── SamcoPositionEnhanced.h │ ├── SamcoBoard.h │ └── SamcoPositionEnhanced.cpp └── LightgunButtons │ ├── library.properties │ ├── LightgunButtons.h │ ├── LightgunButtons.cpp │ └── COPYING ├── SamcoEnhanced ├── SamcoColours.h ├── SamcoPreferences.h ├── SamcoPreferences.cpp ├── README.md └── SamcoEnhanced.ino └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /libraries/BasicKeyboard/keywords.txt: -------------------------------------------------------------------------------- 1 | # Datatypes 2 | BasicKeyboard KEYWORD1 3 | 4 | # Methods and Functions 5 | press KEYWORD2 6 | release KEYWORD2 7 | releaseAll KEYWORD2 8 | 9 | # Constants 10 | -------------------------------------------------------------------------------- /libraries/AbsMouse5/keywords.txt: -------------------------------------------------------------------------------- 1 | # Datatypes 2 | AbsMouse5 KEYWORD1 3 | 4 | # Methods and Functions 5 | init KEYWORD2 6 | move KEYWORD2 7 | movex KEYWORD2 8 | movey KEYWORD2 9 | press KEYWORD2 10 | release KEYWORD2 11 | releaseAll KEYWORD2 12 | report KEYWORD2 13 | 14 | # Constants 15 | MOUSE_BTN_LEFT LITERAL1 16 | MOUSE_BTN_RIGHT LITERAL1 17 | MOUSE_BTN_MIDDLE LITERAL1 18 | MOUSE_BTN_BACKWARD LITERAL1 19 | MOUSE_BTN_FORWARD LITERAL1 20 | -------------------------------------------------------------------------------- /libraries/DFRobotIRPositionEx/library.properties: -------------------------------------------------------------------------------- 1 | name=DFRobotIRPositionEx 2 | version=1.0.2 3 | author=DFRobot Angelo 4 | maintainer=Prow 5 | sentence=DFRobot IR Positioning Camera extended functionality. 6 | paragraph=A library based on DFRobotIRPosition with extended functionality. See http://wiibrew.org/wiki/Wiimote#IR_Camera 7 | category=Sensors 8 | url=https://github.com/DFRobot/DFRobotIRPosition 9 | architectures=* 10 | -------------------------------------------------------------------------------- /libraries/SamcoPositionEnhanced/library.properties: -------------------------------------------------------------------------------- 1 | name=SamcoPositionEnhanced 2 | version=1.0.0 3 | author=Sam Ballantyne 4 | maintainer=Mike Lynch 5 | sentence=Calculate the centre position from 4 surrounding coordinates. 6 | paragraph=The original use is to convert the 4 positions from the DFRobot IR Positioning camera into a single centre point for use as a light gun (absolute position HID mouse device). 7 | category=Data Processing 8 | url= 9 | architectures=* 10 | -------------------------------------------------------------------------------- /libraries/AbsMouse5/library.properties: -------------------------------------------------------------------------------- 1 | name=absmouse5 2 | version=1.0.0 3 | author=Jonathan Edgecombe/Mike Lynch 4 | maintainer=Mike Lynch 5 | sentence=Absolute positioning USB HID mouse library. 6 | paragraph=This library plugs into the Arduino HID library and supports TinyUSB. Modified from the absmouse library to be 5 buttons. 7 | category=Device Control 8 | url=https://github.com/Prow7 9 | architectures=* 10 | includes=AbsMouse5.h 11 | depends=Adafruit_TinyUSB_Library 12 | -------------------------------------------------------------------------------- /libraries/BasicKeyboard/library.properties: -------------------------------------------------------------------------------- 1 | name=BasicKeyboard 2 | version=0.0.1 3 | author=Mike Lynch 4 | maintainer=Mike Lynch 5 | sentence=Basic USB HID keyboard library. 6 | paragraph=Basic USB HID keyboard library. This implements a basic USB HID keyboard device with the keys defined in the "Keyboard/Keypad Page (0x07)" section in the "HID Usage Tables for USB" document. 7 | category=Device Control 8 | url=https://github.com/Prow7 9 | architectures=* 10 | includes=RawKeyboard.h 11 | depends=Adafruit_TinyUSB_Library 12 | -------------------------------------------------------------------------------- /libraries/LightgunButtons/library.properties: -------------------------------------------------------------------------------- 1 | name=LightgunButtons 2 | version=1.0.0 3 | author=Mike Lynch 4 | maintainer=Mike Lynch 5 | sentence=A simple USB HID button library with advanced debouncing. 6 | paragraph=Originally intended for use with a light gun but can be used for any USB keyboard and/or mouse HID device. The HID reporting can be enable and disabled during run time. No Interrupts are required. Periodically poll the buttons and check the various bit mask button values. 7 | category=Signal Input/Output 8 | url= 9 | architectures=* 10 | depends=AbsMouse5,BasicKeyboard 11 | -------------------------------------------------------------------------------- /libraries/AbsMouse5/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Jonathan Edgecombe 2 | 3 | Permission to use, copy, modify, and distribute this software for any 4 | purpose with or without fee is hereby granted, provided that the above 5 | copyright notice and this permission notice appear in all copies. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 | -------------------------------------------------------------------------------- /libraries/BasicKeyboard/LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2024 Mike Lynch 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /libraries/SamcoPositionEnhanced/SamcoConst.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoConst.h 3 | * @brief Global constants for the Samco light gun. 4 | * 5 | * @copyright Mike Lynch, 2021 6 | * @copyright GNU Lesser General Public License 7 | * 8 | * @author Mike Lynch 9 | * @version V1.0 10 | * @date 2021 11 | */ 12 | 13 | #ifndef _SAMCOCONST_H_ 14 | #define _SAMCOCONST_H_ 15 | 16 | // DFRobot IR positioning camera resolution 17 | constexpr int CamResX = 1024; 18 | constexpr int CamResY = 768; 19 | 20 | // DFRobot IR positioning camera maximum X and Y 21 | constexpr int CamMaxX = CamResX - 1; 22 | constexpr int CamMaxY = CamResY - 1; 23 | 24 | // shift amount for extra precision for the maths 25 | // since the median is an average of 4 values, use 2 more bits 26 | constexpr int CamToMouseShift = 2; 27 | 28 | // multiplier to convert IR camera position to mouse position 29 | constexpr int CamToMouseMult = 1 << CamToMouseShift; 30 | 31 | // mouse resolution 32 | constexpr int MouseResX = CamResX * CamToMouseMult; 33 | constexpr int MouseResY = CamResY * CamToMouseMult; 34 | 35 | // Mouse position maximum X and Y 36 | constexpr int MouseMaxX = MouseResX - 1; 37 | constexpr int MouseMaxY = MouseResY - 1; 38 | 39 | #endif // _SAMCOCONST_H_ 40 | -------------------------------------------------------------------------------- /libraries/AbsMouse5/README.md: -------------------------------------------------------------------------------- 1 | # AbsMouse5 2 | Basic 5 button (no scroll wheel) absolute positioning USB HID mouse. Supports Arduino and TinyUSB stacks. 3 | 4 | Based on the AbsMouse Arduino library. Modified to be a 5 button device and support TinyUSB. 5 | 6 | ## Arduino USB 7 | Include `AbsMouse5.h` and an `AbsMouse5` object will be included in your sketch. The AbsMouse5 uses the Arduino HID() object and adds a mouse using report ID 1, the same as the Arduino Mouse object. Do not use both AbsMouse5 and the Arduino Mouse library in the same sketch. 8 | ```c++ 9 | #include 10 | 11 | void setup() { 12 | AbsMouse5.init(1920, 1080); 13 | } 14 | 15 | void loop() { 16 | // do some stuff 17 | AbsMouse5.move(500, 200); 18 | AbsMouse5.press(MOUSE_BTN_LEFT); 19 | AbsMouse5.release(MOUSE_BTN_LEFT); 20 | // do some other stuff 21 | } 22 | ``` 23 | ## Using TinyUSB 24 | TinyUSB requires creating an instance of the AbsMouse5 object with the report ID for the mouse. The mouse is not automatically included in the USB HID report descriptor. The AbsMouse5 `TUD_HID_REPORT_DESC_ABSMOUSE5_BASIC()` macro must be used for the mouse report descriptor. 25 | 26 | #### TinyUSB Example with Adafruit USB HID 27 | ```c++ 28 | #include 29 | #include 30 | 31 | // mouse report ID 32 | constexpr uint8_t HID_RID_MOUSE = 1; 33 | 34 | // HID report descriptor using AbsMouse5 template 35 | uint8_t const hidReportDesc[] = { 36 | TUD_HID_REPORT_DESC_ABSMOUSE5_BASIC(HID_REPORT_ID(HID_RID_MOUSE)) 37 | }; 38 | 39 | // USB HID instance 40 | Adafruit_USBD_HID usbHid; 41 | 42 | // AbsMouse5 instance 43 | AbsMouse5_ AbsMouse5(HID_RID_MOUSE); 44 | 45 | void setup() { 46 | usbHid.setReportDescriptor(hidReportDesc, sizeof(hidReportDesc)); 47 | usbHid.begin(); 48 | AbsMouse5.init(1920, 1080); 49 | } 50 | 51 | void loop() { 52 | // do some stuff 53 | AbsMouse5.move(500, 200); 54 | AbsMouse5.press(MOUSE_BTN_LEFT); 55 | AbsMouse5.release(MOUSE_BTN_LEFT); 56 | // do some other stuff 57 | } 58 | ``` 59 | -------------------------------------------------------------------------------- /libraries/BasicKeyboard/README.md: -------------------------------------------------------------------------------- 1 | # BasicKeyboard library 2 | 3 | Basic USB HID keyboard library. This implements a basic USB HID keyboard with the keys defined in the "Keyboard/Keypad Page (0x07)" section in the [HID Usage Tables for USB](https://usb.org/document-library/hid-usage-tables-15) document. 4 | 5 | The BasicKeyboard uses the standard 6 key with 8 modifier flags HID keyboard report. 6 | 7 | The defined USB HID key codes and modifier flags must be used. There is no ASCII translation provided like what is found in the Arduino keyboard library. 8 | 9 | The library supports the Arduino and TinyUSB USB stacks. 10 | 11 | The rollover error state is not reported. Up to 6 keys can be pressed simultaneously, not including the modifier keys. The 8 modifier keys (CTRL, SHIFT, etc.) are reported as a separate bitmask byte. 12 | 13 | # Usage 14 | 15 | Copy the BasicKeyboard folder to your "Arduino/libraries" folder. 16 | 17 | #include 18 | 19 | See `BasicKeyboard.h` for details. The key codes and modifier key flags are defined in `usb_hid_keys.h`. 20 | 21 | ## Using Arduino USB 22 | When using the Arduino USB stack, include the `BasicKeyboard.h` and a `BasicKeyboard` object will be included in your sketch. The BasicKeyboard uses the Arduino HID() object and adds a keyboard using report ID 2, the same as the Arduino Keyboard object. Do not use both BasicKeyboard and the Arduino Keyboard library in the same sketch. 23 | 24 | ## Using TinyUSB 25 | TinyUSB requires creating an instance of the BasicKeyboard object with the report ID for the keyboard. The keyboard is not automatically included in the USB HID report descriptor. The TinyUSB `TUD_HID_REPORT_DESC_KEYBOARD()` macro can be used for the keyboard report descriptor. 26 | 27 | #### Example using the Adafruit USB HID 28 | ```cpp 29 | #include 30 | #include 31 | 32 | // keyboard report ID 33 | constexpr uint8_t HID_RID_KEYBOARD = 1; 34 | 35 | // HID report descriptor using TinyUSB's template 36 | uint8_t const hidReportDesc[] = { 37 | TUD_HID_REPORT_DESC_KEYBOARD(HID_REPORT_ID(HID_RID_KEYBOARD)) 38 | }; 39 | 40 | // USB HID instance 41 | Adafruit_USBD_HID usbHid; 42 | 43 | // BasicKeyboard instance 44 | BasicKeyboard_ BasicKeyboard(HID_RID_KEYBOARD); 45 | 46 | void setup() { 47 | usbHid.setReportDescriptor(hidReportDesc, sizeof(hidReportDesc)); 48 | usbHid.begin(); 49 | } 50 | ``` 51 | -------------------------------------------------------------------------------- /libraries/SamcoPositionEnhanced/SamcoPositionEnhanced.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoPositionEnhanced.h 3 | * @brief Samco Light Gun library for 4 LED setup 4 | * @n Header file for Samco Light Gun 4 LED setup 5 | * 6 | * @copyright [Samco](http://www.samco.co.nz), 2021 7 | * @copyright GNU Lesser General Public License 8 | * 9 | * @author [Sam Ballantyne](samuelballantyne@hotmail.com) 10 | * @version V1.0 11 | * @date 2020 12 | */ 13 | 14 | #ifndef _SamcoPositionEnhanced_h_ 15 | #define _SamcoPositionEnhanced_h_ 16 | 17 | #include 18 | #include "SamcoConst.h" 19 | 20 | class SamcoPositionEnhanced { 21 | 22 | int positionXX[4]; ///< position x. 23 | int positionYY[4]; ///< position y. 24 | 25 | int positionX[4]; 26 | int positionY[4]; 27 | 28 | unsigned int see[4]; 29 | 30 | int medianY = MouseMaxY / 2; 31 | int medianX = MouseMaxX / 2; 32 | 33 | int FinalX[4] = {400 * CamToMouseMult, 623 * CamToMouseMult, 400 * CamToMouseMult, 623 * CamToMouseMult}; 34 | int FinalY[4] = {200 * CamToMouseMult, 200 * CamToMouseMult, 568 * CamToMouseMult, 568 * CamToMouseMult}; 35 | 36 | float xDistTop; 37 | float xDistBottom; 38 | float yDistLeft; 39 | float yDistRight; 40 | 41 | float angleTop; 42 | float angleBottom; 43 | float angleLeft; 44 | float angleRight; 45 | 46 | float angle; 47 | float height; 48 | 49 | float angleOffset[4]; 50 | 51 | int xx; 52 | int yy; 53 | 54 | unsigned int start = 0; 55 | 56 | unsigned int seenFlags = 0; 57 | public: 58 | 59 | /// @brief Main function to calculate X, Y, and H 60 | void begin(const int* px, const int* py, unsigned int seen, int cx, int cy); 61 | 62 | int testX(int index) const { return FinalX[index]; } 63 | int testY(int index) const { return FinalY[index]; } 64 | unsigned int testSee(int index) const { return see[index]; } 65 | int testMedianX() const { return medianX; } 66 | int testMedianY() const { return medianY; } 67 | 68 | /// @brief X position 69 | int x() const { return xx; } 70 | 71 | /// @brief Y position 72 | int y() const { return yy; } 73 | 74 | /// @brief Height 75 | float h() const { return height; } 76 | 77 | /// @brief Bit mask of positions the camera saw 78 | unsigned int seen() const { return seenFlags; } 79 | }; 80 | 81 | #endif // _SamcoPositionEnhanced_h_ 82 | -------------------------------------------------------------------------------- /SamcoEnhanced/SamcoColours.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoColours.h 3 | * @brief Collection of unique colours for RGB LEDs such as Dot Stars or Neopixels. 4 | * 5 | * @copyright Mike Lynch, 2021 6 | * @copyright GNU Lesser General Public License 7 | * 8 | * @author Mike Lynch 9 | * @version V1.0 10 | * @date 2021 11 | */ 12 | 13 | #ifndef _SAMCOCOLOURS_H_ 14 | #define _SAMCOCOLOURS_H_ 15 | 16 | #include 17 | 18 | // macro to scale an 8 bit colour value by an 8 bit value 19 | // as seen by the math, 255 means full value 20 | #define COLOR_BRI_ADJ_COLOR(brightness, color) ((((brightness) * ((color) & 0xFF)) / 255) & 0xFF) 21 | //#define COLOR_BRI_ADJ_COLOR(brightness, color) (color) 22 | 23 | // macro to scale a 32-bit RGBW word with an 8 bit brightness value 24 | #define COLOR_BRI_ADJ_RGB(brightness, rgb) COLOR_BRI_ADJ_COLOR(brightness, rgb) \ 25 | | (COLOR_BRI_ADJ_COLOR(brightness, (rgb >> 8)) << 8) \ 26 | | (COLOR_BRI_ADJ_COLOR(brightness, (rgb >> 16)) << 16) \ 27 | | (COLOR_BRI_ADJ_COLOR(brightness, (rgb >> 24)) << 24) 28 | 29 | // some distinct colours from Wikipedia https://en.wikipedia.org/wiki/Lists_of_colors 30 | // also adjusted the brightness to make them look even more distinct on an ItsyBitsy DotStar 31 | // ... yeah I spent too much time on this 32 | namespace WikiColor { 33 | constexpr uint32_t Amber = COLOR_BRI_ADJ_RGB(130, 0xFFBF00); 34 | constexpr uint32_t Blue = COLOR_BRI_ADJ_RGB(225, 0x0000FF); 35 | constexpr uint32_t Carnation_pink = COLOR_BRI_ADJ_RGB(165, 0xFFA6C9); 36 | constexpr uint32_t Cerulean_blue = COLOR_BRI_ADJ_RGB(255, 0x2A52BE); 37 | constexpr uint32_t Cornflower_blue = COLOR_BRI_ADJ_RGB(175, 0x6495ED); 38 | constexpr uint32_t Cyan = COLOR_BRI_ADJ_RGB(145, 0x00FFFF); 39 | constexpr uint32_t Electric_indigo = COLOR_BRI_ADJ_RGB(235, 0x6F00FF); 40 | constexpr uint32_t Ghost_white = COLOR_BRI_ADJ_RGB(135, 0xF8F8FF); 41 | constexpr uint32_t Golden_yellow = COLOR_BRI_ADJ_RGB(135, 0xFFDF00); 42 | constexpr uint32_t Green = COLOR_BRI_ADJ_RGB(140, 0x00FF00); 43 | constexpr uint32_t Green_Lizard = COLOR_BRI_ADJ_RGB(145, 0xA7F432); 44 | constexpr uint32_t Magenta = COLOR_BRI_ADJ_RGB(140, 0xFF00FF); 45 | constexpr uint32_t Orange = COLOR_BRI_ADJ_RGB(150, 0xFF7F00); 46 | constexpr uint32_t Red = COLOR_BRI_ADJ_RGB(145, 0xFF0000); 47 | constexpr uint32_t Salmon = COLOR_BRI_ADJ_RGB(175, 0xFA8072); 48 | constexpr uint32_t Yellow = COLOR_BRI_ADJ_RGB(135, 0xFFFF00); 49 | }; 50 | 51 | #endif // _SAMCOCOLOURS_H_ 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SAMCO Prow Enhanced - Arduino Powered Light Gun 2 | 3 | Based on the 4IR Beta "Big Code Update" SAMCO project from https://github.com/samuelballantyne/IR-Light-Gun 4 | 5 | ## Enhancements 6 | - Increased precision for maths and mouse pointer position 7 | - Glitch-free DFRobot positioning (DFRobotIRPositionEx library) 8 | - IR camera sensitivity adjustment (DFRobotIRPositionEx library) 9 | - Faster IIC clock option for IR camera (DFRobotIRPositionEx library) 10 | - Optional averaging modes can be enabled to slightly reduce mouse position jitter 11 | - Enhanced button debouncing and handling (LightgunButtons library) 12 | - Modified AbsMouse to be a 5 button device (AbsMouse5 library) 13 | - Multiple calibration profiles 14 | - Save settings and calibration profiles to flash memory (SAMD) or EEPROM (ATmega32U4) 15 | - Built in Processing mode for use with the SAMCO Processing sketch 16 | 17 | ## Requirements 18 | - Adafruit ItsyBitsy M0, M4, RP2040 (or any SAMD21, SAMD51, or RP2040 dev board) 19 | - DFRobot IR Positioning Camera (SEN0158) 20 | - 4 IR LED emitters 21 | - Arduino development environment 22 | 23 | With minor modifications it should work with any SAMD21, SAMD51, or RP2040 boards. See the SAMCO project for build details: https://github.com/samuelballantyne/IR-Light-Gun 24 | 25 | The ATmega32U4 is no longer officially supported. 26 | 27 | ## Installation 28 | 1. Ensure you have the Arduino development environment installed with support for your board. 29 | 2. If you use an ItsyBitsy M0 or M4 then install the **Adafruit DotStar** and **Adafruit SPIFlash** libraries in the Library Manager. If you use an ItsyBitsy RP2040 then install **Adafruit NeoPixel** and **Adafruit TinyUSB**. 30 | 3. Copy all the folders under [libraries](libraries/) into your Arduino libraries folder. 31 | 4. Copy the [SamcoEnhanced](SamcoEnhanced/) folder to your Arduino sketch folder. 32 | 5. Open the [SamcoEnhanced](SamcoEnhanced/) sketch. 33 | 34 | ## Compiling and Configuration Options 35 | If you are using an ItsyBitsy M0 or M4 then I recommend you set the Optimize option to -O3 (or faster). If you are using an ItsyBitsy RP2040 then I recommend the -O3 Optimize option. If you are using an ItsyBitsy M4 (or any other SAMD51 board) then set the CPU Speed to 120 MHz standard. If you are using an ItsyBitsy RP2040 then set the CPU Speed to 125 or 133 MHz. There is no need for overclocking. The ItsyBitsy RP2040 must use the Adafruit TinyUSB stack. The SAMD devices can use either Arduino or TinyUSB USB stack. 36 | 37 | > Note: The RP2040 boards tend to default to the `Pico SDK` USB stack so you will see a build error until you switch to TinyUSB. 38 | 39 | ## Sketch Configuration 40 | The sketch is configured for a SAMCO 2.0 (GunCon 2) build. If you are using a SAMCO 2.0 PCB or your build matches the SAMCO 2.0 button assignment then the sketch will work as is. If you use the ItsyBitsy RP2040 with the SAMCO 2.0 PCB or a different set of buttons then the sketch will have to be modified. 41 | 42 | ## Additional information 43 | See the [README](SamcoEnhanced/README.md) file in the sketch folder for details on operation and configuration. Also see the README files in [libraries](libraries/) for more information on library functionality. -------------------------------------------------------------------------------- /SamcoEnhanced/SamcoPreferences.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoPreferences.h 3 | * @brief Samco Prow Enhanced light gun preferences to save in non-volatile memory. 4 | * 5 | * @copyright Mike Lynch, 2021 6 | * @copyright GNU Lesser General Public License 7 | * 8 | * @author Mike Lynch 9 | * @version V1.0 10 | * @date 2021 11 | */ 12 | 13 | #ifndef _SAMCOPREFERENCES_H_ 14 | #define _SAMCOPREFERENCES_H_ 15 | 16 | #include 17 | #include 18 | 19 | #ifdef SAMCO_FLASH_ENABLE 20 | class Adafruit_SPIFlashBase; 21 | #endif // SAMCO_FLASH_ENABLE 22 | 23 | /// @brief Static instance of preferences to save in non-volatile memory 24 | class SamcoPreferences 25 | { 26 | public: 27 | /// @brief Error codes 28 | enum Errors_e { 29 | Error_Success = 0, 30 | Error_NoStorage = -1, 31 | Error_Read = -2, 32 | Error_NoData = -3, 33 | Error_Write = -4, 34 | Error_Erase = -5 35 | }; 36 | 37 | /// @brief Header ID 38 | typedef union HeaderId_u { 39 | uint8_t bytes[4]; 40 | uint32_t u32; 41 | } __attribute__ ((packed)) HeaderId_t; 42 | 43 | /// @brief Profile data 44 | typedef struct ProfileData_s { 45 | uint16_t xScale; ///< X Scale * 1000 46 | uint16_t yScale; ///< Y Scale * 1000 47 | uint32_t xCenter : 12; 48 | uint32_t yCenter : 12; 49 | uint32_t irSensitivity : 3; 50 | uint32_t runMode : 5; 51 | uint32_t reserved; 52 | uint32_t reserved2; 53 | } __attribute__ ((packed)) ProfileData_t; 54 | 55 | /// @brief Preferences that can be stored in flash 56 | typedef struct Preferences_s { 57 | // pointer to ProfileData_t array 58 | SamcoPreferences::ProfileData_t* pProfileData; 59 | 60 | // number of ProfileData_t entries 61 | uint8_t profileCount; 62 | 63 | // default profile 64 | uint8_t profile; 65 | } __attribute__ ((packed)) Preferences_t; 66 | 67 | // single instance of the preference data 68 | static Preferences_t preferences; 69 | 70 | // header ID to ensure junk isn't loaded if preferences aren't saved 71 | static const HeaderId_t HeaderId; 72 | 73 | /// @brief Required size for the preferences 74 | static unsigned int Size() { return sizeof(ProfileData_t) * preferences.profileCount + sizeof(HeaderId_u) + sizeof(preferences.profile); } 75 | 76 | #ifdef SAMCO_FLASH_ENABLE 77 | 78 | /// @brief Load preferences 79 | /// @return An error code from Errors_e 80 | static int Load(Adafruit_SPIFlashBase& flash); 81 | 82 | /// @brief Save preferences 83 | /// @return An error code from Errors_e 84 | static int Save(Adafruit_SPIFlashBase& flash); 85 | 86 | /// @brief Get a string for a given error code 87 | static const char* ErrorCodeToString(int error); 88 | 89 | private: 90 | // error text table 91 | static const char* ErrorText[6]; 92 | 93 | #else 94 | /// @brief Load preferences 95 | /// @return An error code from Errors_e 96 | static int Load(); 97 | 98 | /// @brief Save preferences 99 | /// @return An error code from Errors_e 100 | static int Save(); 101 | #endif 102 | }; 103 | 104 | #endif // _SAMCOPREFERENCES_H_ 105 | -------------------------------------------------------------------------------- /SamcoEnhanced/SamcoPreferences.cpp: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoPreferences.cpp 3 | * @brief Samco Prow Enhanced light gun preferences to save in non-volatile memory. 4 | * 5 | * @copyright Mike Lynch, 2021 6 | * @copyright GNU Lesser General Public License 7 | * 8 | * @author Mike Lynch 9 | * @version V1.0 10 | * @date 2021 11 | */ 12 | 13 | #include "SamcoPreferences.h" 14 | 15 | #ifdef SAMCO_FLASH_ENABLE 16 | #include 17 | #endif // SAMCO_FLASH_ENABLE 18 | #ifdef SAMCO_EEPROM_ENABLE 19 | #include 20 | #endif // SAMCO_EEPROM_ENABLE 21 | 22 | // 4 byte header ID 23 | const SamcoPreferences::HeaderId_t SamcoPreferences::HeaderId = {'P', 'r', 'o', 'w'}; 24 | 25 | #if defined(SAMCO_FLASH_ENABLE) 26 | 27 | // must match Errors_e order 28 | const char* SamcoPreferences::ErrorText[6] = { 29 | "Success", 30 | "No storage memory", 31 | "Read error", 32 | "No preferences saved", 33 | "Write error", 34 | "Erase failed" 35 | }; 36 | 37 | const char* SamcoPreferences::ErrorCodeToString(int error) 38 | { 39 | if(error >= 0) { 40 | // all positive values are success 41 | error = 0; 42 | } else { 43 | error = -error; 44 | } 45 | if(error < sizeof(ErrorText) / sizeof(ErrorText[0])) { 46 | return ErrorText[error]; 47 | } 48 | return ""; 49 | } 50 | 51 | int SamcoPreferences::Load(Adafruit_SPIFlashBase& flash) 52 | { 53 | uint32_t u32; 54 | uint32_t fr = flash.readBuffer(0, (uint8_t*)&u32, sizeof(u32)); 55 | if(fr != 4) { 56 | return Error_Read; 57 | } 58 | 59 | if(u32 != HeaderId.u32) { 60 | return Error_NoData; 61 | } 62 | 63 | fr = flash.readBuffer(4, &preferences.profile, 1); 64 | if(fr != 1) { 65 | return Error_Read; 66 | } 67 | 68 | const uint32_t length = sizeof(ProfileData_t) * preferences.profileCount; 69 | fr = flash.readBuffer(5, (uint8_t*)preferences.pProfileData, length); 70 | 71 | return fr == length ? Error_Success : Error_Read; 72 | } 73 | 74 | int SamcoPreferences::Save(Adafruit_SPIFlashBase& flash) 75 | { 76 | bool success = flash.eraseSector(0); 77 | if(!success) { 78 | return Error_Erase; 79 | } 80 | 81 | uint32_t fw = flash.writeBuffer(0, (uint8_t*)&HeaderId.u32, sizeof(HeaderId.u32)); 82 | if(fw != sizeof(HeaderId.u32)) { 83 | return Error_Write; 84 | } 85 | 86 | fw = flash.writeBuffer(4, &preferences.profile, 1); 87 | if(fw != 1) { 88 | return Error_Write; 89 | } 90 | 91 | const uint32_t length = sizeof(ProfileData_t) * preferences.profileCount; 92 | fw = flash.writeBuffer(5, (uint8_t*)preferences.pProfileData, length); 93 | 94 | return fw == length ? Error_Success : Error_Write; 95 | } 96 | 97 | #elif defined(SAMCO_EEPROM_ENABLE) 98 | 99 | int SamcoPreferences::Load() 100 | { 101 | uint32_t u32; 102 | EEPROM.get(0, u32); 103 | if(u32 != HeaderId.u32) { 104 | return Error_NoData; 105 | } 106 | 107 | preferences.profile = EEPROM.read(4); 108 | uint8_t* p = ((uint8_t*)preferences.pProfileData); 109 | for(unsigned int i = 0; i < sizeof(ProfileData_t) * preferences.profileCount; ++i) { 110 | p[i] = EEPROM.read(5 + i); 111 | } 112 | return Error_Success; 113 | } 114 | 115 | int SamcoPreferences::Save() 116 | { 117 | EEPROM.put(0, HeaderId.u32); 118 | EEPROM.write(4, preferences.profile); 119 | uint8_t* p = ((uint8_t*)preferences.pProfileData); 120 | for(unsigned int i = 0; i < sizeof(ProfileData_t) * preferences.profileCount; ++i) { 121 | EEPROM.write(5 + i, p[i]); 122 | } 123 | return Error_Success; 124 | } 125 | 126 | #else 127 | 128 | int SamcoPreferences::Load() 129 | { 130 | return Error_NoStorage; 131 | } 132 | 133 | int SamcoPreferences::Save() 134 | { 135 | return Error_NoStorage; 136 | } 137 | 138 | #endif 139 | -------------------------------------------------------------------------------- /libraries/AbsMouse5/src/AbsMouse5.cpp: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file AbsMouse5.cpp 3 | * @brief 5 button absolute mouse. 4 | * @n Based on AbsMouse Arduino library. Modified to be a 5 button device. 5 | */ 6 | 7 | #if defined(USE_TINYUSB) 8 | #include 9 | #elif defined(CFG_TUSB_MCU) 10 | #error Incompatible USB stack. Use Arduino or Adafruit TinyUSB. 11 | #else 12 | #include 13 | #endif 14 | 15 | #include "AbsMouse5.h" 16 | 17 | #if defined(_USING_HID) 18 | // The Arduino Mouse library uses a fixed report ID value of 1 19 | static const uint8_t _AbsMouse5HIDReportDescriptor[] PROGMEM = { 20 | 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) 21 | 0x09, 0x02, // Usage (Mouse) 22 | 0xA1, 0x01, // Collection (Application) 23 | 0x09, 0x01, // Usage (Pointer) 24 | 0xA1, 0x00, // Collection (Physical) 25 | 0x85, 0x01, // Report ID (1) 26 | 0x05, 0x09, // Usage Page (Button) 27 | 0x19, 0x01, // Usage Minimum (0x01) 28 | 0x29, 0x05, // Usage Maximum (0x05) 29 | 0x15, 0x00, // Logical Minimum (0) 30 | 0x25, 0x01, // Logical Maximum (1) 31 | 0x95, 0x05, // Report Count (5) 32 | 0x75, 0x01, // Report Size (1) 33 | 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) 34 | 0x95, 0x01, // Report Count (1) (3 bit padding) 35 | 0x75, 0x03, // Report Size (3) 36 | 0x81, 0x03, // Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) 37 | 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) 38 | 0x09, 0x30, // Usage (X) 39 | 0x09, 0x31, // Usage (Y) 40 | 0x16, 0x00, 0x00, // Logical Minimum (0) 41 | 0x26, 0xFF, 0x7F, // Logical Maximum (32767) 42 | 0x36, 0x00, 0x00, // Physical Minimum (0) 43 | 0x46, 0xFF, 0x7F, // Physical Maximum (32767) 44 | 0x75, 0x10, // Report Size (16) 45 | 0x95, 0x02, // Report Count (2) 46 | 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) 47 | 0xC0, // End Collection 48 | 0xC0 // End Collection 49 | }; 50 | 51 | // AbsMouse5 instance 52 | AbsMouse5_ AbsMouse5(1); 53 | #endif // _USING_HID 54 | 55 | AbsMouse5_::AbsMouse5_(uint8_t reportId) : _reportId(reportId), _buttons(0), _x(0), _y(0), _width(32767l), _height(32767l), _autoReport(true) 56 | { 57 | #if defined(_USING_HID) 58 | static HIDSubDescriptor descriptor(_AbsMouse5HIDReportDescriptor, sizeof(_AbsMouse5HIDReportDescriptor)); 59 | HID().AppendDescriptor(&descriptor); 60 | #endif // _USING_HID 61 | } 62 | 63 | void AbsMouse5_::init(uint16_t width, uint16_t height, bool autoReport) 64 | { 65 | _width = width; 66 | _height = height; 67 | _autoReport = autoReport; 68 | } 69 | 70 | void AbsMouse5_::report(void) 71 | { 72 | uint8_t buffer[5]; 73 | buffer[0] = _buttons; 74 | buffer[1] = (uint8_t)_x; 75 | buffer[2] = (uint8_t)(_x >> 8); 76 | buffer[3] = (uint8_t)_y; 77 | buffer[4] = (uint8_t)(_y >> 8); 78 | #if defined(_USING_HID) 79 | // the descriptor above and Arduino Mouse library use a fixed report ID of 1 80 | HID().SendReport(1, buffer, 5); 81 | #endif // _USING_HID 82 | #if defined(USE_TINYUSB) 83 | if (TinyUSBDevice.suspended()) { 84 | TinyUSBDevice.remoteWakeup(); 85 | } 86 | while (!tud_hid_ready()) yield(); 87 | tud_hid_report(_reportId, buffer, 5); 88 | yield(); 89 | #endif // USE_TINYUSB 90 | } 91 | 92 | void AbsMouse5_::move(uint16_t x, uint16_t y) 93 | { 94 | x = (uint16_t)((32767ul * ((uint32_t)x)) / _width); 95 | y = (uint16_t)((32767ul * ((uint32_t)y)) / _height); 96 | 97 | if(x != _x || y != _y) { 98 | _x = x; 99 | _y = y; 100 | autoreport(); 101 | } 102 | } 103 | 104 | void AbsMouse5_::press(uint8_t button) 105 | { 106 | const uint8_t new_buttons = _buttons | button; 107 | if(new_buttons != _buttons) { 108 | _buttons = new_buttons; 109 | autoreport(); 110 | } 111 | } 112 | 113 | void AbsMouse5_::release(uint8_t button) 114 | { 115 | const uint8_t new_buttons = _buttons & ~button; 116 | if(new_buttons != _buttons) { 117 | _buttons = new_buttons; 118 | autoreport(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /libraries/DFRobotIRPositionEx/README.md: -------------------------------------------------------------------------------- 1 | # DFRobotIRPositionEx Arduino library 2 | A modified version of the DFRobotIRPosition library with extended functionality. This is for use with DFRobot's IR Positioning camera (SEN0158). Much of the extended functionality comes from the WiiBrew wiki: http://wiibrew.org/wiki/Wiimote#IR_Camera 3 | 4 | ## New features 5 | - Added Basic data format which has less IIC bytes than Extended format. 6 | - Added unpacking the object size data from the Extended data format. 7 | - added object seen flags to know when positions update and are visible or aren't seen. 8 | - Added functions to atomically read the position data. 9 | - Added sensitivity settings from the WiiBrew wiki. 10 | - Added IIC clock setting. Testing with SAMD confirms it works up to at least 1MHz. 11 | 12 | ## Overview 13 | The DFRobot IR positioning camera has a resolution of 1024x768 and tracks up to 4 infrared objects. According to the WiiBrew wiki it works best with 940nm infrared emitters. 14 | 15 | --- 16 | 17 | # Non-atomic position data discovery 18 | When I first started testing the IR positioning camera I noticed that occasionally an object position would jump (or glitch) by a noticeable amount for a single frame. I didn't think too much of it other than it must be some inherent behaviour glitch that can happen. However, after more testing with camera, I was initially puzzled by two observations. 19 | 20 | The first thing I noticed is sometimes a Y position would be returned with a value greater than 767 but less than 1023. The vertical resolution is 768 so values in that range are unexpected. A Y value of 1023 is expected when no object is seen. Otherwise, the Y value is expected to be less than 768. It was uncommon but not difficult to reproduce Y values of 768 and sometimes values a bit over 800 were returned. What's going on here? 21 | 22 | Secondly, I wrote some test code to determine the rate at which the position data updates. The code was a simple loop to request the data and compare with the previously received data. If there are any differences in the data then assume the position updated. Obviously I was shaking the camera around to ensure movement would be detected with each update. When I began testing this, I noticed that lower IIC clock rates reported higher position update rates. For example, using an IIC clock rate of 1MHz my test code reported ~215 FPS. When I slowed down the IIC clock to 100kbps (Arduino default), the test reported over 300 FPS for the position changing. This was initially counter-intuitive to me. 23 | 24 | Then it finally clicked. The position data is not being reported atomically. In other words, the position data in the IR camera may update while reading the bytes over IIC. This is a problem because the low byte and high byte for a position will not be the position from a single processed frame from the camera. This totally explains everything I was observing. 768 is a value with the low 8 bits clear (7:0) and the high bits (9:8) set to 1, so this can happen when observing an object that goes from Y position 0 to no longer seen (off camera). It also explains why a slower IIC clock rate detects more changes; really all that's happening is you are more likely to catch the non-atomic position data update while reading the bytes from IIC. 25 | 26 | My theory was confirmed by adding "atomic" position read functions to the library to fetch the data multiple times until two consecutive sets of data are identical. Actually a slight optimization is that a maximum of 3 reads should ensure coherent position data. The logic is, if the first 2 sets of position data do not match, then fetch the data a third time and use it. I call the functions "atomic" although it's really just a workaround to ensure coherent position data is used. 27 | 28 | The final result is that using the "atomic" functions reveals the camera updates the position at ~209 times a second. 29 | 30 | # Final Thoughts 31 | I can only speculate that there must be a proper way to read the position data atomically without fetching it multiple times and comparing the data for a match. Maybe there's a data sync pin that is not exposed? Maybe there's a register setting not documented on the WiiBrew wiki for this? It's also odd that there is no formal data sheet that I'm aware of. The best and most complete information I have seen is in the WiiBrew wiki. 32 | -------------------------------------------------------------------------------- /libraries/SamcoPositionEnhanced/SamcoBoard.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoBoard.h 3 | * @brief Build configuration for Arduino boards. 4 | * 5 | * @copyright Mike Lynch, 2021 6 | * @copyright GNU Lesser General Public License 7 | * 8 | * @author Mike Lynch 9 | * @version V1.0 10 | * @date 2021 11 | */ 12 | 13 | #ifndef _SAMCOBOARD_H_ 14 | #define _SAMCOBOARD_H_ 15 | 16 | // sadly even Arduino doesn't have ideal defines... very odd there is a generic __SAMD51__, but not __SAMD21__? 17 | // I'll add that anyway along with the known ItsyBitsy defines that are the supported boards 18 | #if defined(ADAFRUIT_ITSYBITSY_M0) || defined(ARDUINO_ITSYBITSY_M0) || defined(__SAMD21__) || defined(__SAMD21G18A__) 19 | // use SAMD21 peripherals 20 | #define SAMCO_SAMD21 1 21 | 22 | // DFRobot IR camera IIC clock 23 | // even with cheap clips and the full length IR cam cable 1MHz is fine 24 | #define DFROBOT_IR_IIC_CLOCK 1000000 25 | 26 | // timer configuration 27 | #define TIMER_PRESCALER_DIV 16 28 | #define TIMER_TC_CTRLA_PRESCALER_DIV TC_CTRLA_PRESCALER_DIV16 29 | 30 | // software button anti-glitch mask 31 | #define BTN_AG_MASK 0x3FF 32 | #define BTN_AG_MASK2 0xFFF 33 | #elif defined(ADAFRUIT_ITSYBITSY_M4_EXPRESS) || defined(ARDUINO_ITSYBITSY_M4) || defined(__SAMD51__) || defined(__SAMD51G19A__) 34 | // use SAMD51 peripherals 35 | #define SAMCO_SAMD51 1 36 | 37 | // DFRobot IR camera IIC clock 38 | // even with cheap clips and the full length IR cam cable 1MHz is fine 39 | #define DFROBOT_IR_IIC_CLOCK 1000000 40 | 41 | // timer configuration 42 | #define TIMER_PRESCALER_DIV 16 43 | #define TIMER_TC_CTRLA_PRESCALER_DIV TC_CTRLA_PRESCALER_DIV16 44 | 45 | // software button anti-glitch mask 46 | #define BTN_AG_MASK 0xFFFFFFFF 47 | #define BTN_AG_MASK2 0xFFFFFFFF 48 | #elif defined(ARDUINO_AVR_ITSYBITSY32U4_5V) || defined(ARDUINO_AVR_MICRO) || defined(ARDUINO_AVR_PROMICRO) || defined(ARDUINO_AVR_LEONARDO) 49 | // ATmega32u4 50 | #define SAMCO_ATMEGA32U4 1 51 | 52 | // AVR has EEPROM 53 | #define SAMCO_EEPROM_ENABLE 1 54 | 55 | // DFRobot IR camera IIC clock 56 | // The ATmega32u4 datasheet says a maximum of 400kHz 57 | #define DFROBOT_IR_IIC_CLOCK 400000 58 | 59 | // software button anti-glitch mask 60 | #define BTN_AG_MASK 0x3 61 | #define BTN_AG_MASK2 0xF 62 | #elif defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ADAFRUIT_ITSYBITSY_RP2040) 63 | // Raspberry Pi Pico RP2040 64 | #define SAMCO_RP2040 1 65 | 66 | // DFRobot IR camera IIC clock 67 | // even with cheap clips and the full length IR cam cable 1MHz is fine 68 | #define DFROBOT_IR_IIC_CLOCK 1000000 69 | 70 | // Earle Philhower Arduino RP2040 reserves 4KB of flash using the Arduino EEPROM object, neat! 71 | #define SAMCO_EEPROM_ENABLE 1 72 | 73 | // software button anti-glitch 74 | #define BTN_AG_MASK 0xFFFFFFFF 75 | #define BTN_AG_MASK2 0xFFFFFFFF 76 | #else 77 | // unknown board 78 | // this will use millis() for camera update timing instead of a hardware timer 79 | #define SAMCO_NO_HW_TIMER 1 80 | #define DFROBOT_IR_IIC_CLOCK 400000 81 | 82 | // software button anti-glitch mask 83 | #define BTN_AG_MASK1 0xF 84 | #define BTN_AG_MASK2 0xF 85 | #endif // determine SAMCO_xxx board 86 | 87 | // specific ItsyBitsy board configuration 88 | #if defined(ADAFRUIT_ITSYBITSY_M0) || defined(ARDUINO_ITSYBITSY_M0) 89 | // included Dot Star on ItsyBitsy M0 90 | #define DOTSTAR_DATAPIN 41 91 | #define DOTSTAR_CLOCKPIN 40 92 | #define DOTSTAR_ENABLE 1 93 | 94 | // use flash 95 | #define SAMCO_FLASH_ENABLE 1 96 | #endif // ADAFRUIT_ITSYBITSY_M0 97 | #if defined(ADAFRUIT_ITSYBITSY_M4_EXPRESS) || defined(ARDUINO_ITSYBITSY_M4) 98 | // included Dot Star on ItsyBitsy M4 99 | #define DOTSTAR_DATAPIN 8 100 | #define DOTSTAR_CLOCKPIN 6 101 | #define DOTSTAR_ENABLE 1 102 | 103 | // use flash 104 | #define SAMCO_FLASH_ENABLE 1 105 | #endif // ADAFRUIT_ITSYBITSY_M4_EXPRESS 106 | #if defined(ARDUINO_ADAFRUIT_ITSYBITSY_RP2040) 107 | // included Neopixel on ItsyBitsy RP2040 108 | #define NEOPIXEL_PIN 17 109 | #define NEOPIXEL_ENABLEPIN 16 110 | #endif // ARDUINO_ADAFRUIT_ITSYBITSY_RP2040 111 | 112 | // auto-detect flash presence if it is not yet enabled and no EEPROM 113 | #if !defined(SAMCO_FLASH_ENABLE) && !defined(SAMCO_EEPROM_ENABLE) 114 | #if defined(EXTERNAL_FLASH_USE_QSPI) || defined(EXTERNAL_FLASH_USE_SPI) 115 | #define SAMCO_FLASH_ENABLE 1 116 | #endif // EXTERNAL_FLASH_USE 117 | #endif // SAMCO_FLASH_ENABLE 118 | 119 | #endif // _SAMCOBOARD_H_ 120 | -------------------------------------------------------------------------------- /libraries/AbsMouse5/src/AbsMouse5.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file AbsMouse5.h 3 | * @brief Basic 5 button (no scroll wheel) absolute positioning USB HID mouse. Supports Arduino and TinyUSB USB stacks. 4 | * @n Based on the AbsMouse Arduino library. Modified to be a 5 button device. 5 | * @n For TinyUSB, include a TUD_HID_REPORT_DESC_ABSMOUSE5_BASIC(RID) in the descriptor report. 6 | */ 7 | 8 | #ifndef _ABSMOUSE5_H_ 9 | #define _ABSMOUSE5_H_ 10 | 11 | #include 12 | 13 | // Mouse button bit mask defines. 14 | // TinyUSB can also use the MOUSE_BUTTON_ values from hid_mouse_button_bm_t enum in hid.h. 15 | #define MOUSE_BTN_LEFT 0x01 16 | #define MOUSE_BTN_RIGHT 0x02 17 | #define MOUSE_BTN_MIDDLE 0x04 18 | #define MOUSE_BTN_4 0x08 19 | #define MOUSE_BTN_BACKWARD 0x08 20 | #define MOUSE_BTN_5 0x10 21 | #define MOUSE_BTN_FORWARD 0x10 22 | 23 | // TinyUSB report descriptor macro for a basic 5 button absolute mouse (no scroll wheel) 24 | #if defined(USE_TINYUSB) 25 | #include 26 | 27 | #define TUD_HID_REPORT_DESC_ABSMOUSE5_BASIC(...) \ 28 | HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ 29 | HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ 30 | HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ 31 | /* Report ID if any */\ 32 | __VA_ARGS__ \ 33 | HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ 34 | HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ 35 | HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ 36 | HID_USAGE_MIN ( 1 ) ,\ 37 | HID_USAGE_MAX ( 5 ) ,\ 38 | HID_LOGICAL_MIN ( 0 ) ,\ 39 | HID_LOGICAL_MAX ( 1 ) ,\ 40 | /* Left, Right, Middle, Backward, Forward buttons */ \ 41 | HID_REPORT_COUNT( 5 ) ,\ 42 | HID_REPORT_SIZE ( 1 ) ,\ 43 | HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ 44 | /* 3 bit padding */ \ 45 | HID_REPORT_COUNT( 1 ) ,\ 46 | HID_REPORT_SIZE ( 3 ) ,\ 47 | HID_INPUT ( HID_CONSTANT ) ,\ 48 | HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ 49 | /* X, Y absolute position [0, 32767] */ \ 50 | HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ 51 | HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ 52 | HID_LOGICAL_MIN ( 0x00 ) ,\ 53 | HID_LOGICAL_MAX_N ( 0x7FFF, 2 ) ,\ 54 | HID_PHYSICAL_MIN ( 0x00 ) ,\ 55 | HID_PHYSICAL_MAX_N( 0x7FFF, 2 ) ,\ 56 | HID_REPORT_SIZE ( 16 ) ,\ 57 | HID_REPORT_COUNT ( 2 ) ,\ 58 | HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ 59 | HID_COLLECTION_END , \ 60 | HID_COLLECTION_END 61 | #endif // USE_TINYUSB 62 | 63 | // 5 button absolute mouse 64 | class AbsMouse5_ 65 | { 66 | private: 67 | const uint8_t _reportId; 68 | uint8_t _buttons; 69 | uint16_t _x; 70 | uint16_t _y; 71 | uint32_t _width; 72 | uint32_t _height; 73 | bool _autoReport; 74 | 75 | /// @brief Call report() if auto report is enabled. 76 | inline void autoreport() { 77 | if(_autoReport) { 78 | report(); 79 | } 80 | } 81 | 82 | public: 83 | /// @brief Constructor. 84 | /// @param[in] reportId TinyUSB report ID. Ignored when using Arduino HID. 85 | AbsMouse5_(uint8_t reportId); 86 | 87 | /// @brief Initialize the absolute mouse. 88 | /// @param widthMax Maximum width value. 89 | /// @param heightMax Maximum height value. 90 | /// @param autoReport True to call report() any time the mouse state changes. 91 | /// False to require explicit call to report(). 92 | void init(uint16_t widthMax = 32767, uint16_t heightMax = 32767, bool autoReport = true); 93 | 94 | /// @brief Send a USB report. 95 | void report(); 96 | 97 | /// @brief Move the mouse X and Y positions. 98 | /// @param x X position 99 | /// @param y Y position 100 | void move(uint16_t x, uint16_t y); 101 | 102 | /// @brief Move the mouse X position. 103 | void movex(uint16_t x) { move(x, _y); } 104 | 105 | /// @brief Move the mouse Y position. 106 | void movey(uint16_t y) { move(_x, y); } 107 | 108 | /// @brief Press mouse button(s). 109 | /// @param b Button mask. 110 | void press(uint8_t b = MOUSE_BTN_LEFT); 111 | 112 | /// @brief Release mouse button(s). 113 | /// @param b Button mask. 114 | void release(uint8_t b = MOUSE_BTN_LEFT); 115 | 116 | /// @brief Release all mouse buttons. 117 | void releaseAll() { release(0x1f); } 118 | }; 119 | 120 | // global singleton 121 | extern AbsMouse5_ AbsMouse5; 122 | 123 | #endif // _ABSMOUSE5_H_ 124 | -------------------------------------------------------------------------------- /libraries/BasicKeyboard/src/BasicKeyboard.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Basic USB HID keyboard library. This implements a basic USB HID keyboard with the keys 3 | * defined in the "Keyboard/Keypad Page (0x07)" section in the HID Usage Tables for USB document. 4 | * https://usb.org/document-library/hid-usage-tables-15 5 | * 6 | * See usb_hid_keys.h for the key code and modifier flag defines. 7 | * 8 | * When using the Arduino USB stack, a BasicKeyboard object will be included and the keybaord 9 | * added to HID() using report ID 2. This is the same report ID the Arduino Keyboard uses. 10 | * 11 | * When using TinyUSB, include a TUD_HID_REPORT_DESC_KEYBOARD(RID_KEYBOARD) 12 | * in the descriptor report. 13 | * 14 | * In your main sketch declare the keyboard instance with the reort ID: 15 | * BasicKeyboard_ Keyboard(RID_KEYBOARD); 16 | * 17 | * NOTE: This code is derived and stripped down from the standard Arduino 18 | * Keyboard.h and Keyboard.cpp code. The copyright on that original code 19 | * is as follows. 20 | * 21 | * Copyright (c) 2015, Arduino LLC 22 | * Original code (pre-library): Copyright (c) 2011, Peter Barrett 23 | * 24 | * This library is free software; you can redistribute it and/or 25 | * modify it under the terms of the GNU Lesser General Public 26 | * License as published by the Free Software Foundation; either 27 | * version 2.1 of the License, or (at your option) any later version. 28 | * 29 | * This library is distributed in the hope that it will be useful, 30 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 31 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 32 | * Lesser General Public License for more details. 33 | * 34 | * You should have received a copy of the GNU Lesser General Public 35 | * License along with this library; if not, write to the Free Software 36 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 37 | */ 38 | 39 | #ifndef _BASICKEYBOARD_H_ 40 | #define _BASICKEYBOARD_H_ 41 | 42 | #include 43 | #include "usb_hid_keys.h" 44 | 45 | // USB HID key report structure: up to 6 keys and modifiers 46 | typedef struct 47 | { 48 | uint8_t modifiers; 49 | uint8_t reserved; 50 | uint8_t keys[6]; 51 | } KeyReport_t; 52 | 53 | class BasicKeyboard_ 54 | { 55 | private: 56 | const uint8_t _reportId; 57 | KeyReport_t _keyReport; 58 | bool _autoReport; 59 | 60 | /// @brief Call report() if auto report is enabled. 61 | inline void autoreport() { 62 | if(_autoReport) { 63 | report(); 64 | } 65 | } 66 | 67 | /// @brief Update the report data with a key press. 68 | /// @param keyCode Key code. 69 | /// @return True for success. 70 | /// False if the key code is invalid or 6 keys are already pressed. 71 | bool prepareKeyPress(uint8_t keyCode); 72 | 73 | /// @brief Release a key from the report data. 74 | /// @param keyCode Key code. 75 | /// @return True if the key code is valid. 76 | bool prepareKeyRelease(uint8_t keyCode); 77 | 78 | public: 79 | /// @brief Constructor. 80 | /// @param[in] reportId TinyUSB report ID. Ignored when using Arduino HID. 81 | BasicKeyboard_(uint8_t reportId); 82 | 83 | /// @brief Set automatic report when keys are pressed or released. 84 | /// @param autoReport True to call report() any time a key is pressed or released. 85 | /// False to require explicit call to report(). 86 | void setAutoReport(bool autoReport) { _autoReport = autoReport; } 87 | 88 | /// @brief Send a USB report. 89 | void report(); 90 | 91 | /// @brief Press a key. 92 | /// @param keyCode Key code. 93 | /// @return True if the key is pressed. 94 | /// False if the key code is invalid or 6 keys are already pressed. 95 | bool press(uint8_t keyCode); 96 | 97 | /// @brief Press modifers and a key. 98 | /// @details If the key code is invalid then the modifier keys will not change. 99 | /// @param modMask Modifier bitmask of keys to press. This value will be bitwise OR'd 100 | /// to the current modifier mask. Bits set to 1 will press. 101 | /// @param keyCode Key code. 102 | /// @return True if the key is pressed. 103 | /// False if the key code is invalid or 6 keys are already pressed. 104 | bool press(uint8_t modMask, uint8_t keyCode); 105 | 106 | /// @brief Press modifier keys. 107 | /// @param modMask Modifier bitmask of keys to press. This value will be bitwise OR'd 108 | /// to the current modifier mask. Bits set to 1 will press. 109 | void pressModifers(uint8_t modMask); 110 | 111 | /// @brief Release a key. 112 | /// @param keyCode Key code. 113 | /// @return True if the key code is valid. 114 | bool release(uint8_t keyCode); 115 | 116 | /// @brief Release modifers and a key. 117 | /// @details If the key code is invalid then the modifier keys will not change. 118 | /// @param modMask Modifier bitmask of keys to release. Bits set to 1 will release. 119 | /// 0 will keep the existing value. 120 | /// @param keyCode Key code. 121 | /// @return True if the key code is valid. 122 | bool release(uint8_t modMask, uint8_t keyCode); 123 | 124 | /// @brief Release modifier keys. 125 | /// @param modMask Modifier bitmask of keys to release. Bits set to 1 will release. 126 | /// 0 will keep the existing value. 127 | void releaseModifers(uint8_t modMask); 128 | 129 | /// @brief Release all keys. 130 | void releaseAll(); 131 | 132 | /// @brief Check if a key code is valid. 133 | /// @param keyCode Key code. 134 | /// @return True if the key code is valid. 135 | static bool isKeyCodeValid(uint8_t keyCode) { return (keyCode != 0) && (keyCode <= KEY_RIGHTMETA); } 136 | }; 137 | 138 | extern BasicKeyboard_ BasicKeyboard; 139 | 140 | #endif // _BASICKEYBOARD_H_ 141 | -------------------------------------------------------------------------------- /libraries/BasicKeyboard/src/BasicKeyboard.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * NOTE: This code is derived and stripped down from the standard Arduino 3 | * Keyboard.h and Keyboard.cpp code. The copyright on that original code 4 | * is as follows. 5 | * 6 | * Copyright (c) 2015, Arduino LLC 7 | * Original code (pre-library): Copyright (c) 2011, Peter Barrett 8 | * 9 | * This library is free software; you can redistribute it and/or 10 | * modify it under the terms of the GNU Lesser General Public 11 | * License as published by the Free Software Foundation; either 12 | * version 2.1 of the License, or (at your option) any later version. 13 | * 14 | * This library is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | * Lesser General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU Lesser General Public 20 | * License along with this library; if not, write to the Free Software 21 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 22 | */ 23 | 24 | #ifdef USE_TINYUSB 25 | #include 26 | #else 27 | #include 28 | #endif 29 | 30 | #include "BasicKeyboard.h" 31 | 32 | #if defined(_USING_HID) 33 | // HID keyboard report descriptor copied from the Arduino Keyabord library, 34 | // found in Keyboard.cpp. It uses report ID 2. 35 | static const uint8_t _hidRawKbReportDescriptor[] PROGMEM = { 36 | // Keyboard 37 | 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47 38 | 0x09, 0x06, // USAGE (Keyboard) 39 | 0xa1, 0x01, // COLLECTION (Application) 40 | 0x85, 0x02, // REPORT_ID (2) 41 | 0x05, 0x07, // USAGE_PAGE (Keyboard) 42 | 43 | 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) 44 | 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) 45 | 0x15, 0x00, // LOGICAL_MINIMUM (0) 46 | 0x25, 0x01, // LOGICAL_MAXIMUM (1) 47 | 0x75, 0x01, // REPORT_SIZE (1) 48 | 49 | 0x95, 0x08, // REPORT_COUNT (8) 50 | 0x81, 0x02, // INPUT (Data,Var,Abs) 51 | 0x95, 0x01, // REPORT_COUNT (1) 52 | 0x75, 0x08, // REPORT_SIZE (8) 53 | 0x81, 0x03, // INPUT (Cnst,Var,Abs) 54 | 55 | 0x95, 0x06, // REPORT_COUNT (6) 56 | 0x75, 0x08, // REPORT_SIZE (8) 57 | 0x15, 0x00, // LOGICAL_MINIMUM (0) 58 | 0x25, 0x73, // LOGICAL_MAXIMUM (115) 59 | 0x05, 0x07, // USAGE_PAGE (Keyboard) 60 | 61 | 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) 62 | 0x29, 0x73, // USAGE_MAXIMUM (Keyboard Application) 63 | 0x81, 0x00, // INPUT (Data,Ary,Abs) 64 | 0xc0, // END_COLLECTION 65 | }; 66 | 67 | // BasicKeyboard instance 68 | BasicKeyboard_ BasicKeyboard(2); 69 | #endif // _USING_HID 70 | 71 | BasicKeyboard_::BasicKeyboard_(uint8_t reportId) : _reportId(reportId), _autoReport(true) 72 | { 73 | memset(&_keyReport, 0, sizeof(_keyReport)); 74 | #if defined(_USING_HID) 75 | static HIDSubDescriptor descriptor(_hidRawKbReportDescriptor, sizeof(_hidRawKbReportDescriptor)); 76 | HID().AppendDescriptor(&descriptor); 77 | #endif // _USING_HID 78 | } 79 | 80 | void BasicKeyboard_::report() 81 | { 82 | #if defined(_USING_HID) 83 | // the descriptor above, copied from the Arduino Keyboard library, use a fixed report ID value of 2 84 | HID().SendReport(2, &_keyReport, sizeof(_keyReport)); 85 | #endif // _USING_HID 86 | #if defined(USE_TINYUSB) 87 | if (TinyUSBDevice.suspended()) { 88 | TinyUSBDevice.remoteWakeup(); 89 | } 90 | while (!tud_hid_ready()) yield(); 91 | tud_hid_keyboard_report(_reportId, _keyReport.modifiers, _keyReport.keys); 92 | yield(); 93 | #endif // USE_TINYUSB 94 | } 95 | 96 | bool BasicKeyboard_::prepareKeyPress(uint8_t key) 97 | { 98 | if (key > KEY_RIGHTMETA || !key) { 99 | // invalid key code 100 | return false; 101 | } 102 | 103 | if (key >= KEY_LEFTCTRL) { 104 | _keyReport.modifiers |= (1 << (key & 7)); 105 | return true; 106 | } else if (_keyReport.keys[0] != key && _keyReport.keys[1] != key && _keyReport.keys[2] != key && 107 | _keyReport.keys[3] != key && _keyReport.keys[4] != key && _keyReport.keys[5] != key) { 108 | // key is not already pressed, assign it to an available slot 109 | for (unsigned int i = 0; i < sizeof(_keyReport.keys); ++i) { 110 | if (_keyReport.keys[i] == 0) { 111 | _keyReport.keys[i] = key; 112 | return true; 113 | } 114 | } 115 | } 116 | 117 | // no slot available 118 | return false; 119 | } 120 | 121 | bool BasicKeyboard_::press(uint8_t key) 122 | { 123 | bool success = prepareKeyPress(key); 124 | if (success) { 125 | autoreport(); 126 | } 127 | return success; 128 | } 129 | 130 | bool BasicKeyboard_::press(uint8_t modMask, uint8_t key) 131 | { 132 | bool success = prepareKeyPress(key); 133 | if (success) { 134 | _keyReport.modifiers |= modMask; 135 | autoreport(); 136 | } 137 | return success; 138 | } 139 | 140 | void BasicKeyboard_::pressModifers(uint8_t modMask) 141 | { 142 | _keyReport.modifiers |= modMask; 143 | autoreport(); 144 | } 145 | 146 | bool BasicKeyboard_::prepareKeyRelease(uint8_t key) 147 | { 148 | if (key > KEY_RIGHTMETA || !key) { 149 | // invalid key code 150 | return false; 151 | } 152 | 153 | if (key >= KEY_LEFTCTRL) { 154 | _keyReport.modifiers &= ~(1 << (key & 7)); 155 | } else { 156 | // check all positions in case the key is present more than once... 157 | // how could that happen? gallop2WhoKnows 158 | for (unsigned int i = 0; i < sizeof(_keyReport.keys); ++i) { 159 | if (_keyReport.keys[i] == key) { 160 | _keyReport.keys[i] = 0; 161 | } 162 | } 163 | } 164 | 165 | return true; 166 | } 167 | 168 | bool BasicKeyboard_::release(uint8_t key) 169 | { 170 | bool success = prepareKeyRelease(key); 171 | if (success) { 172 | autoreport(); 173 | } 174 | return success; 175 | } 176 | 177 | bool BasicKeyboard_::release(uint8_t modMask, uint8_t key) 178 | { 179 | bool success = prepareKeyRelease(key); 180 | if (success) { 181 | _keyReport.modifiers &= ~modMask; 182 | autoreport(); 183 | } 184 | return success; 185 | } 186 | 187 | void BasicKeyboard_::releaseModifers(uint8_t modMask) 188 | { 189 | _keyReport.modifiers &= ~modMask; 190 | autoreport(); 191 | } 192 | 193 | void BasicKeyboard_::releaseAll() 194 | { 195 | memset(&_keyReport, 0, sizeof(_keyReport)); 196 | autoreport(); 197 | } 198 | -------------------------------------------------------------------------------- /libraries/LightgunButtons/LightgunButtons.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file LightgunButtons.h 3 | * @brief HID buttons originally intended for use with a light gun. 4 | * 5 | * @copyright Mike Lynch, 2021 6 | * 7 | * LightgunButtons is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #ifndef _LIGHTGUNBUTTONS_H_ 22 | #define _LIGHTGUNBUTTONS_H_ 23 | 24 | #include 25 | 26 | /// @brief Relatively simple buttons with some decent per-button confirgurable debouncing. 27 | /// @details While intended for a Light gun, can be used for any HID using AbsMouse5 and/or Keyboard. 28 | /// Basic usage is to periodically call Poll() and then check the various bit mask values. 29 | /// This assumes a logical high value for released (0 for pressed). 30 | /// The only limitation is 32 buttons since a uint32_t is used for the button bitmask. 31 | /// If your light gun needs more than 32 buttons then I wanna see pics. 32 | class LightgunButtons { 33 | public: 34 | /// @brief Report type. 35 | enum ReportType_e { 36 | ReportType_Mouse = 0, 37 | ReportType_Keyboard = 1, 38 | ReportType_Internal = 2 39 | // ReportType_Gamepad 40 | }; 41 | 42 | /// @brief Descriptor. 43 | typedef struct Desc_s { 44 | const int pin; ///< Arduino defiuned pin to read. 45 | const uint8_t reportType; ///< Report type. See ReportType_e. 46 | const uint8_t reportCode; ///< Report code. Mouse or key press depending on report type. 47 | const uint8_t debounceTicks; ///< Number of millis() to wait after the button state changes. 48 | const uint32_t debounceFifoMask; ///< Mask checked to ensure button state is consistent (0 to disable) 49 | const char* label; ///< informational label 50 | } Desc_t; 51 | 52 | /// @brief Runtime debouncing state data. 53 | /// The arrays must be the same length as the ButtonDesc[] descriptor array. 54 | typedef struct Data_s { 55 | uint32_t* pArrFifo; ///< Pointer to button fifo array. 56 | uint8_t* pArrDebounceCount; ///< Pointer to button debounce counters. 57 | } Data_t; 58 | 59 | /// @brief Constructor. 60 | LightgunButtons(Data_t data, unsigned int count); 61 | 62 | /// @brief Initialize the buttons. 63 | void Begin(); 64 | 65 | /// @brief Poll button state. 66 | /// @details This will reset pressed, released, and pressedReleased. 67 | /// @param[in] minTicks Minimum number of ticks for poll to update. 68 | /// @return The pressed value. 69 | uint32_t Poll(unsigned long minTicks = 0); 70 | 71 | /// @brief Update the internal repeat value. 72 | /// @details Call after Poll() if the repeat value is required. 73 | /// @return The repeat value. 74 | uint32_t Repeat(); 75 | 76 | /// @brief The buttons that must be defined in the sketch. 77 | static const Desc_t ButtonDesc[]; 78 | 79 | /// @brief Bit mask of newly pressed buttons from last poll, 1 if pressed. 80 | /// @details Resets on each Poll(). 81 | uint32_t pressed; 82 | 83 | /// @brief Bit mask of newly released buttons from last poll, 1 if released. 84 | /// @details Resets on each Poll(). 85 | uint32_t released; 86 | 87 | /// @brief Debounced buttons that internally repeat (pulse) at the specified interval. 88 | /// @details This is for internal use, not related to reporting HID events to the host. 89 | /// This only updates when calling Repeat(). 90 | uint32_t repeat; 91 | 92 | /// @brief Bit mask of debounced buttons, 1 if pressed. 93 | uint32_t debounced; 94 | 95 | /// @brief Bit mask of buttons currently debouncing. 96 | /// @details Buttons can be debouncing after being pressed or released. 97 | uint32_t debouncing; 98 | 99 | /// @brief Bit mask of debounced buttons pressed and released since last poll. 100 | /// @details Track all pressed buttons and set only when all buttons release. 101 | /// Resets on each Poll(). 102 | uint32_t pressedReleased; 103 | 104 | /// @brief Interval for pulsing the repeat value while buttons are pressed for Repeat(). 105 | unsigned int interval; 106 | 107 | /// @brief Bit mask of buttons to enable reporting HID events to host. 108 | uint32_t report; 109 | 110 | /// @brief Enable reporting for all buttons. Set report to 0xFFFFFFFF. 111 | void ReportEnable() { report = 0xFFFFFFFF; } 112 | 113 | /// @brief Disable reporting for all buttons. Clear report to 0. 114 | void ReportDisable() { report = 0; } 115 | 116 | /// @brief Test if pressed button(s) in comibination with already held buttons match given values. 117 | /// @details Test the pressed buttons equals a given value along with a modifer bit mask 118 | /// match with the debounced value. 119 | /// @param[in] pressedMask Bit mask newly pressed buttons to match with pressed. 120 | /// @param[in] modifierMask Bit mask of buttons already held down to match with debounced. 121 | /// @return true if pressedMask equals pressed and the modifierMask is debounced. 122 | bool ModifierPressed(uint32_t pressedMask, uint32_t modifierMask) { 123 | // note that since pressedMask is expected to pressed, it will also be debounced 124 | return ((pressedMask == pressed) && ((modifierMask | pressedMask) == debounced)) ? true : false; 125 | } 126 | 127 | /// @brief Get the button index from a mask or -1 if a single button is not matched 128 | static int MaskToIndex(uint32_t mask); 129 | 130 | private: 131 | /// @brief millis() value from last Poll 132 | unsigned long lastMillis; 133 | 134 | /// @brief millis() value from last Repeat() 135 | unsigned long lastRepeatMillis; 136 | 137 | /// @brief button pin states 138 | uint32_t pinState; 139 | 140 | /// @brief Internal tracked buttons for the final pressedReleased value. 141 | uint32_t internalPressedReleased; 142 | 143 | /// @brief Bit mask of reported pressed buttons. 144 | uint32_t reportedPressed; 145 | 146 | /// @brief Button state FIFO array. 147 | uint32_t* stateFifo; 148 | 149 | /// @brief Button debounce count array. 150 | uint8_t* debounceCount; 151 | 152 | /// @brief Number of buttons. 153 | const unsigned int count; 154 | }; 155 | 156 | /// @brief Helper to allocate button data arrays. 157 | template 158 | class LightgunButtonsStatic { 159 | private: 160 | uint32_t stateFifoArr[count]; 161 | uint8_t debounceCountArr[count]; 162 | 163 | public: 164 | operator LightgunButtons::Data_t() { 165 | LightgunButtons::Data_t d = {stateFifoArr, debounceCountArr}; 166 | return d; 167 | } 168 | }; 169 | 170 | #endif // _LIGHTGUNBUTTONS_H_ 171 | -------------------------------------------------------------------------------- /libraries/LightgunButtons/LightgunButtons.cpp: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file LightgunButtons.cpp 3 | * @brief HID buttons originally intended for use with a light gun. 4 | * 5 | * @copyright Mike Lynch, 2021 6 | * 7 | * LightgunButtons is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include "LightgunButtons.h" 25 | 26 | LightgunButtons::LightgunButtons(Data_t _data, unsigned int _count) : 27 | pressed(0), 28 | released(0), 29 | repeat(0), 30 | debounced(0), 31 | debouncing(0), 32 | pressedReleased(0), 33 | interval(33), 34 | report(0), 35 | lastMillis(0), 36 | lastRepeatMillis(0), 37 | pinState(0xFFFFFFFF), 38 | internalPressedReleased(0), 39 | reportedPressed(0), 40 | count(_count), 41 | stateFifo(_data.pArrFifo), 42 | debounceCount(_data.pArrDebounceCount) 43 | { 44 | } 45 | 46 | void LightgunButtons::Begin() 47 | { 48 | // set button pins to input with pullup 49 | for(unsigned int i = 0; i < count; ++i) { 50 | pinMode(ButtonDesc[i].pin, INPUT_PULLUP); 51 | stateFifo[i] = 0xFFFFFFFF; 52 | debounceCount[i] = 0; 53 | } 54 | } 55 | 56 | uint32_t LightgunButtons::Poll(unsigned long minTicks) 57 | { 58 | unsigned long m = millis(); 59 | unsigned long ticks = m - lastMillis; 60 | uint32_t bitMask; 61 | 62 | // reset pressed and released from last poll 63 | pressed = 0; 64 | released = 0; 65 | pressedReleased = 0; 66 | 67 | if(ticks < minTicks) { 68 | return 0; 69 | } 70 | lastMillis = m; 71 | 72 | if(debouncing && ticks) { 73 | bitMask = 1; 74 | for(unsigned int i = 0; i < count; ++i, bitMask <<= 1) { 75 | const Desc_t& btn = ButtonDesc[i]; 76 | if(debounceCount[i]) { 77 | if(ticks < debounceCount[i]) { 78 | debounceCount[i] -= ticks; 79 | } else { 80 | debounceCount[i] = 0; 81 | debouncing &= ~bitMask; 82 | } 83 | } 84 | } 85 | } 86 | 87 | bitMask = 1; 88 | for(unsigned int i = 0; i < count; ++i, bitMask <<= 1) { 89 | const Desc_t& btn = ButtonDesc[i]; 90 | 91 | // if not debouncing 92 | if(!debounceCount[i]) { 93 | // read the pin, expected to return 0 or 1 94 | uint32_t state = digitalRead(btn.pin); 95 | 96 | // if a state fifo mask is defined 97 | if(btn.debounceFifoMask) { 98 | // add the state to the fifo 99 | stateFifo[i] <<= 1; 100 | stateFifo[i] |= state; 101 | 102 | // apply the mask and check the value 103 | uint32_t m = stateFifo[i] & btn.debounceFifoMask; 104 | if(!m) { 105 | state = 0; 106 | } else if(m == btn.debounceFifoMask) { 107 | // use the bit mask for this button 108 | state = bitMask; 109 | } else { 110 | // button is bouncing, continue to next button 111 | continue; 112 | } 113 | } else { 114 | // no fifo, so change high state into bit mask 115 | if(state) { 116 | state = bitMask; 117 | } 118 | } 119 | 120 | // if existing pin state does not match new state 121 | if((pinState & bitMask) != state) { 122 | // update the pin state 123 | pinState = (pinState & ~bitMask) | state; 124 | 125 | // set the debounce counter and set the flag 126 | debounceCount[i] = btn.debounceTicks; 127 | debouncing |= bitMask; 128 | 129 | if(!state) { 130 | // state is low, button is pressed 131 | 132 | // if reporting is enabled for the button 133 | if(report & bitMask) { 134 | reportedPressed |= bitMask; 135 | if(btn.reportType == ReportType_Mouse) { 136 | AbsMouse5.press(btn.reportCode); 137 | } else if(btn.reportType == ReportType_Keyboard) { 138 | BasicKeyboard.press(btn.reportCode); 139 | } 140 | } 141 | 142 | // button is debounced pressed and add it to the pressed/released combo 143 | debounced |= bitMask; 144 | pressed |= bitMask; 145 | internalPressedReleased |= bitMask; 146 | #ifdef DEBUG_SERIAL 147 | Serial.print("+"); 148 | Serial.println(btn.label); 149 | #endif //DEBUG_SERIAL 150 | } else { 151 | // state high, button is not pressed 152 | 153 | // if the button press was reported then report the release 154 | // note that the report flag is ignored here to avoid stuck buttons 155 | // in case the reporting is disabled while button(s) are pressed 156 | if(reportedPressed & bitMask) { 157 | reportedPressed &= ~bitMask; 158 | if(btn.reportType == ReportType_Mouse) { 159 | AbsMouse5.release(btn.reportCode); 160 | } else if(btn.reportType == ReportType_Keyboard) { 161 | BasicKeyboard.release(btn.reportCode); 162 | } 163 | } 164 | 165 | // clear the debounced state and button is released 166 | debounced &= ~bitMask; 167 | released |= bitMask; 168 | 169 | // if all buttons released 170 | if(!debounced) { 171 | // report the combination pressed/released state 172 | pressedReleased = internalPressedReleased; 173 | internalPressedReleased = 0; 174 | } 175 | 176 | #ifdef DEBUG_SERIAL 177 | Serial.print("-"); 178 | Serial.println(btn.label); 179 | #endif //DEBUG_SERIAL 180 | } 181 | } 182 | } 183 | } 184 | 185 | return pressed; 186 | } 187 | 188 | uint32_t LightgunButtons::Repeat() 189 | { 190 | unsigned long m = millis(); 191 | if(m - lastRepeatMillis >= interval) { 192 | lastRepeatMillis = m; 193 | repeat = debounced; 194 | } else { 195 | repeat = 0; 196 | } 197 | return repeat; 198 | } 199 | 200 | int LightgunButtons::MaskToIndex(uint32_t mask) 201 | { 202 | uint32_t bitMask = 1; 203 | for(unsigned int i = 0; bitMask; ++i, bitMask <<= 1) { 204 | if(bitMask == mask) { 205 | return i; 206 | } 207 | } 208 | return -1; 209 | } 210 | -------------------------------------------------------------------------------- /libraries/BasicKeyboard/src/usb_hid_keys.h: -------------------------------------------------------------------------------- 1 | /** 2 | * USB HID keyboard key codes as per USB usage table doc version 1.5. 3 | * See the "HID Usage Tables for USB" document 4 | * section 10, Keyboard/Keypad Page (0x07). 5 | * 6 | * This is slightly modified from the original: 7 | * Some defines were removed. Only page 0x7 key codes are included. 8 | * Added an underscore to the keypad defines so they are prefixed with KEY_KP_. 9 | * 10 | * Original created by MightyPork, 2016 11 | * https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2 12 | * Public domain 13 | * 14 | * Adapted from: 15 | * https://source.android.com/devices/input/keyboard-devices.html 16 | * 17 | * USB HID Usage Tables 1.5: 18 | * https://usb.org/document-library/hid-usage-tables-15 19 | */ 20 | 21 | #ifndef _USB_HID_KEYS_H_ 22 | #define _USB_HID_KEYS_H_ 23 | 24 | /** 25 | * Modifier masks - used for the first byte in the HID report. 26 | * The corresponding modifier key codes are at the bottom of the key code list, 27 | * near the end of this file. 28 | */ 29 | #define KEY_MOD_LEFTCTRL 0x01 30 | #define KEY_MOD_LEFTSHIFT 0x02 31 | #define KEY_MOD_LEFTALT 0x04 32 | #define KEY_MOD_LEFTMETA 0x08 33 | #define KEY_MOD_RIGHTCTRL 0x10 34 | #define KEY_MOD_RIGHTSHIFT 0x20 35 | #define KEY_MOD_RIGHTALT 0x40 36 | #define KEY_MOD_RIGHTMETA 0x80 37 | 38 | /** 39 | * Key codes - last N slots in the HID report (usually 6). 40 | * 0x00 if no key pressed. 41 | * 42 | * If more than N keys are pressed, the HID reports 43 | * KEY_ERR_ROLLOVER in all slots to indicate this condition. 44 | */ 45 | 46 | #define KEY_NONE 0x00 // No key pressed 47 | #define KEY_ERR_ROLLOVER 0x01 // Keyboard Error Roll Over - used for all slots if too many keys are pressed ("Phantom key") 48 | #define KEY_POSTFAIL 0x02 // Keyboard POST Fail 49 | #define KEY_ERR_UNDEF 0x03 // Keyboard Error Undefined 50 | #define KEY_A 0x04 // Keyboard a and A 51 | #define KEY_B 0x05 // Keyboard b and B 52 | #define KEY_C 0x06 // Keyboard c and C 53 | #define KEY_D 0x07 // Keyboard d and D 54 | #define KEY_E 0x08 // Keyboard e and E 55 | #define KEY_F 0x09 // Keyboard f and F 56 | #define KEY_G 0x0a // Keyboard g and G 57 | #define KEY_H 0x0b // Keyboard h and H 58 | #define KEY_I 0x0c // Keyboard i and I 59 | #define KEY_J 0x0d // Keyboard j and J 60 | #define KEY_K 0x0e // Keyboard k and K 61 | #define KEY_L 0x0f // Keyboard l and L 62 | #define KEY_M 0x10 // Keyboard m and M 63 | #define KEY_N 0x11 // Keyboard n and N 64 | #define KEY_O 0x12 // Keyboard o and O 65 | #define KEY_P 0x13 // Keyboard p and P 66 | #define KEY_Q 0x14 // Keyboard q and Q 67 | #define KEY_R 0x15 // Keyboard r and R 68 | #define KEY_S 0x16 // Keyboard s and S 69 | #define KEY_T 0x17 // Keyboard t and T 70 | #define KEY_U 0x18 // Keyboard u and U 71 | #define KEY_V 0x19 // Keyboard v and V 72 | #define KEY_W 0x1a // Keyboard w and W 73 | #define KEY_X 0x1b // Keyboard x and X 74 | #define KEY_Y 0x1c // Keyboard y and Y 75 | #define KEY_Z 0x1d // Keyboard z and Z 76 | 77 | #define KEY_1 0x1e // Keyboard 1 and ! 78 | #define KEY_2 0x1f // Keyboard 2 and @ 79 | #define KEY_3 0x20 // Keyboard 3 and # 80 | #define KEY_4 0x21 // Keyboard 4 and $ 81 | #define KEY_5 0x22 // Keyboard 5 and % 82 | #define KEY_6 0x23 // Keyboard 6 and ^ 83 | #define KEY_7 0x24 // Keyboard 7 and & 84 | #define KEY_8 0x25 // Keyboard 8 and * 85 | #define KEY_9 0x26 // Keyboard 9 and ( 86 | #define KEY_0 0x27 // Keyboard 0 and ) 87 | 88 | #define KEY_ENTER 0x28 // Keyboard Return (ENTER) 89 | #define KEY_ESC 0x29 // Keyboard ESCAPE 90 | #define KEY_BACKSPACE 0x2a // Keyboard DELETE (Backspace) 91 | #define KEY_TAB 0x2b // Keyboard Tab 92 | #define KEY_SPACE 0x2c // Keyboard Spacebar 93 | #define KEY_MINUS 0x2d // Keyboard - and _ 94 | #define KEY_EQUAL 0x2e // Keyboard = and + 95 | #define KEY_LEFTBRACE 0x2f // Keyboard [ and { 96 | #define KEY_RIGHTBRACE 0x30 // Keyboard ] and } 97 | #define KEY_BACKSLASH 0x31 // Keyboard \ and | 98 | #define KEY_HASHTILDE 0x32 // Keyboard Non-US # and ~ 99 | #define KEY_SEMICOLON 0x33 // Keyboard ; and : 100 | #define KEY_APOSTROPHE 0x34 // Keyboard ' and " 101 | #define KEY_GRAVE 0x35 // Keyboard ` and ~ 102 | #define KEY_COMMA 0x36 // Keyboard , and < 103 | #define KEY_DOT 0x37 // Keyboard . and > 104 | #define KEY_SLASH 0x38 // Keyboard / and ? 105 | #define KEY_CAPSLOCK 0x39 // Keyboard Caps Lock 106 | 107 | #define KEY_F1 0x3a // Keyboard F1 108 | #define KEY_F2 0x3b // Keyboard F2 109 | #define KEY_F3 0x3c // Keyboard F3 110 | #define KEY_F4 0x3d // Keyboard F4 111 | #define KEY_F5 0x3e // Keyboard F5 112 | #define KEY_F6 0x3f // Keyboard F6 113 | #define KEY_F7 0x40 // Keyboard F7 114 | #define KEY_F8 0x41 // Keyboard F8 115 | #define KEY_F9 0x42 // Keyboard F9 116 | #define KEY_F10 0x43 // Keyboard F10 117 | #define KEY_F11 0x44 // Keyboard F11 118 | #define KEY_F12 0x45 // Keyboard F12 119 | 120 | #define KEY_PRINTSCREEN 0x46 // Keyboard Print Screen 121 | #define KEY_SCROLLLOCK 0x47 // Keyboard Scroll Lock 122 | #define KEY_PAUSE 0x48 // Keyboard Pause 123 | #define KEY_INSERT 0x49 // Keyboard Insert 124 | #define KEY_HOME 0x4a // Keyboard Home 125 | #define KEY_PAGEUP 0x4b // Keyboard Page Up 126 | #define KEY_DELETE 0x4c // Keyboard Delete Forward 127 | #define KEY_END 0x4d // Keyboard End 128 | #define KEY_PAGEDOWN 0x4e // Keyboard Page Down 129 | #define KEY_RIGHT 0x4f // Keyboard Right Arrow 130 | #define KEY_LEFT 0x50 // Keyboard Left Arrow 131 | #define KEY_DOWN 0x51 // Keyboard Down Arrow 132 | #define KEY_UP 0x52 // Keyboard Up Arrow 133 | 134 | #define KEY_NUMLOCK 0x53 // Keyboard Num Lock and Clear 135 | #define KEY_KP_SLASH 0x54 // Keypad / 136 | #define KEY_KP_ASTERISK 0x55 // Keypad * 137 | #define KEY_KP_MINUS 0x56 // Keypad - 138 | #define KEY_KP_PLUS 0x57 // Keypad + 139 | #define KEY_KP_ENTER 0x58 // Keypad ENTER 140 | #define KEY_KP_1 0x59 // Keypad 1 and End 141 | #define KEY_KP_2 0x5a // Keypad 2 and Down Arrow 142 | #define KEY_KP_3 0x5b // Keypad 3 and PageDn 143 | #define KEY_KP_4 0x5c // Keypad 4 and Left Arrow 144 | #define KEY_KP_5 0x5d // Keypad 5 145 | #define KEY_KP_6 0x5e // Keypad 6 and Right Arrow 146 | #define KEY_KP_7 0x5f // Keypad 7 and Home 147 | #define KEY_KP_8 0x60 // Keypad 8 and Up Arrow 148 | #define KEY_KP_9 0x61 // Keypad 9 and Page Up 149 | #define KEY_KP_0 0x62 // Keypad 0 and Insert 150 | #define KEY_KP_DOT 0x63 // Keypad . and Delete 151 | 152 | #define KEY_102ND 0x64 // Keyboard Non-US \ and | 153 | #define KEY_COMPOSE 0x65 // Keyboard Application 154 | #define KEY_POWER 0x66 // Keyboard Power 155 | #define KEY_KP_EQUAL 0x67 // Keypad = 156 | 157 | #define KEY_F13 0x68 // Keyboard F13 158 | #define KEY_F14 0x69 // Keyboard F14 159 | #define KEY_F15 0x6a // Keyboard F15 160 | #define KEY_F16 0x6b // Keyboard F16 161 | #define KEY_F17 0x6c // Keyboard F17 162 | #define KEY_F18 0x6d // Keyboard F18 163 | #define KEY_F19 0x6e // Keyboard F19 164 | #define KEY_F20 0x6f // Keyboard F20 165 | #define KEY_F21 0x70 // Keyboard F21 166 | #define KEY_F22 0x71 // Keyboard F22 167 | #define KEY_F23 0x72 // Keyboard F23 168 | #define KEY_F24 0x73 // Keyboard F24 169 | 170 | #define KEY_OPEN 0x74 // Keyboard Execute 171 | #define KEY_HELP 0x75 // Keyboard Help 172 | #define KEY_PROPS 0x76 // Keyboard Menu 173 | #define KEY_SELECT 0x77 // Keyboard Select 174 | #define KEY_STOP 0x78 // Keyboard Stop 175 | #define KEY_AGAIN 0x79 // Keyboard Again 176 | #define KEY_UNDO 0x7a // Keyboard Undo 177 | #define KEY_CUT 0x7b // Keyboard Cut 178 | #define KEY_COPY 0x7c // Keyboard Copy 179 | #define KEY_PASTE 0x7d // Keyboard Paste 180 | #define KEY_FIND 0x7e // Keyboard Find 181 | #define KEY_MUTE 0x7f // Keyboard Mute 182 | #define KEY_VOLUMEUP 0x80 // Keyboard Volume Up 183 | #define KEY_VOLUMEDOWN 0x81 // Keyboard Volume Down 184 | // 0x82 Keyboard Locking Caps Lock 185 | // 0x83 Keyboard Locking Num Lock 186 | // 0x84 Keyboard Locking Scroll Lock 187 | #define KEY_KP_COMMA 0x85 // Keypad Comma 188 | #define KEY_KP_EQUAL_UNIX 0x86 // Keypad Equal Sign on AS/400 (Unix) 189 | #define KEY_RO 0x87 // Keyboard International1 190 | #define KEY_KATAKANAHIRAGANA 0x88 // Keyboard International2 191 | #define KEY_YEN 0x89 // Keyboard International3 192 | #define KEY_HENKAN 0x8a // Keyboard International4 193 | #define KEY_MUHENKAN 0x8b // Keyboard International5 194 | #define KEY_KP_JPCOMMA 0x8c // Keyboard International6 195 | // 0x8d Keyboard International7 196 | // 0x8e Keyboard International8 197 | // 0x8f Keyboard International9 198 | #define KEY_HANGEUL 0x90 // Keyboard LANG1 199 | #define KEY_HANJA 0x91 // Keyboard LANG2 200 | #define KEY_KATAKANA 0x92 // Keyboard LANG3 201 | #define KEY_HIRAGANA 0x93 // Keyboard LANG4 202 | #define KEY_ZENKAKUHANKAKU 0x94 // Keyboard LANG5 203 | // 0x95 Keyboard LANG6 204 | // 0x96 Keyboard LANG7 205 | // 0x97 Keyboard LANG8 206 | // 0x98 Keyboard LANG9 207 | #define KEY_ALTERASE 0x99 // Keyboard Alternate Erase 208 | #define KEY_SYSREQ 0x9a // Keyboard SysReq/Attention 209 | // 0x9b Keyboard Cancel 210 | // 0x9c Keyboard Clear 211 | // 0x9d Keyboard Prior 212 | // 0x9e Keyboard Return 213 | // 0x9f Keyboard Separator 214 | // 0xa0 Keyboard Out 215 | // 0xa1 Keyboard Oper 216 | // 0xa2 Keyboard Clear/Again 217 | // 0xa3 Keyboard CrSel/Props 218 | // 0xa4 Keyboard ExSel 219 | 220 | // 0xb0 Keypad 00 221 | // 0xb1 Keypad 000 222 | // 0xb2 Thousands Separator 223 | // 0xb3 Decimal Separator 224 | // 0xb4 Currency Unit 225 | // 0xb5 Currency Sub-unit 226 | #define KEY_KP_LEFTPAREN 0xb6 // Keypad ( 227 | #define KEY_KP_RIGHTPAREN 0xb7 // Keypad ) 228 | #define KEY_KP_LEFTBRACE 0xb8 // Keypad { 229 | #define KEY_KP_RIGHTBRACE 0xb9 // Keypad } 230 | // 0xba Keypad Tab 231 | // 0xbb Keypad Backspace 232 | // 0xbc Keypad A 233 | // 0xbd Keypad B 234 | // 0xbe Keypad C 235 | // 0xbf Keypad D 236 | // 0xc0 Keypad E 237 | // 0xc1 Keypad F 238 | // 0xc2 Keypad XOR 239 | // 0xc3 Keypad ^ 240 | // 0xc4 Keypad % 241 | // 0xc5 Keypad < 242 | // 0xc6 Keypad > 243 | // 0xc7 Keypad & 244 | // 0xc8 Keypad && 245 | // 0xc9 Keypad | 246 | // 0xca Keypad || 247 | // 0xcb Keypad : 248 | // 0xcc Keypad # 249 | // 0xcd Keypad Space 250 | // 0xce Keypad @ 251 | // 0xcf Keypad ! 252 | // 0xd0 Keypad Memory Store 253 | // 0xd1 Keypad Memory Recall 254 | // 0xd2 Keypad Memory Clear 255 | // 0xd3 Keypad Memory Add 256 | // 0xd4 Keypad Memory Subtract 257 | // 0xd5 Keypad Memory Multiply 258 | // 0xd6 Keypad Memory Divide 259 | // 0xd7 Keypad +/- 260 | // 0xd8 Keypad Clear 261 | // 0xd9 Keypad Clear Entry 262 | // 0xda Keypad Binary 263 | // 0xdb Keypad Octal 264 | // 0xdc Keypad Decimal 265 | // 0xdd Keypad Hexadecimal 266 | 267 | /** 268 | * Key codes for modifier keys. 269 | * For a standard keyboard HID report the first byte is the modifer key bitmask. 270 | * Do a bitwise and with 0x7 to get the corresponding bit in the modifer byte. 271 | */ 272 | #define KEY_LEFTCTRL 0xe0 // Keyboard Left Control 273 | #define KEY_LEFTSHIFT 0xe1 // Keyboard Left Shift 274 | #define KEY_LEFTALT 0xe2 // Keyboard Left Alt 275 | #define KEY_LEFTMETA 0xe3 // Keyboard Left GUI/Win/Apple/Meta 276 | #define KEY_RIGHTCTRL 0xe4 // Keyboard Right Control 277 | #define KEY_RIGHTSHIFT 0xe5 // Keyboard Right Shift 278 | #define KEY_RIGHTALT 0xe6 // Keyboard Right Alt 279 | #define KEY_RIGHTMETA 0xe7 // Keyboard Right GUI/Win/Apple/Meta 280 | 281 | #endif // _USB_HID_KEYS_H_ 282 | -------------------------------------------------------------------------------- /libraries/DFRobotIRPositionEx/DFRobotIRPositionEx.cpp: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file DFRobotIRPositionEx.cpp 3 | * @brief DFRobot's Positioning IR camera with extended functionality 4 | * @n CPP file for DFRobot's Positioning IR camera 5 | * @details Extended functionality comes from http://wiibrew.org/wiki/Wiimote#IR_Camera 6 | * - Added basic data format, less IIC bytes than Extended 7 | * - Added size data to extended data format 8 | * - Added functions to atomically read the position data 9 | * - Added sensitivity settings 10 | * - Added IIC clock setting, appears to work up to at least 1MHz 11 | * 12 | * @copyright [DFRobot](http://www.dfrobot.com), 2016 13 | * @copyright Mike "Prow" Lynch, 2021 14 | * @copyright GNU Lesser General Public License 15 | * 16 | * @author [Angelo](Angelo.qiao@dfrobot.com) 17 | * @author Mike Lynch 18 | * @version V1.0 19 | * @date 2021-07-14 20 | */ 21 | 22 | #include 23 | #include 24 | #include "DFRobotIRPositionEx.h" 25 | 26 | // data lengths 27 | constexpr unsigned int DFRIRdata_LengthBasic = 11; 28 | constexpr unsigned int DFRIRdata_LengthExtended = 13; 29 | constexpr unsigned int DFRIRdata_LengthFull = 9 * 4 + 1; 30 | 31 | // data format mode register values 32 | constexpr uint8_t DFRIRdata_ModeBasic = 0x11; 33 | constexpr uint8_t DFRIRdata_ModeExtended = 0x33; 34 | constexpr uint8_t DFRIRdata_ModeFull = 0x55; 35 | 36 | // IIC delay, the Wiki says to use at least 50ms, but the original source uses 10 37 | constexpr unsigned long DFRIRdata_IICdelay = 10; 38 | 39 | // maximum valid Y position 40 | constexpr int DFRIRdata_MaxY = 767; 41 | 42 | DFRobotIRPositionEx::DFRobotIRPositionEx(TwoWire& _wire) : wire(_wire), seenFlags(0) 43 | { 44 | } 45 | 46 | DFRobotIRPositionEx::~DFRobotIRPositionEx() 47 | { 48 | } 49 | 50 | void DFRobotIRPositionEx::writeTwoIICByte(uint8_t first, uint8_t second) 51 | { 52 | wire.beginTransmission(IRAddress); 53 | wire.write(first); 54 | wire.write(second); 55 | wire.endTransmission(); 56 | } 57 | 58 | void DFRobotIRPositionEx::dataFormat(DataFormat_e format) 59 | { 60 | uint8_t mode = format ? DFRIRdata_ModeExtended : DFRIRdata_ModeBasic; 61 | writeTwoIICByte(0x33, mode); 62 | delay(DFRIRdata_IICdelay); 63 | } 64 | 65 | void DFRobotIRPositionEx::sensitivityLevel(Sensitivity_e sensitivity) 66 | { 67 | // sensitivity data from http://wiibrew.org/wiki/Wiimote#IR_Camera 68 | static const uint8_t reg06[3] = {0x90, 0x90, 0xFF}; 69 | static const uint8_t reg08[3] = {0xC0, 0x41, 0x0C}; 70 | static const uint8_t reg1A[3] = {0x40, 0x40, 0x00}; 71 | if(sensitivity > Sensitivity_Max) { 72 | sensitivity = Sensitivity_Max; 73 | } 74 | writeTwoIICByte(0x06, reg06[sensitivity]); 75 | delay(DFRIRdata_IICdelay); 76 | writeTwoIICByte(0x08, reg08[sensitivity]); 77 | delay(DFRIRdata_IICdelay); 78 | writeTwoIICByte(0x1A, reg1A[sensitivity]); 79 | delay(DFRIRdata_IICdelay); 80 | } 81 | 82 | void DFRobotIRPositionEx::begin(uint32_t clock, DataFormat_e format, Sensitivity_e sensitivity) 83 | { 84 | // looking under the covers, the Wire default is only 100kHz (on AVR and SAMD), so allow a custom setting 85 | // so close to the code being 100% portable... yes the order you call setClock() appears to differ for the RP2040 86 | #ifdef ARDUINO_ARCH_RP2040 87 | // For RP2040 the clock must be set before calling begin() 88 | wire.setClock(clock); 89 | wire.begin(); 90 | #else 91 | // For AVR and SAMD the clock must be changed after begin() 92 | wire.begin(); 93 | wire.setClock(clock); 94 | #endif 95 | // stop camera? 96 | writeTwoIICByte(0x30,0x01); 97 | delay(DFRIRdata_IICdelay); 98 | sensitivityLevel(sensitivity); 99 | dataFormat(format); 100 | // start camera? 101 | writeTwoIICByte(0x30,0x08); 102 | 103 | delay(100); 104 | } 105 | 106 | void DFRobotIRPositionEx::requestPositionExtended() 107 | { 108 | wire.beginTransmission(IRAddress); 109 | wire.write(0x36); 110 | wire.endTransmission(); 111 | wire.requestFrom(IRAddress, DFRIRdata_LengthExtended); 112 | } 113 | 114 | void DFRobotIRPositionEx::requestPositionBasic() 115 | { 116 | wire.beginTransmission(IRAddress); 117 | wire.write(0x36); 118 | wire.endTransmission(); 119 | wire.requestFrom(IRAddress, DFRIRdata_LengthBasic); 120 | } 121 | 122 | bool DFRobotIRPositionEx::availableExtended() 123 | { 124 | if(readPosition(positionData[0], DFRIRdata_LengthExtended)) { 125 | unpackExtendedFrameSeen(0); 126 | return true; 127 | } 128 | return false; 129 | } 130 | 131 | bool DFRobotIRPositionEx::availableExtendedNoSeen() 132 | { 133 | if(readPosition(positionData[0], DFRIRdata_LengthExtended)) { 134 | unpackExtendedFrame(0); 135 | return true; 136 | } 137 | return false; 138 | } 139 | 140 | bool DFRobotIRPositionEx::availableBasic() 141 | { 142 | if(readPosition(positionData[0], DFRIRdata_LengthBasic)) { 143 | unpackBasicFrameSeen(0); 144 | return true; 145 | } 146 | return false; 147 | } 148 | 149 | bool DFRobotIRPositionEx::availableBasicNoSeen() 150 | { 151 | if(readPosition(positionData[0], DFRIRdata_LengthBasic)) { 152 | unpackBasicFrame(0); 153 | return true; 154 | } 155 | return false; 156 | } 157 | 158 | bool DFRobotIRPositionEx::readPosition(PositionData_t& posData, unsigned int length) 159 | { 160 | if(wire.available() == length) { //read only the data lenth fits. 161 | for(int i = 0; i < length; ++i) { 162 | posData.receivedBuffer[i] = wire.read(); 163 | } 164 | 165 | // looks like the header should always be 0, extra sanity for valid data 166 | //if(posData.positionFrame.header != 0) { 167 | // return false; 168 | //} 169 | return true; 170 | } 171 | 172 | // length mismatch, flush the read buffer 173 | while(wire.available()) { 174 | wire.read(); 175 | } 176 | return false; 177 | } 178 | 179 | void DFRobotIRPositionEx::unpackBasicFrame(unsigned int posData) 180 | { 181 | BasicFrame_t& frame = positionData[posData].frame.format.rawBasic[0]; 182 | int high = frame.high; 183 | positionX[0] = (int)frame.x1low | ((high & 0x30) << 4); 184 | positionY[0] = (int)frame.y1low | ((high & 0xC0) << 2); 185 | positionX[1] = (int)frame.x2low | ((high & 0x03) << 8); 186 | positionY[1] = (int)frame.y2low | ((high & 0x0C) << 6); 187 | 188 | frame = positionData[posData].frame.format.rawBasic[1]; 189 | high = frame.high; 190 | positionX[2] = (int)frame.x1low | ((high & 0x30) << 4); 191 | positionY[2] = (int)frame.y1low | ((high & 0xC0) << 2); 192 | positionX[3] = (int)frame.x2low | ((high & 0x03) << 8); 193 | positionY[3] = (int)frame.y2low | ((high & 0x0C) << 6); 194 | } 195 | 196 | void DFRobotIRPositionEx::unpackBasicFrameSeen(unsigned int posData) 197 | { 198 | seenFlags = 0; 199 | BasicFrame_t& frame = positionData[posData].frame.format.rawBasic[0]; 200 | int high = frame.high; 201 | int y = (int)frame.y1low | ((high & 0xC0) << 2); 202 | if(y <= DFRIRdata_MaxY) { 203 | positionY[0] = y; 204 | positionX[0] = (int)frame.x1low | ((high & 0x30) << 4); 205 | seenFlags |= 0x01; 206 | } 207 | y = (int)frame.y2low | ((high & 0x0C) << 6); 208 | if(y <= DFRIRdata_MaxY) { 209 | positionY[1] = y; 210 | positionX[1] = (int)frame.x2low | ((high & 0x03) << 8); 211 | seenFlags |= 0x02; 212 | } 213 | 214 | frame = positionData[posData].frame.format.rawBasic[1]; 215 | high = frame.high; 216 | y = (int)frame.y1low | ((high & 0xC0) << 2); 217 | if(y <= DFRIRdata_MaxY) { 218 | positionY[2] = y; 219 | positionX[2] = (int)frame.x1low | ((high & 0x30) << 4); 220 | seenFlags |= 0x04; 221 | } 222 | y = (int)frame.y2low | ((high & 0x0C) << 6); 223 | if(y <= DFRIRdata_MaxY) { 224 | positionY[3] = y; 225 | positionX[3] = (int)frame.x2low | ((high & 0x03) << 8); 226 | seenFlags |= 0x08; 227 | } 228 | } 229 | 230 | int DFRobotIRPositionEx::basicAtomic(DFRobotIRPositionEx::Retry_e retry) 231 | { 232 | // initial index for positiondata[1] 233 | unsigned int index = 0; 234 | 235 | // initial read in positiondata[0] 236 | requestPositionBasic(); 237 | if(!readPosition(positionData[0], DFRIRdata_LengthBasic)) { 238 | return Error_IICerror; 239 | } 240 | 241 | for(unsigned int i = 0, retries = retry >> 1; i <= retries; ++i) { 242 | requestPositionBasic(); 243 | 244 | // switch to other buffer for next read 245 | index ^= 1; 246 | 247 | if(!readPosition(positionData[index], DFRIRdata_LengthBasic)) { 248 | return Error_IICerror; 249 | } 250 | 251 | // compare but ignore the header byte 252 | if(!memcmp(&positionData[0].receivedBuffer[1], &positionData[1].receivedBuffer[1], DFRIRdata_LengthBasic - 1)) { 253 | // position data is identical so unpack the data 254 | unpackBasicFrameSeen(0); 255 | return Error_Success; 256 | } 257 | } 258 | 259 | if(retry & 1) { 260 | unpackBasicFrameSeen(index); 261 | return Error_SuccessMismatch; 262 | } 263 | 264 | return Error_DataMismatch; 265 | } 266 | 267 | void DFRobotIRPositionEx::unpackExtendedFrame(unsigned int posData) 268 | { 269 | for(int i = 0; i < 4; ++i) { 270 | ExtendedFrame_t& frame = positionData[posData].frame.format.rawExtended[i]; 271 | positionX[i] = (int)frame.xLow | ((int)(frame.xyHighSize & 0x30U) << 4); 272 | positionY[i] = (int)frame.yLow | ((int)(frame.xyHighSize & 0xC0U) << 2); 273 | unpackedSizes[i] = frame.xyHighSize & 0xF; 274 | } 275 | } 276 | 277 | void DFRobotIRPositionEx::unpackExtendedFrameSeen(unsigned int posData) 278 | { 279 | seenFlags = 0; 280 | for(int i = 0; i < 4; ++i) { 281 | ExtendedFrame_t& frame = positionData[posData].frame.format.rawExtended[i]; 282 | int y = (int)frame.yLow | ((int)(frame.xyHighSize & 0xC0U) << 2); 283 | if(y <= DFRIRdata_MaxY) { 284 | positionY[i] = y; 285 | positionX[i] = (int)frame.xLow | ((int)(frame.xyHighSize & 0x30U) << 4); 286 | unpackedSizes[i] = frame.xyHighSize & 0xF; 287 | seenFlags |= 1 << i; 288 | } 289 | } 290 | } 291 | 292 | int DFRobotIRPositionEx::extendedAtomic(DFRobotIRPositionEx::Retry_e retry) 293 | { 294 | // initial index for positiondata[1] 295 | unsigned int index = 0; 296 | 297 | // initial read in positiondata[0] 298 | requestPositionExtended(); 299 | if(!readPosition(positionData[0], DFRIRdata_LengthExtended)) { 300 | return Error_IICerror; 301 | } 302 | 303 | for(unsigned int i = 0, retries = retry >> 1; i <= retries; ++i) { 304 | requestPositionExtended(); 305 | 306 | // switch to other buffer for next read 307 | index ^= 1; 308 | 309 | if(!readPosition(positionData[index], DFRIRdata_LengthExtended)) { 310 | return Error_IICerror; 311 | } 312 | 313 | // compare but ignore the header byte 314 | if(!memcmp(&positionData[0].receivedBuffer[1], &positionData[1].receivedBuffer[1], DFRIRdata_LengthExtended - 1)) { 315 | // position data is identical so unpack the data 316 | unpackExtendedFrameSeen(index); 317 | return Error_Success; 318 | } 319 | } 320 | 321 | if(retry & 1) { 322 | unpackExtendedFrameSeen(index); 323 | return Error_SuccessMismatch; 324 | } 325 | 326 | return Error_DataMismatch; 327 | } 328 | -------------------------------------------------------------------------------- /libraries/SamcoPositionEnhanced/SamcoPositionEnhanced.cpp: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoPositionEnhanced.cpp 3 | * @brief Light Gun library for 4 LED setup 4 | * @n CPP file for Samco Light Gun 4 LED setup 5 | * 6 | * @copyright Samco, https://github.com/samuelballantyne, May 2021 7 | * @copyright GNU Lesser General Public License 8 | * 9 | * @author [Sam Ballantyne](samuelballantyne@hotmail.com) 10 | * @version V1.0 11 | * @date 2021 12 | */ 13 | 14 | #include 15 | #include "SamcoPositionEnhanced.h" 16 | 17 | constexpr int buff = 50 * CamToMouseMult; 18 | 19 | // floating point PI 20 | constexpr float fPI = (float)PI; 21 | 22 | void SamcoPositionEnhanced::begin(const int* px, const int* py, unsigned int seen, int cx, int cy) 23 | { 24 | // Remapping LED postions to use with library. 25 | 26 | positionXX[0] = px[0] << CamToMouseShift; 27 | positionYY[0] = py[0] << CamToMouseShift; 28 | positionXX[1] = px[1] << CamToMouseShift; 29 | positionYY[1] = py[1] << CamToMouseShift; 30 | positionXX[2] = px[2] << CamToMouseShift; 31 | positionYY[2] = py[2] << CamToMouseShift; 32 | positionXX[3] = px[3] << CamToMouseShift; 33 | positionYY[3] = py[3] << CamToMouseShift; 34 | 35 | seenFlags = seen; 36 | 37 | // Wait for all postions to be recognised before starting 38 | 39 | if(seenFlags == 0x0F) { 40 | start = 0xFF; 41 | } else if(!start) { 42 | // all positions not yet seen 43 | return; 44 | } 45 | 46 | for(unsigned int i = 0; i < 4; i++) { 47 | // if LED not seen... 48 | if (!(seenFlags & (1 << i))) { 49 | // if unseen make sure all quadrants have a value if missing apply value with buffer and set to unseen (this step is important for 1 LED usage) 50 | if (!(((positionY[0] < medianY) && (positionX[0] < medianX)) || ((positionY[1] < medianY) && (positionX[1] < medianX)) || ((positionY[2] < medianY) && (positionX[2] < medianX)) || ((positionY[3] < medianY) && (positionX[3] < medianX)))) { 51 | positionX[i] = medianX + (medianX - FinalX[3]) - buff; 52 | positionY[i] = medianY + (medianY - FinalY[3]) - buff; 53 | see[0] = 0; 54 | } 55 | if (!(((positionY[0] < medianY) && (positionX[0] > medianX)) || ((positionY[1] < medianY) && (positionX[1] > medianX)) || ((positionY[2] < medianY) && (positionX[2] > medianX)) || ((positionY[3] < medianY) && (positionX[3] > medianX)))) { 56 | positionX[i] = medianX + (medianX - FinalX[2]) + buff; 57 | positionY[i] = medianY + (medianY - FinalY[2]) - buff; 58 | see[1] = 0; 59 | } 60 | if (!(((positionY[0] > medianY) && (positionX[0] < medianX)) || ((positionY[1] > medianY) && (positionX[1] < medianX)) || ((positionY[2] > medianY) && (positionX[2] < medianX)) || ((positionY[3] > medianY) && (positionX[3] < medianX)))) { 61 | positionX[i] = medianX + (medianX - FinalX[1]) - buff; 62 | positionY[i] = medianY + (medianY - FinalY[1]) + buff; 63 | see[2] = 0; 64 | } 65 | if (!(((positionY[0] > medianY) && (positionX[0] > medianX)) || ((positionY[1] > medianY) && (positionX[1] > medianX)) || ((positionY[2] > medianY) && (positionX[2] > medianX)) || ((positionY[3] > medianY) && (positionX[3] > medianX)))) { 66 | positionX[i] = medianX + (medianX - FinalX[0]) + buff; 67 | positionY[i] = medianY + (medianY - FinalY[0]) + buff; 68 | see[3] = 0; 69 | } 70 | 71 | // if all quadrants have a value apply value with buffer and set to see/unseen 72 | if (positionY[i] < medianY) { 73 | if (positionX[i] < medianX) { 74 | positionX[i] = medianX + (medianX - FinalX[3]) - buff; 75 | positionY[i] = medianY + (medianY - FinalY[3]) - buff; 76 | see[0] = 0; 77 | } 78 | if (positionX[i] > medianX) { 79 | positionX[i] = medianX + (medianX - FinalX[2]) + buff; 80 | positionY[i] = medianY + (medianY - FinalY[2]) - buff; 81 | see[1] = 0; 82 | } 83 | } 84 | if (positionY[i] > medianY) { 85 | if (positionX[i] < medianX) { 86 | positionX[i] = medianX + (medianX - FinalX[1]) - buff; 87 | positionY[i] = medianY + (medianY - FinalY[1]) + buff; 88 | see[2] = 0; 89 | } 90 | if (positionX[i] > medianX) { 91 | positionX[i] = medianX + (medianX - FinalX[0]) + buff; 92 | positionY[i] = medianY + (medianY - FinalY[0]) + buff; 93 | see[3] = 0; 94 | } 95 | } 96 | 97 | } else { 98 | // If LEDS have been seen place in correct quadrant, apply buffer an set to seen. 99 | int mapXX = map(positionXX[i], 0, MouseMaxX, MouseMaxX, 0); 100 | if (positionYY[i] < medianY) { 101 | if (mapXX < medianX) { 102 | positionX[i] = mapXX - buff; 103 | positionY[i] = positionYY[i] - buff; 104 | see[0] <<= 1; 105 | see[0] |= 1; 106 | } else if (mapXX > medianX) { 107 | positionX[i] = mapXX + buff; 108 | positionY[i] = positionYY[i] - buff; 109 | see[1] <<= 1; 110 | see[1] |= 1; 111 | } 112 | } else if (positionYY[i] > medianY) { 113 | if (mapXX < medianX) { 114 | positionX[i] = mapXX - buff; 115 | positionY[i] = positionYY[i] + buff; 116 | see[2] <<= 1; 117 | see[2] |= 1; 118 | } else if (mapXX > medianX) { 119 | positionX[i] = mapXX + buff; 120 | positionY[i] = positionYY[i] + buff; 121 | see[3] <<= 1; 122 | see[3] |= 1; 123 | } 124 | } 125 | } 126 | 127 | // Arrange all values in to quadrants and remove buffer. 128 | // If LEDS have been seen use there value 129 | // If LEDS haven't been seen work out values form live positions 130 | 131 | if (positionY[i] < medianY) { 132 | if (positionX[i] < medianX) { 133 | if (see[0] & 0x02) { 134 | FinalX[0] = positionX[i] + buff; 135 | FinalY[0] = positionY[i] + buff; 136 | } else if (positionY[i] < 0) { 137 | float f = angleBottom + angleOffset[2]; 138 | FinalX[0] = FinalX[2] + round(yDistLeft * cos(f)); 139 | FinalY[0] = FinalY[2] + round(yDistLeft * -sin(f)); 140 | } else if (positionX[i] < 0) { 141 | float f = angleRight - angleOffset[1]; 142 | FinalX[0] = FinalX[1] + round(xDistTop * -cos(f)); 143 | FinalY[0] = FinalY[1] + round(xDistTop * sin(f)); 144 | } 145 | } else if (positionX[i] > medianX) { 146 | if (see[1] & 0x02) { 147 | FinalX[1] = positionX[i] - buff; 148 | FinalY[1] = positionY[i] + buff; 149 | } else if (positionY[i] < 0) { 150 | float f = angleBottom - (angleOffset[3] - fPI); 151 | FinalX[1] = FinalX[3] + round(yDistRight * cos(f)); 152 | FinalY[1] = FinalY[3] + round(yDistRight * -sin(f)); 153 | } else if (positionX[i] > MouseMaxX) { 154 | float f = angleLeft + (angleOffset[0] - fPI); 155 | FinalX[1] = FinalX[0] + round(xDistTop * cos(f)); 156 | FinalY[1] = FinalY[0] + round(xDistTop * -sin(f)); 157 | } 158 | } 159 | } else if (positionY[i] > medianY) { 160 | if (positionX[i] < medianX) { 161 | if (see[2] & 0x02) { 162 | FinalX[2] = positionX[i] + buff; 163 | FinalY[2] = positionY[i] - buff; 164 | } else if (positionY[i] > MouseMaxY) { 165 | float f = angleTop - angleOffset[0]; 166 | FinalX[2] = FinalX[0] + round(yDistLeft * cos(f)); 167 | FinalY[2] = FinalY[0] + round(yDistLeft * -sin(f)); 168 | } else if (positionX[i] < 0) { 169 | float f = angleRight + angleOffset[3]; 170 | FinalX[2] = FinalX[3] + round(xDistBottom * cos(f)); 171 | FinalY[2] = FinalY[3] + round(xDistBottom * -sin(f)); 172 | } 173 | } else if (positionX[i] > medianX) { 174 | if ((see[3] & 0x02)) { 175 | FinalX[3] = positionX[i] - buff; 176 | FinalY[3] = positionY[i] - buff; 177 | } else if (positionY[i] > MouseMaxY) { 178 | float f = angleTop + (angleOffset[1] - fPI); 179 | FinalX[3] = FinalX[1] + round(yDistRight * cos(f)); 180 | FinalY[3] = FinalY[1] + round(yDistRight * -sin(f)); 181 | } else if (positionX[i] > MouseMaxX) { 182 | float f = angleLeft - (angleOffset[2] - fPI); 183 | FinalX[3] = FinalX[2] + round(xDistBottom * -cos(f)); 184 | FinalY[3] = FinalY[2] + round(xDistBottom * sin(f)); 185 | } 186 | } 187 | } 188 | } 189 | 190 | // If all LEDS can be seen update median & angle offsets (resets sketch stop hangs on glitches) 191 | 192 | if (seenFlags == 0x0F) { 193 | medianY = (positionY[0] + positionY[1] + positionY[2] + positionY[3] + 2) / 4; 194 | medianX = (positionX[0] + positionX[1] + positionX[2] + positionX[3] + 2) / 4; 195 | } else { 196 | medianY = (FinalY[0] + FinalY[1] + FinalY[2] + FinalY[3] + 2) / 4; 197 | medianX = (FinalX[0] + FinalX[1] + FinalX[2] + FinalX[3] + 2) / 4; 198 | } 199 | 200 | // If 4 LEDS can be seen and loop has run through 5 times update offsets and height 201 | 202 | if ((1 << 5) & see[0] & see[1] & see[2] & see[3]) { 203 | angleOffset[0] = angleTop - (angleLeft - fPI); 204 | angleOffset[1] = -(angleTop - angleRight); 205 | angleOffset[2] = -(angleBottom - angleLeft); 206 | angleOffset[3] = angleBottom - (angleRight - fPI); 207 | height = (yDistLeft + yDistRight) / 2.0f; 208 | } 209 | 210 | // If 2 LEDS can be seen and loop has run through 5 times update angle and distances 211 | 212 | if ((1 << 5) & see[0] & see[2]) { 213 | angleLeft = atan2(FinalY[2] - FinalY[0], FinalX[0] - FinalX[2]); 214 | yDistLeft = hypot((FinalY[0] - FinalY[2]), (FinalX[0] - FinalX[2])); 215 | } 216 | 217 | if ((1 << 5) & see[3] & see[1]) { 218 | angleRight = atan2(FinalY[3] - FinalY[1], FinalX[1] - FinalX[3]); 219 | yDistRight = hypot((FinalY[3] - FinalY[1]), (FinalX[3] - FinalX[1])); 220 | } 221 | 222 | if ((1 << 5) & see[0] & see[1]) { 223 | angleTop = atan2(FinalY[0] - FinalY[1], FinalX[1] - FinalX[0]); 224 | xDistTop = hypot((FinalY[0] - FinalY[1]), (FinalX[0] - FinalX[1])); 225 | } 226 | 227 | if ((1 << 5) & see[3] & see[2]) { 228 | angleBottom = atan2(FinalY[2] - FinalY[3], FinalX[3] - FinalX[2]); 229 | xDistBottom = hypot((FinalY[2] - FinalY[3]), (FinalX[2] - FinalX[3])); 230 | } 231 | 232 | // Add tilt correction 233 | angle = (atan2(FinalY[0] - FinalY[1], FinalX[1] - FinalX[0]) + atan2(FinalY[2] - FinalY[3], FinalX[3] - FinalX[2])) / 2.0f; 234 | float cosAngle = cos(angle); 235 | float sinAngle = sin(angle); 236 | xx = cx + round(cosAngle * (float)(medianX - cx) - sinAngle * (float)(medianY - cy)); 237 | yy = cy + round(sinAngle * (float)(medianX - cx) + cosAngle * (float)(medianY - cy)); 238 | } 239 | -------------------------------------------------------------------------------- /SamcoEnhanced/README.md: -------------------------------------------------------------------------------- 1 | # SAMCO Prow Enhanced - Arduino Powered Light Gun 2 | 3 | Based on the 4IR Beta "Big Code Update" SAMCO project from https://github.com/samuelballantyne/IR-Light-Gun 4 | 5 | ## Enhancements 6 | - Increased precision for maths and mouse pointer position 7 | - Glitch-free DFRobot positioning (DFRobotIRPositionEx library) 8 | - IR camera sensitivity adjustment (DFRobotIRPositionEx library) 9 | - Faster IIC clock option for IR camera (DFRobotIRPositionEx library) 10 | - Optional averaging modes can be enabled to slightly reduce mouse position jitter 11 | - Enhanced button debouncing and handling (LightgunButtons library) 12 | - Modified AbsMouse to be a 5 button device (AbsMouse5 library) 13 | - Multiple calibration profiles 14 | - Save settings and calibration profiles to flash memory (SAMD) or EEPROM (ATmega32U4) 15 | - Built in Processing mode for use with the SAMCO Processing sketch 16 | 17 | ## Requirements 18 | - Adafruit ItsyBitsy M0, M4, RP2040 (or any SAMD21, SAMD51, or RP2040 dev board) 19 | - DFRobot IR Positioning Camera (SEN0158) 20 | - 4 IR LED emitters 21 | - Arduino development environment 22 | 23 | With minor modifications it should work with any SAMD21, SAMD51, or RP2040 boards. See the SAMCO project for build details: https://github.com/samuelballantyne/IR-Light-Gun 24 | 25 | Note that SAMCO PCBs only offically support the ItsyBitsy M0 or M4. The ItsyBitsy RP2040 should be pin compatible but hasn't been confirmed. 26 | 27 | The sketch is configured with buttons for a SAMCO GunCon 2 PCB. 28 | 29 | The ATmega32U4 is no longer officially supported. 30 | 31 | ## IR Emitter setup 32 | The IR emitters must be arranged with 2 emitters on opposite edges of your screen/monitor forming a rectangle or square. For example, you can use 2 Wii sensor bars; one on top of your screen and one below. 33 | 34 | ## Arduino Board Dependencies 35 | Be sure to install the appropriate boards in the Adruino Boards Manager. 36 | #### RP2040 37 | - [Earle F. Philhower Arduino-Pico](https://github.com/earlephilhower/arduino-pico) 38 | #### SAMD 39 | - Arduino SAMD Boards 40 | - Adafruit SAMD Boards (ItsyBitsy M0, M4, or other Adafruit SAMD board) 41 | 42 | ## Arduino Library Dependencies 43 | Be sure to have the following libraries installed depending on the board you are using (or just install them all). 44 | - Adafruit DotStar (for ItsyBitsy M0 and M4) 45 | - Adafruit NeoPixel (for ItsyBitsy RP2040) 46 | - Adafruit SPI Flash (for ItsyBitsy M0 and M4) 47 | - Adafruit TinyUSB (included for SAMD and RP2040 boards. Required for ItsyBitsy RP2040, can also be used for SAMD) 48 | 49 | ## Included libraries 50 | Copy all folders under [libraries](../libraries/) to your Arduino `libraries` folder. 51 | - AbsMouse5 - 5 button absolute positioning USB HID mouse device 52 | - BasicKeyboard - Basic USB HID keyboard device 53 | - DFRobotIRPositionEx - Modified DFRobot IR Positioning Camera library 54 | - LightgunButtons - Library to handle the physical buttons 55 | - SamcoPositionEnhanced - Slightly modified SAMCO positioning maths 56 | 57 | ## Compiling and Configuration Options 58 | If you are using an ItsyBitsy M0 or M4 then I recommend you set the Optimize option to -O3 (or faster). If you are using an ItsyBitsy RP2040 then I recommend the -O3 Optimize option. If you are using an ItsyBitsy M4 (or any other SAMD51 board) then set the CPU Speed to 120 MHz standard. If you are using an ItsyBitsy RP2040 then set the CPU Speed to 125 or 133 MHz. There is no need for overclocking. The ItsyBitsy RP2040 must use the Adafruit TinyUSB stack. The SAMD devices can use either Arduino or TinyUSB USB stack. 59 | 60 | > Note: The RP2040 boards tend to default to the `Pico SDK` USB stack so you will see a build error until you switch to TinyUSB. 61 | 62 | ## Operation 63 | The light gun operates as a mouse until the button/combination is pressed to enter pause mode. The Arduino serial monitor (or any serial terminal) can be used to see information while the gun is paused and during the calibration procedure. 64 | 65 | Note that the buttons in pause mode (and to enter pause mode) activate when the last button of the combination releases. This is used to detect and differentiate button combinations vs a single button press. 66 | 67 | The mouse position updates at 209Hz so it is extremely responsive. 68 | 69 | ## Run modes 70 | The gun has the following modes of operation: 71 | 1. Normal - The mouse position updates from each frame from the IR positioning camera (no averaging) 72 | 2. Averaging - The position is calculated from a 2 frame moving average (current + previous position) 73 | 3. Averaging2 - The position is calculated from a weighted average of the current frame and 2 previous frames 74 | 4. Processing - Test mode for use with the Processing sketch (this mode is prevented from being assigned to a profile) 75 | 76 | The averaging modes are subtle but do reduce the motion jitter a bit without adding much if any noticeable lag. 77 | 78 | ## Processing mode 79 | The Processing mode is intended for use with the SAMCO Processing sketch. Download Processing from processing.org and find the 4IR Processing sketch from the SAMCO project. The Processing sketch lets you visually see the IR points as seen by the camera. This is very useful aligning the camera when building your light gun and for testing that the camera tracks all 4 points properly. I suppose if you don't want to install Processing then you can just open your favourite serial terminal program and watch the numbers scroll by. 80 | 81 | ## IR camera sensitivity 82 | The IR camera sensitivity can be adjusted. It is recommended to adjust the sensitivity as high as possible. If the IR sensitivity is too low then the pointer precision can suffer. However, too high of a sensitivity can cause the camera to pick up unwanted reflections that will cause the pointer to jump around. It is impossible to know which setting will work best since it is dependent on the specific setup. It depends on how bright the IR emitters are, the distance, camera lens, and if shiny surfaces may cause reflections. 83 | 84 | A sign that the IR sensitivity is too low is if the pointer moves in noticeable coarse steps, as if it has a low resolution to it. If you have the sensitivity level set to max and you notice this then the IR emitters may not be bright enough. 85 | 86 | A sign that the IR sensitivity is too high is if the pointer jumps around erratically. If this happens only while aiming at certain areas of the screen then this is a good indication a reflection is being detected by the camera. If the sensitivity is at max, step it down to high or minimum. Obviously the best solution is to eliminate the reflective surface. The Processing sketch can help daignose this problem since it will visually display the 4 IR points. 87 | 88 | ## Profiles 89 | The sketch is configured with 8 profiles available. Each profile has its own calibration data, run mode, and IR camera sensitivity settings. Each profile can be selected from pause mode by assigning a unique button or combination. 90 | 91 | ## Default Buttons 92 | - Trigger: Left mouse button 93 | - A: Right mouse button 94 | - B: Middle mouse button 95 | - Start: 1 key 96 | - Select: 5 key 97 | - Up/Down/Left/Right: Keyboard arrow keys 98 | - Reload: Enter pause mode 99 | - Pedal: Mouse button 5 100 | 101 | ## Default Buttons in Pause mode 102 | - A, B, Start, Select, Up, Down, Left, Right: select a profile 103 | - Start + Down: Normal gun mode (averaging disabled) 104 | - Start + Up: Normal gun with averaging, switch between the 2 averaging modes (use serial monitor to see the setting) 105 | - Start + A: Processing mode for use with the Processing sketch 106 | - B + Down: Decrease IR camera sensitivity (use serial monitor to see the setting) 107 | - B + Up: Increase IR camera sensitivity (use serial monitor to see the setting) 108 | - Reload: Exit pause mode 109 | - Trigger: Begin calibration 110 | - Start + Select: save settings to non-volatile memory (EEPROM or Flash depending on the board configuration) 111 | 112 | ## How to calibrate 113 | 1. Press **Reload** to enter pause mode. 114 | 2. Press a button to select a profile unless you want to calibration the current profile. 115 | 3. Pull the **Trigger** to begin calibration. 116 | 4. Shoot the pointer at center of the screen and hold the trigger down for 1/3 of a second while keeping a steady aim. 117 | 5. The mouse should lock to the vertical axis. Use the **A**/**B** buttons (can be held down) to adjust the mouse vertical range. **A** will increase and **B** will decrease. Track the pointer at the top and bottom edges of the screen while adjusting. 118 | 6. Pull the **Trigger** for horizontal calibration. 119 | 7. The mouse should lock to the horizontal axis. Use the **A**/**B** buttons (can be held down) to adjust the mouse horizontal range. **A** will increase and **B** will decrease. Track the pointer at the left and right edges of the screen while adjusting. 120 | 8. Pull the **Trigger** to finish and return to run mode. Values will apply to the currently selected profile in memory. 121 | 9. Recommended: After confirming the calibration is good, enter pause mode and press Start and Select to save the calibration to non-volatile memory. 122 | 10. Optional: Open serial monitor and update the `xCenter`, `yCenter`, `xScale`, and `yScale` values in the profile data array in the sketch (no need with step 9). 123 | 124 | Calibration can be cancelled during any step by pressing **Reload** or **Start** or **Select**. The gun will return to pause mode if you cancel the calibration. 125 | 126 | ### Advanced calibration 127 | - During center calibration, press **A** to skip this step and proceed to the vertical calibration 128 | - During vertical calibration, tap **Up** or **Down** to manually fine tune the vertical offset 129 | - During horizontal calibration, tap **Left** or **Right** to manually fine tune the horizontal offset 130 | 131 | ## Saving settings to non-volatile memory 132 | The calibration data and profile settings can be saved in non-volatile memory. The currently selected profile is saved as the default for when the light gun is plugged in. 133 | 134 | For ItsyBitsy M0 and M4 boards the external on-board SPI flash memory is used. For ATmega32U4 the EEPROM is used. 135 | 136 | ## Sketch Configuration 137 | The sketch is configured for a SAMCO 2.0 (GunCon 2) build. If you are using a SAMCO 2.0 PCB or your build matches the SAMCO 2.0 button assignment then the sketch will work as is. If you are using a different set of buttons then the sketch will have to be modified. 138 | 139 | ### Define Buttons 140 | Find the `LightgunButtons::ButtonDesc` array and define all of the buttons. The order of the buttons in the array represent a bit position. Define enum constants in the `ButtonMask_e` enum with the button bit mask values. There is also a `ButtonIndex_e` that defines the index positions in the array, but it is not currently not used except to define the bit mask values. See the `Desc_t` structure in the `LightgunButtons` for details on the structure. 141 | 142 | At the time of this writing, the button pin values will have to be modified if you are using an ItsyBitsy RP2040 with a SAMCO 2.0 PCB. The sketch has the Arduino pin numbers but the RP2040 must use the physical GPIO pins. It is a bit odd but the library does not provide mapping from the Arduino pin label printed on the top of the PCB to the physical GPIO number printed on the bottom of the PCB (for example, it defines D7 as 7). You will have to modify the pin values with the physical GPIO numbers as seen on the bottom of the PCB (or refer to the pinouts from the Adafruit documentation). For example, the trigger is defined with pin 7 but this is GPIO 6 for the RP2040. The A0 through A3 pins are correctly defined from the library. 143 | 144 | ### Behaviour buttons 145 | Below the button definitions are a bunch of constants that configure the buttons to control the gun. For example, enter and exit pause mode, and changing various settings. See the comments above each value for details. 146 | 147 | Most button behaviours can be assigned a combination. If the comment says a button combination is used then it activates when the last button of the combination releases. 148 | 149 | ### Other constants 150 | - `IRSeen0Color` colour for the RGB LED when no IR points are seen 151 | - `CalModeColor` colour for the RGB LED while calibrating 152 | 153 | ### Profiles 154 | There is a `ProfileCount` constant that defines the number of profiles. The `profileData` array has the default values for the profile. If there are no settings saved in non-volatile memory, then these values are used. There is no need to change these values if settings are saved to non-volatile memory. 155 | 156 | Find the `profileDesc` array to configure each profile. The profile descriptor allows you to specify: 157 | - A button/combination to select the profile while in pause mode 158 | - Colour used to light up an RGB LED (ItsyBitsy M0 and M4 include a DotStar) when paused 159 | - A text description for the button/combination 160 | - An optional text label or brief description 161 | -------------------------------------------------------------------------------- /libraries/DFRobotIRPositionEx/DFRobotIRPositionEx.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file DFRobotIRPositionEx.h 3 | * @brief DFRobot's Positioning IR camera with extended functionality 4 | * @n Header file for DFRobot's Positioning IR camera 5 | * @details Extended functionality comes from http://wiibrew.org/wiki/Wiimote#IR_Camera 6 | * - Added basic data format, less IIC bytes than Extended 7 | * - Added size data to extended data format 8 | * - Added functions to atomically read the position data 9 | * - Added sensitivity settings 10 | * - Added IIC clock setting, appears to work up to 1MHz 11 | * 12 | * @copyright [DFRobot](http://www.dfrobot.com), 2016 13 | * @copyright Mike Lynch, 2021 14 | * @copyright GNU Lesser General Public License 15 | * 16 | * @author [Angelo](Angelo.qiao@dfrobot.com) 17 | * @author Mike Lynch 18 | * @version V1.0 19 | * @date 2021-07-14 20 | */ 21 | 22 | #ifndef DFRobotIRPositionEx_h 23 | #define DFRobotIRPositionEx_h 24 | 25 | #include 26 | 27 | // forward declare Wire class 28 | class TwoWire; 29 | 30 | /*! 31 | * @brief DFRobot IR positioning camera with extended functionality. 32 | */ 33 | class DFRobotIRPositionEx { 34 | const int IRAddress = 0xB0 >> 1; ///< IIC address of the sensor 35 | 36 | /*! 37 | * @brief Position data structure for a single extended frame. 38 | */ 39 | typedef struct ExtendedFrame_s { 40 | uint8_t xLow; ///< x position low byte 41 | uint8_t yLow; ///< y position low byte 42 | uint8_t xyHighSize; ///< x and y position high byte and size 43 | } __attribute__ ((packed)) ExtendedFrame_t; 44 | 45 | /*! 46 | * @brief Position data structure for a single basic frame. 47 | */ 48 | typedef struct BasicFrame_s { 49 | uint8_t x1low; ///< x1 position low byte 50 | uint8_t y1low; ///< y1 position low byte 51 | uint8_t high; ///< packed high bits for both points 52 | uint8_t x2low; ///< x2 position low byte 53 | uint8_t y2low; ///< y2 position low byte 54 | } __attribute__ ((packed)) BasicFrame_t; 55 | 56 | /*! 57 | * @brief Position data structure for a single full frame 58 | */ 59 | typedef struct FullFrame_s { 60 | uint8_t xLow; ///< x position low byte 61 | uint8_t yLow; ///< y position low byte 62 | uint8_t xyHighSize; ///< x and y position high byte and size 63 | uint8_t xMin; ///< x minimum (7 bit value) 64 | uint8_t yMin; ///< y minimum (7 bit value) 65 | uint8_t xMax; ///< x maximum (7 bit value) 66 | uint8_t yMax; ///< y maximum (7 bit value) 67 | uint8_t reserved; ///< 0 68 | uint8_t intensity; ///< 8 bit intensity value 69 | } __attribute__ ((packed)) FullFrame_t; 70 | 71 | /*! 72 | * @brief Position data structure to be filled from IIC data. 73 | */ 74 | typedef union PositionData_u { 75 | uint8_t receivedBuffer[13]; ///< received buffer for IIC read 76 | struct { 77 | uint8_t header; 78 | union { 79 | ExtendedFrame_t rawExtended[4]; ///< 4 raw extended positions/frames. 80 | BasicFrame_t rawBasic[2]; ///< 2 raw basic frames. 81 | } __attribute__ ((packed)) format; 82 | } __attribute__ ((packed)) frame; 83 | }__attribute__ ((packed)) PositionData_t; 84 | 85 | /*! 86 | * @brief Write two bytes into the sensor to initialize and send data. 87 | * 88 | * @param first the first byte 89 | * @param second the second byte 90 | */ 91 | void writeTwoIICByte(uint8_t first, uint8_t second); 92 | 93 | /*! 94 | * @brief Request the position data. IIC will block the progress until all the data is recevied. 95 | */ 96 | bool readPosition(PositionData_t& posData, unsigned int length); 97 | 98 | /*! 99 | * @brief Unconditionally unpack basic frame from positionData. Does not update seen flags. 100 | */ 101 | void unpackBasicFrame(unsigned int posData); 102 | 103 | /*! 104 | * @brief Unconditionally unpack extended frame from positionData. Does not update seen flags. 105 | */ 106 | void unpackExtendedFrame(unsigned int posData); 107 | 108 | /*! 109 | * @brief Unpack basic frame from positionData and update position if seen. Seen flags are updated. 110 | */ 111 | void unpackBasicFrameSeen(unsigned int posData); 112 | 113 | /*! 114 | * @brief Unpack extended frame from positionData and update position if seen. Seen flags are updated. 115 | */ 116 | void unpackExtendedFrameSeen(unsigned int posData); 117 | 118 | /*! 119 | * @brief Wire object to use. 120 | */ 121 | TwoWire& wire; 122 | 123 | /*! 124 | * @brief Raw postion data. 125 | */ 126 | PositionData_t positionData[2]; 127 | 128 | /*! 129 | * @brief Unpacked X positions. 130 | */ 131 | int positionX[4]; 132 | 133 | /*! 134 | * @brief Unpacked Y positions. 135 | */ 136 | int positionY[4]; 137 | 138 | /*! 139 | * @brief Unpacked sizes (when extended data format is used). 140 | */ 141 | int unpackedSizes[4]; 142 | 143 | /*! 144 | * @brief Bit mask of seen positions. 145 | */ 146 | unsigned int seenFlags; 147 | 148 | public: 149 | 150 | /*! 151 | * @brief Data format 152 | */ 153 | enum DataFormat_e { 154 | DataFormat_Basic = 0, ///< Basic data format. 155 | DataFormat_Extended = 1 ///< Extended data format that includes sizes. 156 | //DataFormat_Full = 3 ///< Full data format 157 | }; 158 | 159 | /*! 160 | * @brief Camera sensitivity. 161 | * @details Sensitivity levels from http://wiibrew.org/wiki/Wiimote#IR_Camera 162 | */ 163 | enum Sensitivity_e { 164 | Sensitivity_Min = 0, 165 | Sensitivity_Default = 0, ///< default setting from the original library, suggested by "Marcan" 166 | Sensitivity_High = 1, ///< high sensitivity, suggested by "inio" 167 | Sensitivity_Max = 2 ///< maximum sensitivity, suggested by "Kestrel" 168 | }; 169 | 170 | /*! 171 | * @brief Error codes. 172 | * @details Overall success can be be checked by comparing to >= Error_Success (0). 173 | */ 174 | enum Errors_e { 175 | Error_SuccessMismatch = 1, ///< Data mismatch but using last frame data 176 | Error_Success = 0, ///< Success 177 | Error_IICerror = -1, ///< IIC error 178 | Error_DataMismatch = -2, ///< Data mismatch 179 | }; 180 | 181 | /*! 182 | * @brief Retry options for atomic read workaround. 183 | * @details The optimal setting is to use Retry_1s. If paranoid then use Retry_2. The other settings 184 | * are for advanced use cases if update time is liminited. 185 | */ 186 | enum Retry_e { 187 | Retry_0 = 0, ///< No retries, return Error_DataMismatch if mismatch 188 | Retry_0s = 1, ///< No retries, if mismatch then use second frame and return Error_SuccessMismatch 189 | Retry_1 = 2, ///< 1 retry, return Error_DataMismatch if mismatch 190 | Retry_1s = 3, ///< 1 retry, optimal setting, if mismatch then use last frame and return Error_SuccessMismatch 191 | Retry_2 = 4, ///< 2 retries, return Error_DataMismatch if mismatch 192 | Retry_2s = 5 ///< 2 retries, if mismatch then use last frame and return Error_SuccessMismatch 193 | }; 194 | 195 | /*! 196 | * @brief Constructor 197 | */ 198 | DFRobotIRPositionEx(TwoWire& wire); 199 | 200 | /*! 201 | * @brief Destructor 202 | */ 203 | ~DFRobotIRPositionEx(); 204 | 205 | /*! 206 | * @brief Initialize the sensor. 207 | * @param[in] clock IIC clock rate. Defaults to 400kHz. Works up to at least 1MHz. 208 | * @param[in] format Initial data format. Defaults to basic. 209 | * @param[in] sensitivity Initial camera sensitivity. 210 | */ 211 | void begin(uint32_t clock = 400000, DataFormat_e format = DataFormat_Basic, Sensitivity_e sensitivity = Sensitivity_Default); 212 | 213 | /*! 214 | * @brief Set the data format. 215 | */ 216 | void dataFormat(DataFormat_e format); 217 | 218 | /*! 219 | * @brief Set the sensitivity. 220 | */ 221 | void sensitivityLevel(Sensitivity_e sensitivity); 222 | 223 | /*! 224 | * @brief Request the extended position data that includes sizes. 225 | * @details You must set the format to DataFormat_Extended. 226 | */ 227 | void requestPositionExtended(); 228 | 229 | /*! 230 | * @brief Request the basic position data. 231 | * @details You must set the format to DataFormat_Basic. 232 | */ 233 | void requestPositionBasic(); 234 | 235 | /*! 236 | * @brief After requesting the extended position, and the data read from the sensor is ready, True will be returned. 237 | * 238 | * @return Whether data reading is ready. 239 | * @retval true Is ready 240 | * @retval false Is not ready 241 | */ 242 | bool availableExtended(); 243 | 244 | /*! 245 | * @brief Same as availableExtended() but uncondionally unpacks the positions and doesn't update the seen flags. 246 | * @details Useful if you want the unpacked data for analysis. 247 | * 248 | * @return Whether data reading is ready. 249 | * @retval true Is ready 250 | * @retval false Is not ready 251 | */ 252 | bool availableExtendedNoSeen(); 253 | 254 | /*! 255 | * @brief After requesting the basic position, and the data read from the sensor is ready, True will be returned. 256 | * 257 | * @return Whether data reading is ready. 258 | * @retval true Is ready 259 | * @retval false Is not ready 260 | */ 261 | bool availableBasic(); 262 | 263 | /*! 264 | * @brief Same as availableBasic() but uncondionally unpacks the positions and doesn't update the seen flags. 265 | * @details Useful if you want the unpacked data for analysis. 266 | * 267 | * @return Whether data reading is ready. 268 | * @retval true Is ready 269 | * @retval false Is not ready 270 | */ 271 | bool availableBasicNoSeen(); 272 | 273 | /*! 274 | * @brief Atomically update basic position data. 275 | * @details Since there is no aparent signalling to synchronize the read when the position updates, 276 | * this uses a workaround. The position data is read twice and compared. If it is the same then the 277 | * positions are updated. 2 retries will be a maximum of 4 readings and should guarentee success. 278 | * @param[in] retries Number of extra times to retry getting and matching the position. 279 | * @return An error code from Errors_e. 280 | */ 281 | int basicAtomic(DFRobotIRPositionEx::Retry_e retry = DFRobotIRPositionEx::Retry_1s); 282 | 283 | /*! 284 | * @brief Atomically update extended position data that includes the size. 285 | * @details Since there is no aparent signalling to synchronize the read when the position updates, 286 | * this uses a workaround. The position data is read twice and compared. If it is the same then the 287 | * positions are updated. 2 retries will be a maximum of 4 readings and should guarentee success. 288 | * @param[in] retries Number of extra times to retry getting and matching the position. 289 | * @return An error code from Errors_e. 290 | */ 291 | int extendedAtomic(DFRobotIRPositionEx::Retry_e retries = DFRobotIRPositionEx::Retry_1s); 292 | 293 | /*! 294 | * @brief Get the X position of a point. 295 | * 296 | * @param index The index of the 4 light objects ranging from 0 to 3. 297 | * 298 | * @return The X position corresponing to the index. 299 | */ 300 | int x(int index) const { return positionX[index]; } 301 | 302 | /*! 303 | * @brief Get the Y position of a point. 304 | * 305 | * @param index The index of the 4 light objects ranging from 0 to 3. 306 | * 307 | * @return The Y position corresponing to the index. 308 | */ 309 | int y(int index) const { return positionY[index]; } 310 | 311 | /*! 312 | * @brief Get the size of a point. This will be 15 if empty. Must use Extended data format. 313 | * 314 | * @param index The index of the 4 light objects ranging from 0 to 3, 315 | * 316 | * @return The size corresponing to the index. 317 | */ 318 | int size(int index) const { return unpackedSizes[index]; } 319 | 320 | /*! 321 | * @brief Get the 4 X positions. 322 | * 323 | * @return Pointer to array of 4 X positions. 324 | */ 325 | const int* xPositions() const { return positionX; } 326 | 327 | /*! 328 | * @brief Get the 4 Y positions. 329 | * 330 | * @return Pointer to array of 4 Y positions. 331 | */ 332 | const int* yPositions() const { return positionY; } 333 | 334 | /*! 335 | * @brief Get the 4 sizes. Must use Extended data format. 336 | * 337 | * @return Pointer to array of 4 sizes. 338 | */ 339 | const int* sizes() const { return unpackedSizes; } 340 | 341 | /*! 342 | * @brief Get seen bit mask. Bits 0 through 3 are set to 1 when a position is seen and updated. 343 | * 344 | * @return Seen flags. 345 | */ 346 | unsigned int seen() const { return seenFlags; } 347 | }; 348 | 349 | #endif // DFRobotIRPositionEx_h 350 | -------------------------------------------------------------------------------- /libraries/LightgunButtons/COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /SamcoEnhanced/SamcoEnhanced.ino: -------------------------------------------------------------------------------- 1 | /*! 2 | * @file SamcoEnhanced.ino 3 | * @brief SAMCO Prow Enhanced - Arduino Powered Light Gun sketch for 4 IR LED setup. 4 | * Based on the 4IR Beta "Big Code Update" SAMCO project from https://github.com/samuelballantyne/IR-Light-Gun 5 | * 6 | * @copyright Samco, https://github.com/samuelballantyne, June 2020 7 | * @copyright Mike Lynch, July 2021 8 | * @copyright GNU Lesser General Public License 9 | * 10 | * @author [Sam Ballantyne](samuelballantyne@hotmail.com) 11 | * @author Mike Lynch 12 | * @version V1.0 13 | * @date 2021 14 | */ 15 | 16 | /* Default button assignments 17 | * 18 | * Reload will enter Pause mode. 19 | * 20 | * In Pause mode: 21 | * A, B, Start, Select, Up, Down, Left, Right: select a profile 22 | * Start + Down: Normal gun mode (averaging disabled) 23 | * Start + Up: Normal gun with averaging, toggles between the 2 averaging modes (use serial monitor to see the setting) 24 | * Start + A: Processing mode for use with the Processing sketch 25 | * B + Down: Decrease IR camera sensitivity (use serial monitor to see the setting) 26 | * B + Up: Increase IR camera sensitivity (use serial monitor to see the setting) 27 | * Reload: Exit pause mode 28 | * Trigger: Begin calibration 29 | * Start + Select: save settings to non-volatile memory 30 | * 31 | * Note that the buttons in pause mode (and to enter pause mode) activate when the last button of 32 | * the comination releases. 33 | * This is used to detect and differentiate button combinations vs a single button press. 34 | */ 35 | 36 | /* HOW TO CALIBRATE: 37 | * 38 | * Note: I renamed "offset" from the original sketch to "scale" which is a better term for what the setting is. 39 | * The center calibration step determines the offset compensation required for accurate positioning. 40 | * 41 | * Step 1: Press Reload to enter pause mode. 42 | * Optional: Press a button to select a profile: A, B, Start, Select, Up, Down, Left, Right 43 | * Step 2: Pull Trigger to begin calibration. 44 | * Step 3: Shoot cursor at center of the Screen and hold the trigger down for 1/3 of a second. 45 | * Step 4: Mouse should lock to vertical axis. Use A/B buttons (can be held down) buttons to adjust mouse vertical 46 | * range. A will increase, B will decrease. Track the top and bottom edges of the screen while adjusting. 47 | * Step 5: Pull Trigger 48 | * Step 6: Mouse should lock to horizontal axis. Use A/B buttons (can be held down) to adjust mouse horizontal 49 | * range. A will increase, B will decrease. Track the left and right edges of the screen while adjusting. 50 | * Step 7: Pull Trigger to finish and return to run mode. Values will apply to the selected profile. 51 | * Step 8: Recommended: Confirm calibration is good. Enter pause mode and press Start and Select 52 | * to write calibration to non-volatile memory. 53 | * Step 9: Optional: Open serial monitor and update xCenter, yCenter, xScale & yScale values in the 54 | * profile data array below. 55 | * 56 | * Calibration can be cancelled (return to pause mode) during any step by pressing Reload or Start or Select. 57 | */ 58 | 59 | #include 60 | #include 61 | 62 | // include TinyUSB or HID depending on USB stack option 63 | #if defined(USE_TINYUSB) 64 | #include 65 | #elif defined(CFG_TUSB_MCU) 66 | #error Incompatible USB stack. Use Arduino or Adafruit TinyUSB. 67 | #else 68 | // Arduino USB stack 69 | #include 70 | #endif 71 | 72 | #include 73 | #ifdef DOTSTAR_ENABLE 74 | #include 75 | #endif // DOTSTAR_ENABLE 76 | #ifdef NEOPIXEL_PIN 77 | #include 78 | #endif 79 | #ifdef SAMCO_FLASH_ENABLE 80 | #include 81 | #endif // SAMCO_FLASH_ENABLE 82 | #include 83 | #include 84 | #include 85 | #include 86 | #include 87 | #include 88 | #include "SamcoColours.h" 89 | #include "SamcoPreferences.h" 90 | 91 | #ifdef ARDUINO_ARCH_RP2040 92 | #include 93 | #include 94 | 95 | // declare PWM ISR 96 | void rp2040pwmIrq(void); 97 | #endif 98 | 99 | // enable extra serial debug during run mode 100 | //#define PRINT_VERBOSE 1 101 | //#define DEBUG_SERIAL 1 102 | //#define DEBUG_SERIAL 2 103 | 104 | // extra position glitch filtering, 105 | // not required after discoverving the DFRobotIRPositionEx atomic read technique 106 | //#define EXTRA_POS_GLITCH_FILTER 107 | 108 | // numbered index of physcial buttons, must match ButtonDesc[] order 109 | enum ButtonIndex_e { 110 | BtnIdx_Trigger = 0, 111 | BtnIdx_A, 112 | BtnIdx_B, 113 | BtnIdx_Start, 114 | BtnIdx_Select, 115 | BtnIdx_Up, 116 | BtnIdx_Down, 117 | BtnIdx_Left, 118 | BtnIdx_Right, 119 | BtnIdx_Reload, 120 | BtnIdx_Pedal 121 | }; 122 | 123 | // unique bit mask for each physical button, must match ButtonDesc[] order to match the proper button events 124 | enum ButtonMask_e { 125 | BtnMask_Trigger = 1 << BtnIdx_Trigger, 126 | BtnMask_A = 1 << BtnIdx_A, 127 | BtnMask_B = 1 << BtnIdx_B, 128 | BtnMask_Start = 1 << BtnIdx_Start, 129 | BtnMask_Select = 1 << BtnIdx_Select, 130 | BtnMask_Up = 1 << BtnIdx_Up, 131 | BtnMask_Down = 1 << BtnIdx_Down, 132 | BtnMask_Left = 1 << BtnIdx_Left, 133 | BtnMask_Right = 1 << BtnIdx_Right, 134 | BtnMask_Reload = 1 << BtnIdx_Reload, 135 | BtnMask_Pedal = 1 << BtnIdx_Pedal 136 | }; 137 | 138 | // Button descriptor 139 | // The order of the buttons is the order of the button bitmask 140 | // must match ButtonIndex_e order, and the named bitmask values for each button 141 | // see LightgunButtons::Desc_t 142 | // The format is: 143 | // {pin, report type, report code (ignored for internal), debounce time, debounce mask, label} 144 | const LightgunButtons::Desc_t LightgunButtons::ButtonDesc[] = { 145 | {7, LightgunButtons::ReportType_Mouse, MOUSE_BTN_LEFT, 20, BTN_AG_MASK, "Trigger"}, 146 | {A1, LightgunButtons::ReportType_Mouse, MOUSE_BTN_RIGHT, 20, BTN_AG_MASK2, "A"}, 147 | {A0, LightgunButtons::ReportType_Mouse, MOUSE_BTN_MIDDLE, 20, BTN_AG_MASK2, "B"}, 148 | {A2, LightgunButtons::ReportType_Keyboard, KEY_1, 25, BTN_AG_MASK2, "Start"}, 149 | {A3, LightgunButtons::ReportType_Keyboard, KEY_5, 25, BTN_AG_MASK2, "Select"}, 150 | {11, LightgunButtons::ReportType_Keyboard, KEY_UP, 25, BTN_AG_MASK2, "Up"}, 151 | {9, LightgunButtons::ReportType_Keyboard, KEY_DOWN, 25, BTN_AG_MASK2, "Down"}, 152 | {10, LightgunButtons::ReportType_Keyboard, KEY_LEFT, 25, BTN_AG_MASK2, "Left"}, 153 | {12, LightgunButtons::ReportType_Keyboard, KEY_RIGHT, 25, BTN_AG_MASK2, "Right"}, 154 | {13, LightgunButtons::ReportType_Internal, MOUSE_BTN_BACKWARD, 20, BTN_AG_MASK2, "Reload"}, 155 | {4, LightgunButtons::ReportType_Mouse, MOUSE_BTN_FORWARD, 20, BTN_AG_MASK2, "Pedal"} 156 | }; 157 | 158 | // button count constant 159 | constexpr unsigned int ButtonCount = sizeof(LightgunButtons::ButtonDesc) / sizeof(LightgunButtons::ButtonDesc[0]); 160 | 161 | // button runtime data arrays 162 | LightgunButtonsStatic lgbData; 163 | 164 | // button object instance 165 | LightgunButtons buttons(lgbData, ButtonCount); 166 | 167 | /* 168 | // WIP, some sort of generic button handler table for pause mode 169 | // pause button function 170 | typedef void (*PauseModeBtnFn_t)(); 171 | 172 | // pause mode function 173 | typedef struct PauseModeFnEntry_s { 174 | uint32_t buttonMask; 175 | PauseModeBtnFn_t pfn; 176 | } PauseModeFnEntry_t; 177 | */ 178 | 179 | // button combo to exit normal running mode and enter pause mode 180 | // this should be a unique combination you will never use during gameplay, 181 | // or a button with ReportType_Internal 182 | constexpr uint32_t EnterPauseModeBtnMask = BtnMask_Reload; 183 | 184 | // press any button to enter pause mode from Processing mode (this is not a button combo) 185 | constexpr uint32_t EnterPauseModeProcessingBtnMask = BtnMask_A | BtnMask_B | BtnMask_Reload; 186 | 187 | // button combo to exit pause mode back to run mode 188 | constexpr uint32_t ExitPauseModeBtnMask = BtnMask_Reload; 189 | 190 | // press any button to cancel the calibration (this is not a button combo) 191 | constexpr uint32_t CancelCalBtnMask = BtnMask_Reload | BtnMask_Start | BtnMask_Select; 192 | 193 | // button combo to skip the center calibration step 194 | constexpr uint32_t SkipCalCenterBtnMask = BtnMask_A; 195 | 196 | // button combo to save preferences to non-volatile memory 197 | constexpr uint32_t SaveBtnMask = BtnMask_Start | BtnMask_Select; 198 | 199 | // button combo to increase IR sensitivity 200 | constexpr uint32_t IRSensitivityUpBtnMask = BtnMask_B | BtnMask_Up; 201 | 202 | // button combo to decrease IR sensitivity 203 | constexpr uint32_t IRSensitivityDownBtnMask = BtnMask_B | BtnMask_Down; 204 | 205 | // button combinations to select a run mode 206 | constexpr uint32_t RunModeNormalBtnMask = BtnMask_Start | BtnMask_Down; 207 | constexpr uint32_t RunModeAverageBtnMask = BtnMask_Start | BtnMask_Up; 208 | constexpr uint32_t RunModeProcessingBtnMask = BtnMask_Start | BtnMask_A; 209 | 210 | // colour when no IR points are seen 211 | constexpr uint32_t IRSeen0Color = WikiColor::Amber; 212 | 213 | // colour when calibrating 214 | constexpr uint32_t CalModeColor = WikiColor::Red; 215 | 216 | // number of profiles 217 | constexpr unsigned int ProfileCount = 8; 218 | 219 | // run modes 220 | // note that this is a 5 bit value when stored in the profiles 221 | enum RunMode_e { 222 | RunMode_Normal = 0, ///< Normal gun mode, no averaging 223 | RunMode_Average = 1, ///< 2 frame moving average 224 | RunMode_Average2 = 2, ///< weighted average with 3 frames 225 | RunMode_ProfileMax = 2, ///< maximum mode allowed for profiles 226 | RunMode_Processing = 3, ///< Processing test mode 227 | RunMode_Count 228 | }; 229 | 230 | // profiles 231 | // defaults can be populated here, or not worry about these values and just save to flash/EEPROM 232 | // if you have original Samco calibration values, multiply by 4 for the center position and 233 | // scale is multiplied by 1000 and stored as an unsigned integer, see SamcoPreferences::Calibration_t 234 | SamcoPreferences::ProfileData_t profileData[ProfileCount] = { 235 | {1619, 950, MouseMaxX / 2, MouseMaxY / 2, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0}, 236 | {1233, 950, MouseMaxX / 2, MouseMaxY / 2, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0}, 237 | {1538, 855, MouseMaxX / 2, MouseMaxY / 2, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0}, 238 | {1147, 855, MouseMaxX / 2, MouseMaxY / 2, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0}, 239 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0}, 240 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0}, 241 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0}, 242 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal, 0, 0} 243 | }; 244 | /*SamcoPreferences::ProfileData_t profileData[profileCount] = { 245 | {1619, 950, 1899, 1531, DFRobotIRPositionEx::Sensitivity_Max, RunMode_Average}, 246 | {1233, 943, 1864, 1538, DFRobotIRPositionEx::Sensitivity_Max, RunMode_Average}, 247 | {1538, 855, 1878, 1515, DFRobotIRPositionEx::Sensitivity_High, RunMode_Average}, 248 | {1147, 855, 1889, 1507, DFRobotIRPositionEx::Sensitivity_High, RunMode_Average}, 249 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal}, 250 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal}, 251 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal}, 252 | {0, 0, 0, 0, DFRobotIRPositionEx::Sensitivity_Default, RunMode_Normal} 253 | };*/ 254 | 255 | // profile descriptor 256 | typedef struct ProfileDesc_s { 257 | // button(s) to select the profile 258 | uint32_t buttonMask; 259 | 260 | // LED colour 261 | uint32_t color; 262 | 263 | // button label 264 | const char* buttonLabel; 265 | 266 | // optional profile label 267 | const char* profileLabel; 268 | } ProfileDesc_t; 269 | 270 | // profile descriptor 271 | static const ProfileDesc_t profileDesc[ProfileCount] = { 272 | {BtnMask_A, WikiColor::Cerulean_blue, "A", "TV"}, 273 | {BtnMask_B, WikiColor::Cornflower_blue, "B", "TV 4:3"}, 274 | {BtnMask_Start, WikiColor::Green, "Start", "Monitor"}, 275 | {BtnMask_Select, WikiColor::Green_Lizard, "Select", "Monitor 4:3"}, 276 | {BtnMask_Up, WikiColor::Salmon, "Up", NULL}, 277 | {BtnMask_Down, WikiColor::Magenta, "Down", NULL}, 278 | {BtnMask_Left, WikiColor::Electric_indigo, "Left", NULL}, 279 | {BtnMask_Right, WikiColor::Cyan, "Right", NULL} 280 | }; 281 | 282 | // overall calibration defaults, no need to change if data saved to NV memory or populate the profile table 283 | // see profileData[] array below for specific profile defaults 284 | int xCenter = MouseMaxX / 2; 285 | int yCenter = MouseMaxY / 2; 286 | float xScale = 1.64; 287 | float yScale = 0.95; 288 | 289 | // step size for adjusting the scale 290 | constexpr float ScaleStep = 0.001; 291 | 292 | int finalX = 0; // Values after tilt correction 293 | int finalY = 0; 294 | 295 | int moveXAxis = 0; // Unconstrained mouse postion 296 | int moveYAxis = 0; 297 | int moveXAxisArr[3] = {0, 0, 0}; 298 | int moveYAxisArr[3] = {0, 0, 0}; 299 | int moveIndex = 0; 300 | 301 | int conMoveXAxis = 0; // Constrained mouse postion 302 | int conMoveYAxis = 0; 303 | 304 | unsigned int lastSeen = 0; 305 | 306 | #ifdef EXTRA_POS_GLITCH_FILTER 307 | int badFinalTick = 0; 308 | int badMoveTick = 0; 309 | int badFinalCount = 0; 310 | int badMoveCount = 0; 311 | 312 | // number of consecutive bad move values to filter 313 | constexpr unsigned int BadMoveCountThreshold = 3; 314 | 315 | // Used to filter out large jumps/glitches 316 | constexpr int BadMoveThreshold = 49 * CamToMouseMult; 317 | #endif // EXTRA_POS_GLITCH_FILTER 318 | 319 | // profile in use 320 | unsigned int selectedProfile = 0; 321 | 322 | // IR positioning camera 323 | #ifdef ARDUINO_ADAFRUIT_ITSYBITSY_RP2040 324 | DFRobotIRPositionEx dfrIRPos(Wire1); 325 | #else 326 | //DFRobotIRPosition myDFRobotIRPosition; 327 | DFRobotIRPositionEx dfrIRPos(Wire); 328 | #endif 329 | 330 | // Samco positioning 331 | SamcoPositionEnhanced mySamco; 332 | 333 | // operating modes 334 | enum GunMode_e { 335 | GunMode_Init = -1, 336 | GunMode_Run = 0, 337 | GunMode_CalHoriz = 1, 338 | GunMode_CalVert = 2, 339 | GunMode_CalCenter = 3, 340 | GunMode_Pause = 4 341 | }; 342 | GunMode_e gunMode = GunMode_Init; // initial mode 343 | 344 | // run mode 345 | RunMode_e runMode = RunMode_Normal; 346 | 347 | // IR camera sensitivity 348 | DFRobotIRPositionEx::Sensitivity_e irSensitivity = DFRobotIRPositionEx::Sensitivity_Default; 349 | 350 | static const char* RunModeLabels[RunMode_Count] = { 351 | "Normal", 352 | "Averaging", 353 | "Averaging2", 354 | "Processing" 355 | }; 356 | 357 | // preferences saved in non-volatile memory, populated with defaults 358 | SamcoPreferences::Preferences_t SamcoPreferences::preferences = { 359 | profileData, ProfileCount, // profiles 360 | 0, // default profile 361 | }; 362 | 363 | enum StateFlag_e { 364 | // print selected profile once per pause state when the COM port is open 365 | StateFlag_PrintSelectedProfile = (1 << 0), 366 | 367 | // report preferences once per pause state when the COM port is open 368 | StateFlag_PrintPreferences = (1 << 1), 369 | 370 | // enable save (allow save once per pause state) 371 | StateFlag_SavePreferencesEn = (1 << 2), 372 | 373 | // print preferences storage 374 | StateFlag_PrintPreferencesStorage = (1 << 3) 375 | }; 376 | 377 | // when serial connection resets, these flags are set 378 | constexpr uint32_t StateFlagsDtrReset = StateFlag_PrintSelectedProfile | StateFlag_PrintPreferences | StateFlag_PrintPreferencesStorage; 379 | 380 | // state flags, see StateFlag_e 381 | uint32_t stateFlags = StateFlagsDtrReset; 382 | 383 | 384 | #ifdef DOTSTAR_ENABLE 385 | // note if the colours don't match then change the colour format from BGR 386 | // apparently different lots of DotStars may have different colour ordering ¯\_(ツ)_/¯ 387 | Adafruit_DotStar dotstar(1, DOTSTAR_DATAPIN, DOTSTAR_CLOCKPIN, DOTSTAR_BGR); 388 | #endif // DOTSTAR_ENABLE 389 | 390 | #ifdef NEOPIXEL_PIN 391 | Adafruit_NeoPixel neopixel(1, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800); 392 | #endif // NEOPIXEL_PIN 393 | 394 | // flash transport instance 395 | #if defined(EXTERNAL_FLASH_USE_QSPI) 396 | Adafruit_FlashTransport_QSPI flashTransport; 397 | #elif defined(EXTERNAL_FLASH_USE_SPI) 398 | Adafruit_FlashTransport_SPI flashTransport(EXTERNAL_FLASH_USE_CS, EXTERNAL_FLASH_USE_SPI); 399 | #endif 400 | 401 | #ifdef SAMCO_FLASH_ENABLE 402 | // Adafruit_SPIFlashBase non-volatile storage 403 | // flash instance 404 | Adafruit_SPIFlashBase flash(&flashTransport); 405 | 406 | static const char* NVRAMlabel = "Flash"; 407 | 408 | // flag to indicate if non-volatile storage is available 409 | // this will enable in setup() 410 | bool nvAvailable = false; 411 | #endif // SAMCO_FLASH_ENABLE 412 | 413 | #ifdef SAMCO_EEPROM_ENABLE 414 | // EEPROM non-volatile storage 415 | static const char* NVRAMlabel = "EEPROM"; 416 | 417 | // flag to indicate if non-volatile storage is available 418 | // unconditional for EEPROM 419 | bool nvAvailable = true; 420 | #endif 421 | 422 | // non-volatile preferences error code 423 | int nvPrefsError = SamcoPreferences::Error_NoStorage; 424 | 425 | // preferences instance 426 | SamcoPreferences samcoPreferences; 427 | 428 | // number of times the IR camera will update per second 429 | constexpr unsigned int IRCamUpdateRate = 209; 430 | 431 | #ifdef SAMCO_NO_HW_TIMER 432 | // use the millis() or micros() counter instead 433 | unsigned long irPosUpdateTime = 0; 434 | // will set this to 1 when the IR position can update 435 | unsigned int irPosUpdateTick = 0; 436 | 437 | #define SAMCO_NO_HW_TIMER_UPDATE() NoHardwareTimerCamTickMillis() 438 | //define SAMCO_NO_HW_TIMER_UPDATE() NoHardwareTimerCamTickMicros() 439 | 440 | #else 441 | #define SAMCO_NO_HW_TIMER_UPDATE() 442 | // timer will set this to 1 when the IR position can update 443 | volatile unsigned int irPosUpdateTick = 0; 444 | #endif // SAMCO_NO_HW_TIMER 445 | 446 | #ifdef DEBUG_SERIAL 447 | static unsigned long serialDbMs = 0; 448 | static unsigned long frameCount = 0; 449 | static unsigned long irPosCount = 0; 450 | #endif 451 | 452 | // used for periodic serial prints 453 | unsigned long lastPrintMillis = 0; 454 | 455 | #ifdef USE_TINYUSB 456 | 457 | // USB HID Report ID 458 | enum HID_RID_e{ 459 | HID_RID_KEYBOARD = 1, 460 | HID_RID_MOUSE 461 | }; 462 | 463 | // HID report descriptor using TinyUSB's template 464 | uint8_t const hidReportDesc[] = { 465 | TUD_HID_REPORT_DESC_KEYBOARD(HID_REPORT_ID(HID_RID_KEYBOARD)), 466 | TUD_HID_REPORT_DESC_ABSMOUSE5_BASIC(HID_REPORT_ID(HID_RID_MOUSE)) 467 | }; 468 | 469 | // USB HID instance 470 | Adafruit_USBD_HID usbHid; 471 | 472 | // BasicKeyboard instance 473 | BasicKeyboard_ BasicKeyboard(HID_RID_KEYBOARD); 474 | 475 | // AbsMouse5 instance 476 | AbsMouse5_ AbsMouse5(HID_RID_MOUSE); 477 | 478 | #endif // USE_TINYUSB 479 | 480 | void setup() 481 | { 482 | // init DotStar and/or NeoPixel to red during setup() 483 | #ifdef DOTSTAR_ENABLE 484 | dotstar.begin(); 485 | dotstar.setPixelColor(0, 150, 0, 0); 486 | dotstar.show(); 487 | #endif // DOTSTAR_ENABLE 488 | #ifdef NEOPIXEL_ENABLEPIN 489 | pinMode(NEOPIXEL_ENABLEPIN, OUTPUT); 490 | digitalWrite(NEOPIXEL_ENABLEPIN, HIGH); 491 | #endif // NEOPIXEL_ENABLEPIN 492 | #ifdef NEOPIXEL_PIN 493 | neopixel.begin(); 494 | neopixel.setPixelColor(0, 255, 0, 0); 495 | neopixel.show(); 496 | #endif // NEOPIXEL_PIN 497 | 498 | #ifdef ARDUINO_ADAFRUIT_ITSYBITSY_RP2040 499 | // ensure Wire1 SDA and SCL are correct 500 | Wire1.setSDA(2); 501 | Wire1.setSCL(3); 502 | #endif 503 | 504 | // initialize buttons 505 | buttons.Begin(); 506 | 507 | #ifdef SAMCO_FLASH_ENABLE 508 | // init flash and load saved preferences 509 | nvAvailable = flash.begin(); 510 | #endif // SAMCO_FLASH_ENABLE 511 | 512 | if(nvAvailable) { 513 | LoadPreferences(); 514 | } 515 | 516 | // use values from preferences 517 | ApplyInitialPrefs(); 518 | 519 | // Start IR Camera with basic data format 520 | dfrIRPos.begin(DFROBOT_IR_IIC_CLOCK, DFRobotIRPositionEx::DataFormat_Basic, irSensitivity); 521 | 522 | #ifdef USE_TINYUSB 523 | usbHid.setPollInterval(2); 524 | usbHid.setReportDescriptor(hidReportDesc, sizeof(hidReportDesc)); 525 | //usb_hid.setStringDescriptor("TinyUSB HID Composite"); 526 | 527 | usbHid.begin(); 528 | #endif 529 | 530 | Serial.begin(115200); 531 | 532 | AbsMouse5.init(MouseMaxX, MouseMaxY, true); 533 | 534 | // sanity to ensure the cal prefs is populated with at least 1 entry 535 | // in case the table is zero'd out 536 | if(profileData[selectedProfile].xCenter == 0) { 537 | profileData[selectedProfile].xCenter = xCenter; 538 | } 539 | if(profileData[selectedProfile].yCenter == 0) { 540 | profileData[selectedProfile].yCenter = yCenter; 541 | } 542 | if(profileData[selectedProfile].xScale == 0) { 543 | profileData[selectedProfile].xScale = CalScaleFloatToPref(xScale); 544 | } 545 | if(profileData[selectedProfile].yScale == 0) { 546 | profileData[selectedProfile].yScale = CalScaleFloatToPref(yScale); 547 | } 548 | 549 | // fetch the calibration data, other values already handled in ApplyInitialPrefs() 550 | SelectCalPrefs(selectedProfile); 551 | 552 | #ifdef USE_TINYUSB 553 | // wait until device mounted 554 | while(!USBDevice.mounted()) { yield(); } 555 | #else 556 | // was getting weird hangups... maybe nothing, or maybe related to dragons, so wait a bit 557 | delay(100); 558 | #endif 559 | 560 | // IR camera maxes out motion detection at ~300Hz, and millis() isn't good enough 561 | startIrCamTimer(IRCamUpdateRate); 562 | 563 | // this will turn off the DotStar/RGB LED and ensure proper transition to Run 564 | SetMode(GunMode_Run); 565 | } 566 | 567 | void startIrCamTimer(int frequencyHz) 568 | { 569 | #if defined(SAMCO_SAMD21) 570 | startTimerEx(&TC4->COUNT16, GCLK_CLKCTRL_ID_TC4_TC5, TC4_IRQn, frequencyHz); 571 | #elif defined(SAMCO_SAMD51) 572 | startTimerEx(&TC3->COUNT16, TC3_GCLK_ID, TC3_IRQn, frequencyHz); 573 | #elif defined(SAMCO_ATMEGA32U4) 574 | startTimer3(frequencyHz); 575 | #elif defined(SAMCO_RP2040) 576 | rp2040EnablePWMTimer(0, frequencyHz); 577 | irq_set_exclusive_handler(PWM_IRQ_WRAP, rp2040pwmIrq); 578 | irq_set_enabled(PWM_IRQ_WRAP, true); 579 | #endif 580 | } 581 | 582 | #if defined(SAMCO_SAMD21) 583 | void startTimerEx(TcCount16* ptc, uint16_t gclkCtrlId, IRQn_Type irqn, int frequencyHz) 584 | { 585 | // use Generic clock generator 0 586 | GCLK->CLKCTRL.reg = (uint16_t)(GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | gclkCtrlId); 587 | while(GCLK->STATUS.bit.SYNCBUSY == 1); // wait for sync 588 | 589 | ptc->CTRLA.bit.ENABLE = 0; 590 | while(ptc->STATUS.bit.SYNCBUSY == 1); // wait for sync 591 | 592 | // Use the 16-bit timer 593 | ptc->CTRLA.reg |= TC_CTRLA_MODE_COUNT16; 594 | while(ptc->STATUS.bit.SYNCBUSY == 1); // wait for sync 595 | 596 | // Use match mode so that the timer counter resets when the count matches the compare register 597 | ptc->CTRLA.reg |= TC_CTRLA_WAVEGEN_MFRQ; 598 | while(ptc->STATUS.bit.SYNCBUSY == 1); // wait for sync 599 | 600 | // Set prescaler 601 | ptc->CTRLA.reg |= TIMER_TC_CTRLA_PRESCALER_DIV; 602 | while(ptc->STATUS.bit.SYNCBUSY == 1); // wait for sync 603 | 604 | setTimerFrequency(ptc, frequencyHz); 605 | 606 | // Enable the compare interrupt 607 | ptc->INTENSET.reg = 0; 608 | ptc->INTENSET.bit.MC0 = 1; 609 | 610 | NVIC_EnableIRQ(irqn); 611 | 612 | ptc->CTRLA.bit.ENABLE = 1; 613 | while(ptc->STATUS.bit.SYNCBUSY == 1); // wait for sync 614 | } 615 | 616 | void TC4_Handler() 617 | { 618 | // If this interrupt is due to the compare register matching the timer count 619 | if(TC4->COUNT16.INTFLAG.bit.MC0 == 1) { 620 | // clear interrupt 621 | TC4->COUNT16.INTFLAG.bit.MC0 = 1; 622 | 623 | irPosUpdateTick = 1; 624 | } 625 | } 626 | #endif // SAMCO_SAMD21 627 | 628 | #if defined(SAMCO_SAMD51) 629 | void startTimerEx(TcCount16* ptc, uint16_t gclkCtrlId, IRQn_Type irqn, int frequencyHz) 630 | { 631 | // use Generic clock generator 0 632 | GCLK->PCHCTRL[gclkCtrlId].reg = GCLK_PCHCTRL_GEN_GCLK0 | GCLK_PCHCTRL_CHEN; 633 | while(GCLK->SYNCBUSY.reg); // wait for sync 634 | 635 | ptc->CTRLA.bit.ENABLE = 0; 636 | while(ptc->SYNCBUSY.bit.STATUS == 1); // wait for sync 637 | 638 | // Use the 16-bit timer 639 | ptc->CTRLA.reg |= TC_CTRLA_MODE_COUNT16; 640 | while(ptc->SYNCBUSY.bit.STATUS == 1); // wait for sync 641 | 642 | // Use match mode so that the timer counter resets when the count matches the compare register 643 | ptc->WAVE.bit.WAVEGEN = TC_WAVE_WAVEGEN_MFRQ; 644 | while(ptc->SYNCBUSY.bit.STATUS == 1); // wait for sync 645 | 646 | // Set prescaler 647 | ptc->CTRLA.reg |= TIMER_TC_CTRLA_PRESCALER_DIV; 648 | while(ptc->SYNCBUSY.bit.STATUS == 1); // wait for sync 649 | 650 | setTimerFrequency(ptc, frequencyHz); 651 | 652 | // Enable the compare interrupt 653 | ptc->INTENSET.reg = 0; 654 | ptc->INTENSET.bit.MC0 = 1; 655 | 656 | NVIC_EnableIRQ(irqn); 657 | 658 | ptc->CTRLA.bit.ENABLE = 1; 659 | while(ptc->SYNCBUSY.bit.STATUS == 1); // wait for sync 660 | } 661 | 662 | void TC3_Handler() 663 | { 664 | // If this interrupt is due to the compare register matching the timer count 665 | if(TC3->COUNT16.INTFLAG.bit.MC0 == 1) { 666 | // clear interrupt 667 | TC3->COUNT16.INTFLAG.bit.MC0 = 1; 668 | 669 | irPosUpdateTick = 1; 670 | } 671 | } 672 | #endif // SAMCO_SAMD51 673 | 674 | #if defined(SAMCO_SAMD21) || defined(SAMCO_SAMD51) 675 | void setTimerFrequency(TcCount16* ptc, int frequencyHz) 676 | { 677 | int compareValue = (F_CPU / (TIMER_PRESCALER_DIV * frequencyHz)); 678 | 679 | // Make sure the count is in a proportional position to where it was 680 | // to prevent any jitter or disconnect when changing the compare value. 681 | ptc->COUNT.reg = map(ptc->COUNT.reg, 0, ptc->CC[0].reg, 0, compareValue); 682 | ptc->CC[0].reg = compareValue; 683 | 684 | #if defined(SAMCO_SAMD21) 685 | while(ptc->STATUS.bit.SYNCBUSY == 1); 686 | #elif defined(SAMCO_SAMD51) 687 | while(ptc->SYNCBUSY.bit.STATUS == 1); 688 | #endif 689 | } 690 | #endif 691 | 692 | #ifdef SAMCO_ATMEGA32U4 693 | void startTimer3(unsigned long frequencyHz) 694 | { 695 | // disable comapre output mode 696 | TCCR3A = 0; 697 | 698 | //set the pre-scalar to 8 and set Clear on Compare 699 | TCCR3B = (1 << CS31) | (1 << WGM32); 700 | 701 | // set compare value 702 | OCR3A = F_CPU / (8UL * frequencyHz); 703 | 704 | // enable Timer 3 Compare A interrupt 705 | TIMSK3 = 1 << OCIE3A; 706 | } 707 | 708 | // Timer3 compare A interrupt 709 | ISR(TIMER3_COMPA_vect) 710 | { 711 | irPosUpdateTick = 1; 712 | } 713 | #endif // SAMCO_ATMEGA32U4 714 | 715 | #ifdef ARDUINO_ARCH_RP2040 716 | void rp2040EnablePWMTimer(unsigned int slice_num, unsigned int frequency) 717 | { 718 | pwm_config pwmcfg = pwm_get_default_config(); 719 | float clkdiv = (float)clock_get_hz(clk_sys) / (float)(65535 * frequency); 720 | if(clkdiv < 1.0f) { 721 | clkdiv = 1.0f; 722 | } else { 723 | // really just need to round up 1 lsb 724 | clkdiv += 2.0f / (float)(1u << PWM_CH1_DIV_INT_LSB); 725 | } 726 | 727 | // set the clock divider in the config and fetch the actual value that is used 728 | pwm_config_set_clkdiv(&pwmcfg, clkdiv); 729 | clkdiv = (float)pwmcfg.div / (float)(1u << PWM_CH1_DIV_INT_LSB); 730 | 731 | // calculate wrap value that will trigger the IRQ for the target frequency 732 | pwm_config_set_wrap(&pwmcfg, (float)clock_get_hz(clk_sys) / (frequency * clkdiv)); 733 | 734 | // initialize and start the slice and enable IRQ 735 | pwm_init(slice_num, &pwmcfg, true); 736 | pwm_set_irq_enabled(slice_num, true); 737 | } 738 | 739 | void rp2040pwmIrq(void) 740 | { 741 | pwm_hw->intr = 0xff; 742 | irPosUpdateTick = 1; 743 | } 744 | #endif 745 | 746 | #ifdef SAMCO_NO_HW_TIMER 747 | void NoHardwareTimerCamTickMicros() 748 | { 749 | unsigned long us = micros(); 750 | if(us - irPosUpdateTime >= 1000000UL / IRCamUpdateRate) { 751 | irPosUpdateTime = us; 752 | irPosUpdateTick = 1; 753 | } 754 | } 755 | 756 | void NoHardwareTimerCamTickMillis() 757 | { 758 | unsigned long ms = millis(); 759 | if(ms - irPosUpdateTime >= (1000UL + (IRCamUpdateRate / 2)) / IRCamUpdateRate) { 760 | irPosUpdateTime = ms; 761 | irPosUpdateTick = 1; 762 | } 763 | } 764 | #endif // SAMCO_NO_HW_TIMER 765 | 766 | // Periodic yield to run USB tasks. Maybe only required for TinyUSB. 767 | unsigned long lastYieldMillis = 0; 768 | inline void USBYield() 769 | { 770 | // how frequently should yield() be called? gallop2WhoKnows 771 | // I searched the TinyUSB GitHub discussions and didn't find a definitive answer 772 | if(millis() - lastYieldMillis >= 2) { 773 | yield(); 774 | lastYieldMillis = millis(); 775 | } 776 | } 777 | 778 | void loop() 779 | { 780 | USBYield(); 781 | 782 | SAMCO_NO_HW_TIMER_UPDATE(); 783 | 784 | // poll/update button states with 1ms interval so debounce mask is more effective 785 | buttons.Poll(1); 786 | buttons.Repeat(); 787 | 788 | switch(gunMode) { 789 | case GunMode_Pause: 790 | if(buttons.pressedReleased == ExitPauseModeBtnMask) { 791 | SetMode(GunMode_Run); 792 | } else if(buttons.pressedReleased == BtnMask_Trigger) { 793 | SetMode(GunMode_CalCenter); 794 | } else if(buttons.pressedReleased == RunModeNormalBtnMask) { 795 | SetRunMode(RunMode_Normal); 796 | } else if(buttons.pressedReleased == RunModeAverageBtnMask) { 797 | SetRunMode(runMode == RunMode_Average ? RunMode_Average2 : RunMode_Average); 798 | } else if(buttons.pressedReleased == RunModeProcessingBtnMask) { 799 | SetRunMode(RunMode_Processing); 800 | } else if(buttons.pressedReleased == IRSensitivityUpBtnMask) { 801 | IncreaseIrSensitivity(); 802 | } else if(buttons.pressedReleased == IRSensitivityDownBtnMask) { 803 | DecreaseIrSensitivity(); 804 | } else if(buttons.pressedReleased == SaveBtnMask) { 805 | SavePreferences(); 806 | } else { 807 | SelectCalProfileFromBtnMask(buttons.pressedReleased); 808 | } 809 | 810 | PrintResults(); 811 | 812 | break; 813 | case GunMode_CalCenter: 814 | AbsMouse5.move(MouseMaxX / 2, MouseMaxY / 2); 815 | if(buttons.pressedReleased & CancelCalBtnMask) { 816 | CancelCalibration(); 817 | } else if(buttons.pressedReleased == SkipCalCenterBtnMask) { 818 | Serial.println("Calibrate Center skipped"); 819 | SetMode(GunMode_CalVert); 820 | } else if(buttons.pressed & BtnMask_Trigger) { 821 | // trigger pressed, begin center cal 822 | CalCenter(); 823 | // extra delay to wait for trigger to release (though not required) 824 | SetModeWaitNoButtons(GunMode_CalVert, 500); 825 | } 826 | break; 827 | case GunMode_CalVert: 828 | if(buttons.pressedReleased & CancelCalBtnMask) { 829 | CancelCalibration(); 830 | } else { 831 | if(buttons.pressed & BtnMask_Trigger) { 832 | SetMode(GunMode_CalHoriz); 833 | } else { 834 | CalVert(); 835 | } 836 | } 837 | break; 838 | case GunMode_CalHoriz: 839 | if(buttons.pressedReleased & CancelCalBtnMask) { 840 | CancelCalibration(); 841 | } else { 842 | if(buttons.pressed & BtnMask_Trigger) { 843 | ApplyCalToProfile(); 844 | SetMode(GunMode_Run); 845 | } else { 846 | CalHoriz(); 847 | } 848 | } 849 | break; 850 | default: 851 | /* ---------------------- LET'S GO --------------------------- */ 852 | switch(runMode) { 853 | case RunMode_Processing: 854 | ExecRunModeProcessing(); 855 | break; 856 | case RunMode_Average: 857 | case RunMode_Average2: 858 | case RunMode_Normal: 859 | default: 860 | ExecRunMode(); 861 | break; 862 | } 863 | break; 864 | } 865 | 866 | #ifdef DEBUG_SERIAL 867 | PrintDebugSerial(); 868 | #endif // DEBUG_SERIAL 869 | } 870 | 871 | /* ----------------------------------------------- */ 872 | /* --------------------------- METHODS ------------------------- */ 873 | /* ----------------------------------------------- */ 874 | 875 | void ExecRunMode() 876 | { 877 | #ifdef DEBUG_SERIAL 878 | Serial.print("exec run mode "); 879 | Serial.println(RunModeLabels[runMode]); 880 | #endif 881 | moveIndex = 0; 882 | buttons.ReportEnable(); 883 | for(;;) { 884 | USBYield(); 885 | 886 | buttons.Poll(0); 887 | 888 | SAMCO_NO_HW_TIMER_UPDATE(); 889 | if(irPosUpdateTick) { 890 | irPosUpdateTick = 0; 891 | GetPosition(); 892 | 893 | int halfHscale = (int)(mySamco.h() * xScale + 0.5f) / 2; 894 | moveXAxis = map(finalX, xCenter + halfHscale, xCenter - halfHscale, 0, MouseMaxX); 895 | halfHscale = (int)(mySamco.h() * yScale + 0.5f) / 2; 896 | moveYAxis = map(finalY, yCenter + halfHscale, yCenter - halfHscale, 0, MouseMaxY); 897 | 898 | switch(runMode) { 899 | case RunMode_Average: 900 | // 2 position moving average 901 | moveIndex ^= 1; 902 | moveXAxisArr[moveIndex] = moveXAxis; 903 | moveYAxisArr[moveIndex] = moveYAxis; 904 | moveXAxis = (moveXAxisArr[0] + moveXAxisArr[1]) / 2; 905 | moveYAxis = (moveYAxisArr[0] + moveYAxisArr[1]) / 2; 906 | break; 907 | case RunMode_Average2: 908 | // weighted average of current position and previous 2 909 | if(moveIndex < 2) { 910 | ++moveIndex; 911 | } else { 912 | moveIndex = 0; 913 | } 914 | moveXAxisArr[moveIndex] = moveXAxis; 915 | moveYAxisArr[moveIndex] = moveYAxis; 916 | moveXAxis = (moveXAxis + moveXAxisArr[0] + moveXAxisArr[1] + moveXAxisArr[1] + 2) / 4; 917 | moveYAxis = (moveYAxis + moveYAxisArr[0] + moveYAxisArr[1] + moveYAxisArr[1] + 2) / 4; 918 | break; 919 | case RunMode_Normal: 920 | default: 921 | break; 922 | } 923 | 924 | conMoveXAxis = constrain(moveXAxis, 0, MouseMaxX); 925 | conMoveYAxis = constrain(moveYAxis, 0, MouseMaxY); 926 | AbsMouse5.move(conMoveXAxis, conMoveYAxis); 927 | 928 | #ifdef DEBUG_SERIAL 929 | ++irPosCount; 930 | #endif // DEBUG_SERIAL 931 | } 932 | 933 | if(buttons.pressedReleased == EnterPauseModeBtnMask) { 934 | SetMode(GunMode_Pause); 935 | buttons.ReportDisable(); 936 | AbsMouse5.releaseAll(); 937 | BasicKeyboard.releaseAll(); 938 | return; 939 | } 940 | 941 | #ifdef DEBUG_SERIAL 942 | ++frameCount; 943 | PrintDebugSerial(); 944 | #endif // DEBUG_SERIAL 945 | } 946 | } 947 | 948 | // from Samco_4IR_Test_BETA sketch 949 | // for use with the Samco_4IR_Processing_Sketch_BETA Processing sketch 950 | void ExecRunModeProcessing() 951 | { 952 | // constant offset added to output values 953 | const int processingOffset = 100; 954 | 955 | buttons.ReportDisable(); 956 | for(;;) { 957 | USBYield(); 958 | 959 | buttons.Poll(1); 960 | if(buttons.pressedReleased & EnterPauseModeProcessingBtnMask) { 961 | SetMode(GunMode_Pause); 962 | return; 963 | } 964 | 965 | SAMCO_NO_HW_TIMER_UPDATE(); 966 | if(irPosUpdateTick) { 967 | irPosUpdateTick = 0; 968 | 969 | int error = dfrIRPos.basicAtomic(DFRobotIRPositionEx::Retry_2); 970 | if(error == DFRobotIRPositionEx::Error_Success) { 971 | mySamco.begin(dfrIRPos.xPositions(), dfrIRPos.yPositions(), dfrIRPos.seen(), MouseMaxX / 2, MouseMaxY / 2); 972 | UpdateLastSeen(); 973 | for(int i = 0; i < 4; i++) { 974 | Serial.print(map(mySamco.testX(i), 0, MouseMaxX, CamMaxX, 0) + processingOffset); 975 | Serial.print(","); 976 | Serial.print(map(mySamco.testY(i), 0, MouseMaxY, CamMaxY, 0) + processingOffset); 977 | Serial.print(","); 978 | } 979 | Serial.print(map(mySamco.x(), 0, MouseMaxX, CamMaxX, 0) + processingOffset); 980 | Serial.print(","); 981 | Serial.print(map(mySamco.y(), 0, MouseMaxY, CamMaxY, 0) + processingOffset); 982 | Serial.print(","); 983 | Serial.print(map(mySamco.testMedianX(), 0, MouseMaxX, CamMaxX, 0) + processingOffset); 984 | Serial.print(","); 985 | Serial.println(map(mySamco.testMedianY(), 0, MouseMaxY, CamMaxY, 0) + processingOffset); 986 | } else if(error == DFRobotIRPositionEx::Error_IICerror) { 987 | Serial.println("Device not available!"); 988 | } 989 | } 990 | } 991 | } 992 | 993 | // center calibration with a bit of averaging 994 | void CalCenter() 995 | { 996 | unsigned int xAcc = 0; 997 | unsigned int yAcc = 0; 998 | unsigned int count = 0; 999 | unsigned long ms = millis(); 1000 | 1001 | // accumulate center position over a bit of time for some averaging 1002 | while(millis() - ms < 333) { 1003 | // center pointer 1004 | AbsMouse5.move(MouseMaxX / 2, MouseMaxY / 2); 1005 | 1006 | // get position 1007 | if(GetPositionIfReady()) { 1008 | xAcc += finalX; 1009 | yAcc += finalY; 1010 | count++; 1011 | 1012 | xCenter = finalX; 1013 | yCenter = finalY; 1014 | PrintCalInterval(); 1015 | } 1016 | 1017 | // poll buttons 1018 | buttons.Poll(1); 1019 | 1020 | // if trigger not pressed then break out of loop early 1021 | if(!(buttons.debounced & BtnMask_Trigger)) { 1022 | break; 1023 | } 1024 | } 1025 | 1026 | // unexpected, but make sure x and y positions are accumulated 1027 | if(count) { 1028 | xCenter = xAcc / count; 1029 | yCenter = yAcc / count; 1030 | } else { 1031 | Serial.print("Unexpected Center calibration failure, no center position was acquired!"); 1032 | // just continue anyway 1033 | } 1034 | 1035 | PrintCalInterval(); 1036 | } 1037 | 1038 | // vertical calibration 1039 | void CalVert() 1040 | { 1041 | if(GetPositionIfReady()) { 1042 | int halfH = (int)(mySamco.h() * yScale + 0.5f) / 2; 1043 | moveYAxis = map(finalY, yCenter + halfH, yCenter - halfH, 0, MouseMaxY); 1044 | conMoveXAxis = MouseMaxX / 2; 1045 | conMoveYAxis = constrain(moveYAxis, 0, MouseMaxY); 1046 | AbsMouse5.move(conMoveXAxis, conMoveYAxis); 1047 | } 1048 | 1049 | if(buttons.repeat & BtnMask_B) { 1050 | yScale = yScale + ScaleStep; 1051 | } 1052 | 1053 | if(buttons.repeat & BtnMask_A) { 1054 | if(yScale > 0.005f) { 1055 | yScale = yScale - ScaleStep; 1056 | } 1057 | } 1058 | 1059 | if(buttons.pressedReleased == BtnMask_Up) { 1060 | yCenter--; 1061 | } else if(buttons.pressedReleased == BtnMask_Down) { 1062 | yCenter++; 1063 | } 1064 | 1065 | PrintCalInterval(); 1066 | } 1067 | 1068 | // horizontal calibration 1069 | void CalHoriz() 1070 | { 1071 | if(GetPositionIfReady()) { 1072 | int halfH = (int)(mySamco.h() * xScale + 0.5f) / 2; 1073 | moveXAxis = map(finalX, xCenter + halfH, xCenter - halfH, 0, MouseMaxX); 1074 | conMoveXAxis = constrain(moveXAxis, 0, MouseMaxX); 1075 | conMoveYAxis = MouseMaxY / 2; 1076 | AbsMouse5.move(conMoveXAxis, conMoveYAxis); 1077 | } 1078 | 1079 | if(buttons.repeat & BtnMask_B) { 1080 | xScale = xScale + ScaleStep; 1081 | } 1082 | 1083 | if(buttons.repeat & BtnMask_A) { 1084 | if(xScale > 0.005f) { 1085 | xScale = xScale - ScaleStep; 1086 | } 1087 | } 1088 | 1089 | if(buttons.pressedReleased == BtnMask_Left) { 1090 | xCenter--; 1091 | } else if(buttons.pressedReleased == BtnMask_Right) { 1092 | xCenter++; 1093 | } 1094 | 1095 | PrintCalInterval(); 1096 | } 1097 | 1098 | // Helper to get position if the update tick is set 1099 | bool GetPositionIfReady() 1100 | { 1101 | if(irPosUpdateTick) { 1102 | irPosUpdateTick = 0; 1103 | GetPosition(); 1104 | return true; 1105 | } 1106 | return false; 1107 | } 1108 | 1109 | // Get tilt adjusted position from IR postioning camera 1110 | // Updates finalX and finalY values 1111 | void GetPosition() 1112 | { 1113 | int error = dfrIRPos.basicAtomic(DFRobotIRPositionEx::Retry_2); 1114 | if(error == DFRobotIRPositionEx::Error_Success) { 1115 | mySamco.begin(dfrIRPos.xPositions(), dfrIRPos.yPositions(), dfrIRPos.seen(), xCenter, yCenter); 1116 | #ifdef EXTRA_POS_GLITCH_FILTER 1117 | if((abs(mySamco.X() - finalX) > BadMoveThreshold || abs(mySamco.Y() - finalY) > BadMoveThreshold) && badFinalTick < BadMoveCountThreshold) { 1118 | ++badFinalTick; 1119 | } else { 1120 | if(badFinalTick) { 1121 | badFinalCount++; 1122 | badFinalTick = 0; 1123 | } 1124 | finalX = mySamco.X(); 1125 | finalY = mySamco.Y(); 1126 | } 1127 | #else 1128 | finalX = mySamco.x(); 1129 | finalY = mySamco.y(); 1130 | #endif // EXTRA_POS_GLITCH_FILTER 1131 | 1132 | UpdateLastSeen(); 1133 | #if DEBUG_SERIAL == 2 1134 | Serial.print(finalX); 1135 | Serial.print(' '); 1136 | Serial.print(finalY); 1137 | Serial.print(" "); 1138 | Serial.println(mySamco.h()); 1139 | #endif 1140 | } else if(error != DFRobotIRPositionEx::Error_DataMismatch) { 1141 | Serial.println("Device not available!"); 1142 | } 1143 | } 1144 | 1145 | // wait up to given amount of time for no buttons to be pressed before setting the mode 1146 | void SetModeWaitNoButtons(GunMode_e newMode, unsigned long maxWait) 1147 | { 1148 | unsigned long ms = millis(); 1149 | while(buttons.debounced && (millis() - ms < maxWait)) { 1150 | buttons.Poll(1); 1151 | } 1152 | SetMode(newMode); 1153 | } 1154 | 1155 | // update the last seen value 1156 | // only to be called during run mode since this will modify the LED colour 1157 | void UpdateLastSeen() { 1158 | if(lastSeen != mySamco.seen()) { 1159 | if(!lastSeen && mySamco.seen()) { 1160 | LedOff(); 1161 | } else if(lastSeen && !mySamco.seen()) { 1162 | SetLedPackedColor(IRSeen0Color); 1163 | } 1164 | lastSeen = mySamco.seen(); 1165 | } 1166 | } 1167 | 1168 | void SetMode(GunMode_e newMode) 1169 | { 1170 | if(gunMode == newMode) { 1171 | return; 1172 | } 1173 | 1174 | // exit current mode 1175 | switch(gunMode) { 1176 | case GunMode_Run: 1177 | stateFlags |= StateFlag_PrintPreferences; 1178 | break; 1179 | case GunMode_CalHoriz: 1180 | break; 1181 | case GunMode_CalVert: 1182 | break; 1183 | case GunMode_CalCenter: 1184 | break; 1185 | case GunMode_Pause: 1186 | break; 1187 | } 1188 | 1189 | // enter new mode 1190 | gunMode = newMode; 1191 | switch(newMode) { 1192 | case GunMode_Run: 1193 | // begin run mode with all 4 points seen 1194 | lastSeen = 0x0F; 1195 | break; 1196 | case GunMode_CalHoriz: 1197 | break; 1198 | case GunMode_CalVert: 1199 | break; 1200 | case GunMode_CalCenter: 1201 | break; 1202 | case GunMode_Pause: 1203 | stateFlags |= StateFlag_SavePreferencesEn | StateFlag_PrintSelectedProfile; 1204 | break; 1205 | } 1206 | 1207 | SetLedColorFromMode(); 1208 | } 1209 | 1210 | // set new run mode and apply it to the selected profile 1211 | void SetRunMode(RunMode_e newMode) 1212 | { 1213 | if(newMode >= RunMode_Count) { 1214 | return; 1215 | } 1216 | 1217 | // block Processing/test modes being applied to a profile 1218 | if(newMode <= RunMode_ProfileMax && profileData[selectedProfile].runMode != newMode) { 1219 | profileData[selectedProfile].runMode = newMode; 1220 | stateFlags |= StateFlag_SavePreferencesEn; 1221 | } 1222 | 1223 | if(runMode != newMode) { 1224 | runMode = newMode; 1225 | if(!(stateFlags & StateFlag_PrintSelectedProfile)) { 1226 | PrintRunMode(); 1227 | } 1228 | } 1229 | } 1230 | 1231 | void PrintResults() 1232 | { 1233 | if(millis() - lastPrintMillis < 100) { 1234 | return; 1235 | } 1236 | 1237 | if(!Serial.dtr()) { 1238 | stateFlags |= StateFlagsDtrReset; 1239 | return; 1240 | } 1241 | 1242 | PrintPreferences(); 1243 | /* 1244 | Serial.print(finalX); 1245 | Serial.print(" ("); 1246 | Serial.print(MoveXAxis); 1247 | Serial.print("), "); 1248 | Serial.print(finalY); 1249 | Serial.print(" ("); 1250 | Serial.print(MoveYAxis); 1251 | Serial.print("), H "); 1252 | Serial.println(mySamco.H());*/ 1253 | 1254 | //Serial.print("conMove "); 1255 | //Serial.print(conMoveXAxis); 1256 | //Serial.println(conMoveYAxis); 1257 | 1258 | if(stateFlags & StateFlag_PrintSelectedProfile) { 1259 | stateFlags &= ~StateFlag_PrintSelectedProfile; 1260 | PrintSelectedProfile(); 1261 | PrintIrSensitivity(); 1262 | PrintRunMode(); 1263 | PrintCal(); 1264 | } 1265 | 1266 | lastPrintMillis = millis(); 1267 | } 1268 | 1269 | void PrintCalInterval() 1270 | { 1271 | if(millis() - lastPrintMillis < 100) { 1272 | return; 1273 | } 1274 | PrintCal(); 1275 | lastPrintMillis = millis(); 1276 | } 1277 | 1278 | void PrintCal() 1279 | { 1280 | Serial.print("Calibration: Center x,y: "); 1281 | Serial.print(xCenter); 1282 | Serial.print(","); 1283 | Serial.print(yCenter); 1284 | Serial.print(" Scale x,y: "); 1285 | Serial.print(xScale, 3); 1286 | Serial.print(","); 1287 | Serial.println(yScale, 3); 1288 | } 1289 | 1290 | void PrintRunMode() 1291 | { 1292 | if(runMode < RunMode_Count) { 1293 | Serial.print("Mode: "); 1294 | Serial.println(RunModeLabels[runMode]); 1295 | } 1296 | } 1297 | 1298 | // helper in case this changes 1299 | float CalScalePrefToFloat(uint16_t scale) 1300 | { 1301 | return (float)scale / 1000.0f; 1302 | } 1303 | 1304 | // helper in case this changes 1305 | uint16_t CalScaleFloatToPref(float scale) 1306 | { 1307 | return (uint16_t)(scale * 1000.0f); 1308 | } 1309 | 1310 | void PrintPreferences() 1311 | { 1312 | if(!(stateFlags & StateFlag_PrintPreferences) || !Serial.dtr()) { 1313 | return; 1314 | } 1315 | 1316 | stateFlags &= ~StateFlag_PrintPreferences; 1317 | 1318 | PrintNVPrefsError(); 1319 | 1320 | if(stateFlags & StateFlag_PrintPreferencesStorage) { 1321 | stateFlags &= ~StateFlag_PrintPreferencesStorage; 1322 | PrintNVStorage(); 1323 | } 1324 | 1325 | Serial.print("Default Profile: "); 1326 | Serial.println(profileDesc[SamcoPreferences::preferences.profile].profileLabel); 1327 | 1328 | Serial.println("Profiles:"); 1329 | for(unsigned int i = 0; i < SamcoPreferences::preferences.profileCount; ++i) { 1330 | // report if a profile has been cal'd 1331 | if(profileData[i].xCenter && profileData[i].yCenter) { 1332 | size_t len = strlen(profileDesc[i].buttonLabel) + 2; 1333 | Serial.print(profileDesc[i].buttonLabel); 1334 | Serial.print(": "); 1335 | if(profileDesc[i].profileLabel && profileDesc[i].profileLabel[0]) { 1336 | Serial.print(profileDesc[i].profileLabel); 1337 | len += strlen(profileDesc[i].profileLabel); 1338 | } 1339 | while(len < 26) { 1340 | Serial.print(' '); 1341 | ++len; 1342 | } 1343 | Serial.print("Center: "); 1344 | Serial.print(profileData[i].xCenter); 1345 | Serial.print(","); 1346 | Serial.print(profileData[i].yCenter); 1347 | Serial.print(" Scale: "); 1348 | Serial.print(CalScalePrefToFloat(profileData[i].xScale), 3); 1349 | Serial.print(","); 1350 | Serial.print(CalScalePrefToFloat(profileData[i].yScale), 3); 1351 | Serial.print(" IR: "); 1352 | Serial.print((unsigned int)profileData[i].irSensitivity); 1353 | Serial.print(" Mode: "); 1354 | Serial.println((unsigned int)profileData[i].runMode); 1355 | } 1356 | } 1357 | } 1358 | 1359 | void PrintNVStorage() 1360 | { 1361 | #ifdef SAMCO_FLASH_ENABLE 1362 | unsigned int required = SamcoPreferences::Size(); 1363 | #ifndef PRINT_VERBOSE 1364 | if(required < flash.size()) { 1365 | return; 1366 | } 1367 | #endif 1368 | Serial.print("NV Storage capacity: "); 1369 | Serial.print(flash.size()); 1370 | Serial.print(", required size: "); 1371 | Serial.println(required); 1372 | #ifdef PRINT_VERBOSE 1373 | Serial.print("Profile struct size: "); 1374 | Serial.print((unsigned int)sizeof(SamcoPreferences::ProfileData_t)); 1375 | Serial.print(", Profile data array size: "); 1376 | Serial.println((unsigned int)sizeof(profileData)); 1377 | #endif 1378 | #endif // SAMCO_FLASH_ENABLE 1379 | } 1380 | 1381 | void PrintNVPrefsError() 1382 | { 1383 | if(nvPrefsError != SamcoPreferences::Error_Success) { 1384 | Serial.print(NVRAMlabel); 1385 | Serial.print(" error: "); 1386 | #ifdef SAMCO_FLASH_ENABLE 1387 | Serial.println(SamcoPreferences::ErrorCodeToString(nvPrefsError)); 1388 | #else 1389 | Serial.println(nvPrefsError); 1390 | #endif // SAMCO_FLASH_ENABLE 1391 | } 1392 | } 1393 | 1394 | void LoadPreferences() 1395 | { 1396 | if(!nvAvailable) { 1397 | return; 1398 | } 1399 | 1400 | #ifdef SAMCO_FLASH_ENABLE 1401 | nvPrefsError = SamcoPreferences::Load(flash); 1402 | #else 1403 | nvPrefsError = samcoPreferences.Load(); 1404 | #endif // SAMCO_FLASH_ENABLE 1405 | VerifyPreferences(); 1406 | } 1407 | 1408 | void VerifyPreferences() 1409 | { 1410 | // center 0 is used as "no cal data" 1411 | for(unsigned int i = 0; i < ProfileCount; ++i) { 1412 | if(profileData[i].xCenter >= MouseMaxX || profileData[i].yCenter >= MouseMaxY || profileData[i].xScale == 0 || profileData[i].yScale == 0) { 1413 | profileData[i].xCenter = 0; 1414 | profileData[i].yCenter = 0; 1415 | } 1416 | 1417 | // if the scale values are large, assign 0 so the values will be ignored 1418 | if(profileData[i].xScale >= 30000) { 1419 | profileData[i].xScale = 0; 1420 | } 1421 | if(profileData[i].yScale >= 30000) { 1422 | profileData[i].yScale = 0; 1423 | } 1424 | 1425 | if(profileData[i].irSensitivity > DFRobotIRPositionEx::Sensitivity_Max) { 1426 | profileData[i].irSensitivity = DFRobotIRPositionEx::Sensitivity_Default; 1427 | } 1428 | 1429 | if(profileData[i].runMode >= RunMode_Count) { 1430 | profileData[i].runMode = RunMode_Normal; 1431 | } 1432 | } 1433 | 1434 | // if default profile is not valid, use current selected profile instead 1435 | if(SamcoPreferences::preferences.profile >= ProfileCount) { 1436 | SamcoPreferences::preferences.profile = (uint8_t)selectedProfile; 1437 | } 1438 | } 1439 | 1440 | // Apply initial preferences, intended to be called only in setup() after LoadPreferences() 1441 | // this will apply the preferences data as the initial values 1442 | void ApplyInitialPrefs() 1443 | { 1444 | // if default profile is valid then use it 1445 | if(SamcoPreferences::preferences.profile < ProfileCount) { 1446 | // note, just set the value here not call the function to do the set 1447 | selectedProfile = SamcoPreferences::preferences.profile; 1448 | 1449 | // set the current IR camera sensitivity 1450 | if(profileData[selectedProfile].irSensitivity <= DFRobotIRPositionEx::Sensitivity_Max) { 1451 | irSensitivity = (DFRobotIRPositionEx::Sensitivity_e)profileData[selectedProfile].irSensitivity; 1452 | } 1453 | 1454 | // set the run mode 1455 | if(profileData[selectedProfile].runMode < RunMode_Count) { 1456 | runMode = (RunMode_e)profileData[selectedProfile].runMode; 1457 | } 1458 | } 1459 | } 1460 | 1461 | void SavePreferences() 1462 | { 1463 | if(!nvAvailable || !(stateFlags & StateFlag_SavePreferencesEn)) { 1464 | return; 1465 | } 1466 | 1467 | // Only allow one write per pause state until something changes. 1468 | // Extra protection to ensure the same data can't write a bunch of times. 1469 | stateFlags &= ~StateFlag_SavePreferencesEn; 1470 | 1471 | // use selected profile as the default 1472 | SamcoPreferences::preferences.profile = (uint8_t)selectedProfile; 1473 | 1474 | #ifdef SAMCO_FLASH_ENABLE 1475 | nvPrefsError = SamcoPreferences::Save(flash); 1476 | #else 1477 | nvPrefsError = SamcoPreferences::Save(); 1478 | #endif // SAMCO_FLASH_ENABLE 1479 | if(nvPrefsError == SamcoPreferences::Error_Success) { 1480 | Serial.print("Settings saved to "); 1481 | Serial.println(NVRAMlabel); 1482 | } else { 1483 | Serial.println("Error saving Preferences."); 1484 | PrintNVPrefsError(); 1485 | } 1486 | } 1487 | 1488 | void SelectCalProfileFromBtnMask(uint32_t mask) 1489 | { 1490 | // only check if buttons are set in the mask 1491 | if(!mask) { 1492 | return; 1493 | } 1494 | for(unsigned int i = 0; i < ProfileCount; ++i) { 1495 | if(profileDesc[i].buttonMask == mask) { 1496 | SelectCalProfile(i); 1497 | return; 1498 | } 1499 | } 1500 | } 1501 | 1502 | void CycleIrSensitivity() 1503 | { 1504 | uint8_t sens = irSensitivity; 1505 | if(irSensitivity < DFRobotIRPositionEx::Sensitivity_Max) { 1506 | sens++; 1507 | } else { 1508 | sens = DFRobotIRPositionEx::Sensitivity_Min; 1509 | } 1510 | SetIrSensitivity(sens); 1511 | } 1512 | 1513 | void IncreaseIrSensitivity() 1514 | { 1515 | uint8_t sens = irSensitivity; 1516 | if(irSensitivity < DFRobotIRPositionEx::Sensitivity_Max) { 1517 | sens++; 1518 | SetIrSensitivity(sens); 1519 | } 1520 | } 1521 | 1522 | void DecreaseIrSensitivity() 1523 | { 1524 | uint8_t sens = irSensitivity; 1525 | if(irSensitivity > DFRobotIRPositionEx::Sensitivity_Min) { 1526 | sens--; 1527 | SetIrSensitivity(sens); 1528 | } 1529 | } 1530 | 1531 | // set a new IR camera sensitivity and apply to the selected profile 1532 | void SetIrSensitivity(uint8_t sensitivity) 1533 | { 1534 | if(sensitivity > DFRobotIRPositionEx::Sensitivity_Max) { 1535 | return; 1536 | } 1537 | 1538 | if(profileData[selectedProfile].irSensitivity != sensitivity) { 1539 | profileData[selectedProfile].irSensitivity = sensitivity; 1540 | stateFlags |= StateFlag_SavePreferencesEn; 1541 | } 1542 | 1543 | if(irSensitivity != (DFRobotIRPositionEx::Sensitivity_e)sensitivity) { 1544 | irSensitivity = (DFRobotIRPositionEx::Sensitivity_e)sensitivity; 1545 | dfrIRPos.sensitivityLevel(irSensitivity); 1546 | if(!(stateFlags & StateFlag_PrintSelectedProfile)) { 1547 | PrintIrSensitivity(); 1548 | } 1549 | } 1550 | } 1551 | 1552 | void PrintIrSensitivity() 1553 | { 1554 | Serial.print("IR Camera Sensitivity: "); 1555 | Serial.println((int)irSensitivity); 1556 | } 1557 | 1558 | void CancelCalibration() 1559 | { 1560 | Serial.println("Calibration cancelled"); 1561 | // re-print the profile 1562 | stateFlags |= StateFlag_PrintSelectedProfile; 1563 | // re-apply the cal stored in the profile 1564 | RevertToCalProfile(selectedProfile); 1565 | // return to pause mode 1566 | SetMode(GunMode_Pause); 1567 | } 1568 | 1569 | void PrintSelectedProfile() 1570 | { 1571 | Serial.print("Profile: "); 1572 | Serial.println(profileDesc[selectedProfile].profileLabel); 1573 | } 1574 | 1575 | // select a profile 1576 | bool SelectCalProfile(unsigned int profile) 1577 | { 1578 | if(profile >= ProfileCount) { 1579 | return false; 1580 | } 1581 | 1582 | if(selectedProfile != profile) { 1583 | stateFlags |= StateFlag_PrintSelectedProfile; 1584 | selectedProfile = profile; 1585 | } 1586 | 1587 | bool valid = SelectCalPrefs(profile); 1588 | 1589 | // set IR sensitivity 1590 | if(profileData[profile].irSensitivity <= DFRobotIRPositionEx::Sensitivity_Max) { 1591 | SetIrSensitivity(profileData[profile].irSensitivity); 1592 | } 1593 | 1594 | // set run mode 1595 | if(profileData[profile].runMode < RunMode_Count) { 1596 | SetRunMode((RunMode_e)profileData[profile].runMode); 1597 | } 1598 | 1599 | SetLedColorFromMode(); 1600 | 1601 | // enable save to allow setting new default profile 1602 | stateFlags |= StateFlag_SavePreferencesEn; 1603 | return valid; 1604 | } 1605 | 1606 | bool SelectCalPrefs(unsigned int profile) 1607 | { 1608 | if(profile >= ProfileCount) { 1609 | return false; 1610 | } 1611 | 1612 | // if center values are set, assume profile is populated 1613 | if(profileData[profile].xCenter && profileData[profile].yCenter) { 1614 | xCenter = profileData[profile].xCenter; 1615 | yCenter = profileData[profile].yCenter; 1616 | 1617 | // 0 scale will be ignored 1618 | if(profileData[profile].xScale) { 1619 | xScale = CalScalePrefToFloat(profileData[profile].xScale); 1620 | } 1621 | if(profileData[profile].yScale) { 1622 | yScale = CalScalePrefToFloat(profileData[profile].yScale); 1623 | } 1624 | return true; 1625 | } 1626 | return false; 1627 | } 1628 | 1629 | // revert back to useable settings, even if not cal'd 1630 | void RevertToCalProfile(unsigned int profile) 1631 | { 1632 | // if the current profile isn't valid 1633 | if(!SelectCalProfile(profile)) { 1634 | // revert to settings from any valid profile 1635 | for(unsigned int i = 0; i < ProfileCount; ++i) { 1636 | if(SelectCalProfile(i)) { 1637 | break; 1638 | } 1639 | } 1640 | 1641 | // stay selected on the specified profile 1642 | SelectCalProfile(profile); 1643 | } 1644 | } 1645 | 1646 | // apply current cal to the selected profile 1647 | void ApplyCalToProfile() 1648 | { 1649 | profileData[selectedProfile].xCenter = xCenter; 1650 | profileData[selectedProfile].yCenter = yCenter; 1651 | profileData[selectedProfile].xScale = CalScaleFloatToPref(xScale); 1652 | profileData[selectedProfile].yScale = CalScaleFloatToPref(yScale); 1653 | 1654 | stateFlags |= StateFlag_PrintSelectedProfile; 1655 | } 1656 | 1657 | void SetLedPackedColor(uint32_t color) 1658 | { 1659 | #ifdef DOTSTAR_ENABLE 1660 | dotstar.setPixelColor(0, Adafruit_DotStar::gamma32(color & 0x00FFFFFF)); 1661 | dotstar.show(); 1662 | #endif // DOTSTAR_ENABLE 1663 | #ifdef NEOPIXEL_PIN 1664 | neopixel.setPixelColor(0, Adafruit_NeoPixel::gamma32(color & 0x00FFFFFF)); 1665 | neopixel.show(); 1666 | #endif // NEOPIXEL_PIN 1667 | } 1668 | 1669 | void LedOff() 1670 | { 1671 | #ifdef DOTSTAR_ENABLE 1672 | dotstar.setPixelColor(0, 0); 1673 | dotstar.show(); 1674 | #endif // DOTSTAR_ENABLE 1675 | #ifdef NEOPIXEL_PIN 1676 | neopixel.setPixelColor(0, 0); 1677 | neopixel.show(); 1678 | #endif // NEOPIXEL_PIN 1679 | } 1680 | 1681 | void SetLedColorFromMode() 1682 | { 1683 | switch(gunMode) { 1684 | case GunMode_CalHoriz: 1685 | case GunMode_CalVert: 1686 | case GunMode_CalCenter: 1687 | SetLedPackedColor(CalModeColor); 1688 | break; 1689 | case GunMode_Pause: 1690 | SetLedPackedColor(profileDesc[selectedProfile].color); 1691 | break; 1692 | case GunMode_Run: 1693 | if(lastSeen) { 1694 | LedOff(); 1695 | } else { 1696 | SetLedPackedColor(IRSeen0Color); 1697 | } 1698 | break; 1699 | default: 1700 | break; 1701 | } 1702 | } 1703 | 1704 | #ifdef DEBUG_SERIAL 1705 | void PrintDebugSerial() 1706 | { 1707 | // only print every second 1708 | if(millis() - serialDbMs >= 1000 && Serial.dtr()) { 1709 | #ifdef EXTRA_POS_GLITCH_FILTER 1710 | Serial.print("bad final count "); 1711 | Serial.print(badFinalCount); 1712 | Serial.print(", bad move count "); 1713 | Serial.println(badMoveCount); 1714 | #endif // EXTRA_POS_GLITCH_FILTER 1715 | Serial.print("mode "); 1716 | Serial.print(gunMode); 1717 | Serial.print(", IR pos fps "); 1718 | Serial.print(irPosCount); 1719 | Serial.print(", loop/sec "); 1720 | Serial.print(frameCount); 1721 | 1722 | Serial.print(", Mouse X,Y "); 1723 | Serial.print(conMoveXAxis); 1724 | Serial.print(","); 1725 | Serial.println(conMoveYAxis); 1726 | 1727 | frameCount = 0; 1728 | irPosCount = 0; 1729 | serialDbMs = millis(); 1730 | } 1731 | } 1732 | #endif // DEBUG_SERIAL 1733 | --------------------------------------------------------------------------------