Changeset 224 for rtos_arduino


Ignore:
Timestamp:
Apr 30, 2016, 11:29:25 PM (8 years ago)
Author:
ertl-honda
Message:

1.7.10のファイルに更新

Location:
rtos_arduino/trunk
Files:
62 added
3 deleted
51 edited

Legend:

Unmodified
Added
Removed
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/boards.txt

    r136 r224  
     1######################################################
    12#ARDUINO M0 PRO (WITH) BOOTLOADER - PROGRAMMING PORT
    2 arduino_zero_pro_bl_dbg.name=Arduino M0 Pro (Programming Port)
    3 arduino_zero_pro_bl_dbg.vid.0=0x03eb
    4 arduino_zero_pro_bl_dbg.pid.0=0x2111
    5 arduino_zero_pro_bl_dbg.upload.tool=openocd
    6 arduino_zero_pro_bl_dbg.upload.protocol=sam-ba
    7 arduino_zero_pro_bl_dbg.upload.maximum_size=262144
    8 arduino_zero_pro_bl_dbg.upload.use_1200bps_touch=false
    9 arduino_zero_pro_bl_dbg.upload.wait_for_upload_port=false
    10 arduino_zero_pro_bl_dbg.upload.native_usb=false
    11 arduino_zero_pro_bl_dbg.build.mcu=cortex-m0plus
    12 arduino_zero_pro_bl_dbg.build.f_cpu=48000000L
    13 arduino_zero_pro_bl_dbg.build.usb_product="Arduino M0 Pro"
    14 arduino_zero_pro_bl_dbg.build.board=SAM_ZERO
    15 arduino_zero_pro_bl_dbg.build.core=arduino
    16 arduino_zero_pro_bl_dbg.build.extra_flags=-D__SAMD21G18A__ -mthumb {build.usb_flags}
    17 arduino_zero_pro_bl_dbg.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld
    18 arduino_zero_pro_bl_dbg.build.openocdscript=openocd_scripts/arduino_zero.cfg
    19 arduino_zero_pro_bl_dbg.build.variant=arduino_zero
    20 arduino_zero_pro_bl_dbg.build.variant_system_lib=
    21 arduino_zero_pro_bl_dbg.build.vid=0x2a03
    22 arduino_zero_pro_bl_dbg.build.pid=0x804f
    23 arduino_zero_pro_bl_dbg.build.section.start=0x4000
     3mzero_pro_bl_dbg.name=Arduino M0 Pro (Programming Port)
     4mzero_pro_bl_dbg.vid.0=0x03eb
     5mzero_pro_bl_dbg.pid.0=0x2111
     6mzero_pro_bl_dbg.upload.tool=openocd
     7mzero_pro_bl_dbg.upload.protocol=sam-ba
     8mzero_pro_bl_dbg.upload.maximum_size=262144
     9mzero_pro_bl_dbg.upload.use_1200bps_touch=false
     10mzero_pro_bl_dbg.upload.wait_for_upload_port=false
     11mzero_pro_bl_dbg.upload.native_usb=false
     12mzero_pro_bl_dbg.build.mcu=cortex-m0plus
     13mzero_pro_bl_dbg.build.f_cpu=48000000L
     14mzero_pro_bl_dbg.build.usb_product="Arduino M0 Pro"
     15mzero_pro_bl_dbg.build.board=SAM_ZERO
     16mzero_pro_bl_dbg.build.core=arduino
     17mzero_pro_bl_dbg.build.extra_flags=-D__SAMD21G18A__ -mthumb {build.usb_flags}
     18mzero_pro_bl_dbg.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld
     19mzero_pro_bl_dbg.build.openocdscript=openocd_scripts/arduino_zero.cfg
     20mzero_pro_bl_dbg.build.variant=arduino_zero
     21mzero_pro_bl_dbg.build.variant_system_lib=
     22mzero_pro_bl_dbg.build.vid=0x2a03
     23mzero_pro_bl_dbg.build.pid=0x804f
     24mzero_pro_bl_dbg.build.section.start=0x4000
    2425
    25 arduino_zero_pro_bl_dbg.bootloader.tool=openocd
    26 arduino_zero_pro_bl_dbg.bootloader.cmd_unprotect=at91samd bootloader 0
    27 arduino_zero_pro_bl_dbg.bootloader.cmd_protect=at91samd bootloader 16384
    28 arduino_zero_pro_bl_dbg.bootloader.cmd_protect_verify=at91samd bootloader
    29 arduino_zero_pro_bl_dbg.bootloader.file=zero/Bootloader_D21_M0_Pro_150427.hex
     26mzero_pro_bl_dbg.bootloader.tool=openocd
     27mzero_pro_bl_dbg.bootloader.cmd_unprotect=at91samd bootloader 0
     28mzero_pro_bl_dbg.bootloader.cmd_protect=at91samd bootloader 16384
     29mzero_pro_bl_dbg.bootloader.cmd_protect_verify=at91samd bootloader
     30mzero_pro_bl_dbg.bootloader.file=zero/Bootloader_D21_M0_Pro_150427.hex
    3031
     32######################################################
    3133#ARDUINO M0 PRO (WITH) BOOTLOADER - NATIVE PORT
    32 arduino_zero_pro_bl.name=Arduino M0 Pro (Native USB Port)
    33 arduino_zero_pro_bl.vid.0=0x2a03
    34 arduino_zero_pro_bl.pid.0=0x004d
    35 arduino_zero_pro_bl.vid.1=0x2a03
    36 arduino_zero_pro_bl.pid.1=0x804d
    37 arduino_zero_pro_bl.vid.2=0x2a03
    38 arduino_zero_pro_bl.pid.2=0x004f
    39 arduino_zero_pro_bl.vid.3=0x2a03
    40 arduino_zero_pro_bl.pid.3=0x804f
    41 arduino_zero_pro_bl.upload.tool=avrdude
    42 arduino_zero_pro_bl.upload.protocol=stk500v2
    43 arduino_zero_pro_bl.upload.maximum_size=262144
    44 arduino_zero_pro_bl.upload.use_1200bps_touch=true
    45 arduino_zero_pro_bl.upload.wait_for_upload_port=true
    46 arduino_zero_pro_bl.upload.native_usb=true
    47 arduino_zero_pro_bl.upload.speed=57600
    48 arduino_zero_pro_bl.build.mcu=cortex-m0plus
    49 arduino_zero_pro_bl.build.f_cpu=48000000L
    50 arduino_zero_pro_bl.build.usb_product="Arduino M0 Pro"
    51 arduino_zero_pro_bl.build.board=SAM_ZERO
    52 arduino_zero_pro_bl.build.core=arduino
    53 arduino_zero_pro_bl.build.extra_flags=-D__SAMD21G18A__ -mthumb {build.usb_flags}
    54 arduino_zero_pro_bl.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld
    55 arduino_zero_pro_bl.build.variant=arduino_zero
    56 arduino_zero_pro_bl.build.variant_system_lib=
    57 arduino_zero_pro_bl.build.vid=0x2a03
    58 arduino_zero_pro_bl.build.pid=0x804f
    59 arduino_zero_pro_bl.build.section.start=0x4000
    60 arduino_zero_pro_bl.build.emu.mcu=atmega2560
    61 arduino_zero_pro_bl.bootloader.tool=avrdude
    62 arduino_zero_pro_bl.bootloader.low_fuses=0xff
     34mzero_pro_bl.name=Arduino M0 Pro (Native USB Port)
     35mzero_pro_bl.vid.0=0x2a03
     36mzero_pro_bl.pid.0=0x004d
     37mzero_pro_bl.vid.1=0x2a03
     38mzero_pro_bl.pid.1=0x804d
     39mzero_pro_bl.vid.2=0x2a03
     40mzero_pro_bl.pid.2=0x004f
     41mzero_pro_bl.vid.3=0x2a03
     42mzero_pro_bl.pid.3=0x804f
     43mzero_pro_bl.upload.tool=avrdude
     44mzero_pro_bl.upload.protocol=stk500v2
     45mzero_pro_bl.upload.maximum_size=262144
     46mzero_pro_bl.upload.use_1200bps_touch=true
     47mzero_pro_bl.upload.wait_for_upload_port=true
     48mzero_pro_bl.upload.native_usb=true
     49mzero_pro_bl.upload.speed=57600
     50mzero_pro_bl.build.mcu=cortex-m0plus
     51mzero_pro_bl.build.f_cpu=48000000L
     52mzero_pro_bl.build.usb_product="Arduino M0 Pro"
     53mzero_pro_bl.build.board=SAM_ZERO
     54mzero_pro_bl.build.core=arduino
     55mzero_pro_bl.build.extra_flags=-D__SAMD21G18A__ -mthumb {build.usb_flags}
     56mzero_pro_bl.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld
     57mzero_pro_bl.build.variant=arduino_zero
     58mzero_pro_bl.build.variant_system_lib=
     59mzero_pro_bl.build.vid=0x2a03
     60mzero_pro_bl.build.pid=0x804f
     61mzero_pro_bl.build.section.start=0x4000
     62mzero_pro_bl.build.emu.mcu=atmega2560
     63mzero_pro_bl.bootloader.tool=avrdude
     64mzero_pro_bl.bootloader.low_fuses=0xff
    6365
     66######################################################
    6467#ARDUINO M0 (WITH) BOOTLOADER
    65 arduino_zero_bl.name=Arduino M0
    66 arduino_zero_bl.vid.0=0x2a03
    67 arduino_zero_bl.pid.0=0x004d
    68 arduino_zero_bl.vid.1=0x2a03
    69 arduino_zero_bl.pid.1=0x804d
    70 arduino_zero_bl.vid.2=0x2a03
    71 arduino_zero_bl.pid.2=0x004e
    72 arduino_zero_bl.vid.3=0x2a03
    73 arduino_zero_bl.pid.3=0x804e
    74 arduino_zero_bl.upload.tool=avrdude
    75 arduino_zero_bl.upload.protocol=stk500v2
    76 arduino_zero_bl.upload.maximum_size=262144
    77 arduino_zero_bl.upload.use_1200bps_touch=true
    78 arduino_zero_bl.upload.wait_for_upload_port=true
    79 arduino_zero_bl.upload.native_usb=true
    80 arduino_zero_bl.upload.speed=57600
    81 arduino_zero_bl.build.mcu=cortex-m0plus
    82 arduino_zero_bl.build.f_cpu=48000000L
    83 arduino_zero_bl.build.usb_product="Arduino M0"
    84 arduino_zero_bl.build.board=SAM_ZERO
    85 arduino_zero_bl.build.core=arduino
    86 arduino_zero_bl.build.extra_flags=-D__SAMD21G18A__ -mthumb {build.usb_flags}
    87 arduino_zero_bl.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld
    88 arduino_zero_bl.build.variant=arduino_zero
    89 arduino_zero_bl.build.variant_system_lib=
    90 arduino_zero_bl.build.vid=0x2a03
    91 arduino_zero_bl.build.pid=0x804e
    92 arduino_zero_bl.build.section.start=0x4000
    93 arduino_zero_bl.build.emu.mcu=atmega2560
    94 arduino_zero_bl.bootloader.tool=avrdude
    95 arduino_zero_bl.bootloader.low_fuses=0xff
     68mzero_bl.name=Arduino M0
     69mzero_bl.vid.0=0x2a03
     70mzero_bl.pid.0=0x004d
     71mzero_bl.vid.1=0x2a03
     72mzero_bl.pid.1=0x804d
     73mzero_bl.vid.2=0x2a03
     74mzero_bl.pid.2=0x004e
     75mzero_bl.vid.3=0x2a03
     76mzero_bl.pid.3=0x804e
     77mzero_bl.upload.tool=avrdude
     78mzero_bl.upload.protocol=stk500v2
     79mzero_bl.upload.maximum_size=262144
     80mzero_bl.upload.use_1200bps_touch=true
     81mzero_bl.upload.wait_for_upload_port=true
     82mzero_bl.upload.native_usb=true
     83mzero_bl.upload.speed=57600
     84mzero_bl.build.mcu=cortex-m0plus
     85mzero_bl.build.f_cpu=48000000L
     86mzero_bl.build.usb_product="Arduino M0"
     87mzero_bl.build.board=SAM_ZERO
     88mzero_bl.build.core=arduino
     89mzero_bl.build.extra_flags=-D__SAMD21G18A__ -mthumb {build.usb_flags}
     90mzero_bl.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld
     91mzero_bl.build.variant=arduino_zero
     92mzero_bl.build.variant_system_lib=
     93mzero_bl.build.vid=0x2a03
     94mzero_bl.build.pid=0x804e
     95mzero_bl.build.section.start=0x4000
     96mzero_bl.build.emu.mcu=atmega2560
     97mzero_bl.bootloader.tool=avrdude
     98mzero_bl.bootloader.low_fuses=0xff
     99
     100######################################################
     101#ARDUINO TIAN (WITH) BOOTLOADER
     102
     103tian.name=Arduino Tian
     104tian.upload.via_ssh=true
     105tian.vid.0=0x10C4
     106tian.pid.0=0xEA70
     107
     108tian.upload.tool=avrdude
     109#tian.upload.protocol=stk500v2
     110tian.upload.protocol=wiring
     111tian.upload.maximum_size=262144
     112tian.upload.use_1200bps_touch=true
     113tian.upload.wait_for_upload_port=true
     114tian.upload.native_usb=true
     115tian.upload.speed=57600
     116tian.build.mcu=cortex-m0plus
     117tian.build.f_cpu=48000000L
     118tian.build.usb_product="Arduino Tian"
     119tian.build.board=SAMD_TIAN
     120tian.build.core=arduino
     121tian.build.extra_flags=-D__SAMD21G18A__ -mthumb {build.usb_flags}
     122tian.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld
     123tian.build.variant=arduino_zero
     124tian.build.variant_system_lib=
     125tian.build.vid=0x2a03
     126tian.build.pid=0x8052
     127tian.build.section.start=0x4000
     128tian.build.emu.mcu=atmega2560
     129tian.bootloader.tool=avrdude
     130tian.bootloader.low_fuses=0xff
     131tian.bootloader.file=sofia/Sofia_Tian_151118.hex
     132tian.drivers=SiliconLabs-CP2105/Silicon Labs VCP Driver.pkg
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/Print.cpp

    r136 r224  
    115115size_t Print::println(void)
    116116{
    117   size_t n = print('\r');
    118   n += print('\n');
    119   return n;
     117   return write("\r\n");
    120118}
    121119
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/CDC.cpp

    r136 r224  
    1 /* Copyright (c) 2011, Peter Barrett
    2 **
    3 ** Permission to use, copy, modify, and/or distribute this software for
    4 ** any purpose with or without fee is hereby granted, provided that the
    5 ** above copyright notice and this permission notice appear in all copies.
    6 **
    7 ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
    8 ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
    9 ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
    10 ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
    11 ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
    12 ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
    13 ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
    14 ** SOFTWARE.
     1/*
     2  Copyright (c) 2015 Arduino LLC.  All right reserved.
     3
     4  This library is free software; you can redistribute it and/or
     5  modify it under the terms of the GNU Lesser General Public
     6  License as published by the Free Software Foundation; either
     7  version 2.1 of the License, or (at your option) any later version.
     8
     9  This library is distributed in the hope that it will be useful,
     10  but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     12  See the GNU Lesser General Public License for more details.
     13
     14  You should have received a copy of the GNU Lesser General Public
     15  License along with this library; if not, write to the Free Software
     16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     17*/
     18/*
     19** Modified 04/04/2016 by Arduino.org development team
    1520*/
    1621
     
    2025
    2126// Include Atmel headers
    22 #include "Arduino.h"
    23 #include "sam.h"
    24 #include "wiring_constants.h"
    25 #include "USBCore.h"
    26 #include "USB/USB_device.h"
    27 #include "USBDesc.h"
    28 #include "USBAPI.h"
    29 
    30 #include "Reset.h"
    31 
     27#include <Arduino.h>
     28#include <Reset.h>
    3229
    3330#ifdef CDC_ENABLED
    3431
    35 #define CDC_SERIAL_BUFFER_SIZE  64
     32#define CDC_SERIAL_BUFFER_SIZE  256
    3633
    3734/* For information purpose only since RTS is not always handled by the terminal application */
     
    4138#define CDC_LINESTATE_READY             (CDC_LINESTATE_RTS | CDC_LINESTATE_DTR)
    4239
    43 struct ring_buffer
    44 {
     40struct ring_buffer {
    4541        uint8_t buffer[CDC_SERIAL_BUFFER_SIZE];
    4642        volatile uint32_t head;
    4743        volatile uint32_t tail;
     44        volatile bool full;
    4845};
    49 
    50 ring_buffer cdc_rx_buffer = { { 0 }, 0, 0};
    51 
    52 typedef struct
    53 {
    54         uint32_t        dwDTERate;
    55         uint8_t         bCharFormat;
    56         uint8_t         bParityType;
    57         uint8_t         bDataBits;
    58         uint8_t         lineState;
     46ring_buffer cdc_rx_buffer = {{0}, 0, 0, false};
     47
     48typedef struct {
     49        uint32_t dwDTERate;
     50        uint8_t bCharFormat;
     51        uint8_t bParityType;
     52        uint8_t bDataBits;
     53        uint8_t lineState;
    5954} LineInfo;
    6055
    6156_Pragma("pack(1)")
    62 static volatile LineInfo _usbLineInfo = { 
    63    115200, // dWDTERate
    64     0x00,  // bCharFormat
    65     0x00,  // bParityType
    66     0x08,  // bDataBits
    67     0x00   // lineState
     57static volatile LineInfo _usbLineInfo = {
     58        115200, // dWDTERate
     59        0x00,   // bCharFormat
     60        0x00,   // bParityType
     61        0x08,   // bDataBits
     62        0x00    // lineState
    6863};
    6964
    70 static const CDCDescriptor _cdcInterface =
    71 {
    72 #if (defined CDC_ENABLED) && defined(HID_ENABLED)
     65static volatile int32_t breakValue = -1;
     66
     67static CDCDescriptor _cdcInterface = {
    7368        D_IAD(0, 2, CDC_COMMUNICATION_INTERFACE_CLASS, CDC_ABSTRACT_CONTROL_MODEL, 0),
    74 #endif
    75         //      CDC communication interface
    76         D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0),
    77         D_CDCCS( CDC_HEADER, CDC_V1_10 & 0xFF, (CDC_V1_10>>8) & 0x0FF ),        // Header (1.10 bcd)
    78        
    79         D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6),                            // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported
    80         D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE),        // Communication interface is master, data interface is slave 0
    81         D_CDCCS(CDC_CALL_MANAGEMENT,1,1),                                                       // Device handles call management (not)
    82         D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10, 0x10),
    83 
    84         //      CDC data interface
    85         D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0),
    86         D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,EPX_SIZE,0),
    87         D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,EPX_SIZE,0)
     69
     70        // CDC communication interface
     71        D_INTERFACE(CDC_ACM_INTERFACE, 1, CDC_COMMUNICATION_INTERFACE_CLASS, CDC_ABSTRACT_CONTROL_MODEL, 0),
     72        D_CDCCS(CDC_HEADER, CDC_V1_10 & 0xFF, (CDC_V1_10>>8) & 0x0FF), // Header (1.10 bcd)
     73
     74        D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT, 6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported
     75        D_CDCCS(CDC_UNION, CDC_ACM_INTERFACE, CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0
     76        D_CDCCS(CDC_CALL_MANAGEMENT, 1, 1), // Device handles call management (not)
     77        D_ENDPOINT(USB_ENDPOINT_IN(CDC_ENDPOINT_ACM), USB_ENDPOINT_TYPE_INTERRUPT, 0x10, 0x10),
     78
     79        // CDC data interface
     80        D_INTERFACE(CDC_DATA_INTERFACE, 2, CDC_DATA_INTERFACE_CLASS, 0, 0),
     81        D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT), USB_ENDPOINT_TYPE_BULK, EPX_SIZE, 0),
     82        D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ), USB_ENDPOINT_TYPE_BULK, EPX_SIZE, 0)
    8883};
    8984_Pragma("pack()")
    9085
    91 const void* WEAK CDC_GetInterface(void)
    92 {
    93         return  &_cdcInterface;
    94 }
    95 
    96 uint32_t WEAK CDC_GetInterfaceLength(void)
    97 {
    98     return sizeof( _cdcInterface );
    99 }
    100 
    101 bool WEAK CDC_Setup(Setup& setup)
    102 {
    103         uint8_t r = setup.bRequest;
    104         uint8_t requestType = setup.bmRequestType;
     86const void* _CDC_GetInterface(void)
     87{
     88        return &_cdcInterface;
     89}
     90
     91uint32_t _CDC_GetInterfaceLength(void)
     92{
     93        return sizeof(_cdcInterface);
     94}
     95
     96int CDC_GetInterface(uint8_t* interfaceNum)
     97{
     98        interfaceNum[0] += 2;   // uses 2
     99        return USBD_SendControl(&_cdcInterface,sizeof(_cdcInterface));
     100}
     101
     102bool CDC_Setup(Setup& pSetup)
     103{
     104        uint8_t requestType = pSetup.bmRequestType;
     105        uint8_t r = pSetup.bRequest;
    105106
    106107        if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType)
     
    108109                if (CDC_GET_LINE_CODING == r)
    109110                {
    110                         USBD_SendControl(0,(void*)&_usbLineInfo,7);
     111                        USBD_SendControl((void*)&_usbLineInfo, 7);
    111112                        return true;
    112113                }
     
    117118                if (CDC_SET_LINE_CODING == r)
    118119                {
    119                         while( UDD_FifoByteCount(EP0) <15);
    120                         //USBD_RecvControl((void*)&_usbLineInfo,7);
    121                         uint8_t* line = (uint8_t*)&_usbLineInfo;
    122                         for(uint8_t i = 0; i<7; i++)
    123                                 line[i] = setup.data[i];
    124                         return false;
     120                        USBD_RecvControl((void*)&_usbLineInfo, 7);
    125121                }
    126122
    127123                if (CDC_SET_CONTROL_LINE_STATE == r)
    128124                {
    129                         _usbLineInfo.lineState = setup.wValueL;
     125                        _usbLineInfo.lineState = pSetup.wValueL;
     126                }
     127
     128                if (r == CDC_SET_LINE_CODING || r == CDC_SET_CONTROL_LINE_STATE)
     129                {
    130130                        // auto-reset into the bootloader is triggered when the port, already
    131                         // open at 1200 bps, is closed.
    132                         if (1200 == _usbLineInfo.dwDTERate)
     131                        // open at 1200 bps, is closed. We check DTR state to determine if host
     132                        // port is open (bit 0 of lineState).
     133                        if (_usbLineInfo.dwDTERate == 1200 && (_usbLineInfo.lineState & 0x01) == 0)
    133134                        {
    134                                 // We check DTR state to determine if host port is open (bit 0 of lineState).
    135                                 if ((_usbLineInfo.lineState & 0x01) == 0)
    136                                         initiateReset(250);
    137                                 else
    138                                         cancelReset();
     135                                initiateReset(250);
     136                        }
     137                        else
     138                        {
     139                                cancelReset();
    139140                        }
    140141                        return false;
    141142                }
     143
     144                if (r == CDC_SEND_BREAK)
     145                {
     146                        breakValue = ((uint16_t)pSetup.wValueH << 8) | pSetup.wValueL;
     147                        return false;
     148                }
    142149        }
    143150        return false;
     
    159166void Serial_::accept(void)
    160167{
     168        uint8_t buffer[CDC_SERIAL_BUFFER_SIZE];
     169        uint32_t len = USBD_Recv(CDC_ENDPOINT_OUT, &buffer, CDC_SERIAL_BUFFER_SIZE);
     170
     171        uint8_t enableInterrupts = ((__get_PRIMASK() & 0x1) == 0);
     172        __disable_irq();
     173
     174        ring_buffer *ringBuffer = &cdc_rx_buffer;
     175        uint32_t i = ringBuffer->head;
     176
     177        uint32_t k = 0;
     178        while (len > 0 && !ringBuffer->full) {
     179                len--;
     180                ringBuffer->buffer[i++] = buffer[k++];
     181                i %= CDC_SERIAL_BUFFER_SIZE;
     182                if (i == ringBuffer->tail)
     183                        ringBuffer->full = true;
     184        }
     185        ringBuffer->head = i;
     186        if (enableInterrupts) {
     187                __enable_irq();
     188        }
     189}
     190
     191int Serial_::available(void)
     192{
    161193        ring_buffer *buffer = &cdc_rx_buffer;
    162         uint32_t i = (uint32_t)(buffer->head+1) % CDC_SERIAL_BUFFER_SIZE;
    163 
    164         // if we should be storing the received character into the location
    165         // just before the tail (meaning that the head would advance to the
    166         // current location of the tail), we're about to overflow the buffer
    167         // and so we don't write the character or advance the head.
    168         while (i != buffer->tail) {
    169                 uint32_t c;
    170                 if (!USBD_Available(CDC_ENDPOINT_OUT)) {
    171             UDD_ReleaseRX(CDC_ENDPOINT_OUT);
    172                         break;
    173                 }
    174                 c = USBD_Recv(CDC_ENDPOINT_OUT);
    175                 buffer->buffer[buffer->head] = c;
    176                 buffer->head = i;
    177 
    178                 i = (i + 1) % CDC_SERIAL_BUFFER_SIZE;
    179         }
    180 }
    181 
    182 int Serial_::available(void)
     194        if (buffer->full) {
     195                return CDC_SERIAL_BUFFER_SIZE;
     196        }
     197        if (buffer->head == buffer->tail) {
     198                USB->DEVICE.DeviceEndpoint[CDC_ENDPOINT_OUT].EPINTENSET.reg = USB_DEVICE_EPINTENCLR_TRCPT(1);
     199        }
     200        return (uint32_t)(CDC_SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % CDC_SERIAL_BUFFER_SIZE;
     201}
     202
     203int Serial_::peek(void)
    183204{
    184205        ring_buffer *buffer = &cdc_rx_buffer;
    185         return (uint32_t)(CDC_SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % CDC_SERIAL_BUFFER_SIZE;
    186 }
    187 
    188 int Serial_::peek(void)
     206        if (buffer->head == buffer->tail && !buffer->full) {
     207                return -1;
     208        } else {
     209                return buffer->buffer[buffer->tail];
     210        }
     211}
     212
     213
     214// if the ringBuffer is empty: try to fill it
     215// if it's still empty: return -1
     216// else return the last char
     217// so the buffer is filled only when needed
     218int Serial_::read(void)
    189219{
    190220        ring_buffer *buffer = &cdc_rx_buffer;
    191221
    192         if (buffer->head == buffer->tail)
    193         {
    194                 return -1;
    195         }
    196         else
    197         {
    198                 return buffer->buffer[buffer->tail];
    199         }
    200 }
    201 
    202 int Serial_::read(void)
    203 {
    204         ring_buffer *buffer = &cdc_rx_buffer;
    205 
    206222        // if the head isn't ahead of the tail, we don't have any characters
    207         if (buffer->head == buffer->tail)
     223        if (buffer->head == buffer->tail && !buffer->full)
     224        {
     225                if (USBD_Available(CDC_ENDPOINT_OUT))
     226                        accept();
     227        }
     228        if (buffer->head == buffer->tail && !buffer->full)
    208229        {
    209230                return -1;
     
    213234                unsigned char c = buffer->buffer[buffer->tail];
    214235                buffer->tail = (uint32_t)(buffer->tail + 1) % CDC_SERIAL_BUFFER_SIZE;
    215                 if (USBD_Available(CDC_ENDPOINT_OUT))
    216                         accept();
     236                buffer->full = false;
    217237                return c;
    218238        }
     
    231251         bytes sent before the user opens the connection or after
    232252         the connection is closed are lost - just like with a UART. */
    233 
     253        if (_usbLineInfo.lineState > 0)  // Problem with Windows(R)
    234254        {
    235255                uint32_t r = USBD_Send(CDC_ENDPOINT_IN, buffer, size);
    236256
    237                 if (r > 0)
    238                 {
     257                if (r == 0) {
    239258                        return r;
    240                 } else
    241                 {
     259                } else {
    242260                        setWriteError();
    243261                        return 0;
    244262                }
    245         }
     263         }
    246264        setWriteError();
    247265        return 0;
     
    259277// We add a short delay before returning to fix a bug observed by Federico
    260278// where the port is configured (lineState != 0) but not quite opened.
    261 
    262279Serial_::operator bool()
    263280{
     
    277294}
    278295
    279 Serial_ SerialUSB;
     296int32_t Serial_::readBreak() {
     297        uint8_t enableInterrupts = ((__get_PRIMASK() & 0x1) == 0);
     298
     299        // disable interrupts,
     300        // to avoid clearing a breakValue that might occur
     301        // while processing the current break value
     302        __disable_irq();
     303
     304        int32_t ret = breakValue;
     305
     306        breakValue = -1;
     307
     308        if (enableInterrupts) {
     309                // re-enable the interrupts
     310                __enable_irq();
     311        }
     312
     313        return ret;
     314}
     315
     316unsigned long Serial_::baud() {
     317        return _usbLineInfo.dwDTERate;
     318}
     319
     320uint8_t Serial_::stopbits() {
     321        return _usbLineInfo.bCharFormat;
     322}
     323
     324uint8_t Serial_::paritytype() {
     325        return _usbLineInfo.bParityType;
     326}
     327
     328uint8_t Serial_::numbits() {
     329        return _usbLineInfo.bDataBits;
     330}
     331
     332bool Serial_::dtr() {
     333        return _usbLineInfo.lineState & 0x1;
     334}
     335
     336bool Serial_::rts() {
     337        return _usbLineInfo.lineState & 0x2;
     338}
     339
     340Serial_ SerialUSB(USBDevice);
    280341
    281342#endif
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/HID.cpp

    r136 r224  
    2121#include "USBDesc.h"
    2222#include "sam.h"
    23 #include "USB/USB_device.h"
    2423
    2524
     
    4544//      HID report descriptor
    4645_Pragma("pack(1)")
    47 extern const uint8_t _hidReportDescriptor[] = {
     46extern const uint32_t _hidReportDescriptor[] = {
    4847        //      Mouse
    4948    0x05, 0x01,                    //   USAGE_PAGE (Generic Desktop)    // 54
     
    162161uint32_t WEAK HID_GetDescriptor(void)
    163162{
    164         return USBD_SendControl(0,_hidReportDescriptor,sizeof(_hidReportDescriptor));
     163        return USBD_SendControl(_hidReportDescriptor,sizeof(_hidReportDescriptor));
    165164}
    166165
     
    197196                if (HID_GET_IDLE == r)
    198197                {
    199                         UDD_Send(0, &_hid_idle, 1);
    200                         UDD_ClearIN();
     198                        USBD_Send(0, &_hid_idle, 1);
     199                        USB->DEVICE.DeviceEndpoint[EP0].EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_BK1RDY;
    201200                        return true;
    202201                }
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/USBAPI.h

    r136 r224  
    11/*
    2   Copyright (c) 2012 Arduino.  All right reserved.
     2  Copyright (c) 2015 Arduino LLC.  All right reserved.
    33
    44  This library is free software; you can redistribute it and/or
     
    1616  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    1717*/
    18 
    19 #ifndef __USBAPI__
    20 #define __USBAPI__
    21 
    22 
    23 /* Define attribute */
    24 #if defined   ( __CC_ARM   ) /* Keil uVision 4 */
    25     #define WEAK (__attribute__ ((weak)))
    26 #elif defined ( __ICCARM__ ) /* IAR Ewarm 5.41+ */
    27     #define WEAK __weak
    28 #elif defined (  __GNUC__  ) /* GCC CS */
    29     #define WEAK __attribute__ ((weak))
    30 #endif
    31 
     18/*
     19**Modified 04/04/2016 by Arduino.org development team
     20*/
     21
     22#pragma once
     23
     24#define WEAK __attribute__ ((weak))
     25
     26#define HSTPIPCFG_PTYPE_BLK 1
     27#define HSTPIPCFG_PTOKEN_IN 2
     28#define HSTPIPCFG_PTOKEN_OUT 3
     29#define HSTPIPCFG_PBK_1_BANK 4
     30#define HSTPIPCFG_PTYPE_INTRPT 5
     31
     32#define EP0      0
     33#define EPX_SIZE 64 // 64 for Full Speed, EPT size max is 1024
    3234
    3335#if defined __cplusplus
     
    3739
    3840//================================================================================
    39 //================================================================================
    40 //      USB
    41 
    42 class USBDevice_
    43 {
    44 public:
    45         USBDevice_();
     41// USB
     42//================================================================================
     43//================================================================================
     44// Low level API
     45typedef struct {
     46        union {
     47                uint8_t bmRequestType;
     48                struct {
     49                        uint8_t direction : 5;
     50                        uint8_t type : 2;
     51                        uint8_t transferDirection : 1;
     52                };
     53        };
     54        uint8_t bRequest;
     55        uint8_t wValueL;
     56        uint8_t wValueH;
     57        uint16_t wIndex;
     58        uint16_t wLength;
     59} Setup;
     60
     61
     62class USBDevice_ {
     63public:
     64        USBDevice_() {};
     65
     66        // USB Device API
     67        void init();
     68        bool attach();  // Serial port goes down too...
     69        bool detach();
     70
    4671        bool configured();
    4772
    48         bool attach();
    49         bool detach();  // Serial port goes down too...
    50         void poll();
    51         void init();
    52 };
     73private:
     74        bool initialized;
     75};
     76
    5377extern USBDevice_ USBDevice;
    5478
    5579//================================================================================
    56 //================================================================================
    5780//      Serial over CDC (Serial1 is the physical port)
    5881
    5982class Serial_ : public Stream
    6083{
    61 private:
    62         RingBuffer *_cdc_rx_buffer;
    63 public:
     84public:
     85        Serial_(USBDevice_ &_usb) : usb(_usb) { }
    6486        void begin(uint32_t baud_count);
    6587        void begin(unsigned long, uint8_t);
     
    7597        using Print::write; // pull in write(str) from Print
    7698        operator bool();
     99
     100        // This method allows processing "SEND_BREAK" requests sent by
     101        // the USB host. Those requests indicate that the host wants to
     102        // send a BREAK signal and are accompanied by a single uint16_t
     103        // value, specifying the duration of the break. The value 0
     104        // means to end any current break, while the value 0xffff means
     105        // to start an indefinite break.
     106        // readBreak() will return the value of the most recent break
     107        // request, but will return it at most once, returning -1 when
     108        // readBreak() is called again (until another break request is
     109        // received, which is again returned once).
     110        // This also mean that if two break requests are received
     111        // without readBreak() being called in between, the value of the
     112        // first request is lost.
     113        // Note that the value returned is a long, so it can return
     114        // 0-0xffff as well as -1.
     115        int32_t readBreak();
     116
     117        // These return the settings specified by the USB host for the
     118        // serial port. These aren't really used, but are offered here
     119        // in case a sketch wants to act on these settings.
     120        uint32_t baud();
     121        uint8_t stopbits();
     122        uint8_t paritytype();
     123        uint8_t numbits();
     124        bool dtr();
     125        bool rts();
     126        enum {
     127                ONE_STOP_BIT = 0,
     128                ONE_AND_HALF_STOP_BIT = 1,
     129                TWO_STOP_BITS = 2,
     130        };
     131        enum {
     132                NO_PARITY = 0,
     133                ODD_PARITY = 1,
     134                EVEN_PARITY = 2,
     135                MARK_PARITY = 3,
     136                SPACE_PARITY = 4,
     137        };
     138
     139private:
     140        USBDevice_ &usb;
     141        RingBuffer *_cdc_rx_buffer;
    77142};
    78143extern Serial_ SerialUSB;
     
    171236//================================================================================
    172237//================================================================================
    173 //      Low level API
    174 
    175 typedef struct
    176 {
    177         uint8_t bmRequestType;
    178         uint8_t bRequest;
    179         uint8_t wValueL;
    180         uint8_t wValueH;
    181         uint16_t wIndex;
    182         uint16_t wLength;
    183         uint8_t data[8];
    184 } Setup;
    185 
    186 //================================================================================
    187 //================================================================================
    188238//      HID 'Driver'
    189239
     
    202252uint32_t                MSC_GetInterface(uint8_t* interfaceNum);
    203253uint32_t                MSC_GetDescriptor(uint32_t i);
    204 bool    MSC_Setup(Setup& setup);
     254bool    MSC_Setup(Setup& pSetup);
    205255bool    MSC_Data(uint8_t rx,uint8_t tx);
    206256
     
    209259//      CDC 'Driver'
    210260
    211 const void* CDC_GetInterface(/*uint8_t* interfaceNum*/);
    212 uint32_t WEAK CDC_GetInterfaceLength(void);
     261int CDC_GetInterface(uint8_t* interfaceNum);
     262const void* _CDC_GetInterface(void);
     263uint32_t _CDC_GetInterfaceLength(void);
    213264uint32_t                CDC_GetOtherInterface(uint8_t* interfaceNum);
    214265uint32_t                CDC_GetDescriptor(uint32_t i);
    215 bool    CDC_Setup(Setup& setup);
    216 
    217 //================================================================================
    218 //================================================================================
    219 
    220 uint32_t USBD_SendControl(uint8_t flags, const void* d, uint32_t len);
     266bool    CDC_Setup(Setup& pSetup);
     267
     268
     269//================================================================================
     270//================================================================================
     271
     272uint32_t USBD_SendControl(const void* _data, uint32_t len);
    221273uint32_t USBD_RecvControl(void* d, uint32_t len);
     274void USBD_Calibrate();
    222275uint32_t USBD_SendInterfaces(void);
    223276bool USBD_ClassInterfaceRequest(Setup& setup);
     
    228281uint32_t USBD_Recv(uint32_t ep, void* data, uint32_t len);              // non-blocking
    229282uint32_t USBD_Recv(uint32_t ep);                                                        // non-blocking
     283uint8_t USBD_armRecv(uint32_t ep);
    230284void USBD_Flush(uint32_t ep);
    231285uint32_t USBD_Connected(void);
    232286
    233287#endif  // __cplusplus
    234 #endif  // __USBAPI__
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/USBCore.cpp

    r136 r224  
    1 // Copyright (c) 2010, Peter Barrett
    21/*
    3 ** Permission to use, copy, modify, and/or distribute this software for
    4 ** any purpose with or without fee is hereby granted, provided that the
    5 ** above copyright notice and this permission notice appear in all copies.
    6 **
    7 ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
    8 ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
    9 ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
    10 ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
    11 ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
    12 ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
    13 ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
    14 ** SOFTWARE.
     2  Copyright (c) 2015 Arduino LLC.  All right reserved.
     3
     4  This library is free software; you can redistribute it and/or
     5  modify it under the terms of the GNU Lesser General Public
     6  License as published by the Free Software Foundation; either
     7  version 2.1 of the License, or (at your option) any later version.
     8
     9  This library is distributed in the hope that it will be useful,
     10  but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     12  See the GNU Lesser General Public License for more details.
     13
     14  You should have received a copy of the GNU Lesser General Public
     15  License along with this library; if not, write to the Free Software
     16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    1517*/
     18/*
     19**Modified 04/04/2016 by Arduino.org development team
     20*/
     21
     22#include <Arduino.h>
     23
     24#include "SAMD21_USBDevice.h"
     25#include "USB_host.h"
    1626
    1727#include <stdlib.h>
    1828#include <stdio.h>
    1929#include <stdint.h>
    20 //#include "../Arduino.h"
    21 
    22 #include "sam.h"
    23 #include "wiring_constants.h"
    24 #include "USBCore.h"
    25 #include "USB/USB_device.h"   // needed for USB PID define
    26 #include "USBDesc.h"
    27 #include "USBAPI.h"
    28 
    29 #define TRACE_CORE(x)
    30 
    31 //==================================================================
    32 
    33 
    34 
    35 /*
    36 #if (defined CDC_ENABLED) && defined(HID_ENABLED)
    37 //#define USB_PID_ZERO       0x004B  // CDC and HID
    38 #define USB_PID_ZERO       0x804d  // CDC only
    39 #else
    40 #if (defined CDC_ENABLED)
    41 #define USB_PID_ZERO       0x804d  // CDC only  usbserial.name
    42 #else
    43 #define USB_PID_ZERO       0x804d  // HID only
    44 #endif
    45 #endif
    46 */
    47 
    48 #define USB_PID_ZERO_PRO        0x804d
    49 
    50 // USB Device
    51 //#define USB_VID                       0x2a03 // arduino srl vid
    52 //#undef USB_PID
    53 //#define USB_PID            USB_PID_ZERO
    54 
    55 //==================================================================
     30#include <limits.h>
     31
     32USBDevice_SAMD21G18x usbd;
    5633
    5734static char isRemoteWakeUpEnabled = 0;
    5835static char isEndpointHalt = 0;
     36
     37extern void (*gpf_isr)(void);
    5938
    6039
     
    6443};
    6544
     45#define USB_PID_ZERO_PRO        0x804d
     46#define USB_PRODUCT "Arduino M0 Pro"
    6647#ifndef USB_PRODUCT
    6748// Use a hardcoded product name if none is provided
     
    8869
    8970
    90 
    91 //      DEVICE DESCRIPTOR
    9271#if (defined CDC_ENABLED) && defined(HID_ENABLED)
    9372const DeviceDescriptor USB_DeviceDescriptor =
     
    10180#endif
    10281
     82
    10383//==================================================================
    10484
    10585volatile uint32_t _usbConfiguration = 0;
    106 volatile uint32_t _usbInitialized = 0;
    10786volatile uint32_t _usbSetInterface = 0;
    10887
     88static __attribute__((__aligned__(4))) //__attribute__((__section__(".bss_hram0")))
     89uint8_t udd_ep_out_cache_buffer[7][64];
     90
     91static __attribute__((__aligned__(4))) //__attribute__((__section__(".bss_hram0")))
     92uint8_t udd_ep_in_cache_buffer[7][64];
     93
    10994//==================================================================
    11095
    111 
    112 //      Number of bytes, assumes a rx endpoint
    113 uint32_t USBD_Available(uint32_t ep)
    114 {
    115         return UDD_FifoByteCount(ep);
    116 }
    117 
    118 //      Non Blocking receive
    119 //      Return number of bytes read
    120 uint32_t USBD_Recv(uint32_t ep, void* d, uint32_t len)
    121 {
    122         if (!_usbConfiguration || len < 0)
     96bool _dry_run = false;
     97bool _pack_message = false;
     98uint16_t _pack_size = 0;
     99uint8_t _pack_buffer[256];
     100
     101
     102void packMessages(bool val)
     103{
     104        if (val) {
     105                _pack_message = true;
     106                _pack_size = 0;
     107        } else {
     108                _pack_message = false;
     109                USBD_SendControl(_pack_buffer, _pack_size);
     110        }
     111}
     112
     113// Blocking Send of data to an endpoint
     114uint32_t USBD_Send(uint32_t ep, const void *data, uint32_t len)
     115{
     116        uint32_t length = 0;
     117
     118        if (!_usbConfiguration)
    123119                return -1;
    124 
    125         uint32_t n = UDD_FifoByteCount(ep);
    126         len = min(n,len);
    127         n = len;
    128         uint8_t* dst = (uint8_t*)d;
    129         while (n--)
    130                 *dst++ = UDD_Recv8(ep);
    131        
    132        
    133        
    134        
    135         if (len && !UDD_FifoByteCount(ep)) // release empty buffer
    136                 UDD_ReleaseRX(ep);
    137                
    138   //----- Tx & Rx led blinking during transmission ----- begin ----     
    139         PORT->Group[1].OUTTGL.reg =0x00000008 ;  //RxLED
    140         for(int i=0; i < 100000; i++)
    141         {
    142                 asm("NOP");
    143         }
    144         PORT->Group[1].OUTTGL.reg =0x00000008 ;
    145   //----- Tx & Rx led blinking during transmission ----- end ----
     120        if (len > 16384)
     121                return -1;
     122
     123        PORT->Group[0].OUTCLR.reg =0x08000000 ; //TxLED on
     124        // Flash area
     125        while (len != 0)
     126        {
     127                if (len >= 64) {
     128                        length = 64;
     129                } else {
     130                        length = len;
     131                }
     132
     133                /* memcopy could be safer in multi threaded environment */
     134                memcpy(&udd_ep_in_cache_buffer[ep], data, length);
     135
     136                usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]);
     137
     138                usbd.epBank1SetByteCount(ep, length);
     139
     140                // Clear the transfer complete flag
     141                usbd.epBank1AckTransferComplete(ep);
     142
     143                // RAM buffer is full, we can send data (IN)
     144                usbd.epBank1SetReady(ep);
     145
     146                // Wait for transfer to complete
     147                while (!usbd.epBank1IsTransferComplete(ep)) {
     148                        ;  // need fire exit.
     149                }
     150                len -= length;
     151                data = (char *)data + length;
     152        }
    146153        return len;
    147154}
    148155
    149 //      Recv 1 byte if ready
    150 uint32_t USBD_Recv(uint32_t ep)
    151 {
    152         uint8_t c;
    153         if (USBD_Recv(ep, &c, 1) != 1)
    154                 return -1;
    155         else
    156                 return c;
    157 }
    158 
    159 //      Blocking Send of data to an endpoint
    160 uint32_t USBD_Send(uint32_t ep, const void* d, uint32_t len)
    161 {
    162         int r = len;
    163         const uint8_t* data = (const uint8_t*)d;
    164 
    165     if (!_usbConfiguration)
    166     {
    167         TRACE_CORE(printf("pb conf\n\r");)
    168                 return -1;
    169     }
    170         UDD_Send(ep, data, len);
    171 
    172         /* Clear the transfer complete flag  */
    173         udd_clear_transf_cplt(ep);
    174         /* Set the bank as ready */
    175         udd_bk_rdy(ep);
    176 
    177         /* Wait for transfer to complete */
    178         while (! udd_is_transf_cplt(ep));  // need fire exit.
    179        
    180   //----- Tx & Rx led blinking during transmission ----- begin ----
    181         PORT->Group[0].OUTTGL.reg =0x08000000 ; //TxLED
    182         for(int i=0; i < 100000; i++)
    183         {
    184                 asm("NOP");
    185         }
    186         PORT->Group[0].OUTTGL.reg =0x08000000 ;
    187         /*for(int i=0; i < 100000; i++)
    188         {
    189                 asm("NOP");
    190         }*/
    191   //----- Tx & Rx led blinking during transmission ----- end ----       
    192         return r;
    193 }
    194 
    195 uint32_t USBD_SendControl(uint8_t flags, const void* d, uint32_t len)
    196 {
    197         const uint8_t* data = (const uint8_t*)d;
     156uint32_t USBD_armSend(uint32_t ep, const void* data, uint32_t len)
     157{
     158        memcpy(&udd_ep_in_cache_buffer[ep], data, len);
     159
     160        // Get endpoint configuration from setting register
     161        usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]);
     162        usbd.epBank1SetMultiPacketSize(ep, 0);
     163        usbd.epBank1SetByteCount(ep, len);
     164
     165        return len;
     166}
     167
     168uint32_t USBD_SendControl(const void* _data, uint32_t len)
     169{
     170        const uint8_t *data = reinterpret_cast<const uint8_t *>(_data);
    198171        uint32_t length = len;
    199172        uint32_t sent = 0;
    200173        uint32_t pos = 0;
    201174
    202         TRACE_CORE(printf("=> USBD_SendControl TOTAL len=%lu\r\n", len);)
    203 
    204                 while (len > 0)
    205                 {
    206                         sent = UDD_Send(EP0, data + pos, len);
    207                         TRACE_CORE(printf("=> USBD_SendControl sent=%lu\r\n", sent);)
    208                         pos += sent;
    209                         len -= sent;
    210                 }
     175        if (_dry_run == true)
     176                return length;
     177
     178        if (_pack_message == true) {
     179                memcpy(&_pack_buffer[_pack_size], data, len);
     180                _pack_size += len;
     181                return length;
     182        }
     183
     184        while (len > 0)
     185        {
     186                sent = USBD_armSend(EP0, data + pos, len);
     187                pos += sent;
     188                len -= sent;
     189        }
    211190
    212191        return length;
    213192}
    214193
    215 // Send a USB descriptor string. The string is stored as a
    216 // plain ASCII string but is sent out as UTF-16 with the
    217 // correct 2-byte prefix
    218 static bool USB_SendStringDescriptor(const uint8_t *string, int wLength)
    219 {
    220         uint16_t buff[64];
     194bool USBD_SendStringDescriptor(const uint8_t *string, uint8_t maxlen)
     195{
     196        if (maxlen < 2)
     197                return false;
     198
     199        uint16_t buff[maxlen/2];
    221200        int l = 1;
    222201
    223         wLength -= 2;
    224         while (*string && wLength>0)
     202        maxlen -= 2;
     203        while (*string && maxlen>0)
    225204        {
    226205                buff[l++] = (uint8_t)(*string++);
    227                 wLength -= 2;
     206                maxlen -= 2;
    228207        }
    229208        buff[0] = (3<<8) | (l*2);
    230209
    231         return USBD_SendControl(0, (uint8_t*)buff, l*2);
    232 }
    233 
    234 uint32_t USBD_RecvControl(void* d, uint32_t len)
    235 {
    236         udd_ack_out_received(0);
    237 
    238         return len;
    239 }
    240 
    241 //      Handle CLASS_INTERFACE requests
    242 bool USBD_ClassInterfaceRequest(Setup& setup)
    243 {
    244         uint8_t i = setup.wIndex;
    245 
    246         TRACE_CORE(printf("=> USBD_ClassInterfaceRequest\r\n");)
    247 
    248 #ifdef CDC_ENABLED
    249         if (CDC_ACM_INTERFACE == i)
    250         {
    251                 if( CDC_Setup(setup) == false )
    252                 {
    253                         send_zlp();
    254                 }
     210        return USBD_SendControl((uint8_t*)buff, l*2);
     211}
     212
     213uint8_t USBD_SendInterfaces(uint32_t* total)
     214{
     215        uint8_t interfaces = 0;
     216
     217#if defined(CDC_ENABLED)
     218        total[0] += CDC_GetInterface(&interfaces);
     219#endif
     220
     221        return interfaces;
     222}
     223
     224// Construct a dynamic configuration descriptor
     225// This really needs dynamic endpoint allocation etc
     226uint32_t USBD_SendConfiguration(uint32_t maxlen)
     227{
     228        uint32_t total = 0;
     229        // Count and measure interfaces
     230        _dry_run = true;
     231        uint8_t interfaces = USBD_SendInterfaces(&total);
     232
     233        _Pragma("pack(1)")
     234        ConfigDescriptor config = D_CONFIG((uint16_t)(total + sizeof(ConfigDescriptor)), interfaces);
     235        _Pragma("pack()")
     236
     237        //      Now send them
     238        _dry_run = false;
     239
     240        if (maxlen == sizeof(ConfigDescriptor)) {
     241                USBD_SendControl(&config, sizeof(ConfigDescriptor));
    255242                return true;
    256243        }
    257 #endif
    258 
    259 #ifdef HID_ENABLED
    260         if (HID_INTERFACE == i)
    261         {
    262                 if( HID_Setup(setup) == true )
    263                 {
    264                         send_zlp();
    265                 }
    266                 return true;
    267         }
    268 #endif
    269 
    270         return false;
    271 }
    272 
    273 //      Construct a dynamic configuration descriptor
    274 //      This really needs dynamic endpoint allocation etc
    275 //      TODO
    276 static bool USBD_SendConfiguration(uint32_t maxlen)
    277 {
    278         uint8_t cache_buffer[128];
    279         uint8_t i;
    280 
    281         const uint8_t* interfaces;
    282         uint32_t interfaces_length = 0;
    283         uint8_t num_interfaces[1];
    284        
    285         num_interfaces[0] = 0;
    286 
    287 #if (defined CDC_ENABLED) && defined(HID_ENABLED)
    288     num_interfaces[0] += 3;
    289     interfaces = (const uint8_t*) CDC_GetInterface();
    290     interfaces_length = CDC_GetInterfaceLength() + HID_GetInterfaceLength();
    291     if( maxlen > CDC_GetInterfaceLength() + HID_GetInterfaceLength() + sizeof(ConfigDescriptor) )
    292     {
    293             maxlen = CDC_GetInterfaceLength() + HID_GetInterfaceLength() + sizeof(ConfigDescriptor);
    294     }
    295 
    296 #else
    297 #ifdef CDC_ENABLED
    298     num_interfaces[0] += 2;
    299         interfaces = (const uint8_t*) CDC_GetInterface();
    300         interfaces_length += CDC_GetInterfaceLength();
    301         if( maxlen > CDC_GetInterfaceLength()+ sizeof(ConfigDescriptor) )
    302         {
    303                 maxlen = CDC_GetInterfaceLength()+ sizeof(ConfigDescriptor);
    304         }
    305 #endif
    306 
    307 #ifdef HID_ENABLED
    308     num_interfaces[0] += 1;
    309         interfaces = (const uint8_t*) HID_GetInterface();
    310         interfaces_length += HID_GetInterfaceLength();
    311         if( maxlen > HID_GetInterfaceLength()+ sizeof(ConfigDescriptor) )
    312         {
    313                 maxlen = HID_GetInterfaceLength()+ sizeof(ConfigDescriptor);
    314         }
    315 #endif
    316 #endif
    317 
    318 _Pragma("pack(1)")
    319         ConfigDescriptor config = D_CONFIG((uint16_t)(interfaces_length + sizeof(ConfigDescriptor)),num_interfaces[0]);
    320 _Pragma("pack()")
    321 
    322         memcpy( cache_buffer, &config, sizeof(ConfigDescriptor) );
    323 
    324 #if (defined CDC_ENABLED) && defined(HID_ENABLED)
    325         for ( i=0; i<CDC_GetInterfaceLength(); i++)
    326         {
    327                 cache_buffer[i+sizeof(ConfigDescriptor)] = interfaces[i];
    328         }
    329         interfaces = (const uint8_t*) HID_GetInterface();
    330         for ( i=0; i<HID_GetInterfaceLength(); i++)
    331         {
    332                 cache_buffer[i+sizeof(ConfigDescriptor)+CDC_GetInterfaceLength()] = interfaces[i];
    333         }
    334 #else
    335 #ifdef HID_ENABLED
    336         for ( i=0; i<interfaces_length; i++)
    337         {
    338                 cache_buffer[i+sizeof(ConfigDescriptor)] = interfaces[i];
    339         }
    340 #endif
    341 
    342 #ifdef CDC_ENABLED
    343         for ( i=0; i<interfaces_length; i++)
    344         {
    345                 cache_buffer[i+sizeof(ConfigDescriptor)] = interfaces[i];
    346         }
    347 #endif 
    348 #endif
    349 
    350         if (maxlen > sizeof(cache_buffer))
    351         {
    352                  maxlen = sizeof(cache_buffer);
    353         }
    354         USBD_SendControl(0,cache_buffer, maxlen );
     244
     245        total = 0;
     246
     247        packMessages(true);
     248        USBD_SendControl(&config, sizeof(ConfigDescriptor));
     249        USBD_SendInterfaces(&total);
     250        packMessages(false);
     251
    355252        return true;
    356253}
    357254
    358 static bool USBD_SendDescriptor(Setup* pSetup)
    359 {
    360         uint8_t t = pSetup->wValueH;
     255bool USBD_SendDescriptor(Setup &setup)
     256{
     257        uint8_t t = setup.wValueH;
    361258        uint8_t desc_length = 0;
    362         const uint8_t* desc_addr = 0;
    363 
    364         if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
    365         {
    366                 TRACE_CORE(printf("=> USBD_SendDescriptor : USB_CONFIGURATION_DESCRIPTOR_TYPE length=%d\r\n", setup.wLength);)
    367                 return USBD_SendConfiguration(pSetup->wLength);
    368         }
    369 
    370 #ifdef HID_ENABLED
    371         if (HID_REPORT_DESCRIPTOR_TYPE == t)
    372         {
    373                 TRACE_CORE(puts("=> USBD_SendDescriptor : HID_REPORT_DESCRIPTOR_TYPE\r\n");)
    374                 return HID_GetDescriptor();
    375         }
    376         if (HID_HID_DESCRIPTOR_TYPE == t)
    377         {
    378                 uint8_t tab[9] = D_HIDREPORT((uint8_t)HID_SizeReportDescriptor());
    379 
    380                 TRACE_CORE(puts("=> USBD_SendDescriptor : HID_HID_DESCRIPTOR_TYPE\r\n");)
    381 
    382                 return USBD_SendControl(0, tab, sizeof(tab));
    383         }
    384 #endif
    385 
    386         if (USB_DEVICE_DESCRIPTOR_TYPE == t)
    387         {
    388                 TRACE_CORE(puts("=> USBD_SendDescriptor : USB_DEVICE_DESCRIPTOR_TYPE\r\n");)
    389                 desc_addr = (const uint8_t*)&USB_DeviceDescriptor;
    390         if( *desc_addr > pSetup->wLength ) {
    391             desc_length = pSetup->wLength;
    392         }
     259        bool _cdcComposite;
     260        int ret;
     261        const uint8_t *desc_addr = 0;
     262
     263        if (t == USB_CONFIGURATION_DESCRIPTOR_TYPE)
     264        {
     265                return USBD_SendConfiguration(setup.wLength);
     266        }
     267
     268        if (t == USB_DEVICE_DESCRIPTOR_TYPE)
     269        {
     270                if (setup.wLength == 8)
     271                        _cdcComposite = 1;
     272
     273                desc_addr = _cdcComposite ?  (const uint8_t*)&USB_DeviceDescriptor : (const uint8_t*)&USB_DeviceDescriptor;
     274
     275                if (*desc_addr > setup.wLength) {
     276                        desc_length = setup.wLength;
     277                }
    393278        }
    394279        else if (USB_STRING_DESCRIPTOR_TYPE == t)
    395280        {
    396                 TRACE_CORE(puts("=> USBD_SendDescriptor : USB_STRING_DESCRIPTOR_TYPE\r\n");)
    397                 if (pSetup->wValueL == 0) {
     281                if (setup.wValueL == 0) {
    398282                        desc_addr = (const uint8_t*)&STRING_LANGUAGE;
    399283                }
    400                 else if (pSetup->wValueL == IPRODUCT) {
    401                         return USB_SendStringDescriptor(STRING_PRODUCT, pSetup->wLength);
    402                 }
    403                 else if (pSetup->wValueL == IMANUFACTURER) {
    404                         return USB_SendStringDescriptor(STRING_MANUFACTURER, pSetup->wLength);
     284                else if (setup.wValueL == IPRODUCT) {
     285                        return USBD_SendStringDescriptor(STRING_PRODUCT, setup.wLength);
     286                }
     287                else if (setup.wValueL == IMANUFACTURER) {
     288                        return USBD_SendStringDescriptor(STRING_MANUFACTURER, setup.wLength);
    405289                }
    406290                else {
    407291                        return false;
    408292                }
    409                 if( *desc_addr > pSetup->wLength ) {
    410                         desc_length = pSetup->wLength;
    411                 }
    412         }
    413     else
    414     {
    415         TRACE_CORE(printf("Device ERROR");)
    416     }
    417 
    418         if (desc_addr == 0)
    419         {
     293                if (*desc_addr > setup.wLength) {
     294                        desc_length = setup.wLength;
     295                }
     296        }
     297        else
     298        {
     299        }
     300
     301        if (desc_addr == 0) {
    420302                return false;
    421303        }
    422304
    423         if (desc_length == 0)
    424         {
     305        if (desc_length == 0) {
    425306                desc_length = *desc_addr;
    426307        }
    427308
    428         TRACE_CORE(printf("=> USBD_SendDescriptor : desc_addr=%p desc_length=%d\r\n", desc_addr, desc_length);)
    429         USBD_SendControl(0, desc_addr, desc_length);
     309        USBD_SendControl(desc_addr, desc_length);
    430310
    431311        return true;
    432312}
    433313
    434 
    435 void EndpointHandler(uint8_t bEndpoint)
    436 {
     314void initEP(uint32_t ep, uint32_t config)
     315{
     316        if (config == (USB_ENDPOINT_TYPE_INTERRUPT | USB_ENDPOINT_IN(0)))
     317        {
     318                usbd.epBank1SetSize(ep, 64);
     319                usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]);
     320                usbd.epBank1SetType(ep, 4); // INTERRUPT IN
     321        }
     322        else if (config == (USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_OUT(0)))
     323        {
     324                usbd.epBank0SetSize(ep, 64);
     325                usbd.epBank0SetAddress(ep, &udd_ep_out_cache_buffer[ep]);
     326                usbd.epBank0SetType(ep, 3); // BULK OUT
     327
     328                // Release OUT EP
     329                usbd.epBank0SetMultiPacketSize(ep, 64);
     330                usbd.epBank0SetByteCount(ep, 0);
     331        }
     332        else if (config == (USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_IN(0)))
     333        {
     334                usbd.epBank1SetSize(ep, 64);
     335                usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]);
     336
     337                // NAK on endpoint IN, the bank is not yet filled in.
     338                usbd.epBank1ResetReady(ep);
     339
     340                usbd.epBank1SetType(ep, 3); // BULK IN
     341        }
     342        else if (config == USB_ENDPOINT_TYPE_CONTROL)
     343        {
     344                // XXX: Needed?
     345//              usbd.epBank0DisableAutoZLP(ep);
     346//              usbd.epBank1DisableAutoZLP(ep);
     347
     348                // Setup Control OUT
     349                usbd.epBank0SetSize(ep, 64);
     350                usbd.epBank0SetAddress(ep, &udd_ep_out_cache_buffer[ep]);
     351                usbd.epBank0SetType(ep, 1); // CONTROL OUT / SETUP
     352
     353                // Setup Control IN
     354                usbd.epBank1SetSize(ep, 64);
     355                usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[0]);
     356                usbd.epBank1SetType(ep, 1); // CONTROL IN
     357
     358                // Release OUT EP
     359                usbd.epBank0SetMultiPacketSize(ep, 64);
     360                usbd.epBank0SetByteCount(ep, 0);
     361
     362                // NAK on endpoint OUT, the bank is full.
     363                usbd.epBank0SetReady(ep);
     364        }
     365}
     366
     367void sendZlp(uint32_t ep)
     368{
     369        // Set the byte count as zero
     370        usbd.epBank1SetByteCount(ep, 0);
     371}
     372
     373void setAddress(uint32_t addr)
     374{
     375        usbd.epBank1SetByteCount(0, 0);
     376        usbd.epBank1AckTransferComplete(0);
     377
     378        // RAM buffer is full, we can send data (IN)
     379        usbd.epBank1SetReady(0);
     380
     381        // Wait for transfer to complete
     382        while (!usbd.epBank1IsTransferComplete(0)) {}
     383
     384        // Set USB address to addr
     385        USB->DEVICE.DADD.bit.DADD = addr; // Address
     386        USB->DEVICE.DADD.bit.ADDEN = 1; // Enable
     387}
     388
     389uint32_t EndPoints[] =
     390{
     391        USB_ENDPOINT_TYPE_CONTROL,
     392
    437393#ifdef CDC_ENABLED
    438         if( bEndpoint == CDC_ENDPOINT_OUT )
    439         {
    440                 udd_ack_out_received(CDC_ENDPOINT_OUT);
    441 
    442                 // Handle received bytes               
     394        USB_ENDPOINT_TYPE_INTERRUPT | USB_ENDPOINT_IN(0),           // CDC_ENDPOINT_ACM
     395        USB_ENDPOINT_TYPE_BULK      | USB_ENDPOINT_OUT(0),               // CDC_ENDPOINT_OUT
     396        USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_IN(0),                // CDC_ENDPOINT_IN
     397#endif
     398
     399};
     400
     401void initEndpoints() {
     402        for (uint8_t i = 1; i < sizeof(EndPoints) && EndPoints[i] != 0; i++) {
     403                initEP(i, EndPoints[i]);
     404        }
     405}
     406
     407bool handleStandardSetup(Setup &setup)
     408{
     409        switch (setup.bRequest) {
     410        case GET_STATUS:
     411                if (setup.bmRequestType == 0)  // device
     412                {
     413                        // Send the device status
     414                        // TODO: Check current configuration for power mode (if device is configured)
     415                        // TODO: Check if remote wake-up is enabled
     416                        uint8_t buff[] = { 0, 0 };
     417                        USBD_armSend(0, buff, 2);
     418                        return true;
     419                }
     420                // if( setup.bmRequestType == 2 ) // Endpoint:
     421                else
     422                {
     423                        // Send the endpoint status
     424                        // Check if the endpoint if currently halted
     425                        uint8_t buff[] = { 0, 0 };
     426                        if (isEndpointHalt == 1)
     427                                buff[0] = 1;
     428                        USBD_armSend(0, buff, 2);
     429                        return true;
     430                }
     431
     432        case CLEAR_FEATURE:
     433                // Check which is the selected feature
     434                if (setup.wValueL == 1) // DEVICEREMOTEWAKEUP
     435                {
     436                        // Enable remote wake-up and send a ZLP
     437                        uint8_t buff[] = { 0, 0 };
     438                        if (isRemoteWakeUpEnabled == 1)
     439                                buff[0] = 1;
     440                        USBD_armSend(0, buff, 2);
     441                        return true;
     442                }
     443                else // if( setup.wValueL == 0) // ENDPOINTHALT
     444                {
     445                        isEndpointHalt = 0;
     446                        sendZlp(0);
     447                        return true;
     448                }
     449
     450        case SET_FEATURE:
     451                // Check which is the selected feature
     452                if (setup.wValueL == 1) // DEVICEREMOTEWAKEUP
     453                {
     454                        // Enable remote wake-up and send a ZLP
     455                        isRemoteWakeUpEnabled = 1;
     456                        uint8_t buff[] = { 0 };
     457                        USBD_armSend(0, buff, 1);
     458                        return true;
     459                }
     460                if (setup.wValueL == 0) // ENDPOINTHALT
     461                {
     462                        // Halt endpoint
     463                        isEndpointHalt = 1;
     464                        sendZlp(0);
     465                        return true;
     466                }
     467
     468        case SET_ADDRESS:
     469                setAddress(setup.wValueL);
     470                return true;
     471
     472        case GET_DESCRIPTOR:
     473                return USBD_SendDescriptor(setup);
     474
     475        case SET_DESCRIPTOR:
     476                return false;
     477
     478        case GET_CONFIGURATION:
     479                USBD_armSend(0, (void*)&_usbConfiguration, 1);
     480                return true;
     481
     482        case SET_CONFIGURATION:
     483                if (REQUEST_DEVICE == (setup.bmRequestType & REQUEST_RECIPIENT)) {
     484
     485                        initEndpoints();
     486                        _usbConfiguration = setup.wValueL;
     487
     488                        #if defined(CDC_ENABLED)
     489                        // Enable interrupt for CDC reception from host (OUT packet)
     490                        usbd.epBank1EnableTransferComplete(CDC_ENDPOINT_ACM);
     491                        usbd.epBank0EnableTransferComplete(CDC_ENDPOINT_OUT);
     492                        #endif
     493
     494                        sendZlp(0);
     495                        return true;
     496                } else {
     497                        return false;
     498                }
     499
     500        case GET_INTERFACE:
     501                USBD_armSend(0, (void*)&_usbSetInterface, 1);
     502                return true;
     503
     504        case SET_INTERFACE:
     505                _usbSetInterface = setup.wValueL;
     506                sendZlp(0);
     507                return true;
     508
     509        default:
     510                return true;
     511        }
     512}
     513
     514bool handleClassInterfaceSetup(Setup& setup)
     515{
     516        uint8_t i = setup.wIndex;
     517
     518        #if defined(CDC_ENABLED)
     519        if (CDC_ACM_INTERFACE == i)
     520        {
     521                if (CDC_Setup(setup) == false) {
     522                        sendZlp(0);
     523                }
     524                return true;
     525        }
     526        #endif
     527
     528        return false;
     529}
     530
     531void stall(uint32_t ep)
     532{
     533        // TODO: test
     534        // TODO: use .bit. notation
     535
     536        // Stall endpoint
     537        USB->DEVICE.DeviceEndpoint[ep].EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ(2);
     538}
     539
     540void handleEndpoint(uint8_t ep)
     541{
     542#if defined(CDC_ENABLED)
     543        if (ep == CDC_ENDPOINT_OUT)
     544        {
     545                // The RAM Buffer is empty: we can receive data
     546                //usbd.epBank0ResetReady(CDC_ENDPOINT_OUT);
     547
     548                // Handle received bytes
    443549                if (USBD_Available(CDC_ENDPOINT_OUT))
     550                        SerialUSB.accept();
     551        }
     552        if (ep == CDC_ENDPOINT_IN)
     553        {
     554                // NAK on endpoint IN, the bank is not yet filled in.
     555                usbd.epBank1ResetReady(CDC_ENDPOINT_IN);
     556                usbd.epBank1AckTransferComplete(CDC_ENDPOINT_IN);
     557        }
     558        if (ep == CDC_ENDPOINT_ACM)
     559        {
     560                // NAK on endpoint IN, the bank is not yet filled in.
     561                usbd.epBank1ResetReady(CDC_ENDPOINT_ACM);
     562                usbd.epBank1AckTransferComplete(CDC_ENDPOINT_ACM);
     563        }
     564#endif
     565
     566}
     567
     568void ISRHandler()
     569{
     570
     571        if (_pack_message == true) {
     572                return;
     573        }
     574        // End-Of-Reset
     575        if (usbd.isEndOfResetInterrupt())
     576        {
     577                // Configure EP 0
     578                initEP(0, USB_ENDPOINT_TYPE_CONTROL);
     579
     580                // Enable Setup-Received interrupt
     581                usbd.epBank0EnableSetupReceived(0);
     582
     583                _usbConfiguration = 0;
     584
     585                usbd.ackEndOfResetInterrupt();
     586        }
     587
     588        // Start-Of-Frame
     589        if (usbd.isStartOfFrameInterrupt())
     590        {
     591                usbd.ackStartOfFrameInterrupt();
     592        }
     593
     594        // Endpoint 0 Received Setup interrupt
     595        if (usbd.epBank0IsSetupReceived(0))
     596        {
     597                usbd.epBank0AckSetupReceived(0);
     598
     599                Setup *setup = reinterpret_cast<Setup *>(udd_ep_out_cache_buffer[0]);
     600
     601                /* Clear the Bank 0 ready flag on Control OUT */
     602                // The RAM Buffer is empty: we can receive data
     603                usbd.epBank0ResetReady(0);
     604
     605                bool ok;
     606                if (REQUEST_STANDARD == (setup->bmRequestType & REQUEST_TYPE)) {
     607                        // Standard Requests
     608                        ok = handleStandardSetup(*setup);
     609                } else {
     610                        // Class Interface Requests
     611                        ok = handleClassInterfaceSetup(*setup);
     612                }
     613
     614                if (ok) {
     615                        usbd.epBank1SetReady(0);
     616                } else {
     617                        stall(0);
     618                }
     619
     620                if (usbd.epBank1IsStalled(0))
    444621                {
    445                         SerialUSB.accept();
    446                 }
    447         }
    448         if( bEndpoint == CDC_ENDPOINT_IN )
    449         {
    450                 udd_ack_in_received(CDC_ENDPOINT_IN);
    451                 /* Clear the transfer complete flag  */
    452                 udd_clear_transf_cplt(CDC_ENDPOINT_IN);
    453                
    454         }
    455         if( bEndpoint == CDC_ENDPOINT_ACM )
    456         {
    457                 udd_ack_in_received(CDC_ENDPOINT_ACM);
    458                 /* Clear the transfer complete flag  */
    459                 udd_clear_transf_cplt(CDC_ENDPOINT_ACM);
    460         }
    461 #endif
    462 
    463 #ifdef HID_ENABLED
    464         /* Nothing to do in our example */
    465 #endif
    466 }
    467 
    468 
    469 void USB_Handler(void)
    470 {
    471         uint16_t flags;
    472         uint8_t i;
    473         uint8_t ept_int;
    474 
    475         ept_int = udd_endpoint_interrupt();
     622                        usbd.epBank1AckStalled(0);
     623
     624                        // Remove stall request
     625                        usbd.epBank1DisableStalled(0);
     626                }
    476627       
    477         /* Not endpoint interrupt */
    478         if (0 == ept_int)
    479         {
    480                 udd_clear_wakeup_interrupt();
    481                 udd_clear_eorsm_interrupt();
    482                 udd_clear_suspend_interrupt();
    483 
    484                 // End of bus reset
    485                 if (Is_udd_reset())
     628        } // end Received Setup handler
     629        PORT->Group[0].OUTSET.reg =0x08000000 ; //TxLED off
     630        PORT->Group[1].OUTSET.reg =0x00000008 ; //RxLED off
     631
     632        uint8_t i=0;
     633        uint8_t ept_int = usbd.epInterruptSummary() & 0xFE; // Remove endpoint number 0 (setup)
     634        while (ept_int != 0)
     635        {
     636                // Check if endpoint has a pending interrupt
     637                if ((ept_int & (1 << i)) != 0)
    486638                {
    487                         TRACE_CORE(printf(">>> End of Reset\r\n");)
    488                         // Reset USB address to 0
    489                         udd_configure_address(0);
    490 
    491                         // Configure EP 0
    492                         UDD_InitEP(0, USB_ENDPOINT_TYPE_CONTROL);
    493                         udd_enable_setup_received_interrupt(0);
    494                         _usbConfiguration = 0;
    495                         udd_ack_reset();
    496                 }
    497 
    498                 if (Is_udd_sof())
    499                 {
    500                         udd_ack_sof();
    501                 }
    502 
    503         }
    504         else
    505         {
    506                 // Endpoint interrupt
    507                 flags = udd_read_endpoint_flag(0);
    508 
    509                 // endpoint received setup interrupt
    510                 if (flags & USB_DEVICE_EPINTFLAG_RXSTP)
    511                 {
    512                         Setup *pSetupData;
    513 
    514                         /* Clear the Received Setup flag */
    515                         udd_read_endpoint_flag(0) = USB_DEVICE_EPINTFLAG_RXSTP;
    516 
    517                         UDD_Recv(EP0, (uint8_t**)&pSetupData);
    518 
    519                         /* Clear the Bank 0 ready flag on Control OUT */
    520                         udd_ack_out_received(0);
    521 
    522                         bool ok = true;
    523                         if (REQUEST_STANDARD == (pSetupData->bmRequestType & REQUEST_TYPE))
     639                        // Endpoint Transfer Complete (0/1) Interrupt
     640                        if (usbd.epBank0IsTransferComplete(i) ||
     641                            usbd.epBank1IsTransferComplete(i))
    524642                        {
    525                                 unsigned char data_to_be_send[2];
    526 
    527                                 // Standard Requests
    528                                 uint8_t r = pSetupData->bRequest;
    529                                 if (GET_STATUS == r)
    530                                 {
    531                                         if( pSetupData->bmRequestType == 0 )  // device
    532                                         {
    533                                                 // Send the device status
    534                                         TRACE_CORE(puts(">>> EP0 Int: GET_STATUS\r\n");)
    535                                                 // Check current configuration for power mode (if device is configured)
    536                                                
    537                                                 // Check if remote wake-up is enabled
    538                                                
    539                                                 data_to_be_send[0]=0;
    540                                                 data_to_be_send[1]=0;
    541                                                 UDD_Send(0, data_to_be_send, 2);
    542                                         }
    543                                         // if( pSetupData->bmRequestType == 2 ) // Endpoint:
    544                                         else
    545                                         {
    546                                                 // Send the endpoint status
    547                                                 // Check if the endpoint if currently halted
    548                                                 if( isEndpointHalt == 1 )
    549                                                         data_to_be_send[0]=1;
    550                                                 else
    551                                                         data_to_be_send[0]=0;
    552                                                 data_to_be_send[1]=0;
    553                                                 UDD_Send(0, data_to_be_send, 2);
    554                                         }
    555                                 }
    556                                 else if (CLEAR_FEATURE == r)
    557                                 {
    558                                    // Check which is the selected feature
    559                                         if( pSetupData->wValueL == 1) // DEVICEREMOTEWAKEUP
    560                                         {
    561                                                 // Enable remote wake-up and send a ZLP
    562                                                 if( isRemoteWakeUpEnabled == 1 )
    563                                                         data_to_be_send[0]=1;
    564                                                 else
    565                                                         data_to_be_send[0]=0;
    566                                                 data_to_be_send[1]=0;
    567                                                 UDD_Send(0, data_to_be_send, 2);
    568                                         }
    569                                         else // if( pSetupData->wValueL == 0) // ENDPOINTHALT
    570                                         {
    571                                                 isEndpointHalt = 0;
    572                                                 send_zlp();
    573                                         }
    574                                 }
    575                                 else if (SET_FEATURE == r)
    576                                 {
    577                                         // Check which is the selected feature
    578                                         if( pSetupData->wValueL == 1) // DEVICEREMOTEWAKEUP
    579                                         {
    580                                                 // Enable remote wake-up and send a ZLP
    581                                                 isRemoteWakeUpEnabled = 1;
    582                                         data_to_be_send[0] = 0;
    583                                                 UDD_Send(0, data_to_be_send, 1);
    584                                         }
    585                                         if( pSetupData->wValueL == 0) // ENDPOINTHALT
    586                                         {
    587                                                 // Halt endpoint
    588                                                 isEndpointHalt = 1;
    589                                                 send_zlp();
    590                                         }
    591                                 }
    592                                 else if (SET_ADDRESS == r)
    593                                 {
    594                                         TRACE_CORE(puts(">>> EP0 Int: SET_ADDRESS\r\n");)
    595                                         UDD_SetAddress(pSetupData->wValueL);
    596                                 }
    597                                 else if (GET_DESCRIPTOR == r)
    598                                 {
    599                                         TRACE_CORE(puts(">>> EP0 Int: GET_DESCRIPTOR\r\n");)
    600                                         ok = USBD_SendDescriptor(pSetupData);
    601                                 }
    602                                 else if (SET_DESCRIPTOR == r)
    603                                 {
    604                                         TRACE_CORE(puts(">>> EP0 Int: SET_DESCRIPTOR\r\n");)
    605                                         ok = false;
    606                                 }
    607                                 else if (GET_CONFIGURATION == r)
    608                                 {
    609                                         TRACE_CORE(puts(">>> EP0 Int: GET_CONFIGURATION\r\n");)
    610                                         UDD_Send(0, (void*)&_usbConfiguration, 1);
    611                                 }
    612                                 else if (SET_CONFIGURATION == r)
    613                                 {
    614                                         if (REQUEST_DEVICE == (pSetupData->bmRequestType & REQUEST_RECIPIENT))
    615                                         {
    616                                                 TRACE_CORE(printf(">>> EP0 Int: SET_CONFIGURATION REQUEST_DEVICE %d\r\n", pSetupData->wValueL);)
    617 #ifdef HID_ENABLED
    618                                                 UDD_InitEP( HID_ENDPOINT_INT, USB_ENDPOINT_TYPE_INTERRUPT | USB_ENDPOINT_IN(0));
    619 #endif
    620 
    621 #ifdef CDC_ENABLED
    622                                                 UDD_InitEP( CDC_ENDPOINT_ACM, USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_IN(0));
    623                                                 UDD_InitEP( CDC_ENDPOINT_OUT, USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_OUT(0));
    624                                                 UDD_InitEP( CDC_ENDPOINT_IN, USB_ENDPOINT_TYPE_INTERRUPT | USB_ENDPOINT_IN(0));
    625 #endif
    626                                                 _usbConfiguration = pSetupData->wValueL;
    627 
    628 #ifdef CDC_ENABLED
    629                                                 // Enable interrupt for CDC reception from host (OUT packet)
    630                                                 udd_ept_enable_it_transf_cplt_in(CDC_ENDPOINT_ACM);
    631                                                 udd_ept_enable_it_transf_cplt_out(CDC_ENDPOINT_OUT);
    632 #endif
    633                                                 send_zlp();
    634                                         }
    635                                         else
    636                                         {
    637                                                 TRACE_CORE(puts(">>> EP0 Int: SET_CONFIGURATION failed!\r\n");)
    638                                                 ok = false;
    639                                         }
    640                                 }
    641                                 else if (GET_INTERFACE == r)
    642                                 {
    643                                         TRACE_CORE(puts(">>> EP0 Int: GET_INTERFACE\r\n");)
    644                                         UDD_Send(0, (void*)&_usbSetInterface, 1);
    645                                 }
    646                                 else if (SET_INTERFACE == r)
    647                                 {
    648                                         _usbSetInterface = pSetupData->wValueL;
    649                                         TRACE_CORE(puts(">>> EP0 Int: SET_INTERFACE\r\n");)
    650                                         send_zlp();
    651                                 }
     643                                handleEndpoint(i);
    652644                        }
    653                         else
    654                         {
    655                                 TRACE_CORE(puts(">>> EP0 Int: ClassInterfaceRequest\r\n");)
    656                                 ok =  USBD_ClassInterfaceRequest(*pSetupData);
    657                         }
    658 
    659                         if (ok)
    660                         {
    661                                 TRACE_CORE(puts(">>> EP0 Int: Send packet\r\n");)
    662                                 UDD_ClearIN();
    663                         }
    664                         else
    665                         {
    666                                 TRACE_CORE(puts(">>> EP0 Int: Stall\r\n");)
    667                                 UDD_Stall(0);
    668                         }
    669 
    670                         if( flags & USB_DEVICE_EPINTFLAG_STALL1 )
    671                         {
    672                                 /* Clear the stall flag */
    673                                 udd_clear_stall_request(0);
    674 
    675                                 // Remove stall request
    676                                 udd_remove_stall_request(0);
    677                         }
    678                 }  // end if USB_DEVICE_EPINTFLAG_RXSTP
    679 
    680                 i=0;
    681                 ept_int &= 0xFE;  // Remove endpoint number 0 (setup)
    682                 while (ept_int != 0)
    683                 {
    684             // Check if endpoint has a pending interrupt
    685             if ((ept_int & (1 << i)) != 0)
    686                         {
    687                                 if( (udd_read_endpoint_flag(i) & USB_DEVICE_EPINTFLAG_TRCPT_Msk ) != 0 )
    688                                
    689                                 {
    690                                         EndpointHandler(i);
    691                                 }
    692                 ept_int &= ~(1 << i);
    693                
    694                 if (ept_int != 0)
    695                                 {
    696                
    697                     TRACE_CORE("\n\r  - ");
    698                 }
    699             }
    700             i++;
    701                         if( i> USB_EPT_NUM) break;  // exit
    702         }
    703         }
    704 }
    705 
     645                        ept_int &= ~(1 << i);
     646                }
     647                i++;
     648                if (i > USB_EPT_NUM)
     649                        break;  // fire exit
     650        }
     651}
     652
     653// USB_Handler ISR
     654extern "C" void UDD_Handler(void) {
     655        ISRHandler();
     656}
    706657
    707658
    708659void USBD_Flush(uint32_t ep)
    709660{
    710         if (UDD_FifoByteCount(ep))
    711         {
    712                 UDD_ReleaseTX(ep);
    713         }
    714 }
    715 
    716 //      Counting frames
    717 uint32_t USBD_Connected(void)
    718 {
    719         uint8_t f = UDD_GetFrameNumber();
    720         return f != UDD_GetFrameNumber();
    721 }
    722 
    723 
    724 //=======================================================================
    725 //=======================================================================
    726 
    727 USBDevice_ USBDevice;
    728 
    729 USBDevice_::USBDevice_()
    730 {
     661        if (USBD_Available(ep)) {
     662                // RAM buffer is full, we can send data (IN)
     663                usbd.epBank1SetReady(ep);
     664
     665                // Clear the transfer complete flag
     666                usbd.epBank1AckTransferComplete(ep);
     667        }
     668}
     669
     670
     671bool connected()
     672{
     673        // Count frame numbers
     674        uint8_t f = USB->DEVICE.FNUM.bit.FNUM;
     675        //delay(3);
     676        return f != USB->DEVICE.FNUM.bit.FNUM;
     677}
     678
     679uint8_t armRecvCtrlOUT(uint32_t ep)
     680{
     681        // Get endpoint configuration from setting register
     682        usbd.epBank0SetAddress(ep, &udd_ep_out_cache_buffer[ep]);
     683        usbd.epBank0SetMultiPacketSize(ep, 8);
     684        usbd.epBank0SetByteCount(ep, 0);
     685
     686        usbd.epBank0ResetReady(ep);
     687
     688        // Wait OUT
     689        while (!usbd.epBank0IsReady(ep)) {}
     690        while (!usbd.epBank0IsTransferComplete(ep)) {}
     691        return usbd.epBank0ByteCount(ep);
     692}
     693
     694
     695uint32_t USBD_RecvControl(void *_data, uint32_t len)
     696{
     697        uint8_t *data = reinterpret_cast<uint8_t *>(_data);
     698
     699        // The RAM Buffer is empty: we can receive data
     700        usbd.epBank0ResetReady(0);
     701
     702        //usbd.epBank0AckSetupReceived(0);
     703        uint32_t read = armRecvCtrlOUT(0);
     704        if (read > len)
     705                read = len;
     706        //while (!usbd.epBank0AckTransferComplete(0)) {}
     707        uint8_t *buffer = udd_ep_out_cache_buffer[0];
     708        for (uint32_t i=0; i<len; i++) {
     709                data[i] = buffer[i];
     710        }
     711
     712        return read;
     713}
     714
     715// Number of bytes, assumes a rx endpoint
     716uint32_t USBD_Available(uint32_t ep)
     717{
     718        return usbd.epBank0ByteCount(ep);
     719}
     720
     721uint8_t armRecv(uint32_t ep)
     722{
     723        uint16_t count = usbd.epBank0ByteCount(ep);
     724        if (count >= 64) {
     725                usbd.epBank0SetByteCount(ep, count - 64);
     726        } else {
     727                usbd.epBank0SetByteCount(ep, 0);
     728        }
     729        return usbd.epBank0ByteCount(ep);
     730}
     731
     732// Non Blocking receive
     733// Return number of bytes read
     734uint32_t USBD_Recv(uint32_t ep, void *_data, uint32_t len)
     735{
     736        if (!_usbConfiguration)
     737                return -1;
     738
     739        PORT->Group[1].OUTCLR.reg =0x00000008 ; //RxLED on
     740        if (USBD_Available(ep) < len)
     741                len = USBD_Available(ep);
     742
     743        armRecv(ep);
     744
     745        usbd.epBank0DisableTransferComplete(ep);
     746
     747        memcpy(_data, udd_ep_out_cache_buffer[ep], len);
     748
     749        // release empty buffer
     750        if (len && !USBD_Available(ep)) {
     751                // The RAM Buffer is empty: we can receive data
     752                usbd.epBank0ResetReady(ep);
     753
     754                // Clear Transfer complete 0 flag
     755                usbd.epBank0AckTransferComplete(ep);
     756        }
     757
     758        return len;
     759}
     760
     761// Recv 1 byte if ready
     762uint32_t USBD_Recv(uint32_t ep)
     763{
     764        uint8_t c;
     765        if (USBD_Recv(ep, &c, 1) != 1) {
     766                return -1;
     767        } else {
     768                return c;
     769        }
     770}
     771
     772
     773
     774//==================================================================
     775
     776void USBDevice_::init()
     777{
     778        // Enable USB clock
     779        PM->APBBMASK.reg |= PM_APBBMASK_USB;
     780
     781        // Set up the USB DP/DN pins
     782        PORT->Group[0].PINCFG[PIN_PA24G_USB_DM].bit.PMUXEN = 1;
     783        PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg &= ~(0xF << (4 * (PIN_PA24G_USB_DM & 0x01u)));
     784        PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg |= MUX_PA24G_USB_DM << (4 * (PIN_PA24G_USB_DM & 0x01u));
     785        PORT->Group[0].PINCFG[PIN_PA25G_USB_DP].bit.PMUXEN = 1;
     786        PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg &= ~(0xF << (4 * (PIN_PA25G_USB_DP & 0x01u)));
     787        PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg |= MUX_PA25G_USB_DP << (4 * (PIN_PA25G_USB_DP & 0x01u));
     788
     789        // Put Generic Clock Generator 0 as source for Generic Clock Multiplexer 6 (USB reference)
     790        GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(6)     | // Generic Clock Multiplexer 6
     791                            GCLK_CLKCTRL_GEN_GCLK0 | // Generic Clock Generator 0 is source
     792                            GCLK_CLKCTRL_CLKEN;
     793        while (GCLK->STATUS.bit.SYNCBUSY)
     794                ;
     795
     796        USB_SetHandler(&UDD_Handler);
     797
     798        // Reset USB Device
     799        usbd.reset();
     800
     801        usbd.calibrate();
     802        usbd.setUSBDeviceMode();
     803        usbd.runInStandby();
     804        usbd.setFullSpeed();
     805
     806        // Configure interrupts
     807        NVIC_SetPriority((IRQn_Type) USB_IRQn, 0UL);
     808        NVIC_EnableIRQ((IRQn_Type) USB_IRQn);
     809
     810        usbd.enable();
     811
     812        initialized = true;
    731813}
    732814
    733815bool USBDevice_::attach()
    734816{
    735   if (_usbInitialized != 0UL)
    736   {
    737     UDD_Attach();
     817        if (!initialized)
     818                return false;
     819
     820        usbd.attach();
     821        usbd.enableEndOfResetInterrupt();
     822        usbd.enableStartOfFrameInterrupt();
     823
    738824        _usbConfiguration = 0;
    739825        return true;
    740   }
    741   else
    742   {
    743     return false;
    744   }
    745 }
     826}
     827
    746828
    747829bool USBDevice_::detach()
    748830{
    749         if (_usbInitialized != 0UL)
    750         {
    751                 UDD_Detach();
    752                 return true;
    753         }
    754         else
    755         {
     831        if (!initialized)
    756832                return false;
    757         }
     833        usbd.detach();
     834        return true;
    758835}
    759836
    760837bool USBDevice_::configured()
    761838{
    762         return _usbConfiguration;
    763 }
    764 
    765 void USBDevice_::poll()
    766 {
    767 }
    768 
    769 void USBDevice_::init()
    770 {
    771         UDD_Init();
    772         _usbInitialized=1UL;
    773 }
     839        return _usbConfiguration != 0;
     840}
     841
     842
     843       
     844/*
     845 * USB Device instance
     846 * -------------------
     847 */
     848
     849// USBDevice class instance
     850USBDevice_ USBDevice;
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/USBCore.h

    r136 r224  
    1 // Copyright (c) 2010, Peter Barrett
    21/*
    3 ** Permission to use, copy, modify, and/or distribute this software for
    4 ** any purpose with or without fee is hereby granted, provided that the
    5 ** above copyright notice and this permission notice appear in all copies.
    6 **
    7 ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
    8 ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
    9 ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
    10 ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
    11 ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
    12 ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
    13 ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
    14 ** SOFTWARE.
     2  Copyright (c) 2014 Arduino LLC.  All right reserved.
     3
     4  This library is free software; you can redistribute it and/or
     5  modify it under the terms of the GNU Lesser General Public
     6  License as published by the Free Software Foundation; either
     7  version 2.1 of the License, or (at your option) any later version.
     8
     9  This library is distributed in the hope that it will be useful,
     10  but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     12  See the GNU Lesser General Public License for more details.
     13
     14  You should have received a copy of the GNU Lesser General Public
     15  License along with this library; if not, write to the Free Software
     16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    1517*/
     18/*
     19**Modified 04/04/2016 by Arduino.org development team
     20*/
     21
    1622
    1723#ifndef __USBCORE_H__
     
    3036#define SET_INTERFACE                           11
    3137
     38// bEndpointAddress in Endpoint Descriptor
     39#define USB_ENDPOINT_DIRECTION_MASK            0x80
     40#define USB_ENDPOINT_OUT(addr)                 ((addr) | 0x00)
     41#define USB_ENDPOINT_IN(addr)                  ((addr) | 0x80)
     42
     43#define USB_ENDPOINTS                          7
     44
     45#define USB_ENDPOINT_TYPE_MASK                 0x03
     46#define USB_ENDPOINT_TYPE_CONTROL              0x00
     47#define USB_ENDPOINT_TYPE_ISOCHRONOUS          0x01
     48#define USB_ENDPOINT_TYPE_BULK                 0x02
     49#define USB_ENDPOINT_TYPE_INTERRUPT            0x03
    3250
    3351// bmRequestType
     
    4765#define REQUEST_RECIPIENT                       0x1F
    4866
    49 #define REQUEST_DEVICETOHOST_CLASS_INTERFACE  (REQUEST_DEVICETOHOST + REQUEST_CLASS + REQUEST_INTERFACE)
    50 #define REQUEST_HOSTTODEVICE_CLASS_INTERFACE  (REQUEST_HOSTTODEVICE + REQUEST_CLASS + REQUEST_INTERFACE)
     67#define REQUEST_DEVICETOHOST_CLASS_INTERFACE    (REQUEST_DEVICETOHOST | REQUEST_CLASS | REQUEST_INTERFACE)
     68#define REQUEST_HOSTTODEVICE_CLASS_INTERFACE    (REQUEST_HOSTTODEVICE | REQUEST_CLASS | REQUEST_INTERFACE)
     69#define REQUEST_DEVICETOHOST_STANDARD_INTERFACE (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_INTERFACE)
    5170
    5271//      Class requests
     
    5574#define CDC_GET_LINE_CODING                     0x21
    5675#define CDC_SET_CONTROL_LINE_STATE      0x22
     76#define CDC_SEND_BREAK                          0x23
    5777
    5878#define MSC_RESET                                       0xFF
     
    108128#define MSC_SUBCLASS_SCSI                                               0x06
    109129#define MSC_PROTOCOL_BULK_ONLY                                  0x50
    110 
    111 #define HID_HID_DESCRIPTOR_TYPE                                 0x21
    112 #define HID_REPORT_DESCRIPTOR_TYPE                              0x22
    113 #define HID_PHYSICAL_DESCRIPTOR_TYPE                    0x23
    114 
    115 #define TX_RX_LED_PULSE_MS 100     //----- Tx & Rx led blinking during transmission (declaration)
    116130
    117131_Pragma("pack(1)")
     
    225239typedef struct
    226240{
    227 #if (defined CDC_ENABLED) && defined(HID_ENABLED)
    228241        //      IAD
    229242        IADDescriptor                           iad;    // Only needed on compound device
    230 #endif
    231243        //      Control
    232244        InterfaceDescriptor                     cif;
     
    249261        EndpointDescriptor                      out;
    250262} MSCDescriptor;
     263
    251264
    252265typedef struct
     
    273286
    274287#define D_DEVICE(_class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs) \
    275         { 18, 1, 0x110, _class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs }
     288        { 18, 1, 0x200, _class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs }
    276289/* Table 9-8. Standard Device Descriptor
    277290 * bLength, bDescriptorType, bcdUSB, bDeviceClass, bDeviceSubClass, bDeviceProtocol, bMaxPacketSize0,
     
    279292
    280293#define D_CONFIG(_totalLength,_interfaces) \
    281         { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_SELF_POWERED, USB_CONFIG_POWER_MA(500) }
     294        { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED, USB_CONFIG_POWER_MA(500) }
    282295/* Table 9-10. Standard Configuration Descriptor
    283296 * bLength, bDescriptorType, wTotalLength, bNumInterfaces, bConfigurationValue, iConfiguration
    284297 * bmAttributes, bMaxPower */
    285  
     298
    286299#define D_INTERFACE(_n,_numEndpoints,_class,_subClass,_protocol) \
    287300        { 9, 4, _n, 0, _numEndpoints, _class,_subClass, _protocol, 0 }
     
    289302 * bLength, bDescriptorType, bInterfaceNumber, bAlternateSetting, bNumEndpoints, bInterfaceClass,
    290303 * bInterfaceSubClass, bInterfaceProtocol, iInterface */
    291  
     304
    292305#define D_ENDPOINT(_addr,_attr,_packetSize, _interval) \
    293306        { 7, 5, _addr,_attr,_packetSize, _interval }
     
    297310#define D_IAD(_firstInterface, _count, _class, _subClass, _protocol) \
    298311        { 8, 11, _firstInterface, _count, _class, _subClass, _protocol, 0 }
    299 /* iadclasscode_r10.pdf, Table 9–Z. Standard Interface Association Descriptor
     312/* iadclasscode_r10.pdf, Table 9\96Z. Standard Interface Association Descriptor
    300313 * bLength, bDescriptorType, bFirstInterface, bInterfaceCount, bFunctionClass, bFunctionSubClass, bFunctionProtocol, iFunction */
    301314#define D_HIDREPORT(_descriptorLength) \
     
    303316/* HID1_11.pdf  E.8 HID Descriptor (Mouse)
    304317 * bLength, bDescriptorType, bcdHID, bCountryCode, bNumDescriptors, bDescriptorType, wItemLength */
    305 
     318 
    306319// Functional Descriptor General Format
    307320#define D_CDCCS(_subtype,_d0,_d1)       { 5, 0x24, _subtype, _d0, _d1 }
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/USBDesc.h

    r136 r224  
    1 // Copyright (c) 2010, Peter Barrett
    21/*
    3 ** Permission to use, copy, modify, and/or distribute this software for
    4 ** any purpose with or without fee is hereby granted, provided that the
    5 ** above copyright notice and this permission notice appear in all copies.
    6 **
    7 ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
    8 ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
    9 ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
    10 ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
    11 ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
    12 ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
    13 ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
    14 ** SOFTWARE.
     2  Copyright (c) 2014 Arduino LLC.  All right reserved.
     3
     4  This library is free software; you can redistribute it and/or
     5  modify it under the terms of the GNU Lesser General Public
     6  License as published by the Free Software Foundation; either
     7  version 2.1 of the License, or (at your option) any later version.
     8
     9  This library is distributed in the hope that it will be useful,
     10  but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     12  See the GNU Lesser General Public License for more details.
     13
     14  You should have received a copy of the GNU Lesser General Public
     15  License along with this library; if not, write to the Free Software
     16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     17*/
     18/*
     19**Modified 04/04/2016 by Arduino.org development team
    1520*/
    1621
     
    2227#define HID_ENABLED
    2328
     29
     30#ifdef CDC_ENABLED
     31#define CDC_INTERFACE_COUNT 2
     32#define CDC_ENPOINT_COUNT 3
     33#endif
     34
    2435// CDC
    2536#define CDC_ACM_INTERFACE       0       // CDC ACM
    2637#define CDC_DATA_INTERFACE      1       // CDC Data
     38#define CDC_FIRST_ENDPOINT  1
    2739#define CDC_ENDPOINT_ACM        1
    2840#define CDC_ENDPOINT_OUT        2
    2941#define CDC_ENDPOINT_IN         3
     42
     43#ifdef CDC_ENABLED
     44#define CDC_RX CDC_ENDPOINT_OUT
     45#define CDC_TX CDC_ENDPOINT_IN
     46#endif
    3047
    3148// HID
     
    3350#define HID_ENDPOINT_INT        4 
    3451
     52
     53#define ISERIAL_MAX_LEN        20
     54
    3555// Defined string description
    3656#define IMANUFACTURER   1
    37 #define IPRODUCT                2
     57#define IPRODUCT    2
     58#define ISERIAL    3
    3859
    3960#endif /* __USBDESC_H__ */
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/USB_host.h

    r136 r224  
    1 /* ----------------------------------------------------------------------------
    2  *         SAM Software Package License
    3  * ----------------------------------------------------------------------------
    4  * Copyright (c) 2011-2012, Atmel Corporation
    5  *
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following condition is met:
    10  *
    11  * - Redistributions of source code must retain the above copyright notice,
    12  * this list of conditions and the disclaimer below.
    13  *
    14  * Atmel's name may not be used to endorse or promote products derived from
    15  * this software without specific prior written permission.
    16  *
    17  * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
    18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
    20  * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
    21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
    23  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    24  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    25  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
    26  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    27  * ----------------------------------------------------------------------------
    28  */
     1/*
     2  Copyright (c) 2014 Arduino LLC.  All right reserved.
     3
     4  This library is free software; you can redistribute it and/or
     5  modify it under the terms of the GNU Lesser General Public
     6  License as published by the Free Software Foundation; either
     7  version 2.1 of the License, or (at your option) any later version.
     8
     9  This library is distributed in the hope that it will be useful,
     10  but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     12  See the GNU Lesser General Public License for more details.
     13
     14  You should have received a copy of the GNU Lesser General Public
     15  License along with this library; if not, write to the Free Software
     16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     17*/
     18/*
     19**Modified 04/04/2016 by Arduino.org development team
     20*/
    2921
    3022#ifndef USB_HOST_H_INCLUDED
     
    3224
    3325#include <stdint.h>
    34 
     26#include "samd21_host.h"
    3527#ifdef __cplusplus
    3628extern "C" {
    3729#endif
    3830
    39 #define tokSETUP                UOTGHS_HSTPIPCFG_PTOKEN_SETUP
    40 #define tokIN                   UOTGHS_HSTPIPCFG_PTOKEN_IN
    41 #define tokOUT                  UOTGHS_HSTPIPCFG_PTOKEN_OUT
    42 #define tokINHS                 UOTGHS_HSTPIPCFG_PTOKEN_IN
    43 #define tokOUTHS                UOTGHS_HSTPIPCFG_PTOKEN_OUT
     31#define tokSETUP                USB_HOST_PCFG_PTOKEN_SETUP
     32#define tokIN                   USB_HOST_PCFG_PTOKEN_IN
     33#define tokOUT                  USB_HOST_PCFG_PTOKEN_OUT
     34#define tokINHS                 USB_HOST_PCFG_PTOKEN_IN
     35#define tokOUTHS                USB_HOST_PCFG_PTOKEN_OUT
    4436
    4537//! \brief Device speed
     
    5850} uhd_vbus_state_t;
    5951
    60 //extern uhd_speed_t uhd_get_speed(void);
    61 
    62 extern void UHD_SetStack(void (*pf_isr)(void));
    6352extern void UHD_Init(void);
    64 extern void UHD_BusReset(void);
     53extern void UHD_Handler(void);
     54extern void USB_SetHandler(void (*pf_isr)(void));
    6555extern uhd_vbus_state_t UHD_GetVBUSState(void);
    6656extern uint32_t UHD_Pipe0_Alloc(uint32_t ul_add, uint32_t ul_ep_size);
    6757extern uint32_t UHD_Pipe_Alloc(uint32_t ul_dev_addr, uint32_t ul_dev_ep, uint32_t ul_type, uint32_t ul_dir, uint32_t ul_maxsize, uint32_t ul_interval, uint32_t ul_nb_bank);
     58extern void UHD_Pipe_CountZero(uint32_t ul_pipe);
    6859extern void UHD_Pipe_Free(uint32_t ul_pipe);
    6960extern uint32_t UHD_Pipe_Read(uint32_t ul_pipe, uint32_t ul_size, uint8_t* data);
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/samd21_host.c

    r136 r224  
    1 /* ----------------------------------------------------------------------------
    2  *         SAM Software Package License
    3  * ----------------------------------------------------------------------------
    4  * Copyright (c) 2011-2012, Atmel Corporation
    5  *
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following condition is met:
    10  *
    11  * - Redistributions of source code must retain the above copyright notice,
    12  * this list of conditions and the disclaimer below.
    13  *
    14  * Atmel's name may not be used to endorse or promote products derived from
    15  * this software without specific prior written permission.
    16  *
    17  * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
    18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
    20  * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
    21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
    23  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    24  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    25  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
    26  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    27  * ----------------------------------------------------------------------------
    28  */
     1/*
     2  Copyright (c) 2014 Arduino LLC.  All right reserved.
     3
     4  This library is free software; you can redistribute it and/or
     5  modify it under the terms of the GNU Lesser General Public
     6  License as published by the Free Software Foundation; either
     7  version 2.1 of the License, or (at your option) any later version.
     8
     9  This library is distributed in the hope that it will be useful,
     10  but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     12  See the GNU Lesser General Public License for more details.
     13
     14  You should have received a copy of the GNU Lesser General Public
     15  License along with this library; if not, write to the Free Software
     16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     17*/
     18/*
     19** Modified 04/04/2016 by Arduino.org development team
     20*/
     21
     22
    2923
    3024#include <stdio.h>
     25#include <stdint.h>
     26#include <string.h>
     27
     28#include "../Arduino.h"
     29#include "variant.h"
     30#include "USB_host.h"
     31#include "samd21_host.h"
     32#include "sam.h"
     33#include "wiring_digital.h"
     34#include "wiring_private.h"
     35
     36#define HOST_DEFINED
    3137
    3238#ifdef HOST_DEFINED
     
    3541#define TRACE_UOTGHS_HOST(x)
    3642
    37 //extern void (*gpf_isr)(void);
    38 
    3943// Handle UOTGHS Host driver state
    4044static uhd_vbus_state_t uhd_state = UHD_STATE_NO_VBUS;
    4145
    42  __attribute__((__aligned__(4))) UsbHostDescriptor usb_pipe_table[USB_EPT_NUM];
     46__attribute__((__aligned__(4))) volatile UsbHostDescriptor usb_pipe_table[USB_EPT_NUM];
     47
     48extern void (*gpf_isr)(void);
    4349
    4450
    4551// NVM Software Calibration Area Mapping
    4652// USB TRANSN calibration value. Should be written to the USB PADCAL register.
    47 #define NVM_USB_PAD_TRANSN_POS  45
    48 #define NVM_USB_PAD_TRANSN_SIZE 5
     53#define NVM_USB_PAD_TRANSN_POS     45
     54#define NVM_USB_PAD_TRANSN_SIZE    5
    4955// USB TRANSP calibration value. Should be written to the USB PADCAL register.
    50 #define NVM_USB_PAD_TRANSP_POS  50
    51 #define NVM_USB_PAD_TRANSP_SIZE 5
     56#define NVM_USB_PAD_TRANSP_POS     50
     57#define NVM_USB_PAD_TRANSP_SIZE    5
    5258// USB TRIM calibration value. Should be written to the USB PADCAL register.
    53 #define NVM_USB_PAD_TRIM_POS  55
    54 #define NVM_USB_PAD_TRIM_SIZE 3
     59#define NVM_USB_PAD_TRIM_POS       55
     60#define NVM_USB_PAD_TRIM_SIZE      3
     61
     62static void UHD_ISR(void);
    5563
    5664/**
     
    6068{
    6169        uint32_t pad_transn;
    62     uint32_t pad_transp;
    63     uint32_t pad_trim;
     70        uint32_t pad_transp;
     71        uint32_t pad_trim;
     72        uint32_t i;
     73
     74//      USB_SetHandler(&USB_Handler);
     75        USB_SetHandler(&UHD_ISR);
    6476
    6577        /* Enable USB clock */
    6678        PM->APBBMASK.reg |= PM_APBBMASK_USB;
    6779
    68         /* Set up the USB DP/DN pins */
    69         PORT->Group[0].PINCFG[PIN_PA24G_USB_DM].bit.PMUXEN = 1;
    70         PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg &= ~(0xF << (4 * (PIN_PA24G_USB_DM & 0x01u)));
    71         PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg |= MUX_PA24G_USB_DM << (4 * (PIN_PA24G_USB_DM & 0x01u));
    72         PORT->Group[0].PINCFG[PIN_PA25G_USB_DP].bit.PMUXEN = 1;
    73         PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg &= ~(0xF << (4 * (PIN_PA25G_USB_DP & 0x01u)));
    74         PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg |= MUX_PA25G_USB_DP << (4 * (PIN_PA25G_USB_DP & 0x01u));
     80        /* Set up the USB DP/DM pins */
     81        pinPeripheral( 33ul, PIO_COM );
     82        pinPeripheral( 34ul, PIO_COM );
    7583
    7684        /* ----------------------------------------------------------------------------------------------
    77          * Put Generic Clock Generator 0 as source for Generic Clock Multiplexer 6 (USB reference)
    78          */
    79         GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID( 6 ) | // Generic Clock Multiplexer 6
    80                                         GCLK_CLKCTRL_GEN_GCLK0 | // Generic Clock Generator 0 is source
    81                                         GCLK_CLKCTRL_CLKEN ;
    82 
    83         while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
    84         {
    85         /* Wait for synchronization */
     85        * Put Generic Clock Generator 0 as source for Generic Clock Multiplexer 6 (USB reference)
     86        */
     87        GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(6) |        // Generic Clock Multiplexer 6
     88                                                GCLK_CLKCTRL_GEN_GCLK0 |    // Generic Clock Generator 0 is source
     89                                                GCLK_CLKCTRL_CLKEN;
     90
     91        while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY)
     92        {
     93                /* Wait for synchronization */
    8694        }
    8795
    8896        /* Reset */
    8997        USB->HOST.CTRLA.bit.SWRST = 1;
    90         while (USB->HOST.SYNCBUSY.bit.SWRST) {
     98        while (USB->HOST.SYNCBUSY.bit.SWRST)
     99        {
    91100                /* Sync wait */
    92101        }
    93102
    94         udd_enable();
     103        //  uhd_enable();
     104        USB->DEVICE.CTRLA.reg |= USB_CTRLA_ENABLE | USB_CTRLA_MODE;
     105        uhd_force_host_mode();
     106        while (USB->HOST.SYNCBUSY.reg == USB_SYNCBUSY_ENABLE);
    95107
    96108        /* Load Pad Calibration */
    97         pad_transn =( *((uint32_t *)(NVMCTRL_OTP4)  // Non-Volatile Memory Controller
    98         + (NVM_USB_PAD_TRANSN_POS / 32))
    99         >> (NVM_USB_PAD_TRANSN_POS % 32))
    100         & ((1 << NVM_USB_PAD_TRANSN_SIZE) - 1);
    101 
    102         if (pad_transn == 0x1F) {  // maximum value (31)
     109        pad_transn = (*((uint32_t *)(NVMCTRL_OTP4)       // Non-Volatile Memory Controller
     110                                        + (NVM_USB_PAD_TRANSN_POS / 32))
     111                                        >> (NVM_USB_PAD_TRANSN_POS % 32))
     112                                & ((1 << NVM_USB_PAD_TRANSN_SIZE) - 1);
     113
     114        if (pad_transn == 0x1F)         // maximum value (31)
     115        {
    103116                pad_transn = 5;
    104117        }
     
    106119        USB->HOST.PADCAL.bit.TRANSN = pad_transn;
    107120
    108         pad_transp =( *((uint32_t *)(NVMCTRL_OTP4)
    109         + (NVM_USB_PAD_TRANSP_POS / 32))
    110         >> (NVM_USB_PAD_TRANSP_POS % 32))
    111         & ((1 << NVM_USB_PAD_TRANSP_SIZE) - 1);
    112 
    113         if (pad_transp == 0x1F) {  // maximum value (31)
     121        pad_transp = (*((uint32_t *)(NVMCTRL_OTP4)
     122                                        + (NVM_USB_PAD_TRANSP_POS / 32))
     123                                        >> (NVM_USB_PAD_TRANSP_POS % 32))
     124                                & ((1 << NVM_USB_PAD_TRANSP_SIZE) - 1);
     125
     126        if (pad_transp == 0x1F)         // maximum value (31)
     127        {
    114128                pad_transp = 29;
    115129        }
     
    117131        USB->HOST.PADCAL.bit.TRANSP = pad_transp;
    118132
    119         pad_trim =( *((uint32_t *)(NVMCTRL_OTP4)
    120         + (NVM_USB_PAD_TRIM_POS / 32))
    121         >> (NVM_USB_PAD_TRIM_POS % 32))
    122         & ((1 << NVM_USB_PAD_TRIM_SIZE) - 1);
    123 
    124         if (pad_trim == 0x7) {  // maximum value (7)
     133        pad_trim = (*((uint32_t *)(NVMCTRL_OTP4)
     134                                        + (NVM_USB_PAD_TRIM_POS / 32))
     135                                >> (NVM_USB_PAD_TRIM_POS % 32))
     136                                & ((1 << NVM_USB_PAD_TRIM_SIZE) - 1);
     137
     138        if (pad_trim == 0x7)         // maximum value (7)
     139        {
    125140                pad_trim = 3;
    126141        }
     
    128143        USB->HOST.PADCAL.bit.TRIM = pad_trim;
    129144
     145
    130146        /* Set the configuration */
    131         udd_force_host_mode();
    132         udd_device_run_in_standby();
    133     // Set address of USB SRAM
    134         USB->HOST.DESCADD.reg = (uint32_t)(&usb_endpoint_table[0]);
    135         // For USB_SPEED_FULL
    136         udd_force_full_speed();
    137         for (uint32_t i = 0; i < sizeof(usb_endpoint_table); i++) {
    138                 (*(uint32_t *)(&usb_endpoint_table[0]+i)) = 0;
    139         }
     147        uhd_run_in_standby();
     148        // Set address of USB SRAM
     149        USB->HOST.DESCADD.reg = (uint32_t)(&usb_pipe_table[0]);
     150        // For USB_SPEED_FULL
     151        uhd_force_full_speed();
     152        for (i = 0; i < sizeof(usb_pipe_table); i++)
     153        {
     154                (*(uint32_t *)(&usb_pipe_table[0] + i)) = 0;
     155        }
    140156
    141157        uhd_state = UHD_STATE_NO_VBUS;
    142158
     159        // Put VBUS on USB port
     160        pinMode( 32ul, OUTPUT );
     161        digitalWrite( 32ul, HIGH );
     162
     163        uhd_enable_connection_int();
     164
     165        USB->HOST.INTENSET.reg = USB_HOST_INTENSET_DCONN;
     166        USB->HOST.INTENSET.reg = USB_HOST_INTENSET_WAKEUP;
     167        USB->HOST.INTENSET.reg = USB_HOST_INTENSET_DDISC;
     168
    143169        USB->HOST.CTRLB.bit.VBUSOK = 1;
    144170
    145171        // Configure interrupts
    146         NVIC_SetPriority((IRQn_Type) USB_IRQn, 0UL);
    147         NVIC_EnableIRQ((IRQn_Type) USB_IRQn);
    148 }
    149 
    150 //static void UHD_ISR(void)
    151 void USB_Handler(void)
    152 {
    153         uint16_t flags;
    154         uint8_t i;
    155         uint8_t ept_int;
    156 
    157         ept_int = udd_endpoint_interrupt();
    158        
    159         /* Not endpoint interrupt */
    160         if (0 == ept_int)
    161         {
    162 
    163 
    164         }
    165         else
    166         {
    167                 /* host interrupts */
     172        NVIC_SetPriority((IRQn_Type)USB_IRQn, 0UL);
     173        NVIC_EnableIRQ((IRQn_Type)USB_IRQn);
     174}
     175
     176
     177static void UHD_ISR(void)
     178//void USB_Handler(void)
     179{
     180   uint16_t flags;
     181
     182        if (USB->HOST.CTRLA.bit.MODE) {
     183                /*host mode ISR */
    168184
    169185                /* get interrupt flags */
     
    171187
    172188                /* host SOF interrupt */
    173                 if (flags & USB_HOST_INTFLAG_HSOF) {
     189                if (flags & USB_HOST_INTFLAG_HSOF)
     190                {
    174191                        /* clear the flag */
    175192                        USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_HSOF;
    176                         uhd_state = UHD_STATE_CONNECTED;
     193                        uhd_state             = UHD_STATE_CONNECTED;
    177194                        return;
    178195                }
    179196
    180197                /* host reset interrupt */
    181                 if (flags & USB_HOST_INTFLAG_RST) {
     198                if (flags & USB_HOST_INTFLAG_RST)
     199                {
    182200                        /* clear the flag */
    183201                        USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_RST;
    184                         uhd_state = UHD_STATE_DISCONNECTED; //UHD_STATE_ERROR;
     202                        uhd_state             = UHD_STATE_DISCONNECTED;    //UHD_STATE_ERROR;
    185203                        return;
    186204                }
    187205
    188206                /* host upstream resume interrupts */
    189                 if (flags & USB_HOST_INTFLAG_UPRSM) {
     207                if (flags & USB_HOST_INTFLAG_UPRSM)
     208                {
    190209                        /* clear the flags */
    191210                        USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_UPRSM;
    192                         uhd_state = UHD_STATE_DISCONNECTED; //UHD_STATE_ERROR;
     211                        uhd_state             = UHD_STATE_DISCONNECTED;    //UHD_STATE_ERROR;
    193212                        return;
    194213                }
    195214
    196215                /* host downstream resume interrupts */
    197                 if (flags & USB_HOST_INTFLAG_DNRSM) {
     216                if (flags & USB_HOST_INTFLAG_DNRSM)
     217                {
    198218                        /* clear the flags */
    199219                        USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_DNRSM;
    200                         uhd_state = UHD_STATE_DISCONNECTED; //UHD_STATE_ERROR;
     220                        uhd_state             = UHD_STATE_DISCONNECTED;    //UHD_STATE_ERROR;
    201221                        return;
    202222                }
    203223
    204224                /* host wakeup interrupts */
    205                 if (flags & USB_HOST_INTFLAG_WAKEUP) {
     225                if (flags & USB_HOST_INTFLAG_WAKEUP)
     226                {
    206227                        /* clear the flags */
    207228                        USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_WAKEUP;
    208                         uhd_state = UHD_STATE_CONNECTED; //UHD_STATE_ERROR;
     229                        uhd_state             = UHD_STATE_CONNECTED;    //UHD_STATE_ERROR;
    209230                        return;
    210231                }
    211232
    212233                /* host ram access interrupt  */
    213                 if (flags & USB_HOST_INTFLAG_RAMACER) {
     234                if (flags & USB_HOST_INTFLAG_RAMACER)
     235                {
    214236                        /* clear the flag */
    215237                        USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_RAMACER;
    216                         uhd_state = UHD_STATE_DISCONNECTED; //UHD_STATE_ERROR;
     238                        uhd_state             = UHD_STATE_DISCONNECTED;    //UHD_STATE_ERROR;
    217239                        return;
    218240                }
    219241
    220242                /* host connect interrupt */
    221                 if (flags & USB_HOST_INTFLAG_DCONN) {
    222                         TRACE_UOTGHS_HOST(printf(">>> UHD_ISR : Connection INT\r\n");)
     243                if (flags & USB_HOST_INTFLAG_DCONN)
     244                {
     245                        TRACE_UOTGHS_HOST(printf(">>> UHD_ISR : Connection INT\r\n");
     246                                                        )
    223247                        /* clear the flag */
    224248                        uhd_ack_connection();
     
    231255                }
    232256
    233                 /* host disconnect interrupt    */
    234                 if (flags & USB_HOST_INTFLAG_DDISC) {
    235                         TRACE_UOTGHS_HOST(printf(">>> UHD_ISR : Disconnection INT\r\n");)
     257                /* host disconnect interrupt  */
     258                if (flags & USB_HOST_INTFLAG_DDISC)
     259                {
     260                        TRACE_UOTGHS_HOST(printf(">>> UHD_ISR : Disconnection INT\r\n");
     261                                                        )
    236262                        /* clear the flag */
    237263                        uhd_ack_disconnection();
     
    246272                        return;
    247273                }
    248 
    249         }
    250 
    251 }
    252 
    253 
    254 
    255 
    256 /**
    257  * \brief Trigger a USB bus reset.
    258  */
    259 void UHD_BusReset(void)
    260 {
    261         USB->HOST.CTRLB.bit.BUSRESET = 1;;
    262 }
     274        }
     275        else {
     276                while(1);
     277        }
     278}
     279
     280
    263281
    264282/**
     
    269287uhd_vbus_state_t UHD_GetVBUSState(void)
    270288{
    271         return uhd_state;
    272 }
    273 
     289   return uhd_state;
     290}
    274291
    275292
     
    283300 * \retval 1 error.
    284301 */
    285 uint32_t UHD_Pipe0_Alloc(uint32_t ul_add, uint32_t ul_ep_size)
    286 {
    287         struct usb_host_pipe_config cfg;
    288 
    289         if (ep_size < 8)
    290         {
    291                 return 0;
    292         }
    293 
    294         /* set pipe config */
    295         USB->HOST.HostPipe[0].PCFG.bit.BK = 0;
    296         USB->HOST.HostPipe[0].PCFG.bit.PTYPE = USB_HOST_PIPE_TYPE_CONTROL;
    297         USB->HOST.HostPipe[0].BINTERVAL.reg = 0;
    298         USB->HOST.HostPipe[0].PCFG.bit.PTOKEN = USB_HOST_PIPE_TOKEN_SETUP;
    299 
    300         memset((uint8_t *)&usb_pipe_table[pipe_num], 0, sizeof(usb_pipe_table[0]));
    301         usb_pipe_table[pipe_num].HostDescBank[0].CTRL_PIPE.bit.PDADDR = 0;
    302         usb_pipe_table[pipe_num].HostDescBank[0].CTRL_PIPE.bit.PEPNUM = 0;
    303         usb_pipe_table[pipe_num].HostDescBank[0].PCKSIZE.bit.SIZE = 0x03;  // 64 bytes
    304 
    305         USB->HOST.HostPipe[pipe_num].PINTENSET.reg = USB_HOST_PINTENSET_TRCPT_Msk;
    306         USB->HOST.HostPipe[pipe_num].PINTENSET.reg = USB_HOST_PINTENSET_TRFAIL | USB_HOST_PINTENSET_PERR;
    307         USB->HOST.HostPipe[pipe_num].PINTENSET.reg = USB_HOST_PINTENSET_TXSTP;
    308         USB->HOST.HostPipe[pipe_num].PINTENSET.reg = USB_HOST_PINTENSET_STALL;
    309 
    310         return 1;
    311 }
     302uint32_t UHD_Pipe0_Alloc(uint32_t ul_add , uint32_t ul_ep_size)
     303{
     304        (void)(ul_add); // Unused argument
     305
     306        if( USB->HOST.STATUS.reg & USB_HOST_STATUS_SPEED(1) )
     307                ul_ep_size = USB_PCKSIZE_SIZE_8_BYTES;  // Low Speed
     308        else
     309                ul_ep_size = USB_PCKSIZE_SIZE_64_BYTES; // Full Speed
     310
     311        USB->HOST.HostPipe[0].PCFG.bit.PTYPE = 1; //USB_HOST_PCFG_PTYPE_CTRL;
     312        usb_pipe_table[0].HostDescBank[0].CTRL_PIPE.bit.PEPNUM = 0;
     313        usb_pipe_table[0].HostDescBank[0].PCKSIZE.bit.SIZE = ul_ep_size;
     314
     315        return 0;
     316}
     317
    312318
    313319/**
     
    336342{
    337343        /* set pipe config */
    338         USB->HOST.HostPipe[ul_dev_ep].PCFG.bit.BK = ul_nb_bank;
    339         USB->HOST.HostPipe[ul_dev_ep].PCFG.bit.PTYPE = ul_type;
    340         USB->HOST.HostPipe[ul_dev_ep].BINTERVAL.reg = ul_interval;
    341 
    342         if (ul_dir & USB_EP_DIR_IN)
    343         {
    344                 USB->HOST.HostPipe[ul_dev_ep].PCFG.bit.PTOKEN = USB_HOST_PIPE_TOKEN_IN;
    345                 USB->HOST.HostPipe[ul_dev_ep].PSTATUSSET.reg = USB_HOST_PSTATUSSET_BK0RDY;
    346         }
     344        USB->HOST.HostPipe[ul_dev_ep].PCFG.bit.BK    = ul_nb_bank;
     345        USB->HOST.HostPipe[ul_dev_ep].PCFG.reg &= ~USB_HOST_PCFG_MASK;  // USB->HOST.HostPipe[0].PCFG.bit.PTYPE = 1; //USB_HOST_PCFG_PTYPE_CTRL;
     346        USB->HOST.HostPipe[ul_dev_ep].PCFG.reg |= ul_type;
     347        USB->HOST.HostPipe[ul_dev_ep].BINTERVAL.reg  = ul_interval;
     348
     349   if (ul_dir & USB_EP_DIR_IN)
     350   {
     351      USB->HOST.HostPipe[ul_dev_ep].PCFG.bit.PTOKEN = USB_HOST_PCFG_PTOKEN_IN;
     352      USB->HOST.HostPipe[ul_dev_ep].PSTATUSSET.reg  = USB_HOST_PSTATUSSET_BK0RDY;
     353   }
     354   else
     355   {
     356      USB->HOST.HostPipe[ul_dev_ep].PCFG.bit.PTOKEN = USB_HOST_PCFG_PTOKEN_OUT;
     357      USB->HOST.HostPipe[ul_dev_ep].PSTATUSCLR.reg  = USB_HOST_PSTATUSCLR_BK0RDY;
     358   }
     359
     360        if( USB->HOST.STATUS.reg & USB_HOST_STATUS_SPEED(1) )
     361           ul_maxsize = USB_PCKSIZE_SIZE_8_BYTES;  // Low Speed
    347362        else
    348         {
    349                 USB->HOST.HostPipe[ul_dev_ep].PCFG.bit.PTOKEN = USB_HOST_PIPE_TOKEN_OUT;
    350                 USB->HOST.HostPipe[ul_dev_ep].PSTATUSCLR.reg =  USB_HOST_PSTATUSCLR_BK0RDY;
    351         }
    352 
    353         memset((uint8_t *)&usb_descriptor_table.usb_pipe_table[ul_dev_ep], 0, sizeof(usb_pipe_table[ul_dev_ep]));
    354 
    355         usb_descriptor_table.usb_pipe_table[ul_dev_ep].HostDescBank[0].CTRL_PIPE.bit.PDADDR = ul_dev_addr;
    356         usb_descriptor_table.usb_pipe_table[ul_dev_ep].HostDescBank[0].CTRL_PIPE.bit.PEPNUM = ul_dev_ep;
    357         usb_descriptor_table.usb_pipe_table[ul_dev_ep].HostDescBank[0].PCKSIZE.bit.SIZE = 0x03;  // 64 bytes
    358 
    359         USB->HOST.HostPipe[pipe_num].PINTENSET.reg = USB_HOST_PINTENSET_TRCPT_Msk;
    360         USB->HOST.HostPipe[pipe_num].PINTENSET.reg = USB_HOST_PINTENSET_TRFAIL | USB_HOST_PINTENSET_PERR;
    361         USB->HOST.HostPipe[pipe_num].PINTENSET.reg = USB_HOST_PINTENSET_STALL;
    362 
    363         return 1;
    364 }
    365 
     363           ul_maxsize = USB_PCKSIZE_SIZE_64_BYTES; // Full Speed
     364
     365   memset((uint8_t *)&usb_pipe_table[ul_dev_ep], 0, sizeof(usb_pipe_table[ul_dev_ep]));
     366
     367   usb_pipe_table[ul_dev_ep].HostDescBank[0].CTRL_PIPE.bit.PDADDR = ul_dev_addr;
     368   usb_pipe_table[ul_dev_ep].HostDescBank[0].CTRL_PIPE.bit.PEPNUM = ul_dev_ep;
     369   usb_pipe_table[ul_dev_ep].HostDescBank[0].PCKSIZE.bit.SIZE     = ul_maxsize;
     370
     371   return 1;
     372}
     373
     374
     375void UHD_Pipe_CountZero(uint32_t ul_pipe)
     376{
     377        usb_pipe_table[ul_pipe].HostDescBank[0].PCKSIZE.bit.BYTE_COUNT = 0;
     378}
    366379
    367380/**
     
    372385void UHD_Pipe_Free(uint32_t ul_pipe)
    373386{
    374         // Unalloc pipe
    375         uhd_disable_pipe(ul_pipe);
    376         uhd_unallocate_memory(ul_pipe);
    377         uhd_reset_pipe(ul_pipe);
    378 
    379         // The Pipe is frozen and no additional requests will be sent to the device on this pipe address.
    380         USB->HOST.HostPipe[pipe_num].PSTATUSSET.reg = USB_HOST_PSTATUSSET_PFREEZE;
    381 }
     387   // The Pipe is frozen and no additional requests will be sent to the device on this pipe address.
     388   USB->HOST.HostPipe[ul_pipe].PSTATUSSET.reg = USB_HOST_PSTATUSSET_PFREEZE;
     389}
     390
    382391
    383392/**
     
    390399 * \return number of data read.
    391400 */
    392 uint32_t UHD_Pipe_Read(uint32_t pipe_num, uint32_t buf_size, uint8_t* buf)
    393 {
    394         if (USB->HOST.HostPipe[pipe_num].PCFG.bit.PTYPE == USB_HOST_PIPE_TYPE_DISABLE)
    395         {
    396                 return 0;
    397         }
    398 
    399         /* get pipe config from setting register */
    400         usb_descriptor_table.usb_pipe_table[pipe_num].HostDescBank[0].ADDR.reg = (uint32_t)buf;
    401         usb_descriptor_table.usb_pipe_table[pipe_num].HostDescBank[0].PCKSIZE.bit.BYTE_COUNT = 0;
    402         usb_descriptor_table.usb_pipe_table[pipe_num].HostDescBank[0].PCKSIZE.bit.MULTI_PACKET_SIZE = buf_size;
    403         USB->HOST.HostPipe[pipe_num].PCFG.bit.PTOKEN = USB_HOST_PIPE_TOKEN_IN;
    404 
    405         /* Start transfer */
    406         USB->HOST.HostPipe[pipe_num].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_BK0RDY;
    407 
    408         // Unfreeze pipe
    409         USB->HOST.HostPipe[pipe_num].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_PFREEZE;
    410 
    411         return buf_size;
    412 }
     401uint32_t UHD_Pipe_Read(uint32_t pipe_num, uint32_t buf_size, uint8_t *buf)
     402{
     403   if (USB->HOST.HostPipe[pipe_num].PCFG.bit.PTYPE == USB_HOST_PTYPE_DIS)
     404   {
     405      return 0;
     406   }
     407
     408   /* get pipe config from setting register */
     409   usb_pipe_table[pipe_num].HostDescBank[0].ADDR.reg = (uint32_t)buf;
     410   usb_pipe_table[pipe_num].HostDescBank[0].PCKSIZE.bit.BYTE_COUNT        = 0;
     411   usb_pipe_table[pipe_num].HostDescBank[0].PCKSIZE.bit.MULTI_PACKET_SIZE = buf_size;
     412   USB->HOST.HostPipe[pipe_num].PCFG.bit.PTOKEN = USB_HOST_PCFG_PTOKEN_IN;
     413
     414   /* Start transfer */
     415   USB->HOST.HostPipe[pipe_num].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_BK0RDY;
     416
     417   // Unfreeze pipe
     418   USB->HOST.HostPipe[pipe_num].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_PFREEZE;
     419
     420   return buf_size;
     421}
     422
    413423
    414424/**
     
    419429 * \param data Buffer containing data to write.
    420430 */
    421 void UHD_Pipe_Write(uint32_t ul_pipe, uint32_t ul_size, uint8_t* data)
    422 {
    423 
    424         if (USB->HOST.HostPipe[pipe_num].PCFG.bit.PTYPE == USB_HOST_PIPE_TYPE_DISABLE)
    425         {
    426                 return 0;
    427         }
    428 
    429         /* get pipe config from setting register */
    430         usb_descriptor_table.usb_pipe_table[pipe_num].HostDescBank[0].ADDR.reg = (uint32_t)buf;
    431         usb_descriptor_table.usb_pipe_table[pipe_num].HostDescBank[0].PCKSIZE.bit.BYTE_COUNT = buf_size;
    432         usb_descriptor_table.usb_pipe_table[pipe_num].HostDescBank[0].PCKSIZE.bit.MULTI_PACKET_SIZE = 0;
    433         USB->HOST.HostPipe[pipe_num].PCFG.bit.PTOKEN = USB_HOST_PIPE_TOKEN_OUT;
    434 
    435 
    436         return 1;
     431void UHD_Pipe_Write(uint32_t ul_pipe, uint32_t ul_size, uint8_t *buf)
     432{
     433   /* get pipe config from setting register */
     434   usb_pipe_table[ul_pipe].HostDescBank[0].ADDR.reg = (uint32_t)buf;
     435   usb_pipe_table[ul_pipe].HostDescBank[0].PCKSIZE.bit.BYTE_COUNT = ul_size;
     436   usb_pipe_table[ul_pipe].HostDescBank[0].PCKSIZE.bit.MULTI_PACKET_SIZE = 0;
    437437}
    438438
     
    445445void UHD_Pipe_Send(uint32_t ul_pipe, uint32_t ul_token_type)
    446446{
    447         /* Start transfer */
    448         USB->HOST.HostPipe[pipe_num].PSTATUSSET.reg = USB_HOST_PSTATUSSET_BK0RDY;
    449 
     447        USB->HOST.HostPipe[ul_pipe].PCFG.bit.PTOKEN = ul_token_type;
     448
     449   /* Start transfer */
     450        if(ul_token_type == USB_HOST_PCFG_PTOKEN_SETUP )
     451        {
     452                USB->HOST.HostPipe[ul_pipe].PINTFLAG.reg = USB_HOST_PINTFLAG_TXSTP;
     453                USB->HOST.HostPipe[ul_pipe].PSTATUSSET.reg = USB_HOST_PSTATUSSET_BK0RDY;
     454        }
     455        else if(ul_token_type == USB_HOST_PCFG_PTOKEN_IN )
     456        {
     457                USB->HOST.HostPipe[ul_pipe].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_BK0RDY;
     458        }
     459        else
     460        {
     461                USB->HOST.HostPipe[ul_pipe].PINTFLAG.reg = USB_HOST_PINTFLAG_TRCPT(1);  // Transfer Complete 0
     462                USB->HOST.HostPipe[ul_pipe].PSTATUSSET.reg = USB_HOST_PSTATUSSET_BK0RDY;
     463        }
     464   
    450465        // Unfreeze pipe
    451         USB->HOST.HostPipe[pipe_num].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_PFREEZE;
    452 }
     466    uhd_unfreeze_pipe(ul_pipe);
     467}
     468
     469#define USB_HOST_PINTFLAG_TRCPT_Pos 0            /**< \brief (USB_HOST_PINTFLAG) Transfer Complete 0/1 Interrupt Flag */
     470#define USB_HOST_PINTFLAG_TRCPT_Msk (0x3u << USB_HOST_PINTFLAG_TRCPT_Pos)
     471#define USB_HOST_PINTFLAG_TRCPT(value) ((USB_HOST_PINTFLAG_TRCPT_Msk & ((value) << USB_HOST_PINTFLAG_TRCPT_Pos)))
    453472
    454473/**
     
    463482uint32_t UHD_Pipe_Is_Transfer_Complete(uint32_t ul_pipe, uint32_t ul_token_type)
    464483{
    465 
    466         // Freeze pipe
    467         USB->HOST.HostPipe[pipe_num].PSTATUSSET.reg = USB_HOST_PSTATUSSET_PFREEZE;
    468         switch(uhd_ctrl_request_phase) {
    469                 case UHD_CTRL_REQ_PHASE_DATA_IN:
    470                 _uhd_ctrl_phase_data_in(p_callback_para->transfered_size);
    471                 break;
    472                 case UHD_CTRL_REQ_PHASE_ZLP_IN:
    473                 _uhd_ctrl_request_end(UHD_TRANS_NOERROR);
    474                 break;
    475                 case UHD_CTRL_REQ_PHASE_DATA_OUT:
    476                 _uhd_ctrl_phase_data_out();
    477                 break;
    478                 case UHD_CTRL_REQ_PHASE_ZLP_OUT:
    479                 _uhd_ctrl_request_end(UHD_TRANS_NOERROR);
    480                 break;
    481         }
    482         return 0;
    483 }
    484 
    485 #endif
    486 
     484   // Check for transfer completion depending on token type
     485   switch (ul_token_type)
     486   {
     487      case USB_HOST_PCFG_PTOKEN_SETUP:
     488         if (Is_uhd_setup_ready(ul_pipe))
     489         {
     490            uhd_ack_setup_ready(ul_pipe);
     491            uhd_freeze_pipe(ul_pipe);
     492            return 1;
     493         }
     494                 break;
     495
     496      case USB_HOST_PCFG_PTOKEN_IN:
     497         if (Is_uhd_in_received(ul_pipe))
     498         {
     499            // IN packet received
     500            uhd_ack_in_received(ul_pipe);
     501                        // Freeze will stop after the transfer
     502                        uhd_freeze_pipe(ul_pipe);
     503            return 1;
     504         }
     505                 break;
     506 
     507      case USB_HOST_PCFG_PTOKEN_OUT:
     508         if (Is_uhd_out_ready(ul_pipe))
     509         {
     510            // OUT packet sent
     511            uhd_ack_out_ready(ul_pipe);
     512            uhd_freeze_pipe(ul_pipe);
     513            return 1;
     514         }
     515                 break;
     516   }
     517
     518   return 0;
     519}
     520
     521#endif //  HOST_DEFINED
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/USB/samd21_host.h

    r136 r224  
    1 /* ----------------------------------------------------------------------------
    2  *         SAM Software Package License
    3  * ----------------------------------------------------------------------------
    4  * Copyright (c) 2011-2012, Atmel Corporation
    5  *
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following condition is met:
    10  *
    11  * - Redistributions of source code must retain the above copyright notice,
    12  * this list of conditions and the disclaimer below.
    13  *
    14  * Atmel's name may not be used to endorse or promote products derived from
    15  * this software without specific prior written permission.
    16  *
    17  * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
    18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
    20  * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
    21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
    23  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    24  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    25  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
    26  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    27  * ----------------------------------------------------------------------------
    28  */
     1/*
     2  Copyright (c) 2014 Arduino LLC.  All right reserved.
     3
     4  This library is free software; you can redistribute it and/or
     5  modify it under the terms of the GNU Lesser General Public
     6  License as published by the Free Software Foundation; either
     7  version 2.1 of the License, or (at your option) any later version.
     8
     9  This library is distributed in the hope that it will be useful,
     10  but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     12  See the GNU Lesser General Public License for more details.
     13
     14  You should have received a copy of the GNU Lesser General Public
     15  License along with this library; if not, write to the Free Software
     16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     17*/
     18/*
     19**Modified 04/04/2016 by Arduino.org development team
     20*/
    2921
    3022#ifndef UOTGHS_HOST_H_INCLUDED
    3123#define UOTGHS_HOST_H_INCLUDED
    32 
    3324
    3425#ifdef __cplusplus
     
    3627#endif
    3728
    38 //! \ingroup usb_host_group
    39 //! \defgroup uhd_group USB Host Driver (UHD)
    40 //! UOTGHS low-level driver for USB host mode
    41 //!
    42 //! @{
     29extern __attribute__((__aligned__(4))) volatile UsbHostDescriptor usb_pipe_table[USB_EPT_NUM];
    4330
    44 //! @name UOTGHS Host IP properties
    45 //!
    46 //! @{
    47 //! Get maximal number of endpoints
    48 #define uhd_get_pipe_max_nbr()                (9)
    49 #define UOTGHS_EPT_NUM                        (uhd_get_pipe_max_nbr()+1)
    50 //! @}
     31#define  USB_EP_DIR_IN        0x80  // USB_SETUP_DEVICE_TO_HOST
     32#define  USB_EP_DIR_OUT       0x00  // USB_SETUP_HOST_TO_DEVICE
    5133
    52 //! @name Host Vbus line control
    53 //!
    54 //! VBOF is an optional output pin which allows to enable or disable
    55 //! the external VBus generator.
    56 //!
    57 //! @{
    58 //! Enables hardware control of USB_VBOF output pin when a Vbus error occur
    59 #define uhd_enable_vbus_error_hw_control()    (Clr_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBUSHWC))
    60 //! Disables hardware control of USB_VBOF output pin when a Vbus error occur
    61 #define uhd_disable_vbus_error_hw_control()   (Set_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBUSHWC))
     34#define USB_HOST_PTYPE_DIS     USB_HOST_PCFG_PTYPE(0x0) // Pipe is disabled
     35#define USB_HOST_PTYPE_CTRL    USB_HOST_PCFG_PTYPE(0x1) // Pipe is enabled and configured as CONTROL
     36#define USB_HOST_PTYPE_ISO     USB_HOST_PCFG_PTYPE(0x2) // Pipe is enabled and configured as ISO
     37#define USB_HOST_PTYPE_BULK    USB_HOST_PCFG_PTYPE(0x3) // Pipe is enabled and configured as BULK
     38#define USB_HOST_PTYPE_INT     USB_HOST_PCFG_PTYPE(0x4) // Pipe is enabled and configured as INTERRUPT
     39#define USB_HOST_PTYPE_EXT     USB_HOST_PCFG_PTYPE(0x5) // Pipe is enabled and configured as EXTENDED
    6240
    63 //! Pin and function for USB_VBOF according to configuration from USB_VBOF
    64 #define USB_VBOF_PIN            USB_VBOF_GPIO
    65 #define USB_VBOF_FUNCTION       USB_VBOF_FLAGS
    66 //! Output USB_VBOF onto its pin
    67 #define uhd_output_vbof_pin() do {\
    68         pio_configure_pin(USB_VBOF_PIN, USB_VBOF_FUNCTION); \
    69 } while (0)
     41#define USB_HOST_NB_BK_1                1
    7042
    71 //! Set USB_VBOF output pin polarity
    72 #define uhd_set_vbof_active_high()            (Set_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBUSPO))
    73 #define uhd_set_vbof_active_low()             (Clr_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBUSPO))
    74 //! Requests VBus activation
    75 #define uhd_enable_vbus()                     (Set_bits(UOTGHS->UOTGHS_SFR, UOTGHS_SR_VBUSRQ))
    76 //! Requests VBus deactivation
    77 #define uhd_disable_vbus()                    (Set_bits(UOTGHS->UOTGHS_SCR, UOTGHS_SR_VBUSRQ))
    78 //! Tests if VBus activation has been requested
    79 #define Is_uhd_vbus_enabled()                 (Tst_bits(UOTGHS->UOTGHS_SR, UOTGHS_SR_VBUSRQ))
    80 //! @}
     43#define USB_HOST_PCFG_PTOKEN_SETUP  USB_HOST_PCFG_PTOKEN(0x0)
     44#define USB_HOST_PCFG_PTOKEN_IN     USB_HOST_PCFG_PTOKEN(0x1)
     45#define USB_HOST_PCFG_PTOKEN_OUT    USB_HOST_PCFG_PTOKEN(0x2)
    8146
    82 //! @name Host Vbus line monitoring
    83 //!
    84 //! The VBus level is always checked by USBC hardware.
    85 //!
    86 //! @{
    87 #define uhd_enable_vbus_error_interrupt()     (Set_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBERRE))
    88 #define uhd_disable_vbus_error_interrupt()    (Clr_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBERRE))
    89 #define Is_uhd_vbus_error_interrupt_enabled() (Tst_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBERRE))
    90 #define uhd_ack_vbus_error_interrupt()        (Set_bits(UOTGHS->UOTGHS_SCR, UOTGHS_SCR_VBERRIC))
    91 #define Is_uhd_vbus_error_interrupt()         (Tst_bits(UOTGHS->UOTGHS_SR, UOTGHS_SR_VBERRI))
    92 //! @}
     47#define USB_ERRORFLOW         USB_HOST_STATUS_BK_ERRORFLOW
     48#define USB_ERRORTIMEOUT      USB_HOST_STATUS_PIPE_TOUTER
     49#define USB_ERROR_DATATOGGLE  USB_HOST_STATUS_PIPE_DTGLER
    9350
    94 #define uhd_ack_errors_interrupt()            (UOTGHS->UOTGHS_SCR = (UOTGHS_SCR_VBERRIC|UOTGHS_SCR_BCERRIC|UOTGHS_SCR_HNPERRIC|UOTGHS_SCR_STOIC))
    95 #define Is_uhd_errors_interrupt()             (Tst_bits(UOTGHS->UOTGHS_CTRL, UOTGHS_CTRL_VBERRE|UOTGHS_CTRL_BCERRE|UOTGHS_CTRL_HNPERRE|UOTGHS_CTRL_STOE))
    96 #define uhd_enable_suspend_error_interrupt()
    97 #define uhd_enable_hnp_error_interrupt()
    98 #define uhd_enable_bconn_error_interrupt()
     51#define USB_PCKSIZE_SIZE_8_BYTES        0
     52#define USB_PCKSIZE_SIZE_16_BYTES       1
     53#define USB_PCKSIZE_SIZE_32_BYTES       2
     54#define USB_PCKSIZE_SIZE_64_BYTES       3
     55#define USB_PCKSIZE_SIZE_128_BYTES      4
     56#define USB_PCKSIZE_SIZE_256_BYTES      5
     57#define USB_PCKSIZE_SIZE_512_BYTES      6
     58#define USB_PCKSIZE_SIZE_1023_BYTES_FS  7   
     59#define USB_PCKSIZE_SIZE_1024_BYTES_HS  7 
    9960
    100 //! @name USB device connection/disconnection monitoring
    101 //! @{
    102 #define uhd_enable_connection_int()           (UOTGHS->UOTGHS_HSTIER = UOTGHS_HSTIER_DCONNIES)
    103 #define uhd_disable_connection_int()          (UOTGHS->UOTGHS_HSTIDR = UOTGHS_HSTIDR_DCONNIEC)
    104 #define Is_uhd_connection_int_enabled()       (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_DCONNIE))
    105 #define uhd_ack_connection()                  (UOTGHS->UOTGHS_HSTICR = UOTGHS_HSTICR_DCONNIC)
    106 #define Is_uhd_connection()                   (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_DCONNI))
     61#define USB_HOST_DTGL(p)               (USB->HOST.HostPipe[p].PSTATUS.reg & USB_HOST_PSTATUS_DTGL)>>USB_HOST_PSTATUS_DTGL_Pos
    10762
    108 #define uhd_enable_disconnection_int()        (UOTGHS->UOTGHS_HSTIER = UOTGHS_HSTIER_DDISCIES)
    109 #define uhd_disable_disconnection_int()       (UOTGHS->UOTGHS_HSTIDR = UOTGHS_HSTIDR_DDISCIEC)
    110 #define Is_uhd_disconnection_int_enabled()    (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_DDISCIE))
    111 #define uhd_ack_disconnection()               (UOTGHS->UOTGHS_HSTICR = UOTGHS_HSTICR_DDISCIC)
    112 #define Is_uhd_disconnection()                (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_DDISCI))
    113 //! @}
     63// USB host connection/disconnection monitoring
     64#define uhd_enable_connection_int()           USB->HOST.INTENSET.reg = USB_HOST_INTENSET_DCONN
     65#define uhd_disable_connection_int()          USB->HOST.INTENCLR.reg = USB_HOST_INTENCLR_DCONN
     66#define uhd_ack_connection()                  USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_DCONN
    11467
    115 //! @name USB device speed control
    116 //! @{
    117 #define uhd_get_speed_mode()                  (Rd_bits(UOTGHS->UOTGHS_SR, UOTGHS_SR_SPEED_Msk))
    118 #define Is_uhd_low_speed_mode()                 (uhd_get_speed_mode() == UOTGHS_SR_SPEED_LOW_SPEED)
    119 #define Is_uhd_full_speed_mode()                (uhd_get_speed_mode() == UOTGHS_SR_SPEED_FULL_SPEED)
    120 #define Is_uhd_high_speed_mode()                (uhd_get_speed_mode() == UOTGHS_SR_SPEED_HIGH_SPEED)
    121 //! Enable high speed mode
    122 # define uhd_enable_high_speed_mode()        (Wr_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_SPDCONF_Msk, UOTGHS_HSTCTRL_SPDCONF_HIGH_SPEED))
    123 //! Disable high speed mode
    124 # define uhd_disable_high_speed_mode()       (Wr_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_SPDCONF_Msk, UOTGHS_HSTCTRL_SPDCONF_FORCED_FS))
    125 //! @}
     68#define uhd_enable_disconnection_int()        USB->HOST.INTENSET.reg = USB_HOST_INTENSET_DDISC
     69#define uhd_disable_disconnection_int()       USB->HOST.INTENCLR.reg = USB_HOST_INTENCLR_DDISC
     70#define uhd_ack_disconnection()               USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_DDISC
    12671
    127 //! @name Bus events control
    128 //! These macros manage the bus events: reset, SOF, resume, wakeup.
    129 //! @{
     72// Initiates a USB register reset
     73#define uhd_start_USB_reg_reset()             USB->HOST.CTRLA.bit.SWRST = 1;
    13074
    131 //! Initiates a reset event
    132 //! @{
    133 #define uhd_start_reset()                            (Set_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_RESET))
    134 #define Is_uhd_starting_reset()                      (Tst_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_RESET))
    135 #define uhd_stop_reset()                             (Clr_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_RESET))
     75// Bus Reset
     76#define Is_uhd_starting_reset()             (USB->HOST.CTRLB.bit.BUSRESET == 1)
     77#define UHD_BusReset()                      USB->HOST.CTRLB.bit.BUSRESET = 1
     78#define uhd_stop_reset()                    // nothing to do
    13679
    137 #define uhd_enable_reset_sent_interrupt()            (UOTGHS->UOTGHS_HSTIER = UOTGHS_HSTIER_RSTIES)
    138 #define uhd_disable_reset_sent_interrupt()           (UOTGHS->UOTGHS_HSTIDR = UOTGHS_HSTIDR_RSTIEC)
    139 #define Is_uhd_reset_sent_interrupt_enabled()        (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_RSTIE))
    140 #define uhd_ack_reset_sent()                         (UOTGHS->UOTGHS_HSTICR = UOTGHS_HSTICR_RSTIC)
    141 #define Is_uhd_reset_sent()                          (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_RSTI))
    142 //! @}
     80#define uhd_ack_reset_sent()                         USB->HOST.INTFLAG.reg = USB_HOST_INTFLAG_RST
     81#define Is_uhd_reset_sent()                          (USB->HOST.INTFLAG.reg & USB_HOST_INTFLAG_RST)
    14382
    144 //! Initiates a SOF events
    145 //! @{
    146 #define uhd_enable_sof()                             (Set_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_SOFE))
    147 #define uhd_disable_sof()                            (Clr_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_SOFE))
    148 #define Is_uhd_sof_enabled()                         (Tst_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_SOFE))
    149 #define uhd_get_sof_number()                         ((UOTGHS->UOTGHS_HSTFNUM&UOTGHS_HSTFNUM_FNUM_Msk)>>UOTGHS_HSTFNUM_FNUM_Pos)
    150 #define uhd_get_microsof_number()                    ((UOTGHS->UOTGHS_HSTFNUM&UOTGHS_HSTFNUM_MFNUM_Msk)>>UOTGHS_HSTFNUM_MFNUM_Pos)
    151 #define uhd_get_frame_position()                     (Rd_bits(UOTGHS->UOTGHS_HSTFNUM, UOTGHS_HSTFNUM_FLENHIGH_Msk))
    152 #define uhd_enable_sof_interrupt()                   (UOTGHS->UOTGHS_HSTIER = UOTGHS_HSTIER_HSOFIES)
    153 #define uhd_disable_sof_interrupt()                  (UOTGHS->UOTGHS_HSTIDR = UOTGHS_HSTIDR_HSOFIEC)
    154 #define Is_uhd_sof_interrupt_enabled()               (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_HSOFIE))
    155 #define uhd_ack_sof()                                (UOTGHS->UOTGHS_HSTICR = UOTGHS_HSTICR_HSOFIC)
    156 #define Is_uhd_sof()                                 (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_HSOFI))
    157 //! @}
     83// Initiates a SOF events
     84#define uhd_enable_sof()                             USB->HOST.CTRLB.bit.SOFE = 1
     85#define uhd_disable_sof()                            USB->HOST.CTRLB.bit.SOFE = 0
     86#define Is_uhd_sof_enabled()                         (USB->HOST.CTRLB & USB_HOST_CTRLB_SOFE)
     87#define Is_uhd_sof()                                 (USB->HOST.INTFLAG.reg & USB_HOST_INTFLAG_HSOF)
    15888
    159 //! Initiates a resume event
    160 //! It is called downstream resume event.
    161 //! @{
    162 #define uhd_send_resume()                            (Set_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_RESUME))
    163 #define Is_uhd_sending_resume()                      (Tst_bits(UOTGHS->UOTGHS_HSTCTRL, UOTGHS_HSTCTRL_RESUME))
     89// USB address of pipes
     90#define uhd_configure_address(pipe_num, addr) usb_pipe_table[pipe_num].HostDescBank[0].CTRL_PIPE.bit.PDADDR = addr
     91#define uhd_get_configured_address(pipe_num)  usb_pipe_table[pipe_num].HostDescBank[0].CTRL_PIPE.bit.PDADDR
    16492
    165 #define uhd_enable_downstream_resume_interrupt()     (UOTGHS->UOTGHS_HSTIER = UOTGHS_HSTIER_RSMEDIES)
    166 #define uhd_disable_downstream_resume_interrupt()    (UOTGHS->UOTGHS_HSTIDR = UOTGHS_HSTIDR_RSMEDIEC)
    167 #define Is_uhd_downstream_resume_interrupt_enabled() (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_RSMEDIE))
    168 #define uhd_ack_downstream_resume()                  (UOTGHS->UOTGHS_HSTICR = UOTGHS_HSTICR_RSMEDIC)
    169 #define Is_uhd_downstream_resume()                   (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_RSMEDI))
    170 //! @}
     93// Pipes
     94#define uhd_freeze_pipe(p)                       USB->HOST.HostPipe[p].PSTATUSSET.reg = USB_HOST_PSTATUSSET_PFREEZE
     95#define uhd_unfreeze_pipe(p)                     USB->HOST.HostPipe[p].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_PFREEZE
     96#define Is_uhd_pipe_frozen(p)                    ((USB->HOST.HostPipe[p].PSTATUS.reg&USB_HOST_PSTATUS_PFREEZE)==USB_HOST_PSTATUS_PFREEZE)
    17197
    172 //! Detection of a wake-up event
    173 //! A wake-up event is received when the host controller is in the suspend mode:
    174 //! - and an upstream resume from the peripheral is detected.
    175 //! - and a peripheral disconnection is detected.
    176 //! @{
    177 #define uhd_enable_wakeup_interrupt()                (UOTGHS->UOTGHS_HSTIER = UOTGHS_HSTIER_HWUPIES)
    178 #define uhd_disable_wakeup_interrupt()               (UOTGHS->UOTGHS_HSTIDR = UOTGHS_HSTIDR_HWUPIEC)
    179 #define Is_uhd_wakeup_interrupt_enabled()            (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_HWUPIE))
    180 #define uhd_ack_wakeup()                             (UOTGHS->UOTGHS_HSTICR = UOTGHS_HSTICR_HWUPIC)
    181 #define Is_uhd_wakeup()                              (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_HWUPI))
     98// Pipe configuration
     99#define uhd_configure_pipe_token(p, token)       USB->HOST.HostPipe[p].PCFG.bit.PTOKEN = token
    182100
    183 #define uhd_enable_upstream_resume_interrupt()       (UOTGHS->UOTGHS_HSTIER = UOTGHS_HSTIER_RXRSMIES)
    184 #define uhd_disable_upstream_resume_interrupt()      (UOTGHS->UOTGHS_HSTIDR = UOTGHS_HSTIDR_RXRSMIEC)
    185 #define Is_uhd_upstream_resume_interrupt_enabled()   (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_RXRSMIE))
    186 #define uhd_ack_upstream_resume()                    (UOTGHS->UOTGHS_HSTICR = UOTGHS_HSTICR_RXRSMIC)
    187 #define Is_uhd_upstream_resume()                     (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_RXRSMI))
    188 //! @}
    189 //! @}
     101// Pipe data management
     102#define uhd_byte_count(p)                        usb_pipe_table[p].HostDescBank[0].PCKSIZE.bit.BYTE_COUNT
     103#define uhd_ack_setup_ready(p)                   USB->HOST.HostPipe[p].PINTFLAG.reg = USB_HOST_PINTFLAG_TXSTP
     104#define Is_uhd_setup_ready(p)                    ((USB->HOST.HostPipe[p].PINTFLAG.reg&USB_HOST_PINTFLAG_TXSTP) == USB_HOST_PINTFLAG_TXSTP)
     105#define uhd_ack_in_received(p)                   USB->HOST.HostPipe[p].PINTFLAG.reg = USB_HOST_PINTFLAG_TRCPT(1)
     106#define Is_uhd_in_received(p)                    ((USB->HOST.HostPipe[p].PINTFLAG.reg&USB_HOST_PINTFLAG_TRCPT(1)) == USB_HOST_PINTFLAG_TRCPT(1))
     107#define uhd_ack_out_ready(p)                     USB->HOST.HostPipe[p].PINTFLAG.reg = USB_HOST_PINTFLAG_TRCPT(1)
     108#define Is_uhd_out_ready(p)                      ((USB->HOST.HostPipe[p].PINTFLAG.reg&USB_HOST_PINTFLAG_TRCPT(1)) == USB_HOST_PINTFLAG_TRCPT(1))
     109#define uhd_ack_nak_received(p)                  usb_pipe_table[p].HostDescBank[1].STATUS_BK.reg &= ~USB_HOST_STATUS_BK_ERRORFLOW
     110#define Is_uhd_nak_received(p)                   (usb_pipe_table[p].HostDescBank[1].STATUS_BK.reg & USB_HOST_STATUS_BK_ERRORFLOW)
    190111
     112// Endpoint Interrupt Summary
     113#define uhd_endpoint_interrupt()            USB->HOST.PINTSMRY.reg
    191114
    192 //! @name Pipes management
    193 //! @{
     115// Run in Standby
     116#define uhd_run_in_standby()                USB->HOST.CTRLA.reg |= USB_CTRLA_RUNSTDBY
     117// Force host mode
     118#define uhd_force_host_mode()               USB->HOST.CTRLA.reg |= USB_CTRLA_MODE
    194119
    195 //! USB address of pipes
    196 //! @{
    197 #define uhd_configure_address(p, addr) \
    198                 (Wr_bitfield((&UOTGHS->UOTGHS_HSTADDR1)[(p)>>2], \
    199                 UOTGHS_HSTADDR1_HSTADDRP0_Msk << (((p)&0x03)<<3), addr))
    200 #define uhd_get_configured_address(p) \
    201                 (Rd_bitfield((&UOTGHS->UOTGHS_HSTADDR1)[(p)>>2], \
    202                 UOTGHS_HSTADDR1_HSTADDRP0_Msk << (((p)&0x03)<<3)))
    203 //! @}
     120// Enable USB macro
     121#define uhd_enable()                        USB->HOST.CTRLA.reg |= USB_CTRLA_ENABLE
     122// Disable USB macro
     123#define uhd_disable()                       USB->HOST.CTRLA.reg &= ~USB_CTRLA_ENABLE
    204124
    205 //! Pipe enable
    206 //! Enable, disable, reset, freeze
    207 //! @{
    208 #define uhd_enable_pipe(p) \
    209                 (Set_bits(UOTGHS->UOTGHS_HSTPIP, UOTGHS_HSTPIP_PEN0 << (p)))
    210 #define uhd_disable_pipe(p) \
    211                 (Clr_bits(UOTGHS->UOTGHS_HSTPIP, UOTGHS_HSTPIP_PEN0 << (p)))
    212 #define Is_uhd_pipe_enabled(p) \
    213                 (Tst_bits(UOTGHS->UOTGHS_HSTPIP, UOTGHS_HSTPIP_PEN0 << (p)))
    214 #define uhd_reset_pipe(p) \
    215                 (Set_bits(UOTGHS->UOTGHS_HSTPIP, UOTGHS_HSTPIP_PEN0 << (p))); \
    216                 (Clr_bits(UOTGHS->UOTGHS_HSTPIP, UOTGHS_HSTPIP_PEN0 << (p)))
    217 #define Is_uhd_resetting_pipe(p) \
    218                 (Tst_bits(UOTGHS->UOTGHS_HSTPIP, UOTGHS_HSTPIP_PEN0 << (p)))
    219 #define uhd_freeze_pipe(p)                       (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_PFREEZES)
    220 #define uhd_unfreeze_pipe(p)                     (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_PFREEZEC)
    221 #define Is_uhd_pipe_frozen(p)                    (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_PFREEZE))
    222 #define uhd_reset_data_toggle(p)                 (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_RSTDTS)
    223 #define Is_uhd_data_toggle_reset(p)              (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_RSTDT))
    224 //! @}
    225 
    226 //! Pipe configuration
    227 //! @{
    228 #define uhd_configure_pipe_int_req_freq(p,freq)  (Wr_bitfield(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_INTFRQ_Msk, (freq)))
    229 #define uhd_get_pipe_int_req_freq(p)             (Rd_bitfield(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_INTFRQ_Msk))
    230 #define uhd_configure_pipe_endpoint_number(p,ep) (Wr_bitfield(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PEPNUM_Msk, (ep)))
    231 #define uhd_get_pipe_endpoint_address(p) \
    232                 (uhd_is_pipe_in(p) ?\
    233                         (uhd_get_pipe_endpoint_number(p) | USB_EP_DIR_IN) :\
    234                         (uhd_get_pipe_endpoint_number(p) | USB_EP_DIR_OUT))
    235 #define uhd_get_pipe_endpoint_number(p)          (Rd_bitfield(UOTGHS->UOTGHS_HSTPIPCFG[p], (UOTGHS_HSTPIPCFG_PEPNUM_Msk)))
    236 #define uhd_configure_pipe_type(p, type)         (Wr_bitfield(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PTYPE_Msk, type))
    237 #define uhd_get_pipe_type(p)                     (Rd_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PTYPE_Msk))
    238 #define uhd_enable_pipe_bank_autoswitch(p)       (Set_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_AUTOSW))
    239 #define uhd_disable_pipe_bank_autoswitch(p)      (Clr_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_AUTOSW))
    240 #define Is_uhd_pipe_bank_autoswitch_enabled(p)   (Tst_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_AUTOSW))
    241 #define uhd_configure_pipe_token(p, token)       (Wr_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PTOKEN_Msk, token))
    242 #define uhd_get_pipe_token(p)                    (Rd_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PTOKEN_Msk))
    243 #define uhd_is_pipe_in(p)                        (UOTGHS_HSTPIPCFG_PTOKEN_IN==uhd_get_pipe_token(p))
    244 #define uhd_is_pipe_out(p)                       (UOTGHS_HSTPIPCFG_PTOKEN_OUT==uhd_get_pipe_token(p))
    245 //! Bounds given integer size to allowed range and rounds it up to the nearest
    246 //! available greater size, then applies register format of UOTGHS controller
    247 //! for pipe size bit-field.
    248 #define uhd_format_pipe_size(size) \
    249                 (32 - clz(((uint32_t)min(max(size, 8), 1024) << 1) - 1) - 1 - 3)
    250 #define uhd_configure_pipe_size(p,size) \
    251                 (Wr_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PSIZE_Msk, uhd_format_pipe_size(size)))
    252 #define uhd_get_pipe_size(p)                     (8<<((Rd_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], (UOTGHS_HSTPIPCFG_PSIZE_Msk)))>> UOTGHS_HSTPIPCFG_PSIZE_Pos))
    253 #define uhd_configure_pipe_bank(p,bank)          (Wr_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PBK_Msk, (bank)))
    254 #define uhd_get_pipe_bank(p)                     (Rd_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PBK_Msk))
    255 #define uhd_allocate_memory(p)                   (Set_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_ALLOC))
    256 #define uhd_unallocate_memory(p)                 (Clr_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_ALLOC))
    257 #define Is_uhd_memory_allocated(p)               (Tst_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_ALLOC))
    258 
    259 //! Enable PING management only available in HS mode
    260 #  define uhd_enable_ping(p)                     (Set_bits(UOTGHS->UOTGHS_HSTPIPCFG[p], UOTGHS_HSTPIPCFG_PINGEN))
    261 //#endif
    262 #define uhd_configure_pipe(p, freq, ep_num, type, token, size, bank, bank_switch) \
    263         (UOTGHS->UOTGHS_HSTPIPCFG[p] = \
    264                 (bank)|\
    265                 ((uhd_format_pipe_size(size)<<UOTGHS_HSTPIPCFG_PSIZE_Pos)&UOTGHS_HSTPIPCFG_PSIZE_Msk)|\
    266                 ((token)&UOTGHS_HSTPIPCFG_PTOKEN_Msk)|\
    267                 ((type)&UOTGHS_HSTPIPCFG_PTYPE_Msk)|\
    268                 (((ep_num)<<UOTGHS_HSTPIPCFG_PEPNUM_Pos)&UOTGHS_HSTPIPCFG_PEPNUM_Msk)|\
    269                 bank_switch |\
    270                 (((freq)<<UOTGHS_HSTPIPCFG_INTFRQ_Pos)&UOTGHS_HSTPIPCFG_INTFRQ_Msk))
    271 
    272 #define Is_uhd_pipe_configured(p)                (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_CFGOK))
    273 //! @}
    274 
    275 //! Pipe main interrupts management
    276 //! @{
    277 #define uhd_enable_pipe_interrupt(p)            (UOTGHS->UOTGHS_HSTIER = (UOTGHS_HSTIER_PEP_0 << (p)))
    278 #define uhd_disable_pipe_interrupt(p)           (UOTGHS->UOTGHS_HSTIDR = (UOTGHS_HSTIDR_PEP_0 << (p)))
    279 #define Is_uhd_pipe_interrupt_enabled(p)        (Tst_bits(UOTGHS->UOTGHS_HSTIMR, UOTGHS_HSTIMR_PEP_0 << (p)))
    280 #define Is_uhd_pipe_interrupt(p)                (Tst_bits(UOTGHS->UOTGHS_HSTISR, UOTGHS_HSTISR_PEP_0 << (p)))
    281 //! returns the lowest pipe number generating a pipe interrupt or UOTGHS_EPT_NUM if none
    282 #define uhd_get_interrupt_pipe_number() \
    283         (ctz(((UOTGHS->UOTGHS_HSTISR >> 8) & (UOTGHS->UOTGHS_HSTIMR >> 8)) | (1 << UOTGHS_EPT_NUM)))
    284 //! @}
    285 
    286 //! Pipe overflow and underflow for isochronous and interrupt endpoints
    287 //! @{
    288 #define uhd_enable_overflow_interrupt(p)         (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_OVERFIES)
    289 #define uhd_disable_overflow_interrupt(p)        (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_OVERFIEC)
    290 #define Is_uhd_overflow_interrupt_enabled(p)     (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_OVERFIE))
    291 #define uhd_ack_overflow_interrupt(p)            (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_OVERFIC)
    292 #define Is_uhd_overflow(p)                       (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_OVERFI))
    293 
    294 #define uhd_enable_underflow_interrupt(p)        (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_UNDERFIES)
    295 #define uhd_disable_underflow_interrupt(p)       (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_UNDERFIEC)
    296 #define Is_uhd_underflow_interrupt_enabled(p)    (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_UNDERFIE))
    297 #define uhd_ack_underflow_interrupt(p)           (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_UNDERFIC)
    298 #define Is_uhd_underflow(p)                      (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_UNDERFI))
    299 //! @}
    300 
    301 //! USB packet errors management
    302 //! @{
    303 #define uhd_enable_stall_interrupt(p)            (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_RXSTALLDES)
    304 #define uhd_disable_stall_interrupt(p)           (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_RXSTALLDEC)
    305 #define Is_uhd_stall_interrupt_enabled(p)        (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_RXSTALLDE))
    306 #define uhd_ack_stall(p)                         (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_RXSTALLDIC)
    307 #define Is_uhd_stall(p)                          (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_RXSTALLDI))
    308 
    309 #define uhd_enable_pipe_error_interrupt(p)       (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_PERRES)
    310 #define uhd_disable_pipe_error_interrupt(p)      (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_PERREC)
    311 #define Is_uhd_pipe_error_interrupt_enabled(p)   (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_PERRE))
    312 #define uhd_ack_all_errors(p)                    (UOTGHS->UOTGHS_HSTPIPERR[p] = 0UL)
    313 #define Is_uhd_pipe_error(p)                     (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_PERRI))
    314 #define uhd_error_status(p)                      (UOTGHS->UOTGHS_HSTPIPERR[p])
    315 #define Is_uhd_bad_data_toggle(p)                (Tst_bits(UOTGHS->UOTGHS_HSTPIPERR[p], UOTGHS_HSTPIPERR_DATATGL))
    316 #define Is_uhd_data_pid_error(p)                 (Tst_bits(UOTGHS->UOTGHS_HSTPIPERR[p], UOTGHS_HSTPIPERR_DATAPID))
    317 #define Is_uhd_pid_error(p)                      (Tst_bits(UOTGHS->UOTGHS_HSTPIPERR[p], UOTGHS_HSTPIPERR_PID))
    318 #define Is_uhd_timeout_error(p)                  (Tst_bits(UOTGHS->UOTGHS_HSTPIPERR[p], UOTGHS_HSTPIPERR_TIMEOUT))
    319 #define Is_uhd_crc16_error(p)                    (Tst_bits(UOTGHS->UOTGHS_HSTPIPERR[p], UOTGHS_HSTPIPERR_CRC16))
    320 #define uhd_get_error_counter(p)                 (Rd_bits(UOTGHS->UOTGHS_HSTPIPERR[p], UOTGHS_HSTPIPERR_COUNTER))
    321 //! @}
    322 
    323 //! Pipe data management
    324 //! @{
    325 #define uhd_data_toggle(p)                       (Rd_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_DTSEQ))
    326 
    327 #define uhd_enable_bank_interrupt(p)             (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_NBUSYBKES)
    328 #define uhd_disable_bank_interrupt(p)            (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_NBUSYBKEC)
    329 #define Is_uhd_bank_interrupt_enabled(p)         (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_NBUSYBKE))
    330 #define uhd_nb_busy_bank(p)                      (Rd_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_NBUSYBK_Msk))
    331 #define uhd_current_bank(p)                      (Rd_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_CURRBK_Msk ))
    332 
    333 #define uhd_enable_short_packet_interrupt(p)     (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_SHORTPACKETES)
    334 #define uhd_disable_short_packet_interrupt(p)    (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_SHORTPACKETIEC)
    335 #define Is_uhd_short_packet_interrupt_enabled(p) (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_SHORTPACKETIE))  )
    336 #define uhd_ack_short_packet(p)                  (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_SHORTPACKETIC)
    337 #define Is_uhd_short_packet(p)                   (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_SHORTPACKETI))
    338 #define uhd_byte_count(p)                        (Rd_bitfield(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_PBYCT_Msk))
    339 
    340 #define Is_uhd_fifocon(p)                        (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_FIFOCON))
    341 #define uhd_ack_fifocon(p)                       (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_FIFOCONC)
    342 
    343 #define uhd_enable_setup_ready_interrupt(p)      (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_TXSTPES)
    344 #define uhd_disable_setup_ready_interrupt(p)     (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_TXSTPEC)
    345 #define Is_uhd_setup_ready_interrupt_enabled(p)  (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_TXSTPE))
    346 #define uhd_ack_setup_ready(p)                   (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_TXSTPIC)
    347 #define Is_uhd_setup_ready(p)                    (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_TXSTPI))
    348 
    349 #define uhd_enable_in_received_interrupt(p)      (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_RXINES)
    350 #define uhd_disable_in_received_interrupt(p)     (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_RXINEC)
    351 #define Is_uhd_in_received_interrupt_enabled(p)  (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_RXINE))
    352 #define uhd_ack_in_received(p)                   (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_RXINIC)
    353 #define Is_uhd_in_received(p)                    (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_RXINI))
    354 
    355 #define uhd_enable_out_ready_interrupt(p)        (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_TXOUTES)
    356 #define uhd_disable_out_ready_interrupt(p)       (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_TXOUTEC)
    357 #define Is_uhd_out_ready_interrupt_enabled(p)    (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_TXOUTE))
    358 #define uhd_ack_out_ready(p)                     (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_TXOUTIC)
    359 #define Is_uhd_out_ready(p)                      (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_TXOUTI))
    360 #define uhd_raise_out_ready(p)                   (UOTGHS->UOTGHS_HSTPIPIFR[p] = UOTGHS_HSTPIPIFR_TXOUTIS)
    361 
    362 #define uhd_enable_nak_received_interrupt(p)     (UOTGHS->UOTGHS_HSTPIPIER[p] = UOTGHS_HSTPIPIER_NAKEDES)
    363 #define uhd_disable_nak_received_interrupt(p)    (UOTGHS->UOTGHS_HSTPIPIDR[p] = UOTGHS_HSTPIPIDR_NAKEDEC)
    364 #define Is_uhd_nak_received_interrupt_enabled(p) (Tst_bits(UOTGHS->UOTGHS_HSTPIPIMR[p], UOTGHS_HSTPIPIMR_NAKEDE))
    365 #define uhd_ack_nak_received(p)                  (UOTGHS->UOTGHS_HSTPIPICR[p] = UOTGHS_HSTPIPICR_NAKEDIC)
    366 #define Is_uhd_nak_received(p)                   (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_NAKEDI))
    367 
    368 #define Is_uhd_read_enabled(p)                   (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_RWALL))
    369 #define Is_uhd_write_enabled(p)                  (Tst_bits(UOTGHS->UOTGHS_HSTPIPISR[p], UOTGHS_HSTPIPISR_RWALL ))
    370 
    371 #define uhd_enable_continuous_in_mode(p)         (Set_bits(UOTGHS->UOTGHS_HSTPIPINRQ[p], UOTGHS_HSTPIPINRQ_INMODE))
    372 #define uhd_disable_continuous_in_mode(p)        (Clr_bits(UOTGHS->UOTGHS_HSTPIPINRQ[p], UOTGHS_HSTPIPINRQ_INMODE))
    373 #define Is_uhd_continuous_in_mode_enabled(p)     (Tst_bits(UOTGHS->UOTGHS_HSTPIPINRQ[p], UOTGHS_HSTPIPINRQ_INMODE))
    374 
    375 #define uhd_in_request_number(p, in_num)         (Set_bits(UOTGHS->UOTGHS_HSTPIPINRQ[p], (in_num)-1))
    376 #define uhd_get_in_request_number(p)             (((Rd_bits(UOTGHS->UOTGHS_HSTPIPINRQ[p], UOTGHS_HSTPIPINRQ_INRQ_Msk))>>UOTGHS_HSTPIPINRQ_INRQ_Pos)+1)
    377 //! @}
    378 
    379 //! Maximum transfer size on USB DMA
    380 #define UHD_PIPE_MAX_TRANS 0x8000
    381 
    382 //! Get 64-, 32-, 16- or 8-bit access to FIFO data register of selected pipe.
    383 //! @param p      Target Pipe number
    384 //! @param scale  Data scale in bits: 64, 32, 16 or 8
    385 //! @return       Volatile 64-, 32-, 16- or 8-bit data pointer to FIFO data register
    386 //! @warning It is up to the user of this macro to make sure that all accesses
    387 //! are aligned with their natural boundaries except 64-bit accesses which
    388 //! require only 32-bit alignment.
    389 //! @warning It is up to the user of this macro to make sure that used HSB
    390 //! addresses are identical to the DPRAM internal pointer modulo 32 bits.
    391 #define uhd_get_pipe_fifo_access(p, scale) \
    392         (((volatile TPASTE2(U, scale) (*)[UHD_PIPE_MAX_TRANS / ((scale) / 8)])UOTGHS_RAM_ADDR)[(p)])
    393 
     125// Force full speed mode
     126#define uhd_force_full_speed()              USB->HOST.CTRLB.reg &= ~USB_HOST_CTRLB_SPDCONF_Msk
    394127
    395128#ifdef __cplusplus
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/avr/dtostrf.c

    r136 r224  
    2020
    2121char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
     22  asm(".global _printf_float");
    2223  char fmt[20];
    2324  sprintf(fmt, "%%%d.%df", width, prec);
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/startup.c

    r136 r224  
    4646void HardFault_Handler( void )
    4747{
    48   while ( 1 )
    49   {
    50   }
     48        while ( 1 )
     49  {
     50        }
    5151}
    5252
     
    8282void NVMCTRL_Handler         ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
    8383void DMAC_Handler            ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
    84 void USB_Handler             ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
     84void USB_Handler             ( void ) __attribute__ ((weak));
    8585void EVSYS_Handler           ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
    8686void SERCOM0_Handler         ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
     
    406406  while ( 1 )
    407407  {
    408   }
    409 }
     408 }
     409}
     410
     411static void (*usb_isr)(void) = NULL;
     412
     413void USB_Handler(void)
     414{
     415  if (usb_isr)
     416    usb_isr();
     417}
     418
     419void USB_SetHandler(void (*new_usb_isr)(void))
     420{
     421  usb_isr = new_usb_isr;
     422}
     423
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring_analog.c

    r175 r224  
    3131static int DAC_RESOLUTION = 10;
    3232
    33 // Wait for synchronization of registers between the clock domains
    34 static __inline__ void syncDAC() __attribute__((always_inline, unused));
    35 static void syncDAC() {
    36   while (DAC->STATUS.bit.SYNCBUSY == 1)
    37     ;
    38 }
    39 
    4033void analogReadResolution(int res) {
    4134        _readResolution = res;
    4235        while( ADC->STATUS.bit.SYNCBUSY == 1 )
    4336  {
    44     // Waiting for synchroinization
     37    // Waiting for synchronization
    4538  }
    4639        if(res == 8) ADC->CTRLB.bit.RESSEL= ADC_CTRLB_RESSEL_8BIT_Val;
     
    6962  while( ADC->STATUS.bit.SYNCBUSY == 1 )
    7063  {
    71     // Waiting for synchroinization
     64    // Waiting for synchronization
    7265  }
    7366  switch(ulMode)
     
    9184  while( ADC->STATUS.bit.SYNCBUSY == 1 )
    9285  {
    93     // Waiting for synchroinization
     86    // Waiting for synchronization
    9487  }
    9588}
     
    154147        DAC->DATA.reg = ulValue & 0x3FF;  // Dac on 10 bits.
    155148                DAC->CTRLA.bit.ENABLE = 1; // DAC Enabled
    156                 syncDAC();
     149                while (DAC->STATUS.bit.SYNCBUSY == 1); //wait for synchronization
    157150        return;
    158151    }
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring_digital.c

    r136 r224  
    178178
    179179    default:
     180          PORT->Group[g_APinDescription[ulPin].ulPort].OUTSET.reg = (1ul << g_APinDescription[ulPin].ulPin) ;
    180181    break ;
    181182  }
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/SPI.cpp

    r136 r224  
    1313#include "assert.h"
    1414#include "variant.h"
     15#include <Arduino.h>
    1516
    1617SPIClass::SPIClass(SERCOM *p_sercom, uint8_t uc_pinMISO, uint8_t uc_pinSCK, uint8_t uc_pinMOSI)
     
    3839}
    3940
     41
     42void SPIClass::beginSlave()
     43{
     44  // PIO init
     45  pinPeripheral(_uc_pinMiso, g_APinDescription[_uc_pinMiso].ulPinType);
     46  pinPeripheral(_uc_pinSCK, g_APinDescription[_uc_pinSCK].ulPinType);
     47  pinPeripheral(_uc_pinMosi, g_APinDescription[_uc_pinMosi].ulPinType);
     48
     49        // Default speed set to 4Mhz, SPI mode set to MODE 0 and Bit order set to MSB first.
     50        _p_sercom->initSPIslave(SPI_PAD_2_SCK_3, SERCOM_RX_PAD_0, SPI_CHAR_SIZE_8_BITS, MSB_FIRST);
     51       
     52        _p_sercom->enableSPI();
     53}
     54
    4055void SPIClass::end()
    4156{
    4257        _p_sercom->resetSPI();
    4358}
     59
     60
     61void SPIClass::beginTransaction(SPISettings settings)
     62        {
     63                SercomDataOrder bitOrder;
     64                SercomSpiClockMode SpiClockMode;
     65               
     66                interruptSave = intStatus();
     67                noInterrupts();
     68               
     69       
     70                if(settings.bit_order==LSBFIRST) bitOrder = LSB_FIRST;
     71                else if(settings.bit_order==MSBFIRST) bitOrder = MSB_FIRST;
     72                else;
     73               
     74                if(settings.data_mode==SPI_MODE0) SpiClockMode = SERCOM_SPI_MODE_0;
     75                else if(settings.data_mode==SPI_MODE1) SpiClockMode = SERCOM_SPI_MODE_1;
     76                else if(settings.data_mode==SPI_MODE2) SpiClockMode = SERCOM_SPI_MODE_2;
     77                else if(settings.data_mode==SPI_MODE3) SpiClockMode = SERCOM_SPI_MODE_3;
     78                else;
     79               
     80                end();
     81               
     82                pinPeripheral(_uc_pinMiso, g_APinDescription[_uc_pinMiso].ulPinType);
     83                pinPeripheral(_uc_pinSCK, g_APinDescription[_uc_pinSCK].ulPinType);
     84                pinPeripheral(_uc_pinMosi, g_APinDescription[_uc_pinMosi].ulPinType);
     85               
     86                _p_sercom->initSPI(SPI_PAD_2_SCK_3, SERCOM_RX_PAD_0, SPI_CHAR_SIZE_8_BITS, bitOrder);
     87                _p_sercom->initSPIClock(SpiClockMode, settings.interface_clock);
     88       
     89        _p_sercom->enableSPI();
     90        inTransactionFlag=1;
     91        }
     92       
     93void SPIClass::endTransaction(void)
     94{
     95        inTransactionFlag=0;
     96        interrupts();
     97}       
    4498
    4599void SPIClass::setBitOrder(BitOrder order)
     
    76130}
    77131
    78 void SPIClass::setClockDivider(uint8_t div)
     132void SPIClass::setClockDivider(uint16_t div)
    79133{
    80134        _p_sercom->setBaudrateSPI(div);
     
    90144}
    91145
     146byte SPIClass::read()
     147{
     148        return _p_sercom->readDataSPI();
     149}
     150
     151void SPIClass::usingInterrupt(uint8_t intNum)
     152{
     153        uint8_t irestore;
     154        uint32_t mask;
     155       
     156        irestore=intStatus();
     157        noInterrupts();
     158        if(intNum > 13)
     159        {
     160                //Interrupts();
     161                return;
     162        }
     163        else
     164        {
     165                //Pio *pio=g_APinDescription[intNum].ulPort;
     166                mask=g_APinDescription[intNum].ulPin;
     167                interruptMode=1;
     168                interruptMask=mask;
     169        }
     170        if (irestore) interrupts();             
     171}
     172
     173void SPIClass::write(uint8_t data)
     174{
     175        //Writing the data
     176        _p_sercom->writeDataSPI(data);
     177}
     178
     179void SPIClass::transfer(void *data, size_t count)
     180{
     181        uint8_t *p;
     182        //int i=0;
     183                //Serial.println("dentro transfer");
     184        if(count==0) return;
     185        p=(uint8_t *)data;
     186        _p_sercom->writeDataSPI(*p);  //scrittura primo dato
     187       
     188        while(--count > 0)
     189        {
     190                //Serial.println("dentro while");
     191                uint8_t out=*(p+1); //copio in out il prossimo dato
     192                uint8_t in = _p_sercom->readDataSPI();  //leggo dato da SPI
     193                //Serial.println("UNO");
     194                //while(!(SERCOM4->SPI.INTFLAG.bit.RXC));  // controllo trasferimento  //vedere se necessario
     195                //Serial.println("DUE");
     196                //Serial.println(out);
     197                _p_sercom->writeDataSPI(out);   //scrivo il out su SPI
     198                *p++=in; //metto in p il dato letto da spi
     199        }
     200        while(!(SERCOM4->SPI.INTFLAG.bit.TXC));  // controllo trasferimrnto
     201        //Serial.print("*p: ");
     202        //Serial.println(*p);
     203        *p = _p_sercom->readDataSPI();
     204       
     205       
     206               
     207}
     208
     209uint16_t SPIClass::transfer16(uint16_t data)
     210{
     211        union{
     212                uint16_t value;
     213                struct{
     214                        uint8_t lsb;
     215                        uint8_t msb;
     216                };
     217        }in, out;
     218       
     219        in.value = data;
     220       
     221        if(SERCOM4->SPI.CTRLA.bit.DORD==0)
     222        {
     223                _p_sercom->writeDataSPI(in.msb);
     224                while(!(SERCOM4->SPI.INTFLAG.bit.TXC));
     225                out.msb = _p_sercom->readDataSPI();
     226                //while(!(SERCOM4->SPI.INTFLAG.bit.RXC));
     227                _p_sercom->writeDataSPI(in.lsb);
     228                while(!(SERCOM4->SPI.INTFLAG.bit.TXC));
     229                out.lsb = _p_sercom->readDataSPI();
     230        }
     231
     232        else
     233        {
     234                _p_sercom->writeDataSPI(in.lsb);
     235                while(!(SERCOM4->SPI.INTFLAG.bit.TXC));
     236                out.lsb = _p_sercom->readDataSPI();
     237                //while(!(SERCOM4->SPI.INTFLAG.bit.RXC));
     238                _p_sercom->writeDataSPI(in.msb);
     239                while(!(SERCOM4->SPI.INTFLAG.bit.TXC));
     240                out.msb = _p_sercom->readDataSPI();
     241        }
     242
     243                return out.value;
     244}
     245
    92246void SPIClass::attachInterrupt() {
    93247        // Should be enableInterrupt()
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/SPI.h

    r136 r224  
    1414#include "variant.h"
    1515#include "wiring_constants.h"
     16#include <Arduino.h>
     17 
     18//#define LSBFIRST 0 //already defined in wiring_constants.h
     19//#define MSBFIRST 1
    1620
    1721#define SPI_MODE0 0x02
     
    2024#define SPI_MODE3 0x01
    2125
     26
     27#define SPI_CLOCK_DIV2 6       //8 MHz
     28#define SPI_CLOCK_DIV4 12      //4 MHz
     29#define SPI_CLOCK_DIV8 24      //2 MHz
     30#define SPI_CLOCK_DIV16 48     //1 MHz
     31#define SPI_CLOCK_DIV32 96     //500 KHz
     32#define SPI_CLOCK_DIV64 192    //250 KHz
     33#define SPI_CLOCK_DIV128 384   //125 KHz
     34
     35#ifndef intStatus
     36#define intStatus() __intStatus()
     37static inline unsigned char __intStatus(void) __attribute__((always_inline, unused));
     38static inline unsigned char __intStatus(void) {
     39        unsigned int primask, faultmask;
     40        asm volatile ("mrs %0, primask" : "=r" (primask));
     41        if (primask) return 0;
     42        asm volatile ("mrs %0, faultmask" : "=r" (faultmask));
     43        if (faultmask) return 0;
     44        return 1;
     45}
     46#endif
     47
     48class SPISettings {
     49        public:
     50                SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode)
     51                {
     52                        interface_clock = clock;
     53                        bit_order = bitOrder;
     54                        data_mode = dataMode;
     55                       
     56                        /*Serial.print("clock: ");
     57                        Serial.println(interface_clock);
     58                        Serial.print("bit order: ");
     59                        Serial.println(bit_order);
     60                        Serial.print("data mode: ");
     61                        Serial.println(data_mode);*/
     62                }
     63               
     64                SPISettings(void)
     65                {
     66                        interface_clock = 4000000;
     67                        bit_order = MSBFIRST;
     68                        data_mode = SPI_MODE0;
     69                       
     70                        /*Serial.print("clock: ");
     71                        Serial.println(interface_clock);
     72                        Serial.print("bit order: ");
     73                        Serial.println(bit_order);
     74                        Serial.print("data mode: ");
     75                        Serial.println(data_mode);*/
     76                }
     77        private:
     78                uint32_t interface_clock;
     79                uint8_t bit_order;
     80                uint8_t data_mode;
     81       
     82        friend class SPIClass; 
     83};
     84
     85
    2286class SPIClass {
    2387  public:
     
    2589
    2690        byte transfer(uint8_t data);
    27 
     91        void transfer(void *data, size_t count);
     92        byte read(void);
     93        uint16_t transfer16(uint16_t data);
     94        void write(uint8_t data);
    2895        // SPI Configuration methods
     96        void beginTransaction(SPISettings settings);
     97        void endTransaction(void);
     98       
    2999        void attachInterrupt();
    30100        void detachInterrupt();
     101       
     102        void usingInterrupt(uint8_t interruptNumber);
    31103
    32104        void begin();
     105        void beginSlave();
    33106        void end();
    34107       
    35108        void setBitOrder(BitOrder order);
    36109        void setDataMode(uint8_t uc_mode);
    37         void setClockDivider(uint8_t uc_div);
     110        void setClockDivider(uint16_t uc_div);
    38111
    39112  private:
     
    42115        uint8_t _uc_pinMosi;
    43116        uint8_t _uc_pinSCK;
     117        uint8_t interruptMode;
     118        uint32_t interruptMask;
     119        uint8_t interruptSave;
     120        uint8_t inTransactionFlag;
    44121};
    45122
  • rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/programmers.txt

    r136 r224  
    1 zeroedbg.name=M0 Pro Programming Port
     1zeroedbg.name=Atmel EDBG Programming Port
    22zeroedbg.program.tool=openocd
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient/CiaoRestClient.ino

    r175 r224  
    33
    44#define CONNECTOR     "rest"
    5 #define SERVER_ADDR   "192.168.0.100" // change ip address with your server ip address
     5#define SERVER_ADDR   "192.168.1.1" // change ip address with your server ip address
    66
    7 int buttonState = LOW; //this variable tracks the state of the button, low if not pressed, high if pressed
    8 int ledState = -1; //this variable tracks the state of the LED, negative if off, positive if on
     7int buttonState; //this variable tracks the state of the button, low if not pressed, high if pressed
     8int ledState = HIGH; //this variable tracks the state of the LED, negative if off, positive if on
    99long lastDebounceTime = 0;  // the last time the output pin was toggled
    1010long debounceDelay = 50;    // the debounce time; increase if the output flickers
     11String command = "/arduino/mode/13/output";
     12int previous_value = LOW;
    1113
    1214void setup() {
    1315  Ciao.begin();
     16  Ciao.write(CONNECTOR, SERVER_ADDR, command);
    1417  pinMode(2, INPUT);
    1518 
     
    2023  //sample the state of the button - is it pressed or not?
    2124  buttonState = digitalRead(2);
    22  
     25  
    2326  //filter out any noise by setting a time buffer
    24   if ( (millis() - lastDebounceTime) > debounceDelay) {
    25  
    26     //if the button has been pressed, lets toggle the LED from "off to on" or "on to off"
    27     if ( (buttonState == HIGH) && (ledState < 0) ) {
    28  
    29       CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, "/arduino/digital/12/1"); //turn LED on
    30       ledState = -ledState; //now the LED is on, we need to change the state
    31       lastDebounceTime = millis(); //set the current time
     27  if ( (buttonState == HIGH) && (previous_value == LOW) && (millis() - lastDebounceTime) > debounceDelay ) {
     28    if (ledState == HIGH){
     29      command = "/arduino/digital/13/0";
     30      ledState = LOW;
    3231    }
    33     else if ( (buttonState == HIGH) && (ledState > 0) ) {
    34  
    35       CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, "/arduino/digital/12/0"); //turn LED off
    36       ledState = -ledState; //now the LED is off, we need to change the state
    37       lastDebounceTime = millis(); //set the current time
    38        
    39       if (!data.isEmpty()){
    40         Ciao.println( "State: " + String (data.get(1)) );
    41         Ciao.println( "Response: " + String (data.get(2)) );
    42       }
    43       else{
    44         Ciao.println ("Write Error");
    45       }
    46              
     32    else{
     33      command = "/arduino/digital/13/1";
     34      ledState = HIGH;
    4735    }
    48  
     36     
     37    lastDebounceTime = millis(); //set the current time
     38    CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, command); 
     39    if (!data.isEmpty()){
     40      Ciao.println( "State: " + String (data.get(1)) );
     41      Ciao.println( "Response: " + String (data.get(2)) );
     42    }
     43    else{
     44      Ciao.println ("Write Error");
     45    }
     46
    4947  }
    5048 
     49  previous_value = buttonState;
     50 
    5151}
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestServer/CiaoRestServer.ino

    r175 r224  
    11/*
    22
    3  This sketch uses the xmpp connector to receive command for the MCU from a xmpp client.
     3 This sketch uses the restserver connector receive rest calls. It allows access to
     4 the analog and digital pin of the board via rest calls.
     5
     6 supported boards: Yun,Tian.
    47
    58 Possible commands to send from the xmpp client:
    69
    7  * "digital/PIN"        -> to read a digital PIN
    8  * "digital/PIN/VALUE"  -> to write a digital PIN (VALUE: 1/0)
    9  * "analog/PIN/VALUE"   -> to write in a PWM PIN(VALUE range: 0 - 255);
    10  * "analog/PIN"         -> to read a analog PIN
    11  * "servo/PIN/VALUE"      -> to write angle in a SERVO PIN(VALUE range: 0 - 180);
    12  * "mode/PIN/VALUE"     -> to set the PIN mode (VALUE: input / output)
    13  * "ledon"              -> turn on led 13
    14  * "ledoff"             -> turn off led 13
    15  * "ciao"               -> random answers in 5 different languages
    16  
    17  NOTE: be sure to activate and configure xmpp connector on Linino OS
    18        http://labs.arduino.org/Ciao
    19    
     10 * "/arduino/digital/PIN"       -> to read a digital PIN
     11 * "/arduino/digital/PIN/VALUE" -> to write a digital PIN (VALUE: 1/0)
     12 * "/arduino/analog/PIN/VALUE"  -> to write in a PWM PIN(VALUE range: 0 - 255);
     13 * "/arduino/analog/PIN"        -> to read a analog PIN
     14 * "/arduino/servo/PIN/VALUE"   -> to write angle in a SERVO PIN(VALUE range: 0 - 180);
     15 * "/arduino/mode/PIN/VALUE"    -> to set the PIN mode (VALUE: input / output)
     16
     17 Example:
     18 "/arduino/mode/13/output" -> pinMode(13, OUTPUT)
     19 "/arduino/digital/13/1"     -> digitalWrite(13, HIGH)
     20
     21
     22 NOTE: be sure to activate and configure restserver connector on Linino OS
     23  http://labs.arduino.org/Ciao
     24
    2025 created September 2015
    2126 by andrea[at]arduino[dot]org
    22  
     27
    2328 */
    24  
     29
    2530#include <Ciao.h>
    2631#include <Servo.h>
     
    3540void loop() {
    3641
    37   CiaoData data = Ciao.read("restserver");   
    38   if(!data.isEmpty()){ 
     42  CiaoData data = Ciao.read("restserver");
     43  if(!data.isEmpty()){
    3944    String id = data.get(0);
    4045    String sender = data.get(1);
    4146    String message = data.get(2);
    42    
     47
    4348    message.toUpperCase();
    44    
     49
    4550    String command[3];
    46          
     51
    4752    splitString(message,"/",command,3);
    4853    execute(command,id);
     
    7176void servoCommand(String cmd[], String id){
    7277   int pin, value;
    73  
     78
    7479  pin = (cmd[1]).toInt();
    75  
     80
    7681  if (cmd[2] != "-1") {
    7782    value = (cmd[2]).toInt();
     
    8590  }
    8691  else
    87     Ciao.writeResponse("restserver",id,"Invalid command"); 
     92    Ciao.writeResponse("restserver",id,"Invalid command");
    8893}
    8994
    9095void digitalCommand(String cmd[], String id) {
    9196  int pin, value;
    92  
     97
    9398  pin = (cmd[1]).toInt();
    94  
     99
    95100  if (cmd[2] != "-1") {
    96101    value = (cmd[2]).toInt();
     
    99104      Ciao.writeResponse("restserver",id,"Pin D"+String(pin)+" ON");
    100105    else if(value == 0)
    101       Ciao.writeResponse("restserver",id,"Pin D"+String(pin)+" OFF");   
     106      Ciao.writeResponse("restserver",id,"Pin D"+String(pin)+" OFF");
    102107  }
    103108  else if (cmd[2] == "-1") {
     
    111116
    112117  pin = (cmd[1]).toInt();
    113  
     118
    114119  if (cmd[2] != "-1") {
    115120    value =(cmd[2]).toInt();
     
    127132
    128133  pin = (cmd[1]).toInt();
    129  
     134
    130135  if (cmd[2] == "INPUT") {
    131136    pinMode(pin, INPUT);
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/keywords.txt

    r175 r224  
    77#######################################
    88
    9 Ciao            KEYWORD3
    10 CiaoData        KEYWORD3
    11 Wifi            KEYWORD3
    12 WifiData        KEYWORD3
     9Ciao  KEYWORD3
     10CiaoData  KEYWORD3
     11Wifi  KEYWORD3
     12WifiData  KEYWORD3
    1313
    1414#######################################
     
    1616#######################################
    1717
    18 begin                   KEYWORD2
    19 writeResponse   KEYWORD2
    20 available               KEYWORD2
    21 read                    KEYWORD2
    22 write                   KEYWORD2
    23 bool                    KEYWORD2
     18writeResponse KEYWORD2
     19available KEYWORD2
     20read  KEYWORD2
     21write KEYWORD2
    2422
     23#######################################
     24# Constants (LITERAL1)
     25#######################################
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/library.properties

    r175 r224  
    11name=Ciao
    2 version=1.0
     2version=0.0.3
    33author=Arduino srl
    44maintainer=Arduino srl<info@arduino.org>
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/Ciao.h

    r175 r224  
    3030
    3131#include <Arduino.h>
     32#include <Stream.h>
    3233#include "lib/CiaoData.h"
    3334#if defined(__AVR_ATmega328P__)
    34 #include "lib/rest.h"
    3535#include "lib/SC16IS750.h"
    36 #include "lib/espduino.h"
    37 #else
    38 #include <Stream.h>
    3936#endif
    4037
     
    4441#define BAUDRATE 250000
    4542#elif defined(ARDUINO_ARCH_SAMD)
    46 #define BAUDRATE 115200
     43#define BAUDRATE 4000000
    4744#endif
    4845
     
    5552                CiaoData parse( String, String);
    5653                void println(String log){};
    57                 #if defined(__AVR_ATmega32U4__)
    5854                CiaoClass(Stream &_stream);
    59                 #elif defined(ARDUINO_ARCH_SAMD)
    60                 CiaoClass(Serial_ stream);
    61                 #endif
    6255
    6356        private:
    6457                void dropAll();
    6558                bool started;
    66                 #if defined(__AVR_ATmega32U4__)
    6759                Stream &stream;
    68                 #elif defined(ARDUINO_ARCH_SAMD)
    69                 Serial_ stream;
    70                 #endif
    7160};
    7261
     
    8069                }
    8170                #elif defined(ARDUINO_ARCH_SAMD)
    82                 SerialCiaoClass(Serial_ serial)
    83                         : CiaoClass(serial){
    84                         // Empty       
     71                SerialCiaoClass(Serial_ &_serial)
     72                        : CiaoClass(_serial), serial(_serial) {
     73                        // Empty
    8574                }
    8675                #endif
     
    9382                HardwareSerial &serial;
    9483                #elif defined(ARDUINO_ARCH_SAMD)
    95                 Serial_ serial;
     84                Serial_ &serial;
    9685                #endif
    9786};
     
    10392#else
    10493
    105 // class CiaoData {
    106 //      public:
    107                
    108 //              char* get(int index){
    109 //                      return msg_split[index];
    110 //              }
    111  
    112 //      public:
    113 //              char* msg_split[3];
    114                
    115 // };
     94class ArduinoWifiClass : public WifiData
     95{
    11696
    117 class CiaoClass {
     97        public:
     98                void begin();           
     99
     100                boolean connected();
     101                void connect(char* , char*);
     102
     103                void powerON();
     104                void powerOFF();
     105
     106
     107};
     108
     109class CiaoClass : public WifiData
     110{
    118111        public:
    119112                void begin();
     
    124117                CiaoData write( char*, char*, String );            // “rest”, ”hostname”, ”Stringone”,             
    125118                CiaoData write( char*, char*, String, char*);      // “rest”, ”hostname”, ”Stringone”, ”method”
    126                
    127                 void print(String str);
    128                 void println(String str);
    129119       
    130120};
     121
     122
    131123extern CiaoClass Ciao;
     124extern ArduinoWifiClass Wifi;
    132125
    133126#endif
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/Ciao.cpp

    r175 r224  
    2424*/
    2525
    26 #include "Ciao.h"
    2726
    2827#if defined(__AVR_ATmega32U4__) || defined(ARDUINO_ARCH_SAMD)
    2928
    30 #if defined(__AVR_ATmega32U4__)
     29#include "Ciao.h"
     30
    3131CiaoClass::CiaoClass(Stream &_stream) :
    3232        stream(_stream), started(false) {
    3333  // Empty
    3434}
    35 #elif defined(ARDUINO_ARCH_SAMD)
    36 CiaoClass::CiaoClass(Serial_ stream){
    37   // Empty
    38 }
    39 #endif
    4035
    4136void CiaoClass::begin() {
     
    6055    }
    6156        do{
    62                 #if defined(__AVR_ATmega32U4__)
    6357                stream.print(F("run-ciao\n"));                          //start bridge python
    6458                stream.readStringUntil(END_TX_CHAR);
    65                 #endif
    6659                delay(3000);
    6760                stream.println("ciao;r;status");                                //check if bridge python is running
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.cpp

    r175 r224  
    2727#define WIRE Wire
    2828
    29 
    30 WifiData::WifiData(uint8_t prtcl, uint8_t addr_sspin)
    31 {
    32     protocol = prtcl;
    33     if ( protocol == SC16IS750_PROTOCOL_I2C ) {
    34         device_address_sspin = (addr_sspin>>1);
    35     } else {
    36         device_address_sspin = addr_sspin;
    37     }
     29WifiData::WifiData()
     30{
     31    device_address_sspin = (SC16IS750_ADDRESS_AA >> 1);
    3832    peek_flag = 0;
    3933}
     
    4135void WifiData::begin(uint32_t baud)
    4236{
    43     //Serial.println("1111111111111111");
     37
    4438    if ( protocol == SC16IS750_PROTOCOL_I2C) {
    45     //Serial.println("22222222222222");
    4639        WIRE.begin();
    4740    }
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.h

    r175 r224  
    104104#define     SC16IS750_PROTOCOL_I2C  (0)
    105105#define     SC16IS750_PROTOCOL_I2C  (0)
    106 #define     END     "<!--~-->"
     106#define     DELIMITER     "<!--~-->"
     107#define     EOL           '\0'
    107108
    108109class WifiData : public Stream
    109110{
    110111    public:
    111         WifiData(uint8_t prtcl = SC16IS750_PROTOCOL_I2C, uint8_t addr = SC16IS750_ADDRESS_AD);
     112        WifiData();
    112113        void begin(uint32_t baud);                               
    113114        int read();
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.cpp

    r175 r224  
    188188}
    189189
    190 ESP::ESP(Stream *serial, int chip_pd):
    191 _serial(serial), _chip_pd(chip_pd)
     190ESP::ESP(Stream *serial):
     191_serial(serial)
    192192{
    193193  _debugEn = false;
     
    195195}
    196196
    197 ESP::ESP(Stream *serial, Stream* debug, int chip_pd):
    198 _serial(serial), _debug(debug), _chip_pd(chip_pd)
    199 {
    200     _debugEn = true;
    201     //_serial = _debug;
    202     init();
    203 }
     197
    204198void ESP::enable()
    205199{
  • rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.h

    r175 r224  
    9292{
    9393public:
    94   ESP(Stream *serial, Stream* debug, int chip_pd);
    95   ESP(Stream *serial, int chip_pd);
     94  //ESP(Stream *serial, Stream* debug, int chip_pd);
     95  ESP(Stream *serial); //ok
    9696  Stream *_debug;
    9797
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino

    r136 r224  
    2323int previousAnalogValues[TOTAL_ANALOG_PINS];
    2424
    25 byte portStatus[TOTAL_PORTS];   // each bit: 1=pin is digital input, 0=other/ignore
     25byte portStatus[TOTAL_PORTS]; // each bit: 1=pin is digital input, 0=other/ignore
    2626byte previousPINs[TOTAL_PORTS];
    2727
     
    4646  byte i, port, status;
    4747
    48   Firmata.setFirmwareVersion(0, 1);
     48  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
    4949
    5050  for (pin = 0; pin < TOTAL_PINS; pin++) {
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino

    r136 r224  
    5454{
    5555  if (value == 0) {
    56     analogInputsToReport = analogInputsToReport &~ (1 << pin);
     56    analogInputsToReport = analogInputsToReport & ~ (1 << pin);
    5757  }
    5858  else { // everything but 0 enables reporting of that pin
     
    6767void setup()
    6868{
    69   Firmata.setFirmwareVersion(0, 2);
     69  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
    7070  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
    7171  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/EchoString/EchoString.ino

    r136 r224  
    2222
    2323
    24 void sysexCallback(byte command, byte argc, byte*argv)
     24void sysexCallback(byte command, byte argc, byte *argv)
    2525{
    2626  Firmata.sendSysex(command, argc, argv);
     
    2929void setup()
    3030{
    31   Firmata.setFirmwareVersion(0, 1);
     31  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
    3232  Firmata.attach(STRING_DATA, stringCallback);
    3333  Firmata.attach(START_SYSEX, sysexCallback);
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino

    r136 r224  
    5656void outputPort(byte portNumber, byte portValue)
    5757{
    58   portValue = portValue &~ portStatus[portNumber];
     58  portValue = portValue & ~ portStatus[portNumber];
    5959  if (previousPINs[portNumber] != portValue) {
    6060    Firmata.sendDigitalPort(portNumber, portValue);
     
    7373    if (reportPINs[i]) {
    7474      switch (i) {
    75         case 0: outputPort(0, PIND &~ B00000011); break; // ignore Rx/Tx 0/1
     75        case 0: outputPort(0, PIND & ~ B00000011); break; // ignore Rx/Tx 0/1
    7676        case 1: outputPort(1, PINB); break;
    7777        case 2: outputPort(2, PINC); break;
     
    105105      case INPUT:
    106106        pinMode(pin, INPUT);
    107         portStatus[port] = portStatus[port] &~ (1 << (pin - offset));
     107        portStatus[port] = portStatus[port] & ~ (1 << (pin - offset));
    108108        break;
    109109      case OUTPUT:
     
    113113        portStatus[port] = portStatus[port] | (1 << (pin - offset));
    114114        break;
    115         //case ANALOG: // TODO figure this out
     115      //case ANALOG: // TODO figure this out
    116116      default:
    117117        Firmata.sendString("");
     
    123123void analogWriteCallback(byte pin, int value)
    124124{
    125   setPinModeCallback(pin, PWM);
     125  setPinModeCallback(pin, PIN_MODE_PWM);
    126126  analogWrite(pin, value);
    127127}
     
    132132    case 0: // pins 2-7 (don't change Rx/Tx, pins 0 and 1)
    133133      // 0xFF03 == B1111111100000011    0x03 == B00000011
    134       PORTD = (value &~ 0xFF03) | (PORTD & 0x03);
     134      PORTD = (value & ~ 0xFF03) | (PORTD & 0x03);
    135135      break;
    136136    case 1: // pins 8-13 (14,15 are disabled for the crystal)
     
    151151{
    152152  if (value == 0) {
    153     analogInputsToReport = analogInputsToReport &~ (1 << pin);
     153    analogInputsToReport = analogInputsToReport & ~ (1 << pin);
    154154  }
    155155  else { // everything but 0 enables reporting of that pin
     
    203203   * host computer, since once in the loop(), this firmware will only send
    204204   * digital data on change. */
    205   if (reportPINs[0]) outputPort(0, PIND &~ B00000011); // ignore Rx/Tx 0/1
     205  if (reportPINs[0]) outputPort(0, PIND & ~ B00000011); // ignore Rx/Tx 0/1
    206206  if (reportPINs[1]) outputPort(1, PINB);
    207207  if (reportPINs[2]) outputPort(2, PINC);
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino

    r136 r224  
    1313 * included in Arduino 0017
    1414 *
    15  * TODO add message to configure minPulse/maxPulse/degrees
    16  *
    1715 * This example code is in the public domain.
    1816 */
     
    2220
    2321Servo servos[MAX_SERVOS];
     22byte servoPinMap[TOTAL_PINS];
     23byte servoCount = 0;
    2424
    2525void analogWriteCallback(byte pin, int value)
    2626{
    27   if (IS_PIN_SERVO(pin)) {
    28     servos[PIN_TO_SERVO(pin)].write(value);
     27  if (IS_PIN_DIGITAL(pin)) {
     28    servos[servoPinMap[pin]].write(value);
    2929  }
     30}
     31
     32void systemResetCallback()
     33{
     34  servoCount = 0;
    3035}
    3136
     
    3439  byte pin;
    3540
    36   Firmata.setFirmwareVersion(0, 2);
     41  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
    3742  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
     43  Firmata.attach(SYSTEM_RESET, systemResetCallback);
    3844
     45  Firmata.begin(57600);
     46  systemResetCallback();
     47
     48  // attach servos from first digital pin up to max number of
     49  // servos supported for the board
    3950  for (pin = 0; pin < TOTAL_PINS; pin++) {
    40     if (IS_PIN_SERVO(pin)) {
    41       servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin));
     51    if (IS_PIN_DIGITAL(pin)) {
     52      if (servoCount < MAX_SERVOS) {
     53        servoPinMap[pin] = servoCount;
     54        servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin));
     55        servoCount++;
     56      }
    4257    }
    4358  }
    44 
    45   Firmata.begin(57600);
    4659}
    4760
     
    5164    Firmata.processInput();
    5265}
    53 
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino

    r136 r224  
    2828void setup()
    2929{
    30   Firmata.setFirmwareVersion(0, 1);
     30  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
    3131  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
    3232  Firmata.begin(57600);
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino

    r136 r224  
    5353void setup()
    5454{
    55   Firmata.setFirmwareVersion(0, 1);
     55  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
    5656  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
    5757  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino

    r136 r224  
    11/*
    2  * Firmata is a generic protocol for communicating with microcontrollers
    3  * from software on a host computer. It is intended to work with
    4  * any host computer software package.
    5  *
    6  * To download a host software package, please clink on the following link
    7  * to open the download page in your default browser.
    8  *
    9  * http://firmata.org/wiki/Download
    10  */
    11 
    12 /*
     2  Firmata is a generic protocol for communicating with microcontrollers
     3  from software on a host computer. It is intended to work with
     4  any host computer software package.
     5
     6  To download a host software package, please clink on the following link
     7  to open the list of Firmata client libraries your default browser.
     8
     9  https://github.com/firmata/arduino#firmata-client-libraries
     10
    1311  Copyright (C) 2006-2008 Hans-Christoph Steiner.  All rights reserved.
    1412  Copyright (C) 2010-2011 Paul Stoffregen.  All rights reserved.
    1513  Copyright (C) 2009 Shigeru Kobayashi.  All rights reserved.
    16   Copyright (C) 2009-2011 Jeff Hoefs.  All rights reserved.
     14  Copyright (C) 2009-2016 Jeff Hoefs.  All rights reserved.
    1715
    1816  This library is free software; you can redistribute it and/or
     
    2321  See file LICENSE.txt for further informations on licensing terms.
    2422
    25   formatted using the GNU C formatting and indenting
     23  Last updated by Jeff Hoefs: January 10th, 2016
    2624*/
    27 
    28 /*
    29  * TODO: use Program Control to load stored profiles from EEPROM
    30  */
    3125
    3226#include <Servo.h>
     
    3428#include <Firmata.h>
    3529
    36 // move the following defines to Firmata.h?
    37 #define I2C_WRITE B00000000
    38 #define I2C_READ B00001000
    39 #define I2C_READ_CONTINUOUSLY B00010000
    40 #define I2C_STOP_READING B00011000
    41 #define I2C_READ_WRITE_MODE_MASK B00011000
     30#define I2C_WRITE                   B00000000
     31#define I2C_READ                    B00001000
     32#define I2C_READ_CONTINUOUSLY       B00010000
     33#define I2C_STOP_READING            B00011000
     34#define I2C_READ_WRITE_MODE_MASK    B00011000
    4235#define I2C_10BIT_ADDRESS_MODE_MASK B00100000
    43 
    44 #define MAX_QUERIES 8
    45 #define MINIMUM_SAMPLING_INTERVAL 10
    46 
    47 #define REGISTER_NOT_SPECIFIED -1
     36#define I2C_END_TX_MASK             B01000000
     37#define I2C_STOP_TX                 1
     38#define I2C_RESTART_TX              0
     39#define I2C_MAX_QUERIES             8
     40#define I2C_REGISTER_NOT_SPECIFIED  -1
     41
     42// the minimum interval for sampling analog input
     43#define MINIMUM_SAMPLING_INTERVAL   1
     44
    4845
    4946/*==============================================================================
     
    5148 *============================================================================*/
    5249
     50#ifdef FIRMATA_SERIAL_FEATURE
     51SerialFirmata serialFeature;
     52#endif
     53
    5354/* analog inputs */
    5455int analogInputsToReport = 0; // bitwise array to store pin reporting
     
    5960
    6061/* pins configuration */
    61 byte pinConfig[TOTAL_PINS];         // configuration of every pin
    6262byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else
    63 int pinState[TOTAL_PINS];           // any value that has been written
    6463
    6564/* timer variables */
    6665unsigned long currentMillis;        // store the current value from millis()
    6766unsigned long previousMillis;       // for comparison with currentMillis
    68 int samplingInterval = 19;          // how often to run the main loop (in ms)
     67unsigned int samplingInterval = 19; // how often to run the main loop (in ms)
    6968
    7069/* i2c data */
    7170struct i2c_device_info {
    7271  byte addr;
    73   byte reg;
     72  int reg;
    7473  byte bytes;
     74  byte stopTX;
    7575};
    7676
    7777/* for i2c read continuous more */
    78 i2c_device_info query[MAX_QUERIES];
    79 
    80 byte i2cRxData[32];
     78i2c_device_info query[I2C_MAX_QUERIES];
     79
     80byte i2cRxData[64];
    8181boolean isI2CEnabled = false;
    8282signed char queryIndex = -1;
    83 unsigned int i2cReadDelayTime = 0;  // default delay time between i2c read request and Wire.requestFrom()
     83// default delay time between i2c read request and Wire.requestFrom()
     84unsigned int i2cReadDelayTime = 0;
    8485
    8586Servo servos[MAX_SERVOS];
     87byte servoPinMap[TOTAL_PINS];
     88byte detachedServos[MAX_SERVOS];
     89byte detachedServoCount = 0;
     90byte servoCount = 0;
     91
     92boolean isResetting = false;
     93
     94
     95/* utility functions */
     96void wireWrite(byte data)
     97{
     98#if ARDUINO >= 100
     99  Wire.write((byte)data);
     100#else
     101  Wire.send(data);
     102#endif
     103}
     104
     105byte wireRead(void)
     106{
     107#if ARDUINO >= 100
     108  return Wire.read();
     109#else
     110  return Wire.receive();
     111#endif
     112}
     113
    86114/*==============================================================================
    87115 * FUNCTIONS
    88116 *============================================================================*/
    89117
    90 void readAndReportData(byte address, int theRegister, byte numBytes) {
     118void attachServo(byte pin, int minPulse, int maxPulse)
     119{
     120  if (servoCount < MAX_SERVOS) {
     121    // reuse indexes of detached servos until all have been reallocated
     122    if (detachedServoCount > 0) {
     123      servoPinMap[pin] = detachedServos[detachedServoCount - 1];
     124      if (detachedServoCount > 0) detachedServoCount--;
     125    } else {
     126      servoPinMap[pin] = servoCount;
     127      servoCount++;
     128    }
     129    if (minPulse > 0 && maxPulse > 0) {
     130      servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse);
     131    } else {
     132      servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin));
     133    }
     134  } else {
     135    Firmata.sendString("Max servos attached");
     136  }
     137}
     138
     139void detachServo(byte pin)
     140{
     141  servos[servoPinMap[pin]].detach();
     142  // if we're detaching the last servo, decrement the count
     143  // otherwise store the index of the detached servo
     144  if (servoPinMap[pin] == servoCount && servoCount > 0) {
     145    servoCount--;
     146  } else if (servoCount > 0) {
     147    // keep track of detached servos because we want to reuse their indexes
     148    // before incrementing the count of attached servos
     149    detachedServoCount++;
     150    detachedServos[detachedServoCount - 1] = servoPinMap[pin];
     151  }
     152
     153  servoPinMap[pin] = 255;
     154}
     155
     156void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) {
    91157  // allow I2C requests that don't require a register read
    92158  // for example, some devices using an interrupt pin to signify new data available
    93159  // do not always require the register read so upon interrupt you call Wire.requestFrom()
    94   if (theRegister != REGISTER_NOT_SPECIFIED) {
     160  if (theRegister != I2C_REGISTER_NOT_SPECIFIED) {
    95161    Wire.beginTransmission(address);
    96 #if ARDUINO >= 100
    97     Wire.write((byte)theRegister);
    98 #else
    99     Wire.send((byte)theRegister);
    100 #endif
    101     Wire.endTransmission();
     162    wireWrite((byte)theRegister);
     163    Wire.endTransmission(stopTX); // default = true
    102164    // do not set a value of 0
    103165    if (i2cReadDelayTime > 0) {
     
    112174
    113175  // check to be sure correct number of bytes were returned by slave
    114   if (numBytes == Wire.available()) {
    115     i2cRxData[0] = address;
    116     i2cRxData[1] = theRegister;
    117     for (int i = 0; i < numBytes; i++) {
    118 #if ARDUINO >= 100
    119       i2cRxData[2 + i] = Wire.read();
    120 #else
    121       i2cRxData[2 + i] = Wire.receive();
    122 #endif
    123     }
    124   }
    125   else {
    126     if (numBytes > Wire.available()) {
    127       Firmata.sendString("I2C Read Error: Too many bytes received");
    128     } else {
    129       Firmata.sendString("I2C Read Error: Too few bytes received");
    130     }
     176  if (numBytes < Wire.available()) {
     177    Firmata.sendString("I2C: Too many bytes received");
     178  } else if (numBytes > Wire.available()) {
     179    Firmata.sendString("I2C: Too few bytes received");
     180  }
     181
     182  i2cRxData[0] = address;
     183  i2cRxData[1] = theRegister;
     184
     185  for (int i = 0; i < numBytes && Wire.available(); i++) {
     186    i2cRxData[2 + i] = wireRead();
    131187  }
    132188
     
    173229
    174230// -----------------------------------------------------------------------------
     231
     232/* disable the i2c pins so they can be used for other functions */
     233void disableI2CPins() {
     234  isI2CEnabled = false;
     235  // disable read continuous mode for all devices
     236  queryIndex = -1;
     237}
     238
     239/* sets bits in a bit array (int) to toggle the reporting of the analogIns
     240 */
     241//void FirmataClass::setAnalogPinReporting(byte pin, byte state) {
     242//}
     243void reportAnalogCallback(byte analogPin, int value)
     244{
     245  if (analogPin < TOTAL_ANALOG_PINS) {
     246    if (value == 0) {
     247      analogInputsToReport = analogInputsToReport & ~ (1 << analogPin);
     248    } else {
     249      analogInputsToReport = analogInputsToReport | (1 << analogPin);
     250      // prevent during system reset or all analog pin values will be reported
     251      // which may report noise for unconnected analog pins
     252      if (!isResetting) {
     253        // Send pin value immediately. This is helpful when connected via
     254        // ethernet, wi-fi or bluetooth so pin states can be known upon
     255        // reconnecting.
     256        Firmata.sendAnalog(analogPin, analogRead(analogPin));
     257      }
     258    }
     259  }
     260  // TODO: save status to EEPROM here, if changed
     261}
     262
     263// -----------------------------------------------------------------------------
    175264/* sets the pin mode to the correct state and sets the relevant bits in the
    176265 * two bit-arrays that track Digital I/O and PWM status
     
    178267void setPinModeCallback(byte pin, int mode)
    179268{
    180   if (pinConfig[pin] == I2C && isI2CEnabled && mode != I2C) {
     269  if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE)
     270    return;
     271
     272  if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) {
    181273    // disable i2c so pins can be used for other functions
    182274    // the following if statements should reconfigure the pins properly
    183275    disableI2CPins();
    184276  }
    185   if (IS_PIN_SERVO(pin) && mode != SERVO && servos[PIN_TO_SERVO(pin)].attached()) {
    186     servos[PIN_TO_SERVO(pin)].detach();
     277  if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) {
     278    if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) {
     279      detachServo(pin);
     280    }
    187281  }
    188282  if (IS_PIN_ANALOG(pin)) {
    189     reportAnalogCallback(PIN_TO_ANALOG(pin), mode == ANALOG ? 1 : 0); // turn on/off reporting
     283    reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting
    190284  }
    191285  if (IS_PIN_DIGITAL(pin)) {
    192     if (mode == INPUT) {
     286    if (mode == INPUT || mode == PIN_MODE_PULLUP) {
    193287      portConfigInputs[pin / 8] |= (1 << (pin & 7));
    194288    } else {
     
    196290    }
    197291  }
    198   pinState[pin] = 0;
     292  Firmata.setPinState(pin, 0);
    199293  switch (mode) {
    200     case ANALOG:
     294    case PIN_MODE_ANALOG:
    201295      if (IS_PIN_ANALOG(pin)) {
    202296        if (IS_PIN_DIGITAL(pin)) {
    203           pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver
     297          pinMode(PIN_TO_DIGITAL(pin), INPUT);    // disable output driver
     298#if ARDUINO <= 100
     299          // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6
    204300          digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
    205         }
    206         pinConfig[pin] = ANALOG;
     301#endif
     302        }
     303        Firmata.setPinMode(pin, PIN_MODE_ANALOG);
    207304      }
    208305      break;
    209306    case INPUT:
    210307      if (IS_PIN_DIGITAL(pin)) {
    211         pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver
     308        pinMode(PIN_TO_DIGITAL(pin), INPUT);    // disable output driver
     309#if ARDUINO <= 100
     310        // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6
    212311        digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
    213         pinConfig[pin] = INPUT;
     312#endif
     313        Firmata.setPinMode(pin, INPUT);
     314      }
     315      break;
     316    case PIN_MODE_PULLUP:
     317      if (IS_PIN_DIGITAL(pin)) {
     318        pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP);
     319        Firmata.setPinMode(pin, PIN_MODE_PULLUP);
     320        Firmata.setPinState(pin, 1);
    214321      }
    215322      break;
     
    218325        digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM
    219326        pinMode(PIN_TO_DIGITAL(pin), OUTPUT);
    220         pinConfig[pin] = OUTPUT;
    221       }
    222       break;
    223     case PWM:
     327        Firmata.setPinMode(pin, OUTPUT);
     328      }
     329      break;
     330    case PIN_MODE_PWM:
    224331      if (IS_PIN_PWM(pin)) {
    225332        pinMode(PIN_TO_PWM(pin), OUTPUT);
    226333        analogWrite(PIN_TO_PWM(pin), 0);
    227         pinConfig[pin] = PWM;
    228       }
    229       break;
    230     case SERVO:
    231       if (IS_PIN_SERVO(pin)) {
    232         pinConfig[pin] = SERVO;
    233         if (!servos[PIN_TO_SERVO(pin)].attached()) {
    234           servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin));
    235         }
    236       }
    237       break;
    238     case I2C:
     334        Firmata.setPinMode(pin, PIN_MODE_PWM);
     335      }
     336      break;
     337    case PIN_MODE_SERVO:
     338      if (IS_PIN_DIGITAL(pin)) {
     339        Firmata.setPinMode(pin, PIN_MODE_SERVO);
     340        if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) {
     341          // pass -1 for min and max pulse values to use default values set
     342          // by Servo library
     343          attachServo(pin, -1, -1);
     344        }
     345      }
     346      break;
     347    case PIN_MODE_I2C:
    239348      if (IS_PIN_I2C(pin)) {
    240349        // mark the pin as i2c
    241350        // the user must call I2C_CONFIG to enable I2C for a device
    242         pinConfig[pin] = I2C;
    243       }
     351        Firmata.setPinMode(pin, PIN_MODE_I2C);
     352      }
     353      break;
     354    case PIN_MODE_SERIAL:
     355#ifdef FIRMATA_SERIAL_FEATURE
     356      serialFeature.handlePinMode(pin, PIN_MODE_SERIAL);
     357#endif
    244358      break;
    245359    default:
     
    249363}
    250364
     365/*
     366 * Sets the value of an individual pin. Useful if you want to set a pin value but
     367 * are not tracking the digital port state.
     368 * Can only be used on pins configured as OUTPUT.
     369 * Cannot be used to enable pull-ups on Digital INPUT pins.
     370 */
     371void setPinValueCallback(byte pin, int value)
     372{
     373  if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) {
     374    if (Firmata.getPinMode(pin) == OUTPUT) {
     375      Firmata.setPinState(pin, value);
     376      digitalWrite(PIN_TO_DIGITAL(pin), value);
     377    }
     378  }
     379}
     380
    251381void analogWriteCallback(byte pin, int value)
    252382{
    253383  if (pin < TOTAL_PINS) {
    254     switch (pinConfig[pin]) {
    255       case SERVO:
    256         if (IS_PIN_SERVO(pin))
    257           servos[PIN_TO_SERVO(pin)].write(value);
    258         pinState[pin] = value;
     384    switch (Firmata.getPinMode(pin)) {
     385      case PIN_MODE_SERVO:
     386        if (IS_PIN_DIGITAL(pin))
     387          servos[servoPinMap[pin]].write(value);
     388        Firmata.setPinState(pin, value);
    259389        break;
    260       case PWM:
     390      case PIN_MODE_PWM:
    261391        if (IS_PIN_PWM(pin))
    262392          analogWrite(PIN_TO_PWM(pin), value);
    263         pinState[pin] = value;
     393        Firmata.setPinState(pin, value);
    264394        break;
    265395    }
     
    269399void digitalWriteCallback(byte port, int value)
    270400{
    271   byte pin, lastPin, mask = 1, pinWriteMask = 0;
     401  byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0;
    272402
    273403  if (port < TOTAL_PORTS) {
     
    278408      // do not disturb non-digital pins (eg, Rx & Tx)
    279409      if (IS_PIN_DIGITAL(pin)) {
    280         // only write to OUTPUT and INPUT (enables pullup)
    281410        // do not touch pins in PWM, ANALOG, SERVO or other modes
    282         if (pinConfig[pin] == OUTPUT || pinConfig[pin] == INPUT) {
    283           pinWriteMask |= mask;
    284           pinState[pin] = ((byte)value & mask) ? 1 : 0;
     411        if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) {
     412          pinValue = ((byte)value & mask) ? 1 : 0;
     413          if (Firmata.getPinMode(pin) == OUTPUT) {
     414            pinWriteMask |= mask;
     415          } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) {
     416            // only handle INPUT here for backwards compatibility
     417#if ARDUINO > 100
     418            pinMode(pin, INPUT_PULLUP);
     419#else
     420            // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier
     421            pinWriteMask |= mask;
     422#endif
     423          }
     424          Firmata.setPinState(pin, pinValue);
    285425        }
    286426      }
     
    293433
    294434// -----------------------------------------------------------------------------
    295 /* sets bits in a bit array (int) to toggle the reporting of the analogIns
    296  */
    297 //void FirmataClass::setAnalogPinReporting(byte pin, byte state) {
    298 //}
    299 void reportAnalogCallback(byte analogPin, int value)
    300 {
    301   if (analogPin < TOTAL_ANALOG_PINS) {
    302     if (value == 0) {
    303       analogInputsToReport = analogInputsToReport &~ (1 << analogPin);
    304     } else {
    305       analogInputsToReport = analogInputsToReport | (1 << analogPin);
    306     }
    307   }
    308   // TODO: save status to EEPROM here, if changed
    309 }
    310435
    311436void reportDigitalCallback(byte port, int value)
     
    313438  if (port < TOTAL_PORTS) {
    314439    reportPINs[port] = (byte)value;
     440    // Send port value immediately. This is helpful when connected via
     441    // ethernet, wi-fi or bluetooth so pin states can be known upon
     442    // reconnecting.
     443    if (value) outputPort(port, readPort(port, portConfigInputs[port]), true);
    315444  }
    316445  // do not disable analog reporting on these 8 pins, to allow some
     
    322451}
    323452
     453// -----------------------------------------------------------------------------
     454
     455void enableI2CPins()
     456{
     457  byte i;
     458  // is there a faster way to do this? would probaby require importing
     459  // Arduino.h to get SCL and SDA pins
     460  for (i = 0; i < TOTAL_PINS; i++) {
     461    if (IS_PIN_I2C(i)) {
     462      // mark pins as i2c so they are ignore in non i2c data requests
     463      setPinModeCallback(i, PIN_MODE_I2C);
     464    }
     465  }
     466
     467  isI2CEnabled = true;
     468
     469  Wire.begin();
     470}
     471
    324472/*==============================================================================
    325473 * SYSEX-BASED commands
     
    329477{
    330478  byte mode;
     479  byte stopTX;
    331480  byte slaveAddress;
    332   byte slaveRegister;
    333481  byte data;
     482  int slaveRegister;
    334483  unsigned int delayTime;
    335484
     
    338487      mode = argv[1] & I2C_READ_WRITE_MODE_MASK;
    339488      if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) {
    340         Firmata.sendString("10-bit addressing mode is not yet supported");
     489        Firmata.sendString("10-bit addressing not supported");
    341490        return;
    342491      }
    343492      else {
    344493        slaveAddress = argv[0];
     494      }
     495
     496      // need to invert the logic here since 0 will be default for client
     497      // libraries that have not updated to add support for restart tx
     498      if (argv[1] & I2C_END_TX_MASK) {
     499        stopTX = I2C_RESTART_TX;
     500      }
     501      else {
     502        stopTX = I2C_STOP_TX; // default
    345503      }
    346504
     
    350508          for (byte i = 2; i < argc; i += 2) {
    351509            data = argv[i] + (argv[i + 1] << 7);
    352 #if ARDUINO >= 100
    353             Wire.write(data);
    354 #else
    355             Wire.send(data);
    356 #endif
     510            wireWrite(data);
    357511          }
    358512          Wire.endTransmission();
     
    364518            slaveRegister = argv[2] + (argv[3] << 7);
    365519            data = argv[4] + (argv[5] << 7);  // bytes to read
    366             readAndReportData(slaveAddress, (int)slaveRegister, data);
    367520          }
    368521          else {
    369522            // a slave register is NOT specified
     523            slaveRegister = I2C_REGISTER_NOT_SPECIFIED;
    370524            data = argv[2] + (argv[3] << 7);  // bytes to read
    371             readAndReportData(slaveAddress, (int)REGISTER_NOT_SPECIFIED, data);
    372525          }
     526          readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX);
    373527          break;
    374528        case I2C_READ_CONTINUOUSLY:
    375           if ((queryIndex + 1) >= MAX_QUERIES) {
     529          if ((queryIndex + 1) >= I2C_MAX_QUERIES) {
    376530            // too many queries, just ignore
    377531            Firmata.sendString("too many queries");
    378532            break;
    379533          }
     534          if (argc == 6) {
     535            // a slave register is specified
     536            slaveRegister = argv[2] + (argv[3] << 7);
     537            data = argv[4] + (argv[5] << 7);  // bytes to read
     538          }
     539          else {
     540            // a slave register is NOT specified
     541            slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED;
     542            data = argv[2] + (argv[3] << 7);  // bytes to read
     543          }
    380544          queryIndex++;
    381545          query[queryIndex].addr = slaveAddress;
    382           query[queryIndex].reg = argv[2] + (argv[3] << 7);
    383           query[queryIndex].bytes = argv[4] + (argv[5] << 7);
     546          query[queryIndex].reg = slaveRegister;
     547          query[queryIndex].bytes = data;
     548          query[queryIndex].stopTX = stopTX;
    384549          break;
    385550        case I2C_STOP_READING:
     
    390555            queryIndex = -1;
    391556          } else {
     557            queryIndexToSkip = 0;
    392558            // if read continuous mode is enabled for multiple devices,
    393559            // determine which device to stop reading and remove it's data from
    394560            // the array, shifiting other array data to fill the space
    395561            for (byte i = 0; i < queryIndex + 1; i++) {
    396               if (query[i].addr = slaveAddress) {
     562              if (query[i].addr == slaveAddress) {
    397563                queryIndexToSkip = i;
    398564                break;
     
    401567
    402568            for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) {
    403               if (i < MAX_QUERIES) {
     569              if (i < I2C_MAX_QUERIES) {
    404570                query[i].addr = query[i + 1].addr;
    405                 query[i].reg = query[i + 1].addr;
     571                query[i].reg = query[i + 1].reg;
    406572                query[i].bytes = query[i + 1].bytes;
     573                query[i].stopTX = query[i + 1].stopTX;
    407574              }
    408575            }
     
    433600        int maxPulse = argv[3] + (argv[4] << 7);
    434601
    435         if (IS_PIN_SERVO(pin)) {
    436           if (servos[PIN_TO_SERVO(pin)].attached())
    437             servos[PIN_TO_SERVO(pin)].detach();
    438           servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse);
    439           setPinModeCallback(pin, SERVO);
     602        if (IS_PIN_DIGITAL(pin)) {
     603          if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) {
     604            detachServo(pin);
     605          }
     606          attachServo(pin, minPulse, maxPulse);
     607          setPinModeCallback(pin, PIN_MODE_SERVO);
    440608        }
    441609      }
     
    466634          Firmata.write((byte)INPUT);
    467635          Firmata.write(1);
     636          Firmata.write((byte)PIN_MODE_PULLUP);
     637          Firmata.write(1);
    468638          Firmata.write((byte)OUTPUT);
    469639          Firmata.write(1);
    470640        }
    471641        if (IS_PIN_ANALOG(pin)) {
    472           Firmata.write(ANALOG);
    473           Firmata.write(10);
     642          Firmata.write(PIN_MODE_ANALOG);
     643          Firmata.write(10); // 10 = 10-bit resolution
    474644        }
    475645        if (IS_PIN_PWM(pin)) {
    476           Firmata.write(PWM);
    477           Firmata.write(8);
    478         }
    479         if (IS_PIN_SERVO(pin)) {
    480           Firmata.write(SERVO);
     646          Firmata.write(PIN_MODE_PWM);
     647          Firmata.write(8); // 8 = 8-bit resolution
     648        }
     649        if (IS_PIN_DIGITAL(pin)) {
     650          Firmata.write(PIN_MODE_SERVO);
    481651          Firmata.write(14);
    482652        }
    483653        if (IS_PIN_I2C(pin)) {
    484           Firmata.write(I2C);
    485           Firmata.write(1);  // to do: determine appropriate value
    486         }
     654          Firmata.write(PIN_MODE_I2C);
     655          Firmata.write(1);  // TODO: could assign a number to map to SCL or SDA
     656        }
     657#ifdef FIRMATA_SERIAL_FEATURE
     658        serialFeature.handleCapability(pin);
     659#endif
    487660        Firmata.write(127);
    488661      }
     
    496669        Firmata.write(pin);
    497670        if (pin < TOTAL_PINS) {
    498           Firmata.write((byte)pinConfig[pin]);
    499           Firmata.write((byte)pinState[pin] & 0x7F);
    500           if (pinState[pin] & 0xFF80) Firmata.write((byte)(pinState[pin] >> 7) & 0x7F);
    501           if (pinState[pin] & 0xC000) Firmata.write((byte)(pinState[pin] >> 14) & 0x7F);
     671          Firmata.write(Firmata.getPinMode(pin));
     672          Firmata.write((byte)Firmata.getPinState(pin) & 0x7F);
     673          if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F);
     674          if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F);
    502675        }
    503676        Firmata.write(END_SYSEX);
     
    512685      Firmata.write(END_SYSEX);
    513686      break;
    514   }
    515 }
    516 
    517 void enableI2CPins()
    518 {
    519   byte i;
    520   // is there a faster way to do this? would probaby require importing
    521   // Arduino.h to get SCL and SDA pins
    522   for (i = 0; i < TOTAL_PINS; i++) {
    523     if (IS_PIN_I2C(i)) {
    524       // mark pins as i2c so they are ignore in non i2c data requests
    525       setPinModeCallback(i, I2C);
    526     }
    527   }
    528 
    529   isI2CEnabled = true;
    530 
    531   // is there enough time before the first I2C request to call this here?
    532   Wire.begin();
    533 }
    534 
    535 /* disable the i2c pins so they can be used for other functions */
    536 void disableI2CPins() {
    537   isI2CEnabled = false;
    538   // disable read continuous mode for all devices
    539   queryIndex = -1;
    540   // uncomment the following if or when the end() method is added to Wire library
    541   // Wire.end();
    542 }
     687
     688    case SERIAL_MESSAGE:
     689#ifdef FIRMATA_SERIAL_FEATURE
     690      serialFeature.handleSysex(command, argc, argv);
     691#endif
     692      break;
     693  }
     694}
     695
    543696
    544697/*==============================================================================
     
    548701void systemResetCallback()
    549702{
     703  isResetting = true;
     704
    550705  // initialize a defalt state
    551706  // TODO: option to load config from EEPROM instead of default
     707
     708#ifdef FIRMATA_SERIAL_FEATURE
     709  serialFeature.reset();
     710#endif
     711
    552712  if (isI2CEnabled) {
    553713    disableI2CPins();
    554714  }
     715
    555716  for (byte i = 0; i < TOTAL_PORTS; i++) {
    556     reportPINs[i] = false;      // by default, reporting off
    557     portConfigInputs[i] = 0;    // until activated
     717    reportPINs[i] = false;    // by default, reporting off
     718    portConfigInputs[i] = 0;  // until activated
    558719    previousPINs[i] = 0;
    559720  }
    560   // pins with analog capability default to analog input
    561   // otherwise, pins default to digital output
     721
    562722  for (byte i = 0; i < TOTAL_PINS; i++) {
     723    // pins with analog capability default to analog input
     724    // otherwise, pins default to digital output
    563725    if (IS_PIN_ANALOG(i)) {
    564726      // turns off pullup, configures everything
    565       setPinModeCallback(i, ANALOG);
    566     } else {
     727      setPinModeCallback(i, PIN_MODE_ANALOG);
     728    } else if (IS_PIN_DIGITAL(i)) {
    567729      // sets the output to 0, configures portConfigInputs
    568730      setPinModeCallback(i, OUTPUT);
    569731    }
     732
     733    servoPinMap[i] = 255;
    570734  }
    571735  // by default, do not report any analog inputs
    572736  analogInputsToReport = 0;
     737
     738  detachedServoCount = 0;
     739  servoCount = 0;
    573740
    574741  /* send digital inputs to set the initial state on the host computer,
     
    581748  }
    582749  */
     750  isResetting = false;
    583751}
    584752
    585753void setup()
    586754{
    587   Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION);
     755  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
    588756
    589757  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
     
    592760  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
    593761  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
     762  Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
    594763  Firmata.attach(START_SYSEX, sysexCallback);
    595764  Firmata.attach(SYSTEM_RESET, systemResetCallback);
    596765
     766  // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega,
     767  // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this:
     768  // Serial1.begin(57600);
     769  // Firmata.begin(Serial1);
     770  // However do not do this if you are using SERIAL_MESSAGE
     771
    597772  Firmata.begin(57600);
     773  while (!Serial) {
     774    ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101
     775  }
     776
    598777  systemResetCallback();  // reset to default config
    599778}
     
    610789  checkDigitalInputs();
    611790
    612   /* SERIALREAD - processing incoming messagse as soon as possible, while still
     791  /* STREAMREAD - processing incoming messagse as soon as possible, while still
    613792   * checking digital inputs.  */
    614793  while (Firmata.available())
    615794    Firmata.processInput();
    616795
    617   /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over
    618    * 60 bytes. use a timer to sending an event character every 4 ms to
    619    * trigger the buffer to dump. */
     796  // TODO - ensure that Stream buffer doesn't go over 60 bytes
    620797
    621798  currentMillis = millis();
     
    624801    /* ANALOGREAD - do all analogReads() at the configured sampling interval */
    625802    for (pin = 0; pin < TOTAL_PINS; pin++) {
    626       if (IS_PIN_ANALOG(pin) && pinConfig[pin] == ANALOG) {
     803      if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) {
    627804        analogPin = PIN_TO_ANALOG(pin);
    628805        if (analogInputsToReport & (1 << analogPin)) {
     
    634811    if (queryIndex > -1) {
    635812      for (byte i = 0; i < queryIndex + 1; i++) {
    636         readAndReportData(query[i].addr, query[i].reg, query[i].bytes);
    637       }
    638     }
    639   }
    640 }
     813        readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX);
     814      }
     815    }
     816  }
     817
     818#ifdef FIRMATA_SERIAL_FEATURE
     819  serialFeature.update();
     820#endif
     821}
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/keywords.txt

    r136 r224  
    77#######################################
    88
    9 Firmata KEYWORD1
    10 callbackFunction        KEYWORD1
    11 systemResetCallbackFunction     KEYWORD1
    12 stringCallbackFunction  KEYWORD1
    13 sysexCallbackFunction   KEYWORD1
     9Firmata                         KEYWORD1        Firmata
     10callbackFunction                KEYWORD1        callbackFunction
     11systemResetCallbackFunction     KEYWORD1        systemResetCallbackFunction
     12stringCallbackFunction          KEYWORD1        stringCallbackFunction
     13sysexCallbackFunction           KEYWORD1        sysexCallbackFunction
    1414
    1515#######################################
     
    1717#######################################
    1818
    19 begin   KEYWORD2
    20 begin   KEYWORD2
    21 printVersion    KEYWORD2
    22 blinkVersion    KEYWORD2
    23 printFirmwareVersion    KEYWORD2
    24 setFirmwareVersion      KEYWORD2
     19begin                           KEYWORD2
     20printVersion                    KEYWORD2
     21blinkVersion                    KEYWORD2
     22printFirmwareVersion            KEYWORD2
     23setFirmwareVersion              KEYWORD2
    2524setFirmwareNameAndVersion       KEYWORD2
    26 available       KEYWORD2
    27 processInput    KEYWORD2
    28 sendAnalog      KEYWORD2
    29 sendDigital     KEYWORD2
    30 sendDigitalPortPair     KEYWORD2
    31 sendDigitalPort KEYWORD2
    32 sendString      KEYWORD2
    33 sendString      KEYWORD2
    34 sendSysex       KEYWORD2
    35 attach  KEYWORD2
    36 detach  KEYWORD2
    37 flush   KEYWORD2
     25available                       KEYWORD2
     26processInput                    KEYWORD2
     27isParsingMessage                KEYWORD2
     28parse                           KEYWORD2
     29sendAnalog                      KEYWORD2
     30sendDigital                     KEYWORD2
     31sendDigitalPort                 KEYWORD2
     32sendString                      KEYWORD2
     33sendSysex                       KEYWORD2
     34getPinMode                      KEYWORD2
     35setPinMode                      KEYWORD2
     36getPinState                     KEYWORD2
     37setPinState                     KEYWORD2
     38attach                          KEYWORD2
     39detach                          KEYWORD2
     40write                           KEYWORD2
     41sendValueAsTwo7bitBytes KEYWORD2
     42startSysex                      KEYWORD2
     43endSysex                        KEYWORD2
     44writePort                       KEYWORD2
     45readPort                        KEYWORD2
     46disableBlinkVersion             KEYWORD2
    3847
    3948
     
    4251#######################################
    4352
    44 MAX_DATA_BYTES  LITERAL1
     53FIRMATA_MAJOR_VERSION   LITERAL1
     54FIRMATA_MINOR_VERSION   LITERAL1
     55FIRMATA_BUGFIX_VERSION  LITERAL1
    4556
    46 DIGITAL_MESSAGE LITERAL1
    47 ANALOG_MESSAGE  LITERAL1
    48 REPORT_ANALOG   LITERAL1
    49 REPORT_DIGITAL  LITERAL1
    50 REPORT_VERSION  LITERAL1
    51 SET_PIN_MODE    LITERAL1
    52 SYSTEM_RESET    LITERAL1
     57MAX_DATA_BYTES          LITERAL1
    5358
    54 START_SYSEX     LITERAL1
    55 END_SYSEX       LITERAL1
     59DIGITAL_MESSAGE         LITERAL1
     60ANALOG_MESSAGE          LITERAL1
     61REPORT_ANALOG           LITERAL1
     62REPORT_DIGITAL          LITERAL1
     63REPORT_VERSION          LITERAL1
     64SET_PIN_MODE            LITERAL1
     65SET_DIGITAL_PIN_VALUE   LITERAL1
     66SYSTEM_RESET            LITERAL1
     67START_SYSEX             LITERAL1
     68END_SYSEX               LITERAL1
     69REPORT_FIRMWARE         LITERAL1
     70STRING_DATA             LITERAL1
    5671
    57 PWM     LITERAL1
     72PIN_MODE_ANALOG         LITERAL1
     73PIN_MODE_PWM            LITERAL1
     74PIN_MODE_SERVO          LITERAL1
     75PIN_MODE_SHIFT          LITERAL1
     76PIN_MODE_I2C            LITERAL1
     77PIN_MODE_ONEWIRE        LITERAL1
     78PIN_MODE_STEPPER        LITERAL1
     79PIN_MODE_ENCODER        LITERAL1
     80PIN_MODE_SERIAL         LITERAL1
     81PIN_MODE_PULLUP         LITERAL1
     82PIN_MODE_IGNORE         LITERAL1
    5883
     84TOTAL_PINS              LITERAL1
    5985TOTAL_ANALOG_PINS       LITERAL1
    6086TOTAL_DIGITAL_PINS      LITERAL1
    61 TOTAL_PORTS                     LITERAL1
    62 ANALOG_PORT                     LITERAL1
     87TOTAL_PIN_MODES         LITERAL1
     88TOTAL_PORTS             LITERAL1
     89ANALOG_PORT             LITERAL1
     90MAX_SERVOS              LITERAL1
  • rtos_arduino/trunk/arduino_lib/libraries/Firmata/library.properties

    r136 r224  
    11name=Firmata
    2 version=2.3.6
     2version=2.5.2
    33author=Firmata Developers
    4 maintainer=Firmata Developers <firmata-devel@lists.sourceforge.net>
     4maintainer=https://github.com/firmata/arduino
    55sentence=Enables the communication with computer apps using a standard serial protocol. For all Arduino boards.
    66paragraph=The Firmata library implements the Firmata protocol for communicating with software on the host computer. This allows you to write custom firmware without having to create your own protocol and objects for the programming environment that you are using.
    77category=Device Control
    8 url=http://firmata.org
     8url=https://github.com/firmata/arduino
    99architectures=*
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/LuckyTest/LuckyTest.ino

    r175 r224  
    7979
    8080  //read magnetometer sensor
     81  lucky.magnetometer().read();
    8182  Serial.print("Mx: ");
    8283  Serial.print(lucky.magnetometer().x());
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/library.properties

    r175 r224  
    11name=Lucky Shield
    2 version=1.0.2
     2version=1.0.3
    33author=Arduino srl
    44maintainer=Arduino srl <swdev@arduino.org>
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/Lucky.h

    r175 r224  
    4040#include "Wire.h"
    4141
     42#ifdef __SAM3X8E__
     43#define Wire Wire1
     44#endif
     45
    4246class Lucky
    4347{
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.cpp

    r175 r224  
    3232#include "Adafruit_SSD1306.h"
    3333
     34#ifdef __SAM3X8E__
     35#define Wire Wire1
     36#endif
    3437// the memory buffer for the LCD
    3538
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.h

    r175 r224  
    164164  int8_t _i2caddr, _vccstate, sid, sclk, dc, rst, cs;
    165165
    166   boolean hwSPI;
    167   PortReg *mosiport, *clkport, *csport, *dcport;
    168   PortMask mosipinmask, clkpinmask, cspinmask, dcpinmask;
     166  //boolean hwSPI;
     167  //PortReg *mosiport, *clkport, *csport, *dcport;
     168  //PortMask mosipinmask, clkpinmask, cspinmask, dcpinmask;
    169169
    170170  inline void drawFastVLineInternal(int16_t x, int16_t y, int16_t h, uint16_t color) __attribute__((always_inline));
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/BME280.cpp

    r175 r224  
    1919#include "BME280.h"
    2020
     21#ifdef __SAM3X8E__
     22#define Wire Wire1
     23#endif
    2124
    2225/***************************************************************************
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/CAT9555.cpp

    r175 r224  
    2828#include "CAT9555.h"
    2929#include <Wire.h>
     30
     31#ifdef __SAM3X8E__
     32#define Wire Wire1
     33#endif
    3034
    3135// CONSTRUCTUR
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.cpp

    r175 r224  
    1616
    1717//Constructor
    18 MAG3110::MAG3110()
    19 {
    20  
    21 }
    22 
    23 
     18// MAG3110::MAG3110()
     19// {
     20// }
    2421
    2522// Configure magnetometer
    2623void MAG3110::begin(void) {
    27   //CTRL_REG1
    28   //DR2|DR1|DR0|OS1|OS0|FastRead|Trigger|ActiveMode|
    29   // 0 | 1 | 1 | 1 | 1 |    0   |   0   |    1     |=dec121
     24
    3025  Wire.beginTransmission(MAG_ADDR);// transmit to device 0x0E
    31   Wire.write(0x10);                // cntrl register1
    32   Wire.write(0x79); // Active Mode, 1.25 Hz datarate, 8x oversampling
    33   Wire.endTransmission();          // stop transmitting
     26  Wire.write(0x11);              // cntrl register2
     27  Wire.write(0x80);              // send 0x80, enable auto resets
     28  Wire.endTransmission();       // stop transmitting
    3429 
    3530  delay(15);
    3631 
    37   //CTRL_REG2:
    38   //AutoMagRst|---|Raw|Mag_Rst|---|---|---|---|
    39   //    1     | 0 | 0 |   0   | 0 | 0 | 0 | 0 |
    4032  Wire.beginTransmission(MAG_ADDR);// transmit to device 0x0E
    41   Wire.write(0x11);                // cntrl register2
    42   Wire.write(0x80);        // Auto resets before each measurement
    43   Wire.endTransmission();          // stop transmitting
     33  Wire.write(0x10);              // cntrl register1
     34  Wire.write(1);                 // send 0x01, active mode
     35  Wire.endTransmission();       // stop transmitting
    4436}
    4537
     38void MAG3110::read()
     39{
     40  mag_x =read16Data(0x01,0x02);
     41  mag_y =read16Data(0x03,0x04);
     42  mag_z =read16Data(0x05,0x06);
     43}
     44// read X value
    4645
    47 // read X value
    48 int MAG3110::readx(void)
     46int MAG3110::read16Data(byte MSB, byte LSB)
    4947{
    5048  int xl, xh;  //define the MSB and LSB
    5149 
    5250  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
    53   Wire.write(0x01);              // x MSB reg
     51  Wire.write(MSB);              // x MSB reg
    5452  Wire.endTransmission();       // stop transmitting
    5553 
     
    6563 
    6664  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
    67   Wire.write(0x02);              // x LSB reg
     65  Wire.write(LSB);              // x LSB reg
    6866  Wire.endTransmission();       // stop transmitting
    6967 
     
    7674  }
    7775 
    78   int xout = (xl|(xh << 8)); //concatenate the MSB and LSB
    79   return xout;
     76  int out = (xl|(xh << 8)); //concatenate the MSB and LSB
     77  if (out & 0b1000000000000000){
     78     //float yout1 = ((~yout & 0b0111111111111111)+ 1)*(-1) ;
     79    return float ((~out & 0b0111111111111111)+ 1)*(-1) ;
     80  }
     81  return float (out);
    8082}
    8183
    82 //read Y value
    83 int MAG3110::ready(void)
    84 {
    85   int yl, yh;  //define the MSB and LSB
    86  
    87   Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
    88   Wire.write(0x03);              // y MSB reg
    89   Wire.endTransmission();       // stop transmitting
    90  
    91   delayMicroseconds(2); //needs at least 1.3us free time between start and stop
    92  
    93   Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
    94   while(Wire.available())    // slave may send less than requested
    95   {
    96     yh = Wire.read(); // receive the byte
    97   }
    98  
    99   delayMicroseconds(2); //needs at least 1.3us free time between start and stop
    100  
    101   Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
    102   Wire.write(0x04);              // y LSB reg
    103   Wire.endTransmission();       // stop transmitting
    104  
    105   delayMicroseconds(2); //needs at least 1.3us free time between start and stop
    106  
    107   Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
    108   while(Wire.available())    // slave may send less than requested
    109   {
    110     yl = Wire.read(); // receive the byte
    111   }
    112  
    113   int yout = (yl|(yh << 8)); //concatenate the MSB and LSB
    114   return yout;
    115 }
    116 
    117 // read Z value
    118 int MAG3110::readz(void)
    119 {
    120   int zl, zh;  //define the MSB and LSB
    121  
    122   Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
    123   Wire.write(0x05);              // z MSB reg
    124   Wire.endTransmission();       // stop transmitting
    125  
    126   delayMicroseconds(2); //needs at least 1.3us free time between start and stop
    127  
    128   Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
    129   while(Wire.available())    // slave may send less than requested
    130   {
    131     zh = Wire.read(); // receive the byte
    132   }
    133  
    134   delayMicroseconds(2); //needs at least 1.3us free time between start and stop
    135  
    136   Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
    137   Wire.write(0x06);              // z LSB reg
    138   Wire.endTransmission();       // stop transmitting
    139  
    140   delayMicroseconds(2); //needs at least 1.3us free time between start and stop
    141  
    142   Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
    143   while(Wire.available())    // slave may send less than requested
    144   {
    145     zl = Wire.read(); // receive the byte
    146   }
    147  
    148   int zout = (zl|(zh << 8)); //concatenate the MSB and LSB
    149   return zout;
    150 }
    15184
    15285MAG3110 mag3110;
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.h

    r175 r224  
    2525{
    2626  public:
    27     MAG3110();
     27    //constructor
     28    //MAG3110();
     29   
     30    //public methods
    2831    void begin();
    29     int readx();
    30     int ready();
    31     int readz();
    32        
    33         int x(){return readx();};
    34         int y(){return ready();};
    35         int z(){return readz();};
     32    void read();
     33    int x(){return mag_x;};
     34    int y(){return mag_y;};
     35    int z(){return mag_z;};
     36
    3637  private:
     38    //class-only methods:
     39    int read16Data(byte MSB, byte LSB);
     40   
     41    //global variables
     42    int mag_x;
     43    int mag_y;
     44    int mag_z;
     45   
    3746};
    3847
  • rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MMA8491Q.cpp

    r175 r224  
    3030#include "MMA8491Q.h"
    3131#include <Wire.h>
     32
     33#ifdef __SAM3X8E__
     34#define Wire Wire1
     35#endif
    3236
    3337// CONSTRUCTUR
  • rtos_arduino/trunk/arduino_lib/libraries/Servo/src/Servo.h

    r136 r224  
    6666#elif defined(ARDUINO_ARCH_SAMD)
    6767        //#include "samd/ServoTimersSamd.h"
    68         #define MIN_PULSE_WIDTH_SAMD 500
    69         #define MAX_PULSE_WIDTH_SAMD 2100
     68        #define MIN_PULSE_WIDTH_SAMD_TCC 405
     69        #define MAX_PULSE_WIDTH_SAMD_TCC 2300
     70        #define MIN_PULSE_WIDTH_SAMD_TC 1700
     71        #define MAX_PULSE_WIDTH_SAMD_TC 9200
    7072#else   
    7173        #error "This library only supports boards with an AVR,SAM or SAMD processor."
  • rtos_arduino/trunk/arduino_lib/libraries/Servo/src/samd/Servo.cpp

    r136 r224  
    1616  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
    1717*/
     18//Edited by Arduino Srl development team.
    1819
    1920#if defined(ARDUINO_ARCH_SAMD)
     
    2223#include <Servo.h>
    2324
     25
    2426static servo_t servos[MAX_SERVOS];                          // static array of servo structures
    2527
    2628uint8_t ServoCount = 0;                                     // the total number of attached servos
     29uint8_t isTC = 0 ;
     30Tc* TCx ;
    2731Tcc* TCCx;
    2832uint8_t Channelx = 0;
     
    3034// convenience macros
    3135
    32 #define SERVO_MIN() (MIN_PULSE_WIDTH_SAMD)  // minimum value in uS for this servo
    33 #define SERVO_MAX() (MAX_PULSE_WIDTH_SAMD)  // maximum value in uS for this servo
     36#define SERVO_MIN_TCC() (MIN_PULSE_WIDTH_SAMD_TCC)  // minimum value in uS for this servo if TCC timer is used
     37#define SERVO_MAX_TCC() (MAX_PULSE_WIDTH_SAMD_TCC)  // maximum value in uS for this servo if TCC timer is used
     38#define SERVO_MIN_TC() (MIN_PULSE_WIDTH_SAMD_TC)  // minimum value in uS for this servo if TC timer is used
     39#define SERVO_MAX_TC() (MAX_PULSE_WIDTH_SAMD_TC)  // maximum value in uS for this servo if TC timer is used
    3440
    3541/************ static functions common to all instances ***********************/
     
    4652  if (ServoCount < MAX_SERVOS) {
    4753    this->servoIndex = ServoCount++;                    // assign a servo index to this instance
    48   } else {                                                  //su questo costruttore forse si deve tornare
    49     this->servoIndex = INVALID_SERVO;  // too many servos
     54  } else {                                                 
     55    this->servoIndex = INVALID_SERVO;                                   // too many servos
    5056  }
    5157}
     
    5359uint8_t Servo::attach(int pin)
    5460{
    55   return this->attach(pin, MIN_PULSE_WIDTH_SAMD, MAX_PULSE_WIDTH_SAMD);
     61  if((servos[this->servoIndex].Pin.nbr==4) | (servos[this->servoIndex].Pin.nbr==5) | (servos[this->servoIndex].Pin.nbr==10) | (servos[this->servoIndex].Pin.nbr==12) ){
     62        return this->attach(pin, SERVO_MIN_TC(), SERVO_MAX_TC());
     63  }
     64  else{
     65        return this->attach(pin, SERVO_MIN_TCC(), SERVO_MAX_TCC());
     66  }
    5667}
    5768
     
    6374    pinMode(pin, OUTPUT);                                   // set servo pin to output
    6475    servos[this->servoIndex].Pin.nbr = pin;
    65     if(min > MIN_PULSE_WIDTH_SAMD) min = MIN_PULSE_WIDTH_SAMD;
    66         if (max > MAX_PULSE_WIDTH_SAMD) max = MAX_PULSE_WIDTH_SAMD;
     76        int servo_min, servo_max;
     77        if(pin==4 | pin==5 | pin==10 | pin==12){
     78                servo_min=SERVO_MIN_TC();
     79                servo_max=SERVO_MAX_TC();
     80        }
     81        else{
     82                servo_min=SERVO_MIN_TCC();
     83                servo_max=SERVO_MAX_TCC();
     84        }
     85    if(min > servo_min) min = servo_min;
     86        if (max > servo_max) max = servo_max;
    6787        this->min  = min;
    6888    this->max  = max;
     
    7595                        TCCx=TCC0;
    7696                        Channelx=0;
     97                        isTC=0;
    7798                }
    7899                break;
     
    83104                        TCCx=TCC0;
    84105                        Channelx=1;
    85                 }
    86                 break;
    87                
     106                        isTC=0;
     107                }
     108                break;
     109
     110                        case 4:
     111                {
     112                        pinPeripheral(pin, g_APinDescription[pin].ulPinType);
     113                        TCx=TC3;
     114                        Channelx=0;
     115                        isTC=1;
     116                         
     117                }
     118                break;
     119
     120                case 5:
     121                {
     122                        pinPeripheral(pin, g_APinDescription[pin].ulPinType);
     123                        TCx=TC3;
     124                        Channelx=1;
     125                        isTC=1;
     126                         
     127                }
     128                break;
    88129                case 6:
    89130                {
     
    91132                        TCCx=TCC0;
    92133                        Channelx=2;
     134                        isTC=0;
    93135                }
    94136                break;
     
    99141                        TCCx=TCC0;
    100142                        Channelx=3;
     143                        isTC=0;
    101144                }
    102145                break;
     
    107150                        TCCx=TCC1;
    108151                        Channelx=0;
     152                        isTC=0;
    109153                }
    110154                break;
     
    115159                        TCCx=TCC1;
    116160                        Channelx=1;
     161                        isTC=0;
     162                }
     163                break;
     164               
     165                case 10:
     166                {
     167                        pinPeripheral(pin, g_APinDescription[pin].ulPinType);
     168                        TCx=TC3;
     169                        Channelx=0;
     170                        isTC=1;
     171                         
    117172                }
    118173                break;
     
    123178                        TCCx=TCC2;
    124179                        Channelx=0;
     180                        isTC=0;
     181                }
     182                break;
     183               
     184                case 12:
     185                {
     186                        pinPeripheral(pin, g_APinDescription[pin].ulPinType);
     187                        TCx=TC3;
     188                        Channelx=1;
     189                        isTC=1;
     190                         
    125191                }
    126192                break;
     
    131197                        TCCx=TCC2;
    132198                        Channelx=1;
     199                        isTC=0;
    133200                }
    134201                break;
     
    140207       
    141208        if ((TCCx==TCC0) | (TCCx==TCC1)) GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK3 | GCLK_CLKCTRL_ID( GCM_TCC0_TCC1 )) ;
    142         else if(TCCx==TCC2) GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK3 | GCLK_CLKCTRL_ID( GCM_TCC2_TC3 )) ;
     209        else if((TCCx==TCC2) | (TCx==TC3 ))GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK3 | GCLK_CLKCTRL_ID( GCM_TCC2_TC3 )) ;
    143210        else;
    144                
    145         if(servos[this->servoIndex].Pin.isActive == false)
    146         {       
    147                 TCCx->CTRLA.reg &=~(TCC_CTRLA_ENABLE);        //disable TCC module
     211
     212        if(servos[this->servoIndex].Pin.isActive == false){
     213        // Set PORT
     214    if ( isTC )
     215    {
     216      // -- Configure TC
     217      //DISABLE TCx
     218      TCx->COUNT16.CTRLA.reg &=~(TC_CTRLA_ENABLE);
     219      //Set Timer counter Mode to 16 bits
     220          TCx->COUNT16.CTRLA.reg |= TC_CTRLA_MODE_COUNT16;
     221          //Set Prescaler to divide by 2
     222          TCx->COUNT16.CTRLA.reg |= TC_CTRLA_PRESCALER_DIV2;
     223      //Set TCx as normal PWM
     224      TCx->COUNT16.CTRLA.reg |= TC_CTRLA_WAVEGEN_NPWM;
     225          //default value for servo position
     226      TCx->COUNT16.CC[Channelx].reg = 1500;
     227          //ENABLE TCx
     228      TCx->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE;
     229          servos[this->servoIndex].Pin.isActive = true;
     230    }
     231    else
     232    {
     233      // -- Configure TCC
     234         
     235         TCCx->CTRLA.reg &=~(TCC_CTRLA_ENABLE);        //disable TCC module
    148236                TCCx->CTRLA.reg |=TCC_CTRLA_PRESCALER_DIV8;   //setting prescaler to divide by 8
    149237                TCCx->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM;      //Set TCCx as normal PWM
     
    151239                TCCx->PER.reg=20000;                          // setting servo frequency (50 hz)
    152240                TCCx->CTRLA.reg |= TCC_CTRLA_ENABLE ;         //ENABLE TCCx
    153                 servos[this->servoIndex].Pin.isActive = true;
    154         }       
    155    
    156     //servos[this->servoIndex].Pin.isActive = true;  // this must be set after the check for isTimerActive
     241                servos[this->servoIndex].Pin.isActive = true;  
     242    }
     243       
     244        }
    157245  }
    158246  return this->servoIndex;
     
    167255  else if((servos[this->servoIndex].Pin.nbr == 8) | (servos[this->servoIndex].Pin.nbr == 9)) TCC1->CTRLA.reg &=~(TCC_CTRLA_ENABLE);
    168256  else if ((servos[this->servoIndex].Pin.nbr == 11) | (servos[this->servoIndex].Pin.nbr == 13)) TCC2->CTRLA.reg &=~(TCC_CTRLA_ENABLE); 
     257  else if ((servos[this->servoIndex].Pin.nbr == 4 ) | (servos[this->servoIndex].Pin.nbr == 5 ) | (servos[this->servoIndex].Pin.nbr == 10 ) | (servos[this->servoIndex].Pin.nbr == 12 ))TC3->COUNT16.CTRLA.reg &=~(TC_CTRLA_ENABLE);
    169258}
    170259
    171260void Servo::write(int value)
    172 {
    173   // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    174   if (value < MIN_PULSE_WIDTH)
    175   {
    176     if (value < 0)
    177       value = 0;
    178     else if (value > 180)
    179       value = 180;
    180 
    181     value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX());
    182   }
     261
     262  //select the right values for servo motor
     263  int servo_min;
     264  int servo_max;
     265  if((servos[this->servoIndex].Pin.nbr==4) | (servos[this->servoIndex].Pin.nbr==5) | (servos[this->servoIndex].Pin.nbr==10) | (servos[this->servoIndex].Pin.nbr==12) ){
     266        servo_min=SERVO_MIN_TC();
     267        servo_max=SERVO_MAX_TC();
     268        // treat values less than 1700 as angles in degrees (valid values in microseconds are handled as microseconds)
     269        if (value < servo_min)
     270        {
     271                if (value < 0)
     272                        value = 0;
     273                else if (value > 180)
     274                        value = 180;
     275                value = map(value, 0, 180, servo_min, servo_max);
     276        }
     277  }
     278  else{
     279        servo_min=SERVO_MIN_TCC();
     280        servo_max=SERVO_MAX_TCC();
     281        // treat values less than 400 as angles in degrees (valid values in microseconds are handled as microseconds)
     282        if (value < servo_min)
     283        {
     284                if (value < 0)
     285                        value = 0;
     286                else if (value > 180)
     287                        value = 180;
     288                value = map(value, 0, 180, servo_min, servo_max);
     289        }
     290  }
     291   
    183292  writeMicroseconds(value);
    184293}
     
    190299  if( (channel < MAX_SERVOS) )   // ensure channel is valid
    191300  {
    192     if (value < SERVO_MIN())          // ensure pulse width is valid
    193       value = SERVO_MIN();
    194     else if (value > SERVO_MAX())
    195       value = SERVO_MAX();
    196     servos[this->servoIndex].ticks = value;   //da sistemare
     301        //select the right values for servo motor
     302        int servo_min;
     303        int servo_max;
     304        if((servos[this->servoIndex].Pin.nbr==4) | (servos[this->servoIndex].Pin.nbr==5) | (servos[this->servoIndex].Pin.nbr==10) | (servos[this->servoIndex].Pin.nbr==12) ){
     305                servo_min=SERVO_MIN_TC();
     306                servo_max=SERVO_MAX_TC();
     307        }
     308        else{
     309                servo_min=SERVO_MIN_TCC();
     310                servo_max=SERVO_MAX_TCC();
     311        }
     312    if (value < servo_min)          // ensure pulse width is valid
     313      value = servo_min;
     314    else if (value > servo_max)
     315      value = servo_max;
     316    servos[this->servoIndex].ticks = value;
    197317        switch(servos[this->servoIndex].Pin.nbr)
    198318        {
     
    205325                        break;
    206326                       
     327                case 4:
     328                        TC3->COUNT16.CC[0].reg = value;
     329                        break; 
     330                       
     331                case 5:
     332                        TC3->COUNT16.CC[1].reg = value;
     333                        break; 
     334                       
    207335                case 6:
    208336                        TCC0->CC[2].reg=value;
     
    220348                        TCC1->CC[1].reg=value;
    221349                        break;
     350               
     351                case 10:
     352                        TC3->COUNT16.CC[0].reg = value;
     353                        break;         
    222354                       
    223355                case 11:
     
    225357                        break;
    226358
     359                case 12:
     360                        TC3->COUNT16.CC[1].reg = value;
     361                        break; 
     362
    227363                case 13:
    228364                        TCC2->CC[1].reg=value;
     
    234370        }
    235371   
    236     //servos[this->servoIndex].ticks = value;   //da sistemare
     372    //servos[this->servoIndex].ticks = value;   //to be fixed
    237373        //servos[channel].ticks = value;
    238374  }
     
    241377int Servo::read() // return the value as degrees
    242378{
    243   return map(readMicroseconds(), SERVO_MIN(), SERVO_MAX(), 0, 180);
     379  //select the right values for servo motor
     380  int servo_min;
     381  int servo_max;
     382  if((servos[this->servoIndex].Pin.nbr==4) | (servos[this->servoIndex].Pin.nbr==5) | (servos[this->servoIndex].Pin.nbr==10) | (servos[this->servoIndex].Pin.nbr==12) ){
     383        servo_min=SERVO_MIN_TC();
     384        servo_max=SERVO_MAX_TC();
     385        }
     386  else{
     387        servo_min=SERVO_MIN_TCC();
     388        servo_max=SERVO_MAX_TCC();
     389        }
     390  return map(readMicroseconds(), servo_min, servo_max, 0, 180);
    244391}
    245392
  • rtos_arduino/trunk/lib/Makefile.rca

    r136 r224  
    1010              wiring.o wiring_digital.o wiring_analog.o wiring_shift.o \
    1111              WInterrupts.o \
    12               samd21_device.o samd21_host.o \
     12              samd21_host.o \
    1313              dtostrf.o \
    1414              itoa.o \
     
    110110CDEFS += -Dprintf=iprintf \
    111111         -DF_CPU=48000000L \
    112          -DARDUINO=10708 \
     112         -DARDUINO=10710 \
    113113         -DARDUINO_SAM_ZERO \
    114114         -DARDUINO_ARCH_SAMD \
Note: See TracChangeset for help on using the changeset viewer.