Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/SERCOM.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/SERCOM.cpp	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/SERCOM.cpp	(revision 175)
@@ -1,8 +1,27 @@
+/*
+  Copyright (c) 2014 Arduino.  All right reserved.
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the GNU Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
 #include "SERCOM.h"
 #include "variant.h"
 
+
 SERCOM::SERCOM(Sercom* s)
 {
-	sercom = s;
+  sercom = s;
 }
 
@@ -13,6 +32,6 @@
 void SERCOM::initUART(SercomUartMode mode, SercomUartSampleRate sampleRate, uint32_t baudrate)
 {
+  initClockNVIC();
   resetUART();
-  initClockNVIC();
 
   //Setting the CTRLA register
@@ -26,45 +45,38 @@
   if ( mode == UART_INT_CLOCK )
   {
-    uint16_t sampleRateValue ;
-
-    if ( sampleRate == SAMPLE_RATE_x16 )
-    {
-      sampleRateValue = 16 ;
+    uint16_t sampleRateValue;
+
+    if (sampleRate == SAMPLE_RATE_x16) {
+      sampleRateValue = 16;
+    } else {
+      sampleRateValue = 8;
     }
-    else
-    {
-      if ( sampleRate == SAMPLE_RATE_x8 )
-      {
-        sampleRateValue = 8 ;
-      }
-      else
-      {
-        sampleRateValue = 3 ;
-      }
-    }
-
-    // Asynchronous arithmetic mode
-    // 65535 * ( 1 - sampleRateValue * baudrate / SystemCoreClock);
-    // 65535 - 65535 * (sampleRateValue * baudrate / SystemCoreClock));
-    sercom->USART.BAUD.reg = 65535.0f * ( 1.0f - (float)(sampleRateValue) * (float)(baudrate) / (float)(SystemCoreClock));
+
+    // Asynchronous fractional mode (Table 24-2 in datasheet)
+    //   BAUD = fref / (sampleRateValue * fbaud)
+    // (multiply by 8, to calculate fractional piece)
+    uint32_t baudTimes8 = (SystemCoreClock * 8) / (sampleRateValue * baudrate);
+
+    sercom->USART.BAUD.FRAC.FP   = (baudTimes8 % 8);
+    sercom->USART.BAUD.FRAC.BAUD = (baudTimes8 / 8);
   }
 }
 void SERCOM::initFrame(SercomUartCharSize charSize, SercomDataOrder dataOrder, SercomParityMode parityMode, SercomNumberStopBit nbStopBits)
 {
-	//Setting the CTRLA register
-	sercom->USART.CTRLA.reg |=	SERCOM_USART_CTRLA_FORM( (parityMode == SERCOM_NO_PARITY ? 0 : 1) ) |
-								dataOrder << SERCOM_USART_CTRLA_DORD_Pos;
-
-	//Setting the CTRLB register
-	sercom->USART.CTRLB.reg |=	SERCOM_USART_CTRLB_CHSIZE(charSize) |
-								nbStopBits << SERCOM_USART_CTRLB_SBMODE_Pos |
-								(parityMode == SERCOM_NO_PARITY ? 0 : parityMode) << SERCOM_USART_CTRLB_PMODE_Pos; //If no parity use default value
+  //Setting the CTRLA register
+  sercom->USART.CTRLA.reg |=	SERCOM_USART_CTRLA_FORM( (parityMode == SERCOM_NO_PARITY ? 0 : 1) ) |
+                dataOrder << SERCOM_USART_CTRLA_DORD_Pos;
+
+  //Setting the CTRLB register
+  sercom->USART.CTRLB.reg |=	SERCOM_USART_CTRLB_CHSIZE(charSize) |
+                nbStopBits << SERCOM_USART_CTRLB_SBMODE_Pos |
+                (parityMode == SERCOM_NO_PARITY ? 0 : parityMode) << SERCOM_USART_CTRLB_PMODE_Pos; //If no parity use default value
 }
 
 void SERCOM::initPads(SercomUartTXPad txPad, SercomRXPad rxPad)
 {
-	//Setting the CTRLA register
-	sercom->USART.CTRLA.reg |=	SERCOM_USART_CTRLA_TXPO(txPad) |
-								SERCOM_USART_CTRLA_RXPO(rxPad);
+  //Setting the CTRLA register
+  sercom->USART.CTRLA.reg |=	SERCOM_USART_CTRLA_TXPO(txPad) |
+                SERCOM_USART_CTRLA_RXPO(rxPad);
 
   // Enable Transceiver and Receiver
@@ -85,66 +97,76 @@
 void SERCOM::enableUART()
 {
-	//Setting  the enable bit to 1
-	sercom->USART.CTRLA.bit.ENABLE = 0x1u;
-
-	//Wait for then enable bit from SYNCBUSY is equal to 0;
-	while(sercom->USART.SYNCBUSY.bit.ENABLE);
+  //Setting  the enable bit to 1
+  sercom->USART.CTRLA.bit.ENABLE = 0x1u;
+
+  //Wait for then enable bit from SYNCBUSY is equal to 0;
+  while(sercom->USART.SYNCBUSY.bit.ENABLE);
 }
 
 void SERCOM::flushUART()
 {
-	// Wait for transmission to complete
-	while(sercom->USART.INTFLAG.bit.DRE != SERCOM_USART_INTFLAG_DRE);
+  // Wait for transmission to complete
+  while(!sercom->USART.INTFLAG.bit.TXC);
 }
 
 void SERCOM::clearStatusUART()
 {
-	//Reset (with 0) the STATUS register
-	sercom->USART.STATUS.reg = SERCOM_USART_STATUS_RESETVALUE;
+  //Reset (with 0) the STATUS register
+  sercom->USART.STATUS.reg = SERCOM_USART_STATUS_RESETVALUE;
 }
 
 bool SERCOM::availableDataUART()
 {
-	//RXC : Receive Complete
-	return sercom->USART.INTFLAG.bit.RXC;
+  //RXC : Receive Complete
+  return sercom->USART.INTFLAG.bit.RXC;
+}
+
+bool SERCOM::isUARTError()
+{
+  return sercom->USART.INTFLAG.bit.ERROR;
+}
+
+void SERCOM::acknowledgeUARTError()
+{
+  sercom->USART.INTFLAG.bit.ERROR = 1;
 }
 
 bool SERCOM::isBufferOverflowErrorUART()
 {
-	//BUFOVF : Buffer Overflow
-	return sercom->USART.STATUS.bit.BUFOVF;
+  //BUFOVF : Buffer Overflow
+  return sercom->USART.STATUS.bit.BUFOVF;
 }
 
 bool SERCOM::isFrameErrorUART()
 {
-	//FERR : Frame Error
-	return sercom->USART.STATUS.bit.FERR;
+  //FERR : Frame Error
+  return sercom->USART.STATUS.bit.FERR;
 }
 
 bool SERCOM::isParityErrorUART()
 {
-	//PERR : Parity Error
-	return sercom->USART.STATUS.bit.PERR;
+  //PERR : Parity Error
+  return sercom->USART.STATUS.bit.PERR;
 }
 
 bool SERCOM::isDataRegisterEmptyUART()
 {
-	//DRE : Data Register Empty
-	return sercom->USART.INTFLAG.bit.DRE;
+  //DRE : Data Register Empty
+  return sercom->USART.INTFLAG.bit.DRE;
 }
 
 uint8_t SERCOM::readDataUART()
 {
-	return sercom->USART.DATA.bit.DATA;
+  return sercom->USART.DATA.bit.DATA;
 }
 
 int SERCOM::writeDataUART(uint8_t data)
 {
-	//Flush UART buffer
-	flushUART();
-
-	//Put data into DATA register
-	sercom->USART.DATA.reg = (uint16_t)data;
-	return 1;
+  // Wait for data register to be empty
+  while(!isDataRegisterEmptyUART());
+
+  //Put data into DATA register
+  sercom->USART.DATA.reg = (uint16_t)data;
+  return 1;
 }
 
@@ -155,58 +177,73 @@
 void SERCOM::initSPI(SercomSpiTXPad mosi, SercomRXPad miso, SercomSpiCharSize charSize, SercomDataOrder dataOrder)
 {
+  resetSPI();
+  initClockNVIC();
+
+  //Setting the CTRLA register
+  sercom->SPI.CTRLA.reg =	SERCOM_SPI_CTRLA_MODE_SPI_MASTER |
+                          SERCOM_SPI_CTRLA_DOPO(mosi) |
+                          SERCOM_SPI_CTRLA_DIPO(miso) |
+                          dataOrder << SERCOM_SPI_CTRLA_DORD_Pos;
+
+  //Setting the CTRLB register
+  sercom->SPI.CTRLB.reg = SERCOM_SPI_CTRLB_CHSIZE(charSize) |
+                          SERCOM_SPI_CTRLB_RXEN;	//Active the SPI receiver.
+
+
+}
+
+void SERCOM::initSPIslave(SercomSpiTXPad mosi, SercomRXPad miso, SercomSpiCharSize charSize, SercomDataOrder dataOrder)
+{
 	resetSPI();
 	initClockNVIC();
 
-	//Setting the CTRLA register
-	sercom->SPI.CTRLA.reg =	SERCOM_SPI_CTRLA_MODE_SPI_MASTER |
-							            SERCOM_SPI_CTRLA_DOPO(mosi) |
-							            SERCOM_SPI_CTRLA_DIPO(miso) |
-							            dataOrder << SERCOM_SPI_CTRLA_DORD_Pos;
-
-	//Setting the CTRLB register
+	sercom->SPI.CTRLA.reg = SERCOM_SPI_CTRLA_MODE_SPI_SLAVE |
+							            SERCOM_SPI_CTRLA_DOPO(mosi) |  //provo a modificare
+							            SERCOM_SPI_CTRLA_DIPO(miso) |  //provo a modificare
+							            dataOrder << SERCOM_SPI_CTRLA_DORD_Pos;					            
+
 	sercom->SPI.CTRLB.reg = SERCOM_SPI_CTRLB_CHSIZE(charSize) |
-							            SERCOM_SPI_CTRLB_RXEN;	//Active the SPI receiver.
-
-
+							            SERCOM_SPI_CTRLB_RXEN; 	//Active the SPI receiver.
+										
 }
 
 void SERCOM::initSPIClock(SercomSpiClockMode clockMode, uint32_t baudrate)
 {
-	//Extract data from clockMode
-	int cpha, cpol;
-
-	if((clockMode & (0x1ul)) == 0 )
-		cpha = 0;
-	else
-		cpha = 1;
-
-	if((clockMode & (0x2ul)) == 0)
-		cpol = 0;
-	else
-		cpol = 1;
-
-	//Setting the CTRLA register
-	sercom->SPI.CTRLA.reg |=	( cpha << SERCOM_SPI_CTRLA_CPHA_Pos ) |
-								            ( cpol << SERCOM_SPI_CTRLA_CPOL_Pos );
-
-	//Synchronous arithmetic
-	sercom->SPI.BAUD.reg = calculateBaudrateSynchronous(baudrate);
+  //Extract data from clockMode
+  int cpha, cpol;
+
+  if((clockMode & (0x1ul)) == 0 )
+    cpha = 0;
+  else
+    cpha = 1;
+
+  if((clockMode & (0x2ul)) == 0)
+    cpol = 0;
+  else
+    cpol = 1;
+
+  //Setting the CTRLA register
+  sercom->SPI.CTRLA.reg |=	( cpha << SERCOM_SPI_CTRLA_CPHA_Pos ) |
+                            ( cpol << SERCOM_SPI_CTRLA_CPOL_Pos );
+
+  //Synchronous arithmetic
+  sercom->SPI.BAUD.reg = calculateBaudrateSynchronous(baudrate);
 }
 
 void SERCOM::resetSPI()
 {
-	//Setting the Software Reset bit to 1
-	sercom->SPI.CTRLA.bit.SWRST = 1;
-
-	//Wait both bits Software Reset from CTRLA and SYNCBUSY are equal to 0
-	while(sercom->SPI.CTRLA.bit.SWRST || sercom->SPI.SYNCBUSY.bit.SWRST);
+  //Setting the Software Reset bit to 1
+  sercom->SPI.CTRLA.bit.SWRST = 1;
+
+  //Wait both bits Software Reset from CTRLA and SYNCBUSY are equal to 0
+  while(sercom->SPI.CTRLA.bit.SWRST || sercom->SPI.SYNCBUSY.bit.SWRST);
 }
 
 void SERCOM::enableSPI()
 {
-	//Setting the enable bit to 1
-	sercom->SPI.CTRLA.bit.ENABLE = 1;
-
-	while(sercom->SPI.SYNCBUSY.bit.ENABLE)
+  //Setting the enable bit to 1
+  sercom->SPI.CTRLA.bit.ENABLE = 1;
+
+  while(sercom->SPI.SYNCBUSY.bit.ENABLE)
   {
     //Waiting then enable bit from SYNCBUSY is equal to 0;
@@ -216,8 +253,8 @@
 void SERCOM::disableSPI()
 {
-	//Setting the enable bit to 0
-	sercom->SPI.CTRLA.bit.ENABLE = 0;
-
-	while(sercom->SPI.SYNCBUSY.bit.ENABLE)
+  //Setting the enable bit to 0
+  sercom->SPI.CTRLA.bit.ENABLE = 0;
+
+  while(sercom->SPI.SYNCBUSY.bit.ENABLE)
   {
     //Waiting then enable bit from SYNCBUSY is equal to 0;
@@ -227,47 +264,53 @@
 void SERCOM::setDataOrderSPI(SercomDataOrder dataOrder)
 {
-	//Register enable-protected
-	disableSPI();
-
-	sercom->SPI.CTRLA.bit.DORD = dataOrder;
-
-	enableSPI();
-}
-
-void SERCOM::setBaudrateSPI(uint8_t divider)
-{
-	//Can't divide by 0
-	if(divider == 0)
-		return;
-
-	//Register enable-protected
-	disableSPI();
-
-	sercom->SPI.BAUD.reg = calculateBaudrateSynchronous( SERCOM_FREQ_REF / divider );
-
-	enableSPI();
+  //Register enable-protected
+  disableSPI();
+
+  sercom->SPI.CTRLA.bit.DORD = dataOrder;
+
+  enableSPI();
+}
+
+SercomDataOrder SERCOM::getDataOrderSPI()
+{
+  return (sercom->SPI.CTRLA.bit.DORD ? LSB_FIRST : MSB_FIRST);
+}
+
+void SERCOM::setBaudrateSPI(uint16_t divider)
+{
+  //Can't divide by 0
+  if(divider == 0)
+    return;
+
+  //Register enable-protected
+  disableSPI();
+
+  sercom->SPI.BAUD.reg = calculateBaudrateSynchronous( SERCOM_FREQ_REF / divider );
+
+  enableSPI();
 }
 
 void SERCOM::setClockModeSPI(SercomSpiClockMode clockMode)
 {
-	int cpha, cpol;
-	if((clockMode & (0x1ul)) == 0)
-		cpha = 0;
-	else
-		cpha = 1;
-
-	if((clockMode & (0x2ul)) == 0)
-		cpol = 0;
-	else
-		cpol = 1;
-
-	//Register enable-protected
-	disableSPI();
-
-	sercom->SPI.CTRLA.bit.CPOL = cpol;
-	sercom->SPI.CTRLA.bit.CPHA = cpha;
-
-	enableSPI();
-}
+  int cpha, cpol;
+  if((clockMode & (0x1ul)) == 0)
+    cpha = 0;
+  else
+    cpha = 1;
+
+  if((clockMode & (0x2ul)) == 0)
+    cpol = 0;
+  else
+    cpol = 1;
+
+  //Register enable-protected
+  disableSPI();
+
+  sercom->SPI.CTRLA.bit.CPOL = cpol;
+  sercom->SPI.CTRLA.bit.CPHA = cpha;
+
+  enableSPI();
+}
+
 void SERCOM::writeDataSPI(uint8_t data)
 {
@@ -276,6 +319,5 @@
     // Waiting Data Registry Empty
   }
-
-	sercom->SPI.DATA.bit.DATA = data; // Writing data into Data register
+  sercom->SPI.DATA.bit.DATA = data; // Writing data into Data register
 
   while( sercom->SPI.INTFLAG.bit.TXC == 0 || sercom->SPI.INTFLAG.bit.DRE == 0 )
@@ -292,21 +334,33 @@
   }
 
-	return sercom->SPI.DATA.bit.DATA;  // Reading data
+  return sercom->SPI.DATA.bit.DATA;  // Reading data
 }
 
 bool SERCOM::isBufferOverflowErrorSPI()
 {
-	return sercom->SPI.STATUS.bit.BUFOVF;
+  return sercom->SPI.STATUS.bit.BUFOVF;
 }
 
 bool SERCOM::isDataRegisterEmptySPI()
 {
-	//DRE : Data Register Empty
-	return sercom->SPI.INTFLAG.bit.DRE;
-}
+  //DRE : Data Register Empty
+  return sercom->SPI.INTFLAG.bit.DRE;
+}
+
+//bool SERCOM::isTransmitCompleteSPI()
+//{
+//	//TXC : Transmit complete
+//	return sercom->SPI.INTFLAG.bit.TXC;
+//}
+//
+//bool SERCOM::isReceiveCompleteSPI()
+//{
+//	//RXC : Receive complete
+//	return sercom->SPI.INTFLAG.bit.RXC;
+//}
 
 uint8_t SERCOM::calculateBaudrateSynchronous(uint32_t baudrate)
 {
-	return SERCOM_FREQ_REF / (2 * baudrate) - 1;
+  return SERCOM_FREQ_REF / (2 * baudrate) - 1;
 }
 
@@ -315,15 +369,14 @@
  *	===== Sercom WIRE
  *	=========================
-*/
-
+ */
 void SERCOM::resetWIRE()
 {
-	//I2CM OR I2CS, no matter SWRST is the same bit.
-
-	//Setting the Software bit to 1
-	sercom->I2CM.CTRLA.bit.SWRST = 1;
-
-	//Wait both bits Software Reset from CTRLA and SYNCBUSY are equal to 0
-	while(sercom->I2CM.CTRLA.bit.SWRST || sercom->I2CM.SYNCBUSY.bit.SWRST);
+  //I2CM OR I2CS, no matter SWRST is the same bit.
+
+  //Setting the Software bit to 1
+  sercom->I2CM.CTRLA.bit.SWRST = 1;
+
+  //Wait both bits Software Reset from CTRLA and SYNCBUSY are equal to 0
+  while(sercom->I2CM.CTRLA.bit.SWRST || sercom->I2CM.SYNCBUSY.bit.SWRST);
 }
 
@@ -371,13 +424,11 @@
   sercom->I2CS.CTRLA.bit.MODE = I2C_SLAVE_OPERATION ;
 
-  // Enable Quick Command
-  sercom->I2CM.CTRLB.bit.QCEN = 1 ;
-
   sercom->I2CS.ADDR.reg = SERCOM_I2CS_ADDR_ADDR( ucAddress & 0x7Ful ) | // 0x7F, select only 7 bits
-                          SERCOM_I2CS_ADDR_ADDRMASK( 0x3FFul ) ;        // 0x3FF all bits set
+                          SERCOM_I2CS_ADDR_ADDRMASK( 0x3FFul ) ;    // 0x3FF all bits set
 
   // Set the interrupt register
-  sercom->I2CS.INTENSET.reg = SERCOM_I2CS_INTENSET_AMATCH |             // Address Match
-                              SERCOM_I2CS_INTENSET_DRDY ;               // Data Ready
+  sercom->I2CS.INTENSET.reg = SERCOM_I2CS_INTENSET_PREC |   // Stop
+                              SERCOM_I2CS_INTENSET_AMATCH | // Address Match
+                              SERCOM_I2CS_INTENSET_DRDY ;   // Data Ready
 
   while ( sercom->I2CM.SYNCBUSY.bit.SYSOP != 0 )
@@ -395,9 +446,13 @@
 
   // Set master mode and enable SCL Clock Stretch mode (stretch after ACK bit)
-  sercom->I2CM.CTRLA.reg =  SERCOM_I2CM_CTRLA_MODE( I2C_MASTER_OPERATION );
+  sercom->I2CM.CTRLA.reg =  SERCOM_I2CM_CTRLA_MODE( I2C_MASTER_OPERATION )/* |
+                            SERCOM_I2CM_CTRLA_SCLSM*/ ;
 
   // Enable Smart mode and Quick Command
+  //sercom->I2CM.CTRLB.reg =  SERCOM_I2CM_CTRLB_SMEN /*| SERCOM_I2CM_CTRLB_QCEN*/ ;
+
 
   // Enable all interrupts
+//  sercom->I2CM.INTENSET.reg = SERCOM_I2CM_INTENSET_MB | SERCOM_I2CM_INTENSET_SB | SERCOM_I2CM_INTENSET_ERROR ;
 
   // Synchronous arithmetic baudrate
@@ -407,21 +462,33 @@
 void SERCOM::prepareNackBitWIRE( void )
 {
-  // Send a NACK
-  sercom->I2CM.CTRLB.bit.ACKACT = 1;
+  if(isMasterWIRE()) {
+    // Send a NACK
+    sercom->I2CM.CTRLB.bit.ACKACT = 1;
+  } else {
+    sercom->I2CS.CTRLB.bit.ACKACT = 1;
+  }
 }
 
 void SERCOM::prepareAckBitWIRE( void )
 {
-  // Send an ACK
-  sercom->I2CM.CTRLB.bit.ACKACT = 0;
-}
-
-void SERCOM::prepareCommandBitsWire(SercomMasterCommandWire cmd)
-{
-  sercom->I2CM.CTRLB.bit.CMD = cmd;
-
-  while(sercom->I2CM.SYNCBUSY.bit.SYSOP)
-  {
-    // Waiting for synchronization
+  if(isMasterWIRE()) {
+    // Send an ACK
+    sercom->I2CM.CTRLB.bit.ACKACT = 0;
+  } else {
+    sercom->I2CS.CTRLB.bit.ACKACT = 0;
+  }
+}
+
+void SERCOM::prepareCommandBitsWire(uint8_t cmd)
+{
+  if(isMasterWIRE()) {
+    sercom->I2CM.CTRLB.bit.CMD = cmd;
+
+    while(sercom->I2CM.SYNCBUSY.bit.SYSOP)
+    {
+      // Waiting for synchronization
+    }
+  } else {
+    sercom->I2CS.CTRLB.bit.CMD = cmd;
   }
 }
@@ -432,9 +499,11 @@
   address = (address << 0x1ul) | flag;
 
-  // Wait idle bus mode
-  while ( !isBusIdleWIRE() );
+
+  // Wait idle or owner bus mode
+  while ( !isBusIdleWIRE() && !isBusOwnerWIRE() );
 
   // Send start and address
   sercom->I2CM.ADDR.bit.ADDR = address;
+  
 
   // Address Transmitted
@@ -450,4 +519,10 @@
     while( !sercom->I2CM.INTFLAG.bit.SB )
     {
+        // If the slave NACKS the address, the MB bit will be set.
+        // In that case, send a stop condition and return false.
+        if (sercom->I2CM.INTFLAG.bit.MB) {
+            sercom->I2CM.CTRLB.bit.CMD = 3; // Stop condition
+            return false;
+        }
       // Wait transmission complete
     }
@@ -471,65 +546,77 @@
 bool SERCOM::sendDataMasterWIRE(uint8_t data)
 {
-	//Send data
-	sercom->I2CM.DATA.bit.DATA = data;
-
-	//Wait transmission successful
-	while(!sercom->I2CM.INTFLAG.bit.MB);
-
-	//Problems on line? nack received?
-	if(sercom->I2CM.STATUS.bit.RXNACK)
-		return false;
-	else
-		return true;
+  //Send data
+  sercom->I2CM.DATA.bit.DATA = data;
+
+  //Wait transmission successful
+  while(!sercom->I2CM.INTFLAG.bit.MB) {
+
+    // If a bus error occurs, the MB bit may never be set.
+    // Check the bus error bit and bail if it's set.
+    if (sercom->I2CM.STATUS.bit.BUSERR) {
+      return false;
+    }
+  }
+
+  //Problems on line? nack received?
+  if(sercom->I2CM.STATUS.bit.RXNACK)
+    return false;
+  else
+    return true;
 }
 
 bool SERCOM::sendDataSlaveWIRE(uint8_t data)
 {
-	//Send data
-	sercom->I2CS.DATA.bit.DATA = data;
-
-	//Wait data transmission successful
-	while(!sercom->I2CS.INTFLAG.bit.DRDY);
-
-	//Problems on line? nack received?
-	if(sercom->I2CS.STATUS.bit.RXNACK)
-		return false;
-	else
-		return true;
+  //Send data
+  sercom->I2CS.DATA.bit.DATA = data;
+
+  //Wait data transmission successful
+  while(!sercom->I2CS.INTFLAG.bit.DRDY);
+
+  //Problems on line? nack received?
+  if(sercom->I2CS.STATUS.bit.RXNACK)
+    return false;
+  else
+    return true;
 }
 
 bool SERCOM::isMasterWIRE( void )
 {
-	return sercom->I2CS.CTRLA.bit.MODE == I2C_MASTER_OPERATION;
+  return sercom->I2CS.CTRLA.bit.MODE == I2C_MASTER_OPERATION;
 }
 
 bool SERCOM::isSlaveWIRE( void )
 {
-	return sercom->I2CS.CTRLA.bit.MODE == I2C_SLAVE_OPERATION;
+  return sercom->I2CS.CTRLA.bit.MODE == I2C_SLAVE_OPERATION;
 }
 
 bool SERCOM::isBusIdleWIRE( void )
 {
-	return sercom->I2CM.STATUS.bit.BUSSTATE == WIRE_IDLE_STATE;
+  return sercom->I2CM.STATUS.bit.BUSSTATE == WIRE_IDLE_STATE;
+}
+
+bool SERCOM::isBusOwnerWIRE( void )
+{
+  return sercom->I2CM.STATUS.bit.BUSSTATE == WIRE_OWNER_STATE;
 }
 
 bool SERCOM::isDataReadyWIRE( void )
 {
-	return sercom->I2CS.INTFLAG.bit.DRDY;
+  return sercom->I2CS.INTFLAG.bit.DRDY;
 }
 
 bool SERCOM::isStopDetectedWIRE( void )
 {
-	return sercom->I2CS.INTFLAG.bit.PREC;
+  return sercom->I2CS.INTFLAG.bit.PREC;
 }
 
 bool SERCOM::isRestartDetectedWIRE( void )
 {
-	return sercom->I2CS.STATUS.bit.SR;
+  return sercom->I2CS.STATUS.bit.SR;
 }
 
 bool SERCOM::isAddressMatch( void )
 {
-	return sercom->I2CS.INTFLAG.bit.AMATCH;
+  return sercom->I2CS.INTFLAG.bit.AMATCH;
 }
 
@@ -546,8 +633,8 @@
 int SERCOM::availableWIRE( void )
 {
-	if(isMasterWIRE())
-		return sercom->I2CM.INTFLAG.bit.SB;
-	else
-		return sercom->I2CS.INTFLAG.bit.DRDY;
+  if(isMasterWIRE())
+    return sercom->I2CM.INTFLAG.bit.SB;
+  else
+    return sercom->I2CS.INTFLAG.bit.DRDY;
 }
 
@@ -572,51 +659,56 @@
 void SERCOM::initClockNVIC( void )
 {
-	uint8_t clockId = 0;
-	IRQn_Type IdNvic;
-
-	if(sercom == SERCOM0)
-	{
-		clockId = GCM_SERCOM0_CORE;
-		IdNvic = SERCOM0_IRQn;
-	}
-	else if(sercom == SERCOM1)
-	{
-		clockId = GCM_SERCOM1_CORE;
-		IdNvic = SERCOM1_IRQn;
-	}
-	else if(sercom == SERCOM2)
-	{
-		clockId = GCM_SERCOM2_CORE;
-		IdNvic = SERCOM2_IRQn;
-	}
-	else if(sercom == SERCOM3)
-	{
-		clockId = GCM_SERCOM3_CORE;
-		IdNvic = SERCOM3_IRQn;
-	}
-	else if(sercom == SERCOM4)
-	{
-		clockId = GCM_SERCOM4_CORE;
-		IdNvic = SERCOM4_IRQn;
-	}
-	else if(sercom == SERCOM5)
-	{
-		clockId = GCM_SERCOM5_CORE;
-		IdNvic = SERCOM5_IRQn;
-	}
-
-	// Setting NVIC
-	NVIC_EnableIRQ(IdNvic);
-	NVIC_SetPriority (IdNvic, (1<<__NVIC_PRIO_BITS) - 1);  /* set Priority */
-
-	//Setting clock
-	GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID( clockId ) |       // Generic Clock 0 (SERCOMx)
-						          GCLK_CLKCTRL_GEN_GCLK0 | // Generic Clock Generator 0 is source
-						          GCLK_CLKCTRL_CLKEN ;
-
-	while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
-	{
-		/* Wait for synchronization */
-	}
-
-}
+  uint8_t clockId = 0;
+  IRQn_Type IdNvic=PendSV_IRQn ; // Dummy init to intercept potential error later
+
+  if(sercom == SERCOM0)
+  {
+    clockId = GCM_SERCOM0_CORE;
+    IdNvic = SERCOM0_IRQn;
+  }
+  else if(sercom == SERCOM1)
+  {
+    clockId = GCM_SERCOM1_CORE;
+    IdNvic = SERCOM1_IRQn;
+  }
+  else if(sercom == SERCOM2)
+  {
+    clockId = GCM_SERCOM2_CORE;
+    IdNvic = SERCOM2_IRQn;
+  }
+  else if(sercom == SERCOM3)
+  {
+    clockId = GCM_SERCOM3_CORE;
+    IdNvic = SERCOM3_IRQn;
+  }
+  else if(sercom == SERCOM4)
+  {
+    clockId = GCM_SERCOM4_CORE;
+    IdNvic = SERCOM4_IRQn;
+  }
+  else if(sercom == SERCOM5)
+  {
+    clockId = GCM_SERCOM5_CORE;
+    IdNvic = SERCOM5_IRQn;
+  }
+
+  if ( IdNvic == PendSV_IRQn )
+  {
+    // We got a problem here
+    return ;
+  }
+
+  // Setting NVIC
+  NVIC_EnableIRQ(IdNvic);
+  NVIC_SetPriority (IdNvic, (1<<__NVIC_PRIO_BITS) - 1);  /* set Priority */
+
+  //Setting clock
+  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID( clockId ) | // Generic Clock 0 (SERCOMx)
+                      GCLK_CLKCTRL_GEN_GCLK0 | // Generic Clock Generator 0 is source
+                      GCLK_CLKCTRL_CLKEN ;
+
+  while ( GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY )
+  {
+    /* Wait for synchronization */
+  }
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/SERCOM.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/SERCOM.h	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/SERCOM.h	(revision 175)
@@ -1,2 +1,20 @@
+/*
+  Copyright (c) 2014 Arduino.  All right reserved.
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the GNU Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
 #ifndef _SERCOM_CLASS_
 #define _SERCOM_CLASS_
@@ -62,13 +80,13 @@
 typedef enum
 {
-	UART_TX_PAD_0 = 0x0ul,	//Only for UART
-	UART_TX_PAD_2 = 0x1ul,  //Only for UART
+	UART_TX_PAD_0 = 0x0ul,	// Only for UART
+	UART_TX_PAD_2 = 0x1ul,  // Only for UART
+	UART_TX_RTS_CTS_PAD_0_2_3 = 0x2ul,  // Only for UART with TX on PAD0, RTS on PAD2 and CTS on PAD3
 } SercomUartTXPad;
 
 typedef enum
 {
-	SAMPLE_RATE_x16 = 0,	//Arithmetic
-	SAMPLE_RATE_x8 = 0x2,	//Arithmetic
-	SAMPLE_RATE_x3 = 0x3	//Arithmetic
+	SAMPLE_RATE_x16 = 0x1,	//Fractional
+	SAMPLE_RATE_x8 = 0x3,	//Fractional
 } SercomUartSampleRate;
 
@@ -144,7 +162,10 @@
 		uint8_t readDataUART( void ) ;
 		int writeDataUART(uint8_t data) ;
+		bool isUARTError() ;
+		void acknowledgeUARTError() ;
 
 		/* ========== SPI ========== */
 		void initSPI(SercomSpiTXPad mosi, SercomRXPad miso, SercomSpiCharSize charSize, SercomDataOrder dataOrder) ;
+                void initSPIslave(SercomSpiTXPad mosi, SercomRXPad miso, SercomSpiCharSize charSize, SercomDataOrder dataOrder);
 		void initSPIClock(SercomSpiClockMode clockMode, uint32_t baudrate) ;
 
@@ -153,5 +174,6 @@
 		void disableSPI( void ) ;
 		void setDataOrderSPI(SercomDataOrder dataOrder) ;
-		void setBaudrateSPI(uint8_t divider) ;
+		SercomDataOrder getDataOrderSPI( void ) ;
+		void setBaudrateSPI(uint16_t divider) ;
 		void setClockModeSPI(SercomSpiClockMode clockMode) ;
 		void writeDataSPI(uint8_t data) ;
@@ -168,8 +190,8 @@
 		void resetWIRE( void ) ;
 		void enableWIRE( void ) ;
-        void disableWIRE( void );
-        void prepareNackBitWIRE( void ) ;
-        void prepareAckBitWIRE( void ) ;
-        void prepareCommandBitsWire(SercomMasterCommandWire cmd);
+    void disableWIRE( void );
+    void prepareNackBitWIRE( void ) ;
+    void prepareAckBitWIRE( void ) ;
+    void prepareCommandBitsWire(uint8_t cmd);
 		bool startTransmissionWIRE(uint8_t address, SercomWireReadWriteFlag flag) ;
 		bool sendDataMasterWIRE(uint8_t data) ;
@@ -178,4 +200,5 @@
 		bool isSlaveWIRE( void ) ;
 		bool isBusIdleWIRE( void ) ;
+		bool isBusOwnerWIRE( void ) ;
 		bool isDataReadyWIRE( void ) ;
 		bool isStopDetectedWIRE( void ) ;
@@ -183,5 +206,5 @@
 		bool isAddressMatch( void ) ;
 		bool isMasterReadOperationWIRE( void ) ;
-        bool isRXNackReceivedWIRE( void ) ;
+    bool isRXNackReceivedWIRE( void ) ;
 		int availableWIRE( void ) ;
 		uint8_t readDataWIRE( void ) ;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring.c
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring.c	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring.c	(revision 175)
@@ -80,5 +80,5 @@
                    ADC_CTRLB_RESSEL_10BIT;          // Result on 10 bits
     ADC->INPUTCTRL.reg = ADC_INPUTCTRL_MUXNEG_GND | // No Negative input (Internal Ground)
-                         ADC_INPUTCTRL_GAIN_1X;     // Gain setted to 1
+                         ADC_INPUTCTRL_GAIN_DIV2;     // Gain setted to 1/2
   // Averaging (see table 31-2 p.816 datasheet)
   ADC->AVGCTRL.reg = ADC_AVGCTRL_SAMPLENUM_2 |      // 2 samples
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring_analog.c
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring_analog.c	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/cores/arduino/wiring_analog.c	(revision 175)
@@ -64,7 +64,4 @@
 void analogReference( eAnalogReference ulMode )
 {
-
-  // ATTENTION : On this board the default is not 5volts or 3.3volts BUT 1.65 volt
-
    
    
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/README.adoc
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/README.adoc	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/README.adoc	(revision 175)
@@ -0,0 +1,24 @@
+= GSM Library for Arduino =
+
+With the Arduino GSM Shield, this library enables an Arduino board to do most of the operations you can do with a GSM phone: place and receive voice calls, send and receive SMS, and connect to the internet over a GPRS network. 
+
+For more information about this library please visit us at
+http://arduino.cc/en/Reference/GSM
+
+== License ==
+
+Copyright (c) Arduino LLC. All right reserved.
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GPRS_Position/GPRS_Position.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GPRS_Position/GPRS_Position.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GPRS_Position/GPRS_Position.ino	(revision 175)
@@ -0,0 +1,69 @@
+/*
+ GPRS_Position
+
+ A simple Sketch that shows the Longitude  and Latitude
+ using a GSM shield.
+
+ Circuit: 
+ GSM shield attached
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ Notes: 
+ You have to change the apn, login and password.
+ If your SIM has PIN you have to set 
+ 
+ created 3 Apr. 2015
+ by Arduino.org team (http://arduino.org)
+ */
+
+// Library include
+#include <GSM.h>
+// SIM and Network constant
+#define PINNUMBER  ""         // if present, insert Your PIN here
+#define apn "internet.wind"   // change the apn
+//#define apn "ibox.tim.it"
+//#define apn "unico.tim.it"
+//#define apn "wap.tim"
+#define login ""              // insert your login
+#define password ""           // isnert your password
+
+// initialize the library instance
+GSM gsmAccess;            // GSM access: include a 'true' parameter for debug enabled
+GPRS gprsAccess;          // GPRS access
+GSMClient client;         // Client service for TCP connection
+GSM2 gprsPosition;        // GPRS Posistioning system
+
+
+
+void setup() {
+  // put your setup code here, to run once:
+  SerialUSB.begin(9600);
+  
+  // start GSM shield
+ 
+  SerialUSB.println(" ");
+  SerialUSB.print("Connecting GSM network...");
+  if (gsmAccess.begin(PINNUMBER) != GSM_READY)
+  {
+    SerialUSB.println("Error !");
+    while (true);
+  }
+  SerialUSB.println("Ok !");
+  SerialUSB.println("Setting APN...");
+  gprsAccess.attachGPRS(apn, login, password);
+  SerialUSB.print("APN :");
+  SerialUSB.println(apn);
+  SerialUSB.print("Login :");
+  SerialUSB.println(login);
+  SerialUSB.print("Password :");
+  SerialUSB.println(password);
+}
+
+void loop() {
+  // put your main code here, to run repeatedly:
+  
+  SerialUSB.print("Position: ");
+  SerialUSB.println(gprsPosition.getPosition());
+
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GsmWebClient/GsmWebClient.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GsmWebClient/GsmWebClient.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GsmWebClient/GsmWebClient.ino	(revision 175)
@@ -0,0 +1,111 @@
+/*
+  Web client
+
+ This sketch connects to a website through a GSM shield. Specifically,
+ this example downloads the URL "http://arduino.cc/asciilogo.txt" and
+ prints it to the Serial monitor.
+
+ Circuit:
+ * GSM shield attached to an Arduino
+ * SIM card with a data plan
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ created 8 Mar 2012
+ by Tom Igoe
+
+ http://arduino.cc/en/Tutorial/GSMExamplesWebClient
+
+ */
+
+// libraries
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// APN data
+#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
+#define GPRS_LOGIN     "login"    // replace with your GPRS login
+#define GPRS_PASSWORD  "password" // replace with your GPRS password
+
+// initialize the library instance
+GSMClient client;
+GPRS gprs;
+GSM gsmAccess;
+
+// URL, path & port (for example: arduino.cc)
+char server[] = "arduino.cc";
+char path[] = "/asciilogo.txt";
+int port = 80; // port 80 is the default for HTTP
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("Starting Arduino web client.");
+  // connection state
+  boolean notConnected = true;
+
+  // After starting the modem with GSM.begin()
+  // attach the shield to the GPRS network with the APN, login and password
+  while (notConnected)
+  {
+    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
+        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY))
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  SerialUSB.println("connecting...");
+
+  // if you get a connection, report back via serial:
+  if (client.connect(server, port))
+  {
+    SerialUSB.println("connected");
+    // Make a HTTP request:
+    client.print("GET ");
+    client.print(path);
+    client.println(" HTTP/1.1");
+    client.print("Host: ");
+    client.println(server);
+    client.println("Connection: close");
+    client.println();
+  }
+  else
+  {
+    // if you didn't get a connection to the server:
+    SerialUSB.println("connection failed");
+  }
+}
+
+void loop()
+{
+  // if there are incoming bytes available
+  // from the server, read them and print them:
+  if (client.available())
+  {
+    char c = client.read();
+    SerialUSB.print(c);
+  }
+
+  // if the server's disconnected, stop the client:
+  if (!client.available() && !client.connected())
+  {
+    SerialUSB.println();
+    SerialUSB.println("disconnecting.");
+    client.stop();
+
+    // do nothing forevermore:
+    for (;;)
+      ;
+  }
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GsmWebServer/GsmWebServer.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GsmWebServer/GsmWebServer.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/GsmWebServer/GsmWebServer.ino	(revision 175)
@@ -0,0 +1,120 @@
+/*
+ GSM Web Server
+
+ A simple web server that shows the value of the analog input pins.
+ using a GSM shield.
+
+ Circuit:
+ * GSM shield attached
+ * Analog inputs attached to pins A0 through A5 (optional)
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ created 8 Mar 2012
+ by Tom Igoe
+ */
+
+// libraries
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// APN data
+#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
+#define GPRS_LOGIN     "login"    // replace with your GPRS login
+#define GPRS_PASSWORD  "password" // replace with your GPRS password
+
+
+// initialize the library instance
+GPRS gprs;
+GSM gsmAccess;     // include a 'true' parameter for debug enabled
+GSMServer server(80); // port 80 (http default)
+
+// timeout
+const unsigned long __TIMEOUT__ = 10 * 1000;
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  // connection state
+  boolean notConnected = true;
+
+  // Start GSM shield
+  // If your SIM has PIN, pass it as a parameter of begin() in quotes
+  while (notConnected)
+  {
+    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
+        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY))
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  SerialUSB.println("Connected to GPRS network");
+
+  // start server
+  server.begin();
+
+  //Get IP.
+  IPAddress LocalIP = gprs.getIPAddress();
+  SerialUSB.println("Server IP address=");
+  SerialUSB.println(LocalIP);
+}
+
+void loop() {
+
+
+  // listen for incoming clients
+  GSMClient client = server.available();
+
+
+
+  if (client)
+  {
+    while (client.connected())
+    {
+      if (client.available())
+      {
+        SerialUSB.println("Receiving request!");
+        bool sendResponse = false;
+        while (char c = client.read()) {
+          if (c == '\n') sendResponse = true;
+        }
+
+        // if you've gotten to the end of the line (received a newline
+        // character)
+        if (sendResponse)
+        {
+          // send a standard http response header
+          client.println("HTTP/1.1 200 OK");
+          client.println("Content-Type: text/html");
+          client.println();
+          client.println("<html>");
+          // output the value of each analog input pin
+          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
+            client.print("analog input ");
+            client.print(analogChannel);
+            client.print(" is ");
+            client.print(analogRead(analogChannel));
+            client.println("<br />");
+          }
+          client.println("</html>");
+          //necessary delay
+          delay(1000);
+          client.stop();
+        }
+      }
+    }
+  }
+}
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/MakeVoiceCall/MakeVoiceCall.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/MakeVoiceCall/MakeVoiceCall.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/MakeVoiceCall/MakeVoiceCall.ino	(revision 175)
@@ -0,0 +1,118 @@
+/*
+ Make Voice Call
+
+ This sketch, for the Arduino GSM shield, puts a voice call to
+ a remote phone number that you enter through the serial monitor.
+ To make it work, open the serial monitor, and when you see the
+ READY message, type a phone number. Make sure the serial monitor
+ is set to send a just newline when you press return.
+
+ Circuit:
+ * GSM shield
+ * Voice circuit.
+ With no voice circuit the call will send nor receive any sound
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+
+ created Mar 2012
+ by Javier Zorzano
+
+ This example is in the public domain.
+ */
+
+// libraries
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// initialize the library instance
+GSM gsmAccess; // include a 'true' parameter for debug enabled
+GSMVoiceCall vcs;
+
+String remoteNumber = "";  // the number you will call
+char charbuffer[20];
+
+void setup()
+{
+
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("Make Voice Call");
+
+  // connection state
+  boolean notConnected = true;
+
+  // Start GSM shield
+  // If your SIM has PIN, pass it as a parameter of begin() in quotes
+  while (notConnected)
+  {
+    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  SerialUSB.println("GSM initialized.");
+  SerialUSB.println("Enter phone number to call.");
+
+}
+
+void loop()
+{
+
+  // add any incoming characters to the String:
+  while (SerialUSB.available() > 0)
+  {
+    char inChar = SerialUSB.read();
+    // if it's a newline, that means you should make the call:
+    if (inChar == '\n')
+    {
+      // make sure the phone number is not too long:
+      if (remoteNumber.length() < 20)
+      {
+        // let the user know you're calling:
+        SerialUSB.print("Calling to : ");
+        SerialUSB.println(remoteNumber);
+        SerialUSB.println();
+
+        // Call the remote number
+        remoteNumber.toCharArray(charbuffer, 20);
+
+
+        // Check if the receiving end has picked up the call
+        if (vcs.voiceCall(charbuffer))
+        {
+          SerialUSB.println("Call Established. Enter line to end");
+          // Wait for some input from the line
+          while (SerialUSB.read() != '\n' && (vcs.getvoiceCallStatus() == TALKING));
+          // And hang up
+          vcs.hangCall();
+        }
+        SerialUSB.println("Call Finished");
+        remoteNumber = "";
+        SerialUSB.println("Enter phone number to call.");
+      }
+      else
+      {
+        SerialUSB.println("That's too long for a phone number. I'm forgetting it");
+        remoteNumber = "";
+      }
+    }
+    else
+    {
+      // add the latest character to the message to send:
+      if (inChar != '\r')
+        remoteNumber += inChar;
+    }
+  }
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveSMS/ReceiveSMS.ino	(revision 175)
@@ -0,0 +1,100 @@
+/*
+ SMS receiver
+
+ This sketch, for the Arduino GSM shield, waits for a SMS message
+ and displays it through the Serial port.
+
+ Circuit:
+ * GSM shield attached to and Arduino
+ * SIM card that can receive SMS messages
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ created 25 Feb 2012
+ by Javier Zorzano / TD
+
+ This example is in the public domain.
+
+ http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS
+
+*/
+
+// include the GSM library
+#include <GSM.h>
+
+// PIN Number for the SIM
+#define PINNUMBER ""
+
+// initialize the library instances
+GSM gsmAccess;
+GSM_SMS sms;
+
+// Array to hold the number a SMS is retreived from
+char senderNumber[20];
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("SMS Messages Receiver");
+
+  // connection state
+  boolean notConnected = true;
+
+  // Start GSM connection
+  while (notConnected)
+  {
+    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  SerialUSB.println("GSM initialized");
+  SerialUSB.println("Waiting for messages");
+}
+
+void loop()
+{
+  char c;
+
+  // If there are any SMSs available()
+  if (sms.available())
+  {
+    SerialUSB.println("Message received from:");
+
+    // Get remote number
+    sms.remoteNumber(senderNumber, 20);
+    SerialUSB.println(senderNumber);
+
+    // An example of message disposal
+    // Any messages starting with # should be discarded
+    if (sms.peek() == '#')
+    {
+      SerialUSB.println("Discarded SMS");
+      sms.flush();
+    }
+
+    // Read message bytes and print them
+    while (c = sms.read())
+      SerialUSB.print(c);
+
+    SerialUSB.println("\nEND OF MESSAGE");
+
+    // Delete message from modem memory
+    sms.flush();
+    SerialUSB.println("MESSAGE DELETED");
+  }
+
+  delay(1000);
+
+}
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveVoiceCall/ReceiveVoiceCall.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveVoiceCall/ReceiveVoiceCall.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveVoiceCall/ReceiveVoiceCall.ino	(revision 175)
@@ -0,0 +1,107 @@
+/*
+ Receive Voice Call
+
+ This sketch, for the Arduino GSM shield, receives voice calls,
+ displays the calling number, waits a few seconds then hangs up.
+
+ Circuit:
+ * GSM shield
+ * Voice circuit. Refer to to the GSM shield getting started guide
+   at http://www.arduino.org/products/shields/5-arduino-shields/arduino-gsm-shield-2
+ * SIM card that can accept voice calls
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ With no voice circuit the call will connect, but will not send or receive sound
+
+ created Mar 2012
+ by Javier Zorzano
+
+ This example is in the public domain.
+
+ http://arduino.cc/en/Tutorial/GSMExamplesReceiveVoiceCall
+
+ */
+
+// Include the GSM library
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// initialize the library instance
+GSM gsmAccess;
+GSMVoiceCall vcs;
+
+// Array to hold the number for the incoming call
+char numtel[20];
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("Receive Voice Call");
+
+  // connection state
+  boolean notConnected = true;
+
+  // Start GSM shield
+  // If your SIM has PIN, pass it as a parameter of begin() in quotes
+  while (notConnected)
+  {
+    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  // This makes sure the modem correctly reports incoming events
+  vcs.hangCall();
+
+  SerialUSB.println("Waiting for a call");
+}
+
+void loop()
+{
+  // Check the status of the voice call
+  switch (vcs.getvoiceCallStatus())
+  {
+    case IDLE_CALL: // Nothing is happening
+
+      break;
+
+    case RECEIVINGCALL: // Yes! Someone is calling us
+
+      SerialUSB.println("RECEIVING CALL");
+
+      // Retrieve the calling number
+      vcs.retrieveCallingNumber(numtel, 20);
+
+      // Print the calling number
+      SerialUSB.print("Number:");
+      SerialUSB.println(numtel);
+
+      // Answer the call, establish the call
+      vcs.answerCall();
+      break;
+
+    case TALKING:  // In this case the call would be established
+
+      SerialUSB.println("TALKING. Press enter to hang up.");
+      while (SerialUSB.read() != '\n')
+        delay(100);
+      vcs.hangCall();
+      SerialUSB.println("Hanging up and waiting for the next call.");
+      break;
+  }
+  delay(1000);
+}
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveVoiceCallGSM2/ReceiveVoiceCallGSM2.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveVoiceCallGSM2/ReceiveVoiceCallGSM2.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/ReceiveVoiceCallGSM2/ReceiveVoiceCallGSM2.ino	(revision 175)
@@ -0,0 +1,124 @@
+/*
+ Receive Voice Call
+
+ This sketch, for the Arduino GSM shield, receives voice calls,
+ displays the calling number, waits a few seconds then hangs up.
+
+ Circuit:
+ * GSM shield
+ * Voice circuit. Refer to to the GSM shield getting started guide
+   at http://arduino.cc/en/Guide/ArduinoGSMShield#toc11
+ * SIM card that can accept voice calls
+ 
+  ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ With no voice circuit the call will connect, but will not send or receive sound
+
+ created Mar 2012
+ by Javier Zorzano
+
+ This example is in the public domain.
+
+ 
+ Added Arduino GSM Shield 2 features
+ modified Feb 2016
+ by Arduino.org team (http://arduino.org) 
+ 
+ */
+
+// Include the GSM library
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// initialize the library instance
+GSM gsmAccess;
+GSM2 gsmAccessV2;
+GSMVoiceCall vcs;
+
+#define number_len 20    // define incoming call number lenght
+
+// Array to hold the number for the incoming call
+char number[number_len];
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("Receive Voice Call");
+
+  // connection state
+  boolean notConnected = true;
+
+  // Start GSM shield
+  // If your SIM has PIN, pass it as a parameter of begin() in quotes
+  while (notConnected)
+  {
+    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  // This makes sure the modem correctly reports incoming events
+  vcs.hangCall();
+  gsmAccessV2.muteControl(0);  //not allowed by the module
+  gsmAccessV2.CommandEcho(1);  // set echo
+  gsmAccessV2.speakerMode(1);  //set speaker mode
+  gsmAccessV2.speakerLoudness(3); //set speaker loudness
+  gsmAccessV2.swapAudioChannel(1); //set audio channel
+ gsmAccessV2.microphoneGainLevel(1,13); //set microphone gain level
+ gsmAccessV2.ringerSoundLevel(20);  //set ring sound level
+ gsmAccessV2.alertSoundMode(0);   //set alert sound mode (sound)
+ gsmAccessV2.loudSpeakerVolumeLevel(20); //set loudspeaker volume level
+ 
+  SerialUSB.println("Waiting for a call");
+}
+
+void loop()
+{
+  // Check the status of the voice call
+  switch (vcs.getvoiceCallStatus())
+  {
+    case IDLE_CALL: // Nothing is happening
+
+      break;
+
+    case RECEIVINGCALL: // Yes! Someone is calling us
+      
+      SerialUSB.println("RECEIVING CALL");
+      
+      
+      // Retrieve the calling number
+      vcs.retrieveCallingNumber(number, number_len);
+
+      // Print the calling number
+      SerialUSB.print("Number:");
+      SerialUSB.println(number);
+      SerialUSB.println("Press a to answer");
+      while(SerialUSB.read() !='a');
+      // Answer the call, establish the call
+      vcs.answerCall();
+      break;
+
+    case TALKING:  // In this case the call would be established
+
+      SerialUSB.println("TALKING. Press h to hang up.");
+      while (SerialUSB.read() != 'h')
+        delay(100);
+      vcs.hangCall();
+      SerialUSB.println("Hanging up and waiting for the next call.");
+      break;
+  }
+  delay(1000);
+}
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/SendSMS/SendSMS.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/SendSMS/SendSMS.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/SendSMS/SendSMS.ino	(revision 175)
@@ -0,0 +1,113 @@
+/*
+ SMS sender
+
+ This sketch, for the Arduino GSM shield,sends an SMS message
+ you enter in the serial monitor. Connect your Arduino with the
+ GSM shield and SIM card, open the serial monitor, and wait for
+ the "READY" message to appear in the monitor. Next, type a
+ message to send and press "return". Make sure the serial
+ monitor is set to send a newline when you press return.
+
+ Circuit:
+ * GSM shield
+ * SIM card that can send SMS
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ created 25 Feb 2012
+ by Tom Igoe
+
+ This example is in the public domain.
+
+ http://arduino.cc/en/Tutorial/GSMExamplesSendSMS
+ 
+
+ */
+
+// Include the GSM library
+#include <GSM.h>
+
+#define PINNUMBER ""
+
+// initialize the library instance
+GSM gsmAccess;
+GSM_SMS sms;
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("SMS Messages Sender");
+
+  // connection state
+  boolean notConnected = true;
+
+  // Start GSM shield
+  // If your SIM has PIN, pass it as a parameter of begin() in quotes
+  while (notConnected)
+  {
+    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  SerialUSB.println("GSM initialized");
+}
+
+void loop()
+{
+
+  SerialUSB.print("Enter a mobile number: ");
+  char remoteNum[20];  // telephone number to send sms
+  readSerial(remoteNum);
+  SerialUSB.println(remoteNum);
+
+  // sms text
+  SerialUSB.print("Now, enter SMS content: ");
+  char txtMsg[200];
+  readSerial(txtMsg);
+  SerialUSB.println("SENDING");
+  SerialUSB.println();
+  SerialUSB.println("Message:");
+  SerialUSB.println(txtMsg);
+
+  // send the message
+  sms.beginSMS(remoteNum);
+  sms.print(txtMsg);
+  sms.endSMS();
+  SerialUSB.println("\nCOMPLETE!\n");
+}
+
+/*
+  Read input serial
+ */
+int readSerial(char result[])
+{
+  int i = 0;
+  while (1)
+  {
+    while (SerialUSB.available() > 0)
+    {
+      char inChar = SerialUSB.read();
+      if (inChar == '\n')
+      {
+        result[i] = '\0';
+        SerialUSB.flush();
+        return 0;
+      }
+      if (inChar != '\r')
+      {
+        result[i] = inChar;
+        i++;
+      }
+    }
+  }
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino	(revision 175)
@@ -0,0 +1,122 @@
+/*
+ Band Management
+
+ This sketch, for the Arduino GSM shield, checks the band
+ currently configured in the modem and allows you to change
+ it.
+
+ Please check http://www.worldtimezone.com/gsm.html
+ Usual configurations:
+ Europe, Africa, Middle East: E-GSM(900)+DCS(1800)
+ USA, Canada, South America: GSM(850)+PCS(1900)
+ Mexico: PCS(1900)
+ Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)
+
+
+ Circuit:
+ * GSM shield
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ created 12 June 2012
+ by Javier Zorzano, Scott Fitzgerald
+
+ This example is in the public domain.
+ */
+
+// libraries
+#include <GSM.h>
+
+// initialize the library instance
+GSMBand band;
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  // Beginning the band manager restarts the modem
+  SerialUSB.println("Restarting modem...");
+  band.begin();
+  SerialUSB.println("Modem restarted.");
+
+};
+
+
+void loop()
+{
+  // Get current band
+  String bandName = band.getBand(); // Get and print band name
+  SerialUSB.print("Current band:");
+  SerialUSB.println(bandName);
+  SerialUSB.println("Want to change the band youâre on?");
+  String newBandName;
+  newBandName = askUser();
+  // Tell the user what we are about to doâ¦
+  SerialUSB.print("\nConfiguring band ");
+  SerialUSB.println(newBandName);
+  // Change the band
+  boolean operationSuccess;
+  operationSuccess = band.setBand(newBandName);
+  // Tell the user if the operation was OK
+  if (operationSuccess)
+  {
+    SerialUSB.println("Success");
+  }
+  else
+  {
+    SerialUSB.println("Error while changing band");
+  }
+
+  if (operationSuccess)
+  {
+    while (true);
+  }
+}
+
+// This function offers the user different options
+// through the Serial interface
+// The user selects one
+String askUser()
+{
+  String newBand;
+  SerialUSB.println("Select band:");
+  // Print the different options
+  SerialUSB.println("1 : E-GSM(900)");
+  SerialUSB.println("2 : DCS(1800)");
+  SerialUSB.println("3 : PCS(1900)");
+  SerialUSB.println("4 : E-GSM(900)+DCS(1800) ex: Europe");
+  SerialUSB.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");
+  SerialUSB.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");
+
+  // Empty the incoming buffer
+  while (SerialUSB.available())
+    SerialUSB.read();
+
+  // Wait for an answer, just look at the first character
+  while (!SerialUSB.available());
+  char c = SerialUSB.read();
+  if (c == '1')
+    newBand = GSM_MODE_EGSM;
+  else if (c == '2')
+    newBand = GSM_MODE_DCS;
+  else if (c == '3')
+    newBand = GSM_MODE_PCS;
+  else if (c == '4')
+    newBand = GSM_MODE_EGSM_DCS;
+  else if (c == '5')
+    newBand = GSM_MODE_GSM850_PCS;
+  else if (c == '6')
+    newBand = GSM_MODE_GSM850_EGSM_DCS_PCS;
+  else
+    newBand = "GSM_MODE_UNDEFINED";
+  return newBand;
+}
+
+
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/GsmScanNetworks/GsmScanNetworks.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/GsmScanNetworks/GsmScanNetworks.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/GsmScanNetworks/GsmScanNetworks.ino	(revision 175)
@@ -0,0 +1,97 @@
+/*
+
+ GSM Scan Networks
+
+ This example prints out the IMEI number of the modem,
+ then checks to see if it's connected to a carrier. If so,
+ it prints the phone number associated with the card.
+ Then it scans for nearby networks and prints out their signal strengths.
+
+ Circuit:
+ * GSM shield
+ * SIM card
+
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+ 
+ Created 8 Mar 2012
+ by Tom Igoe, implemented by Javier Carazo
+ Modified 4 Feb 2013
+ by Scott Fitzgerald
+
+ http://arduino.cc/en/Tutorial/GSMToolsGsmScanNetworks
+
+ This example code is part of the public domain
+ */
+
+// libraries
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// initialize the library instance
+GSM gsmAccess;     // include a 'true' parameter to enable debugging
+GSMScanner scannerNetworks;
+GSMModem modemTest;
+
+// Save data variables
+String IMEI = "";
+
+// serial monitor result messages
+String errortext = "ERROR";
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("GSM networks scanner");
+  scannerNetworks.begin();
+
+  // connection state
+  boolean notConnected = true;
+
+  // Start GSM shield
+  // If your SIM has PIN, pass it as a parameter of begin() in quotes
+  while (notConnected)
+  {
+    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
+      notConnected = false;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  // get modem parameters
+  // IMEI, modem unique identifier
+  SerialUSB.print("Modem IMEI: ");
+  IMEI = modemTest.getIMEI();
+  IMEI.replace("\n", "");
+  if (IMEI != NULL)
+    SerialUSB.println(IMEI);
+}
+
+void loop()
+{
+  // scan for existing networks, displays a list of networks
+  SerialUSB.println("Scanning available networks. May take some seconds.");
+  SerialUSB.println(scannerNetworks.readNetworks());
+
+  // currently connected carrier
+  SerialUSB.print("Current carrier: ");
+  SerialUSB.println(scannerNetworks.getCurrentCarrier());
+
+  // returns strength and ber
+  // signal strength in 0-31 scale. 31 means power > 51dBm
+  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
+  SerialUSB.print("Signal Strength: ");
+  SerialUSB.print(scannerNetworks.getSignalStrength());
+  SerialUSB.println(" [0-31]");
+
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/PinManagement/PinManagement.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/PinManagement/PinManagement.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/PinManagement/PinManagement.ino	(revision 175)
@@ -0,0 +1,170 @@
+/*
+
+ This example enables you to change or remove the PIN number of
+ a SIM card inserted into a GSM shield.
+
+ Circuit:
+ * GSM shield
+ * SIM card
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ Created 12 Jun 2012
+ by David del Peral
+
+ This example code is part of the public domain
+
+ http://arduino.cc/en/Tutorial/GSMToolsPinManagement
+
+ */
+
+// libraries
+#include <GSM.h>
+
+// pin manager object
+GSMPIN PINManager;
+
+// save input in serial by user
+String user_input = "";
+
+// authenticated with PIN code
+boolean auth = false;
+
+// serial monitor result messages
+String oktext = "OK";
+String errortext = "ERROR";
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("Change PIN example\n");
+  PINManager.begin();
+
+  // check if the SIM have pin lock
+  while (!auth) {
+    int pin_query = PINManager.isPIN();
+    if (pin_query == 1)
+    {
+      // if SIM is locked, enter PIN code
+      SerialUSB.print("Enter PIN code: ");
+      user_input = readSerial();
+      // check PIN code
+      if (PINManager.checkPIN(user_input) == 0)
+      {
+        auth = true;
+        PINManager.setPINUsed(true);
+        SerialUSB.println(oktext);
+      }
+      else
+      {
+        // if PIN code was incorrected
+        SerialUSB.println("Incorrect PIN. Remember that you have 3 opportunities.");
+      }
+    }
+    else if (pin_query == -1)
+    {
+      // PIN code is locked, user must enter PUK code
+      SerialUSB.println("PIN locked. Enter PUK code: ");
+      String puk = readSerial();
+      SerialUSB.print("Now, enter a new PIN code: ");
+      user_input = readSerial();
+      // check PUK code
+      if (PINManager.checkPUK(puk, user_input) == 0)
+      {
+        auth = true;
+        PINManager.setPINUsed(true);
+        SerialUSB.println(oktext);
+      }
+      else
+      {
+        // if PUK o the new PIN are incorrect
+        SerialUSB.println("Incorrect PUK or invalid new PIN. Try again!.");
+      }
+    }
+    else if (pin_query == -2)
+    {
+      // the worst case, PIN and PUK are locked
+      SerialUSB.println("PIN & PUK locked. Use PIN2/PUK2 in a mobile phone.");
+      while (true);
+    }
+    else
+    {
+      // SIM does not requires authetication
+      SerialUSB.println("No pin necessary.");
+      auth = true;
+    }
+  }
+
+  // start GSM shield
+  SerialUSB.print("Checking register in GSM network...");
+  if (PINManager.checkReg() == 0)
+    SerialUSB.println(oktext);
+  // if you are connect by roaming
+  else if (PINManager.checkReg() == 1)
+    SerialUSB.println("ROAMING " + oktext);
+  else
+  {
+    // error connection
+    SerialUSB.println(errortext);
+    while (true);
+  }
+}
+
+void loop()
+{
+  // Function loop implements pin management user menu
+  // Only if you SIM use pin lock, you can change PIN code
+  // user_op variables save user option
+
+  SerialUSB.println("Choose an option:\n1 - On/Off PIN.");
+  if (PINManager.getPINUsed())
+    SerialUSB.println("2 - Change PIN.");
+  String user_op = readSerial();
+  if (user_op == "1")
+  {
+    SerialUSB.println("Enter your PIN code:");
+    user_input = readSerial();
+    // activate/deactivate PIN lock
+    PINManager.switchPIN(user_input);
+  }
+  else if (user_op == "2" & PINManager.getPINUsed())
+  {
+    SerialUSB.println("Enter your actual PIN code:");
+    String oldPIN = readSerial();
+    SerialUSB.println("Now, enter your new PIN code:");
+    String newPIN = readSerial();
+    // change PIN
+    PINManager.changePIN(oldPIN, newPIN);
+  }
+  else
+  {
+    SerialUSB.println("Incorrect option. Try again!.");
+  }
+  delay(1000);
+}
+
+/*
+  Read input serial
+ */
+String readSerial()
+{
+  String text = "";
+  while (1)
+  {
+    while (SerialUSB.available() > 0)
+    {
+      char inChar = SerialUSB.read();
+      if (inChar == '\n')
+      {
+        return text;
+      }
+      if (inChar != '\r')
+        text += inChar;
+    }
+  }
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestGPRS/TestGPRS.ino	(revision 175)
@@ -0,0 +1,206 @@
+/*
+
+ This sketch test the GSM shield's ability to connect to a
+ GPERS network. It asks for APN information through the
+ serial monitor and tries to connect to arduino.cc.
+
+ Circuit:
+ * GSM shield attached
+ * SIM card with data plan
+
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+ 
+ Created 18 Jun 2012
+ by David del Peral
+
+ This example code is part of the public domain
+
+ http://arduino.cc/en/Tutorial/GSMToolsTestGPRS
+
+ */
+
+// libraries
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// initialize the library instance
+GSM gsmAccess;        // GSM access: include a 'true' parameter for debug enabled
+GPRS gprsAccess;  // GPRS access
+GSMClient client;  // Client service for TCP connection
+
+// messages for serial monitor response
+String oktext = "OK";
+String errortext = "ERROR";
+
+// URL and path (for example: arduino.cc)
+char url[] = "arduino.cc";
+char urlproxy[] = "http://arduino.cc";
+char path[] = "/";
+
+// variable for save response obtained
+String response = "";
+
+// use a proxy
+boolean use_proxy = false;
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+}
+
+void loop()
+{
+  use_proxy = false;
+
+  // start GSM shield
+  // if your SIM has PIN, pass it as a parameter of begin() in quotes
+  SerialUSB.print("Connecting GSM network...");
+  if (gsmAccess.begin(PINNUMBER) != GSM_READY)
+  {
+    SerialUSB.println(errortext);
+    while (true);
+  }
+  SerialUSB.println(oktext);
+
+  // read APN introduced by user
+  char apn[50];
+  SerialUSB.print("Enter your APN: ");
+  readSerial(apn);
+  SerialUSB.println(apn);
+
+  // Read APN login introduced by user
+  char login[50];
+  SerialUSB.print("Now, enter your login: ");
+  readSerial(login);
+  SerialUSB.println(login);
+
+  // read APN password introduced by user
+  char password[20];
+  SerialUSB.print("Finally, enter your password: ");
+  readSerial(password);
+
+  // attach GPRS
+  SerialUSB.println("Attaching to GPRS with your APN...");
+  if (gprsAccess.attachGPRS(apn, login, password) != GPRS_READY)
+  {
+    SerialUSB.println(errortext);
+  }
+  else {
+
+    SerialUSB.println(oktext);
+
+    // read proxy introduced by user
+    char proxy[100];
+    SerialUSB.print("If your carrier uses a proxy, enter it, if not press enter: ");
+    readSerial(proxy);
+    SerialUSB.println(proxy);
+
+    // if user introduced a proxy, asks him for proxy port
+    int pport;
+    if (proxy[0] != '\0') {
+      // read proxy port introduced by user
+      char proxyport[10];
+      SerialUSB.print("Enter the proxy port: ");
+      readSerial(proxyport);
+      // cast proxy port introduced to integer
+      pport = (int) proxyport;
+      use_proxy = true;
+      SerialUSB.println(proxyport);
+    }
+
+    // connection with arduino.cc and realize HTTP request
+    SerialUSB.print("Connecting and sending GET request to arduino.cc...");
+    int res_connect;
+
+    // if use a proxy, connect with it
+    if (use_proxy)
+      res_connect = client.connect(proxy, pport);
+    else
+      res_connect = client.connect(url, 80);
+
+    if (res_connect)
+    {
+      // make a HTTP 1.0 GET request (client sends the request)
+      client.print("GET ");
+
+      // if use a proxy, the path is arduino.cc URL
+      if (use_proxy)
+        client.print(urlproxy);
+      else
+        client.print(path);
+
+      client.println(" HTTP/1.0");
+      client.println();
+      SerialUSB.println(oktext);
+    }
+    else
+    {
+      // if you didn't get a connection to the server
+      SerialUSB.println(errortext);
+    }
+    SerialUSB.print("Receiving response...");
+
+    boolean test = true;
+    while (test)
+    {
+      // if there are incoming bytes available
+      // from the server, read and check them
+      if (client.available())
+      {
+        char c = client.read();
+        response += c;
+
+        // cast response obtained from string to char array
+        char responsechar[response.length() + 1];
+        response.toCharArray(responsechar, response.length() + 1);
+
+        // if response includes a "200 OK" substring
+        if (strstr(responsechar, "200 OK") != NULL) {
+          SerialUSB.println(oktext);
+          SerialUSB.println("TEST COMPLETE!");
+          test = false;
+        }
+      }
+
+      // if the server's disconnected, stop the client:
+      if (!client.connected())
+      {
+        SerialUSB.println();
+        SerialUSB.println("disconnecting.");
+        client.stop();
+        test = false;
+      }
+    }
+  }
+}
+
+/*
+  Read input serial
+ */
+int readSerial(char result[])
+{
+  int i = 0;
+  while (1)
+  {
+    while (SerialUSB.available() > 0)
+    {
+      char inChar = SerialUSB.read();
+      if (inChar == '\n')
+      {
+        result[i] = '\0';
+        return 0;
+      }
+      if (inChar != '\r')
+      {
+        result[i] = inChar;
+        i++;
+      }
+    }
+  }
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestModem/TestModem.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestModem/TestModem.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestModem/TestModem.ino	(revision 175)
@@ -0,0 +1,79 @@
+/*
+
+ This example tests to see if the modem of the
+ GSM shield is working correctly. You do not need
+ a SIM card for this example.
+
+ Circuit:
+ * GSM shield attached
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ Created 12 Jun 2012
+ by David del Peral
+ modified 21 Nov 2012
+ by Tom Igoe
+
+ http://arduino.cc/en/Tutorial/GSMToolsTestModem
+
+ This sample code is part of the public domain
+
+ */
+
+// libraries
+#include <GSM.h>
+
+// modem verification object
+GSMModem modem;
+
+// IMEI variable
+String IMEI = "";
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  // start modem test (reset and check response)
+  SerialUSB.print("Starting modem test...");
+  if (modem.begin())
+    SerialUSB.println("modem.begin() succeeded");
+  else
+    SerialUSB.println("ERROR, no modem answer.");
+}
+
+void loop()
+{
+  // get modem IMEI
+  SerialUSB.print("Checking IMEI...");
+  IMEI = modem.getIMEI();
+
+  // check IMEI response
+  if (IMEI != NULL)
+  {
+    // show IMEI in serial monitor
+    SerialUSB.println("Modem's IMEI: " + IMEI);
+    // reset modem to check booting:
+    SerialUSB.print("Resetting modem...");
+    modem.begin();
+    // get and check IMEI one more time
+    if (modem.getIMEI() != NULL)
+    {
+      SerialUSB.println("Modem is functoning properly");
+    }
+    else
+    {
+      SerialUSB.println("Error: getIMEI() failed after modem.begin()");
+    }
+  }
+  else
+  {
+    SerialUSB.println("Error: Could not get IMEI");
+  }
+  // do nothing:
+  while (true);
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestWebServer/TestWebServer.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestWebServer/TestWebServer.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/examples/Tools/TestWebServer/TestWebServer.ino	(revision 175)
@@ -0,0 +1,87 @@
+/*
+  Basic Web Server
+
+ A simple web server that replies with nothing, but prints the client's request
+ and the server IP address.
+
+ Circuit:
+ * GSM shield attached
+ 
+ ATTENTION: to work correctly with M0/M0 pro you have to connect pin 2 to pin 4 of the shield
+
+ created
+ by David Cuartielles
+ modified 21 Nov 2012
+ by Tom Igoe
+
+ http://arduino.cc/en/Tutorial/GSMToolsTestWebServer
+
+ This example code is part of the public domain
+ */
+#include <GSM.h>
+
+// PIN Number
+#define PINNUMBER ""
+
+// APN data
+#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
+#define GPRS_LOGIN     "login"    // replace with your GPRS login
+#define GPRS_PASSWORD  "password" // replace with your GPRS password
+
+
+// initialize the library instance
+GPRS gprs;
+GSM gsmAccess;     // include a 'true' parameter for debug enabled
+GSMServer server(80); // port 80 (http default)
+
+// timeout
+const unsigned long __TIMEOUT__ = 10 * 1000;
+
+void setup()
+{
+  // initialize serial communications and wait for port to open:
+  SerialUSB.begin(9600);
+  while (!SerialUSB) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  SerialUSB.println("starting,..");
+  // connection state
+  boolean connected = true;
+
+  // Start GSM shield
+  // If your SIM has PIN, pass it as a parameter of begin() in quotes
+  while (!connected)
+  {
+    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
+        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY))
+      connected = true;
+    else
+    {
+      SerialUSB.println("Not connected");
+      delay(1000);
+    }
+  }
+
+  SerialUSB.println("Connected to GPRS network");
+
+  // start server
+  server.begin();
+
+  //Get IP.
+  IPAddress LocalIP = gprs.getIPAddress();
+  SerialUSB.println("Server IP address=");
+  SerialUSB.println(LocalIP);
+}
+
+void loop() {
+  GSMClient client = server.available();
+
+  if (client) {
+    if (client.available()) {
+      SerialUSB.write(client.read());
+    }
+  }
+
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/extras/License.txt
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/extras/License.txt	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/extras/License.txt	(revision 175)
@@ -0,0 +1,166 @@
+GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/keywords.txt
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/keywords.txt	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/keywords.txt	(revision 175)
@@ -0,0 +1,84 @@
+#######################################
+# Syntax Coloring Map For GSM
+####################################### 
+# Class
+#######################################
+
+GSM	KEYWORD3
+GSMVoiceCall	KEYWORD3
+GSM_SMS	KEYWORD3
+GPRS	KEYWORD3
+GSMClient	KEYWORD3
+GSMServer	KEYWORD3
+GSMModem	KEYWORD3
+GSMScanner	KEYWORD3
+GSMPIN	KEYWORD3
+GSMBand KEYWORD3
+GSM2	KEYWORD3
+
+#######################################
+# Methods and Functions 
+#######################################	
+
+begin	KEYWORD2
+shutdown	KEYWORD2
+gatVoiceCallStatus	KEYWORD2
+ready	KEYWORD2
+voiceCall	KEYWORD2
+answerCall	KEYWORD2
+hangCall	KEYWORD2
+retrieveCallingNumber	KEYWORD2
+beginSMS	KEYWORD2
+endSMS	KEYWORD2
+remoteNumber	KEYWORD2
+attachGPRS	KEYWORD2
+begnWrite	KEYWORD2
+endWrite	KEYWORD2
+getIMEI	KEYWORD2
+getCurrentCarrier	KEYWORD2
+getSignalStrength	KEYWORD2
+readNetworks	KEYWORD2
+isPIN	KEYWORD2
+checkPIN	KEYWORD2
+checkPUK	KEYWORD2
+changePIN	KEYWORD2
+switchPIN	KEYWORD2
+checkReg	KEYWORD2
+getPINUsed	KEYWORD2
+setPINUsed	KEYWORD2
+getBand		KEYWORD2
+setBand		KEYWORD2
+getvoiceCallStatus	KEYWORD2
+getPosition	KEYWORD2
+swapAudioChannel	KEYWORD2
+microphoneGainLevel	KEYWORD2
+muteControl	KEYWORD2
+loudSpeakerVolumeLevel	KEYWORD2
+ringerSoundLevel	KEYWORD2
+alertSoundMode	KEYWORD2
+speakerLoudness	KEYWORD2
+speakerMode	KEYWORD2
+CommandEcho	KEYWORD2
+
+
+#######################################
+# Constants
+#######################################
+ 
+ERROR	LITERAL1
+IDLE	LITERAL1
+CONNECTING	LITERAL1
+GSM_READY	LITERAL1
+GPRS_READY	LITERAL1
+TRANSPARENT_CONNECTED	LITERAL1
+IDLE_CALL	LITERAL1
+CALLING	LITERAL1
+RECEIVINGCALL	LITERAL1
+TALKING	LITERAL1
+GSM_MODE_UNDEFINED	LITERAL1
+GSM_MODE_EGSM	LITERAL1
+GSM_MODE_DCS	LITERAL1
+GSM_MODE_PCS	LITERAL1
+GSM_MODE_EGSM_DCS	LITERAL1
+GSM_MODE_GSM850_PCS	LITERAL1
+GSM_MODE_GSM850_EGSM_DCS_PCS	LITERAL1
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/library.properties
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/library.properties	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/library.properties	(revision 175)
@@ -0,0 +1,9 @@
+name=GSM
+version=1.0
+author=Arduino
+maintainer=Arduino <info@arduino.cc>
+sentence=Enables GSM/GRPS network connection using the Arduino GSM Shield. For all Arduino boards BUT Arduino DUE.
+paragraph=Use this library to make/receive voice calls, to send and receive SMS with the Quectel M10 GSM module.</br>This library also allows you to connect to internet through the GPRS networks. You can either use web Clients and Servers.</br>
+category=Communication
+url=http://arduino.cc/en/Reference/GSM
+architectures=avr
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/DEFAULT.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/DEFAULT.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/DEFAULT.h	(revision 175)
@@ -0,0 +1,24 @@
+/*
+This file is part of GSM3ShieldV2 library developed by Arduino.org (http://arduino.org).
+
+    GSM3ShieldV2 library is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    GSM3ShieldV2 library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with GSM3ShieldV2 library.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#define DEFAULT_AlertSoundMode 0
+#define DEFAULT_RingerSoundLevel 10
+#define DEFAULT_Channel 1
+#define DEFAULT_MicrophoneGainLevel 10
+#define DEFAULT_LoudSpeakerVolumeLevel 30
+#define DEFAULT_muteControl 0
+#define DEFAULT_speakerMode 1
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM.h	(revision 175)
@@ -0,0 +1,81 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+
+
+Added support for Arduino GSM Shield 2
+Modified Apr. 2015
+by Arduino.org team (http://arduino.org)
+
+*/
+#ifndef _GSM3SIMPLIFIERFILE_
+#define _GSM3SIMPLIFIERFILE_
+
+// This file simplifies the use of the GSM3 library
+// First we include everything. 
+
+#include <GSM3CircularBuffer.h>
+#include <GSM3MobileCellManagement.h>
+#include <GSM3MobileClientService.h>
+#include <GSM3MobileNetworkRegistry.h>
+#include <GSM3MobileServerService.h>
+#include <GSM3ShieldV1AccessProvider.h>
+#include <GSM3ShieldV1BandManagement.h>
+#include <GSM3ShieldV1ClientProvider.h>
+#include <GSM3ShieldV1DataNetworkProvider.h>
+#include <GSM3ShieldV1ModemVerification.h>
+#include <GSM3ShieldV1CellManagement.h>
+#include <GSM3ShieldV1PinManagement.h>
+#include <GSM3ShieldV1ScanNetworks.h>
+#include <GSM3SMSService.h>
+#include <GSM3VoiceCallService.h>
+
+#include <GSM3ShieldV2.h>
+
+#define GSM GSM3ShieldV1AccessProvider
+#define GPRS GSM3ShieldV1DataNetworkProvider
+#define GSMClient GSM3MobileClientService
+#define GSMServer GSM3MobileServerService
+#define GSMVoiceCall GSM3VoiceCallService
+#define GSM_SMS GSM3SMSService
+
+#define GSMPIN GSM3ShieldV1PinManagement
+#define GSMModem GSM3ShieldV1ModemVerification
+#define GSMCell GSM3ShieldV1CellManagement
+#define GSMCell GSM3CellManagement
+#define GSMBand GSM3ShieldV1BandManagement
+#define GSMScanner GSM3ShieldV1ScanNetworks
+
+
+//#define GPRSPosition GSM3ShieldV2
+#define GSM2 GSM3ShieldV2
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3CircularBuffer.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3CircularBuffer.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3CircularBuffer.cpp	(revision 175)
@@ -0,0 +1,319 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3CircularBuffer.h>
+#include <Arduino.h>
+
+GSM3CircularBuffer::GSM3CircularBuffer(GSM3CircularBufferManager* mgr)
+{
+	head=0;
+	tail=0;
+	cbm=mgr;
+}
+
+int GSM3CircularBuffer::write(char c)
+{
+	byte aux=(tail+1)& __BUFFERMASK__;
+	if(aux!=head)
+	{
+		theBuffer[tail]=c;
+		// Lets put an extra zero at the end, so we can
+		// read chains as we like.
+		// This is not exactly perfect, we are always 1+ behind the head
+		theBuffer[aux]=0;
+		tail=aux;
+		return 1;
+	}
+	return 0;
+}
+
+char GSM3CircularBuffer::read()
+{
+	char res;
+	if(head!=tail)
+	{
+		res=theBuffer[head];
+		head=(head+1)& __BUFFERMASK__;
+		//if(cbm)
+		//	cbm->spaceAvailable();
+		return res;
+	}	
+	else
+	{
+		return 0;
+	}
+}
+
+char GSM3CircularBuffer::peek(int increment)
+{
+	char res;
+	byte num_aux;
+	
+	if (tail>head) num_aux = tail-head;
+	else num_aux = 128 - head + tail;
+	
+	if(increment < num_aux)
+	{
+		res=theBuffer[head];
+		return res;
+	}	
+	else
+	{
+		return 0;
+	}
+}
+
+void GSM3CircularBufferManager::spaceAvailable(){return;};
+
+void GSM3CircularBuffer::flush()
+{
+	head=tail;
+}
+
+char* GSM3CircularBuffer::nextString()
+{
+	while(head!=tail)
+	{
+		head=(head+1) & __BUFFERMASK__;
+		if(theBuffer[head]==0)
+		{
+			head=(head+1) & __BUFFERMASK__;
+			return (char*)theBuffer+head;
+		}
+	}
+	return 0;
+}
+
+
+bool GSM3CircularBuffer::locate(const char* reference)
+{
+
+	return locate(reference, head, tail, 0, 0);
+}
+
+bool GSM3CircularBuffer::chopUntil(const char* reference, bool movetotheend, bool usehead)
+{
+	byte from, to;
+
+	if(locate(reference, head, tail, &from, &to))
+	{
+		if(usehead)
+		{
+			if(movetotheend)
+				head=(to+1) & __BUFFERMASK__;
+			else
+				head=from;
+		}
+		else
+		{
+			if(movetotheend)
+				tail=(to+1) & __BUFFERMASK__;
+			else
+				tail=from;
+		}
+		return true;
+	}
+	else
+	{
+		return false;
+	}
+}
+
+bool GSM3CircularBuffer::locate(const char* reference, byte thishead, byte thistail, byte* from, byte* to)
+{
+	int refcursor=0;
+	bool into=false;
+	byte b2, binit;
+	bool possible=1;
+	
+	if(reference[0]==0)
+		return true;
+		
+	for(byte b1=thishead; b1!=thistail;b1=(b1+1)& __BUFFERMASK__)
+	{
+		possible = 1;
+		b2 = b1;
+		while (possible&&(b2!=thistail))
+		{	
+			if(theBuffer[b2]==reference[refcursor])
+			{
+				if(!into)	
+					binit=b2;
+				into=true;
+				refcursor++;
+				if(reference[refcursor]==0)
+				{
+					if(from) 
+						*from=binit;
+					if(to)	
+						*to=b2;
+					return true;
+				}
+			}
+			else if (into==true)
+			{
+				possible = 0;
+				into=false;
+				refcursor=0;
+			}
+			b2=(b2+1)& __BUFFERMASK__;
+		}
+	}
+	return false;
+}
+
+bool GSM3CircularBuffer::extractSubstring(const char* from, const char* to, char* buffer, int bufsize)
+{
+	byte t1;
+	byte h2;
+	byte b;
+	int i;
+	
+//DEBUG
+//SerialUSB.println("Beginning extractSubstring");
+//SerialUSB.print("head,tail=");SerialUSB.print(int(head));SerialUSB.print(",");SerialUSB.println(int(tail));
+	
+	if(!locate(from, head, tail, 0, &t1))
+		return false;
+		
+//DEBUG
+//SerialUSB.println("Located chain from.");
+
+	t1++; //To point the next.
+	if(!locate(to, t1, tail, &h2, 0))
+		return false;
+		
+//DEBUG		
+//SerialUSB.println("Located chain to.");
+/*SerialUSB.print("t1=");SerialUSB.println(int(t1));
+SerialUSB.print("h2=");SerialUSB.println(int(h2));*/
+
+
+	for(i=0,b=t1;i<bufsize, b!=((h2) & __BUFFERMASK__); i++, b=(b+1)& __BUFFERMASK__)
+		buffer[i]=theBuffer[b];
+	buffer[i]=0;
+
+//DEBUG		
+//SerialUSB.println("");
+//SerialUSB.println("Finishing extractSubstring");	
+	
+	return true;	
+}
+
+int GSM3CircularBuffer::readInt()
+{
+	int res=0;
+	byte c;
+	bool anyfound=false;
+	bool negative=false;
+	for(byte b=head + 1; b!=tail; b=(b+1)& __BUFFERMASK__)
+	{
+		c=theBuffer[b];
+		if((c==' ' )&&(!anyfound))
+		{
+		} else if((c=='-' )&&(!anyfound))
+		{
+			negative=true;
+			anyfound=true;  // Don't admit blanks after -
+		} else if((c>='0')&&(c<='9'))
+		{
+			anyfound=true;
+			res=(res*10)+(int)c-48;
+		}
+		else
+			{
+				if(negative)
+					res=(-1)*res;
+				return res;
+			}
+	}
+	if(negative)
+		res=(-1)*res;
+	return res;
+}
+
+void GSM3CircularBuffer::debugBuffer()
+{
+	byte h1=head;
+	byte t1=tail;
+	SerialUSB.println();
+	SerialUSB.print(h1);
+	SerialUSB.print(" ");
+	SerialUSB.print(t1);
+	SerialUSB.print('>');
+	for(byte b=h1; b!=t1; b=(b+1)& __BUFFERMASK__)
+		printCharDebug(theBuffer[b]);
+	SerialUSB.println();
+}
+
+void GSM3CircularBuffer::printCharDebug(uint8_t c)
+{
+	if((c>31)&&(c<127))
+		SerialUSB.print((char)c);
+	else
+	{
+		SerialUSB.print('%');
+		SerialUSB.print(c);
+		SerialUSB.print('%');
+	}
+}
+
+bool GSM3CircularBuffer::retrieveBuffer(char* buffer, int bufsize, int& SizeWritten)
+{
+	byte b;
+	int i;
+	
+	/*for(i=0,b=head;i<bufsize, b!=tail; i++, b=(b+1)& __BUFFERMASK__)
+		{
+			buffer[i]=theBuffer[b];
+		}
+	buffer[i]=0;
+	SizeWritten = i;*/
+	b=head;
+	for(i=0;i<bufsize; i++)
+		{
+			if (b!=tail)
+				{
+					buffer[i]=theBuffer[b];
+					buffer[i+1]=0;
+					b=(b+1)& __BUFFERMASK__;
+					SizeWritten = i + 1;
+				}
+		}
+	
+	
+	return true;	
+}
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3CircularBuffer.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3CircularBuffer.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3CircularBuffer.h	(revision 175)
@@ -0,0 +1,205 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_CIRCULARBUFFER__
+#define __GSM3_CIRCULARBUFFER__
+
+
+#include <inttypes.h>
+#include <stddef.h>
+
+#ifndef byte
+#define byte uint8_t
+#endif
+
+// These values have to be interrelated
+// To-Do: may we have just one? (BUFFERMASK)
+#define __BUFFERSIZE__ 128
+#define __BUFFERMASK__ 0x7F
+
+class GSM3CircularBufferManager
+{
+	public:
+	
+		/** If there is spaceAvailable in the buffer, lets send a XON
+		 */
+		virtual void spaceAvailable();		
+};
+
+class GSM3CircularBuffer
+{
+	private:
+		// Buffer pointers. 
+		// head=tail means buffer empty
+		// tail=head-1 means buffer full
+		// tail=head+1 means just one char (pointed by head)
+		// REMEMBER. head can be moved only by the main program
+		// REMEMBER. tail can be moved only by the other thread (interrupts)
+		// REMEMBER. head and tail can move only FORWARD
+		volatile byte head; // First written one
+		volatile byte tail; // Last written one. 
+		
+		GSM3CircularBufferManager* cbm; // Circular buffer manager
+		
+		// The buffer
+		volatile byte theBuffer[__BUFFERSIZE__];
+		
+		/** Checks if a substring exists in the buffer
+			@param reference	Substring
+			@param thishead		Head
+			@param thistail		Tail
+			@param from			Initial byte position
+			@param to			Final byte position
+			@return true if exists, in otherwise return false
+		 */
+		bool locate(const char* reference, byte thishead, byte thistail, byte* from=0, byte* to=0);
+		
+	public:
+	
+		/** Constructor
+			@param mgr			Circular buffer manager
+		 */
+		GSM3CircularBuffer(GSM3CircularBufferManager* mgr=0);
+		
+		// TO-DO.Check if this formule runs too at the buffer limit
+		
+		/** Get available bytes in circular buffer
+			@return available bytes
+		 */
+		inline byte availableBytes(){ return ((head-(tail+1))&__BUFFERMASK__);};
+		
+		/** Stored bytes in circular buffer
+			@return stored bytes
+		 */
+		inline byte storedBytes(){ return ((tail-head)&__BUFFERMASK__);};
+
+		/** Write a character in circular buffer
+			@param c			Character
+			@return 1 if successful
+		 */
+		int write(char c);
+		
+		/** Returns a character and moves the pointer
+			@return character
+		 */
+		char read();
+		
+		/** Returns a character but does not move the pointer.
+			@param increment	Increment
+			@return character
+		 */
+		char peek(int increment);
+		
+		/** Returns a pointer to the head of the buffer
+			@return buffer with pointer in head
+		*/
+		inline char* firstString(){return (char*)theBuffer+head;};
+		
+		/** Go forward one string
+			@return buffer with one string advance
+		 */
+		char* nextString();
+		
+		/** Flush circular buffer
+		 */
+		void flush();
+		
+		/** Get tail
+			@return tail
+		 */
+		inline byte getTail(){return tail;};
+		
+		/** Get head
+			@return head
+		 */
+		inline byte getHead(){return head;};
+		
+		// Only can be executed from the interrupt!
+		/** Delete circular buffer to the end
+			@param from			Initial byte position
+		 */
+		inline void deleteToTheEnd(byte from){tail=from;};
+		
+		/** Checks if a substring exists in the buffer
+			move=0, dont move, =1,put head at the beginning of the string, =2, put head at the end
+			@param reference
+			@return true if exists, in otherwise return false
+		 */
+		bool locate(const char* reference);
+		
+		/** Locates reference. If found, moves head (or tail) to the beginning (or end)
+			@param reference
+			@param movetotheend
+			@param head
+			@return true if successful
+		 */
+		bool chopUntil(const char* reference, bool movetotheend, bool head=true);
+		
+		/** Reads an integer from the head. Stops with first non blank, non number character
+			@return integer from the head
+		 */
+		int readInt();
+		
+		// Caveat: copies the first bytes until buffer is full
+		
+		/** Extract a substring from circular buffer
+			@param from			Initial byte position
+			@param to			Final byte position
+			@param buffer		Buffer for copy substring
+			@param bufsize		Buffer size
+			@return true if successful, false if substring does not exists
+		 */
+		bool extractSubstring(const char* from, const char* to, char* buffer, int bufsize);
+		
+		/** Retrieve all the contents of buffer from head to tail
+			@param buffer
+			@param bufsize
+			@param SizeWritten
+			@return true if successful
+		 */
+		bool retrieveBuffer(char* buffer, int bufsize, int& SizeWritten);
+		
+		/** Debug function to print the buffer after receiving data from the modem.
+		 */
+		void debugBuffer();
+		
+		/** Utility: dump character if printable, else, put in %x%
+			@param c			Character
+		 */
+		static void printCharDebug(uint8_t c);
+		
+		
+};
+
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3IO.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3IO.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3IO.h	(revision 175)
@@ -0,0 +1,10 @@
+#ifdef TTOPEN_V1
+	#define __POWERPIN__ 5
+	#define __RESETPIN__ 6
+#else
+	#define __RESETPIN__ 7
+#endif
+
+#define __TXPIN__ 3
+#define __RXPIN__ 4
+#define __RXINT__ 3
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileAccessProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileAccessProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileAccessProvider.cpp	(revision 175)
@@ -0,0 +1,3 @@
+#include <GSM3MobileAccessProvider.h>
+
+GSM3MobileAccessProvider* theGSM3MobileAccessProvider;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileAccessProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileAccessProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileAccessProvider.h	(revision 175)
@@ -0,0 +1,73 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILEACCESSPROVIDER_
+#define _GSM3MOBILEACCESSPROVIDER_
+
+enum GSM3_NetworkStatus_t { ERROR, IDLE, CONNECTING, GSM_READY, GPRS_READY, TRANSPARENT_CONNECTED, OFF};
+
+class GSM3MobileAccessProvider
+{
+	public:
+		// Access functions
+		//Configuration functions.
+		/** Establish GSM connection
+			@param pin			PIN code
+			@param restart		Determines if hardware restart
+			@param synchronous	Determines sync mode
+			@return If synchronous, GSM3_NetworkStatus_t. If asynchronous, returns 0.
+		 */
+		virtual inline GSM3_NetworkStatus_t begin(char* pin=0,bool restart=true, bool synchronous=true)=0;
+		
+		/** Check network access status
+			@return 1 if Alive, 0 if down
+		*/
+		virtual inline int isAccessAlive()=0;
+		
+		/** Shutdown the modem (power off really)
+			@return true if successful
+		 */
+		virtual inline bool shutdown()=0;
+		
+		/** Secure shutdown the modem (power off really)
+			@return always true
+		 */
+		virtual inline bool secureShutdown()=0;
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		virtual int ready()=0;
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileCellManagement.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileCellManagement.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileCellManagement.cpp	(revision 175)
@@ -0,0 +1,1 @@
+#include <GSM3MobileCellManagement.h>
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileCellManagement.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileCellManagement.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileCellManagement.h	(revision 175)
@@ -0,0 +1,53 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILECELLMANAGEMENT_
+#define _GSM3MOBILECELLMANAGEMENT_
+
+#include <Arduino.h>
+
+class GSM3MobileCellManagement
+{
+	public:
+		
+		virtual inline int getLocation() {return 0;};
+		
+		virtual inline int getICCID() {return 0;};
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		virtual int ready()=0;
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientProvider.cpp	(revision 175)
@@ -0,0 +1,3 @@
+#include <GSM3MobileClientProvider.h>
+
+GSM3MobileClientProvider* theGSM3MobileClientProvider;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientProvider.h	(revision 175)
@@ -0,0 +1,156 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_MOBILECLIENTPROVIDER__
+#define __GSM3_MOBILECLIENTPROVIDER__
+
+#include <Arduino.h>
+#include <IPAddress.h>
+
+class GSM3MobileClientProvider
+{
+	protected:
+
+		uint8_t sockets;
+
+	public:
+
+		/** Constructor */
+		GSM3MobileClientProvider(){};
+		
+		/** Minimum socket
+			@return socket
+		 */
+		virtual inline int minSocket()=0;
+		
+		/** Maximum socket
+			@return socket
+		 */
+		virtual inline int maxSocket()=0;
+
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		*/
+		virtual int ready()=0;
+		
+		/** Get status socket client
+			@param socket		Socket
+			@return 1 if connected
+		 */
+		virtual bool getStatusSocketClient(uint8_t socket)=0;
+
+		// Socket management
+		
+		/** Get socket
+			@param socket		Socket
+			@return socket
+		 */
+		virtual int getSocket(int socket=-1)=0;
+		
+		/** Release socket
+			@param socket		Socket
+		 */
+		virtual void releaseSocket(int socket)=0;
+
+		// Client socket functions
+		
+		/** Connect to a server via TCP connection
+			@param server		Server name or IP address in a String
+			@param port			Port
+			@param id_socket	Socket
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		virtual int connectTCPClient(const char* server, int port, int id_socket)=0;
+		
+		/** Connect to a server (by IP address) via TCP connection
+			@param add			IP address in IPAddress format
+			@param port			Port
+			@param id_socket	Socket
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		virtual int connectTCPClient(IPAddress add, int port, int id_socket)=0;
+		
+		/** Begin writing through a socket
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		virtual void beginWriteSocket(bool client1Server0, int id_socket)=0;
+		
+		/** Write through a socket. MUST go after beginWriteSocket()
+			@param c 				character to be written
+		 */
+		virtual void writeSocket(uint8_t c)=0;
+		
+		/** Write through a socket. MUST go after beginWriteSocket()
+			@param buf				characters to be written (final 0 will not be written)
+		 */
+		virtual void writeSocket(const char* buf)=0;
+		
+		/** Finish current writing
+		 */	
+		virtual void endWriteSocket()=0;
+		
+		/** Check if there are data to be read in socket.
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if there are data available, 4 if no data, otherwise error
+		 */
+		virtual int availableSocket(bool client, int id_socket)=0;
+		
+		/** Read data (get a character) available in socket
+			@return character
+		 */
+		virtual int readSocket()=0;
+		
+		/** Flush socket
+		 */
+		virtual void flushSocket()=0;
+		
+		/** Get a character but will not advance the buffer head
+			@return character
+		 */
+		virtual int peekSocket()=0;
+		
+		/** Close a socket
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Socket
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		virtual int disconnectTCP(bool client1Server0, int idsocket)=0;
+
+};
+
+extern GSM3MobileClientProvider* theGSM3MobileClientProvider;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientService.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientService.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientService.cpp	(revision 175)
@@ -0,0 +1,260 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3MobileClientService.h>
+#include <GSM3MobileClientProvider.h>
+#include <Arduino.h>
+
+// While there is only a shield (ShieldV1) we will include it by default
+#include <GSM3ShieldV1ClientProvider.h>
+GSM3ShieldV1ClientProvider theShieldV1ClientProvider;
+
+
+#define GSM3MOBILECLIENTSERVICE_CLIENT 0x01 // 1: This side is Client. 0: This side is Server
+#define GSM3MOBILECLIENTSERVICE_WRITING 0x02 // 1: TRUE 0: FALSE
+#define GSM3MOBILECLIENTSERVICE_SYNCH 0x04 // 1: TRUE, compatible with other clients 0: FALSE
+
+#define __TOUTBEGINWRITE__ 10000
+
+
+GSM3MobileClientService::GSM3MobileClientService(bool synch)
+{
+	flags = GSM3MOBILECLIENTSERVICE_CLIENT;
+	if(synch)
+		flags |= GSM3MOBILECLIENTSERVICE_SYNCH;
+	mySocket=255;
+}
+
+GSM3MobileClientService::GSM3MobileClientService(int socket, bool synch)
+{
+	// We are creating a socket on an existing, occupied one.
+	flags=0;
+	if(synch)
+		flags |= GSM3MOBILECLIENTSERVICE_SYNCH;
+	mySocket=socket;
+	theGSM3MobileClientProvider->getSocket(socket);
+	
+}
+
+// Returns 0 if last command is still executing
+// 1 if success
+// >1 if error 
+int GSM3MobileClientService::ready()
+{	
+	return theGSM3MobileClientProvider->ready();
+}
+
+int GSM3MobileClientService::connect(IPAddress add, uint16_t port) 
+{
+	if(theGSM3MobileClientProvider==0)
+		return 2;
+		
+	// TODO: ask for the socket id
+	mySocket=theGSM3MobileClientProvider->getSocket();
+
+	if(mySocket<0)
+		return 2;
+	
+	int res=theGSM3MobileClientProvider->connectTCPClient(add, port, mySocket);
+	if(flags & GSM3MOBILECLIENTSERVICE_SYNCH)
+		res=waitForAnswer();
+	
+	return res;
+};
+
+int GSM3MobileClientService::connect(const char *host, uint16_t port)
+{
+
+	if(theGSM3MobileClientProvider==0)
+		return 2;		
+	// TODO: ask for the socket id
+	mySocket=theGSM3MobileClientProvider->getSocket();
+
+	if(mySocket<0)
+		return 2;
+	
+	int res=theGSM3MobileClientProvider->connectTCPClient(host, port, mySocket);
+	if(flags & GSM3MOBILECLIENTSERVICE_SYNCH)
+		res=waitForAnswer();
+		
+	return res;
+}
+
+int GSM3MobileClientService::waitForAnswer()
+{
+	unsigned long m;
+	m=millis();
+	int res;
+	
+	while(((millis()-m)< __TOUTBEGINWRITE__ )&&(ready()==0)) 
+		delay(100);
+	
+	res=ready();
+
+	// If we get something different from a 1, we are having a problem
+	if(res!=1)
+		res=0;
+
+	return res;
+}
+
+void GSM3MobileClientService::beginWrite(bool sync)
+{
+	flags |= GSM3MOBILECLIENTSERVICE_WRITING;
+	theGSM3MobileClientProvider->beginWriteSocket(flags & GSM3MOBILECLIENTSERVICE_CLIENT, mySocket);
+	if(sync)
+		waitForAnswer();
+}
+
+size_t GSM3MobileClientService::write(uint8_t c)
+{	
+	if(!(flags & GSM3MOBILECLIENTSERVICE_WRITING))
+		beginWrite(true);
+	theGSM3MobileClientProvider->writeSocket(c);
+	return 1;
+}
+
+size_t GSM3MobileClientService::write(const uint8_t* buf)
+{
+	if(!(flags & GSM3MOBILECLIENTSERVICE_WRITING))
+		beginWrite(true);
+	theGSM3MobileClientProvider->writeSocket((const char*)(buf));
+	return strlen((const char*)buf);
+}
+
+size_t GSM3MobileClientService::write(const uint8_t* buf, size_t sz)
+{
+	if(!(flags & GSM3MOBILECLIENTSERVICE_WRITING))
+		beginWrite(true);
+	for(int i=0;i<sz;i++)
+		theGSM3MobileClientProvider->writeSocket(buf[i]);
+	return sz;
+}
+
+void GSM3MobileClientService::endWrite(bool sync)
+{
+	flags ^= GSM3MOBILECLIENTSERVICE_WRITING;
+	theGSM3MobileClientProvider->endWriteSocket();
+	if(sync)
+		waitForAnswer();
+}
+
+uint8_t GSM3MobileClientService::connected()
+{
+	if(mySocket==255)
+		return 0;
+	return theGSM3MobileClientProvider->getStatusSocketClient(mySocket);	 
+}
+
+GSM3MobileClientService::operator bool()
+{
+	return connected()==1;
+};
+
+int GSM3MobileClientService::available()
+{
+	int res;
+
+	// Even if not connected, we are looking for available data
+	
+	if(flags & GSM3MOBILECLIENTSERVICE_WRITING)
+		endWrite(true);
+
+	res=theGSM3MobileClientProvider->availableSocket(flags & GSM3MOBILECLIENTSERVICE_CLIENT,mySocket);
+	if(flags & GSM3MOBILECLIENTSERVICE_SYNCH)
+		res=waitForAnswer();
+
+	return res;
+}
+
+int GSM3MobileClientService::read(uint8_t *buf, size_t size)
+{
+	int i;
+	uint8_t c;
+	
+	for(i=0;i<size;i++)
+	{
+		c=read();
+		if(c==0)
+			break;
+		buf[i]=c;
+	}
+	
+	return i;
+/* This is the old implementation, testing a simpler one
+	int res;
+	// If we were writing, just stop doing it.
+	if(flags & GSM3MOBILECLIENTSERVICE_WRITING)
+		endWrite(true);
+	res=theGSM3MobileClientProvider->readSocket(flags & GSM3MOBILECLIENTSERVICE_CLIENT, (char *)(buf), size, mySocket);
+
+	return res;
+*/
+}
+
+int GSM3MobileClientService::read()
+{
+	if(flags & GSM3MOBILECLIENTSERVICE_WRITING)
+		endWrite(true);
+	int c=theGSM3MobileClientProvider->readSocket();
+	return c;
+}
+
+int GSM3MobileClientService::peek()
+{
+	if(flags & GSM3MOBILECLIENTSERVICE_WRITING)
+		endWrite(true);
+	return theGSM3MobileClientProvider->peekSocket(/*mySocket, false*/);
+}
+
+void GSM3MobileClientService::flush()
+{
+	if(flags & GSM3MOBILECLIENTSERVICE_WRITING)
+		endWrite(true);
+	theGSM3MobileClientProvider->flushSocket(/*mySocket*/);
+	if(flags & GSM3MOBILECLIENTSERVICE_SYNCH)
+		waitForAnswer();
+
+}
+
+void GSM3MobileClientService::stop()
+{
+	if(flags & GSM3MOBILECLIENTSERVICE_WRITING)
+		endWrite(true);
+	theGSM3MobileClientProvider->disconnectTCP(flags & GSM3MOBILECLIENTSERVICE_CLIENT, mySocket);
+	theGSM3MobileClientProvider->releaseSocket(mySocket);
+	mySocket = 0;
+	if(flags & GSM3MOBILECLIENTSERVICE_SYNCH)
+		waitForAnswer();
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientService.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientService.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileClientService.h	(revision 175)
@@ -0,0 +1,162 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILECLIENTSERVICE_
+#define _GSM3MOBILECLIENTSERVICE_
+
+#include <GSM3MobileNetworkProvider.h>
+#include <Client.h>
+
+
+class GSM3MobileClientService : public Client
+{
+	private:
+	
+		uint8_t mySocket;
+		uint8_t flags;
+		
+		/** Blocks waiting for an answer
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int waitForAnswer();
+
+	public:
+	
+		/** Constructor
+			@param synch		Sync mode
+		 */
+		GSM3MobileClientService(bool synch=true);
+		
+		/** Constructor
+			@param socket		Socket
+			@param synch		Sync mode
+		 */
+		GSM3MobileClientService(int socket, bool synch);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		*/
+		int ready();
+		
+		// we take this function out as IPAddress is complex to bring to
+		// version 1.
+		/** Connect to server by IP address
+			@param (IPAddress)
+			@param (uint16_t)
+			@return returns 0 if last command is still executing, 1 success, 2 if there are no resources
+		 */
+		inline int connect(IPAddress, uint16_t);
+
+		/** Connect to server by hostname
+			@param host			Hostname
+			@param port			Port
+			@return returns 0 if last command is still executing, 1 success, 2 if there are no resources
+		 */
+		int connect(const char *host, uint16_t port);
+		
+		/** Initialize write in request
+			@param sync			Sync mode
+		 */
+		void beginWrite(bool sync=false);
+		
+		/** Write a character in request
+			@param c			Character
+			@return size
+		 */
+		size_t write(uint8_t c);
+		
+		/** Write a characters buffer in request
+			@param buf			Buffer
+			@return buffer size
+		 */
+		size_t write(const uint8_t *buf);
+		
+		/** Write a characters buffer with size in request
+			@param (uint8_t*)	Buffer
+			@param (size_t)		Buffer size
+			@return buffer size
+		 */
+		size_t write(const uint8_t*, size_t);
+		
+		/** Finish write request
+			@param sync			Sync mode
+		 */
+		void endWrite(bool sync=false);
+		
+		/** Check if connected to server
+			@return 1 if connected
+		 */
+		uint8_t connected();
+		
+		operator bool();
+		
+		/** Read from response buffer and copy size specified to buffer
+			@param buf			Buffer		
+			@param size			Buffer size
+			@return bytes read
+		 */
+		int read(uint8_t *buf, size_t size);
+		
+		/** Read a character from response buffer
+			@return character
+		 */
+		int read();
+		
+		/** Check if exists a response available
+			@return 1 if exists, 0 if not exists
+		 */
+		int available();
+		
+		/** Read a character from response buffer but does not move the pointer.
+			@return character
+		 */
+		int peek();
+		
+		/** Flush response buffer
+		 */
+		void flush();
+		
+		/** Stop client
+		 */
+		void stop();
+		
+		/** Get socket
+			@return socket
+		 */
+		inline int getSocket(){return (int)mySocket;};
+
+		
+};
+
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileDataNetworkProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileDataNetworkProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileDataNetworkProvider.cpp	(revision 175)
@@ -0,0 +1,3 @@
+#include <GSM3MobileDataNetworkProvider.h>
+
+// GSM3MobileDataNetworkProvider* theGSM3MobileDataNetworkProvider;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileDataNetworkProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileDataNetworkProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileDataNetworkProvider.h	(revision 175)
@@ -0,0 +1,62 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILEDATANETWORKPROVIDER_
+#define _GSM3MOBILEDATANETWORKPROVIDER_
+
+#include <GSM3MobileAccessProvider.h>
+
+// This class is not really useful, but serves as a guideline for programmers
+// We keep it but it should never be linked
+class GSM3MobileDataNetworkProvider
+{
+	public:
+		
+		/** Attach to GPRS/GSM network
+			@param networkId 	APN GPRS
+			@param user			Username
+			@param pass			Password
+			@return connection status
+		 */
+		virtual GSM3_NetworkStatus_t networkAttach(char* networId, char* user, char* pass)=0;
+		
+		/** Detach GPRS/GSM network
+			@return connection status
+		 */
+		virtual GSM3_NetworkStatus_t networkDetach()=0;
+				
+};
+
+extern GSM3MobileDataNetworkProvider* theGSM3MobileDataNetworkProvider;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileMockupProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileMockupProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileMockupProvider.cpp	(revision 175)
@@ -0,0 +1,192 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3MobileNetworkProvider.h>
+#include <GSM3MobileMockupProvider.h>
+#include <inttypes.h>
+#include <HardwareSerial.h>
+#include <Arduino.h>
+
+
+GSM3MobileMockupProvider::GSM3MobileMockupProvider()
+{
+	lineStatus=IDLE;
+	msgExample="Hello#World";
+	msgIndex=0;
+};
+
+int GSM3MobileMockupProvider::begin(char* pin)
+{
+	SerialUSB.println("GSM3MobileMockupProvider::begin()");
+	return 0;
+};
+
+int GSM3MobileMockupProvider::ready()
+{
+	SerialUSB.println("GSM3MobileMockupProvider::ready()");
+	return 1;
+};
+
+int GSM3MobileMockupProvider::beginSMS(const char* number)
+{
+	SerialUSB.println("SM3MobileMockupProvider::beginSMS()");
+	return 0;
+};
+
+void GSM3MobileMockupProvider::writeSMS(char c)
+{
+	SerialUSB.print(c);
+};
+
+int GSM3MobileMockupProvider::endSMS()
+{
+	SerialUSB.println("GSM3MobileMockupProvider::endSMS()");
+};
+
+int GSM3MobileMockupProvider::availableSMS()
+{
+	SerialUSB.println("GSM3MobileMockupProvider::availableSMS()");
+	return 120;
+};
+
+int GSM3MobileMockupProvider::peek()
+{
+	return (int)'H';
+};
+
+int GSM3MobileMockupProvider::remoteSMSNumber(char* number, int nlength)
+{
+	if(nlength>=13)
+		strcpy(number, "+34630538546");
+	return 12;
+};
+
+
+void GSM3MobileMockupProvider::flushSMS()
+{
+	SerialUSB.println("GSM3MobileMockupProvider::flushSMS()");
+};
+
+int GSM3MobileMockupProvider::readSMS()
+{
+	if(msgExample[msgIndex]==0)
+	{
+		msgIndex=0;
+		return 0;
+	}
+	else
+	{
+		msgIndex++;
+		return msgExample[msgIndex-1];
+	};
+};
+
+int GSM3MobileMockupProvider::connectTCPClient(const char* server, int port, int id_socket)
+{
+	SerialUSB.println("GSM3MobileMockupProvider::connectTCPClient()");
+	SerialUSB.print(server);SerialUSB.print(":");SerialUSB.print(port);SerialUSB.print("-");SerialUSB.println(id_socket);
+}
+
+void GSM3MobileMockupProvider::writeSocket(const uint8_t *buf, size_t size, int id_socket)
+{
+	int i;
+	for(i=0;i<size;i++)
+		SerialUSB.print(buf[i]);
+}
+/* I'm taking this off. We'll reply from the NetworkProvider
+uint8_t GSM3MobileMockupProvider::getStatus(uint8_t socket)
+{
+    if((socket>=minSocket())&&(socket<=maxSocket()))
+		return 1;
+	else
+		return 0;
+};
+*/
+
+int GSM3MobileMockupProvider::readSocket(uint8_t *buf, size_t size, int idsocket)
+{
+	int i;
+	int l=strlen(msgExample);
+	for(i=0;(i<size)&&(i<l);i++)
+		buf[i]=msgExample[i];
+	buf[i]=0;
+	return i;
+}
+
+int GSM3MobileMockupProvider::availableSocket(int idsocket)
+{
+	return 1;
+};
+
+int GSM3MobileMockupProvider::readSocket(int idsocket, bool advance)
+{
+	char c;
+	if(msgExample[msgIndex]==0)
+	{
+		msgIndex=0;
+		return 0;
+	}
+	else
+	{
+		c=msgExample[msgIndex];
+		if(advance)
+			msgIndex++;
+	};
+	return c;
+};
+
+void GSM3MobileMockupProvider::flushSocket(int idsocket)
+{
+	while(readSocket(idsocket));
+};
+
+int GSM3MobileMockupProvider::disconnectTCP(int idsocket)
+{
+	SerialUSB.println("GSM3MobileMockupProvider::disconnectTCP()");
+	return 1;
+};
+
+int GSM3MobileMockupProvider::connectTCPServer(int port, char* localIP, int* localIPlength)
+{
+	SerialUSB.println("GSM3MobileMockupProvider::connectTCPServer()");
+	if((localIP!=0)&&(*localIPlength>12))
+		strcpy("192.168.1.1", localIP);
+	return 1;
+};
+
+bool GSM3MobileMockupProvider::getSocketModemStatus(uint8_t s)
+{
+	// Feeling lazy
+	return true;
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileMockupProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileMockupProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileMockupProvider.h	(revision 175)
@@ -0,0 +1,255 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILEMOCKUPPROVIDER_
+#define _GSM3MOBILEMOCKUPPROVIDER_
+
+#include <GSM3MobileNetworkProvider.h>
+#include <GSM3MobileVoiceProvider.h>
+		
+class GSM3MobileMockupProvider: public GSM3MobileNetworkProvider
+{				
+	private:
+		// Introducing this status is quite "heavy". But something like this should
+		// be added to ShieldV1. Or not. 
+		// Note, in ShieldV1 there is no "RECEIVINGSMS" status.
+		enum GSM3_modemlinest_e { IDLE, WAITINGANSWER, SENDINGSMS};
+		GSM3_modemlinest_e lineStatus;
+		char* msgExample;
+		int msgIndex;
+		
+	public:
+	
+		/** Minimum socket
+			@return 1
+		 */
+		inline int minSocket(){return 1;};
+		
+		/** Maximum socket
+			@return 8
+		 */
+		inline int maxSocket(){return 8;};
+
+		/** Constructor */
+		GSM3MobileMockupProvider();
+		
+		/** Get network status
+			@return network status
+		 */
+		inline GSM3_NetworkStatus_t getStatus(){return ERROR;};
+		
+		/** Get voice call status
+			@return call status
+		 */
+		inline GSM3_voiceCall_st getvoiceCallStatus(){return IDLE_CALL;};
+		
+		/** Get last command status
+			@return Returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready();
+		inline void closeCommand(int code){};
+		
+		//Configuration functions.
+		
+		/** Begin connection
+			@param pin			PIN code
+			@return 
+		 */
+		int begin(char* pin=0);
+		
+		/** Check if is modem alive
+			@return 0
+		 */
+		inline int isModemAlive(){return 0;};
+		
+		/** Shutdown the modem (power off really)
+			@return true if successful
+		 */
+		inline bool shutdown(){return false;};
+		
+		//Call functions
+		
+		/** Launch a voice call
+			@param number	 	Phone number to be called
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		inline int voiceCall(const char* number){return 0;};
+		
+		/** Answer a voice call
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		inline int answerCall(){return 0;};
+		
+		/** Hang a voice call
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		inline int hangCall(){return 0;};
+		
+		/** Retrieve phone number of caller
+			@param buffer		Buffer for copy phone number
+			@param bufsize		Buffer size
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		inline int retrieveCallingNumber(char* buffer, int*& bufsize){return 0;};
+		
+		// SMS functions
+		
+		/** Begin a SMS to send it
+			@param number		Destination
+			@return error command if it exists
+		 */
+		int beginSMS(const char* number);
+		
+		/** End SMS
+			@return error command if it exists
+		 */
+		int endSMS();
+		
+		/** Check if SMS available and prepare it to be read
+			@return error command if it exists
+		 */
+		int availableSMS();
+		
+		/** Read a byte but do not advance the buffer header (circular buffer)
+			@return character
+		 */
+		int peek();
+		
+		/** Delete the SMS from Modem memory and proccess answer
+		 */
+		void flushSMS();
+		
+		/** Read sender number phone
+			@param number		Buffer for save number phone
+			@param nlength		Buffer length
+			@return 1 success, >1 error
+		 */
+		int remoteSMSNumber(char* number, int nlength); 
+		
+		/** Read one char for SMS buffer (advance circular buffer)
+			@return character
+		 */
+		int readSMS();
+		
+		/** Write a SMS character by character
+			@param c			Character
+		 */
+		void writeSMS(char c);
+		
+		// Socket functions
+		
+		/** Connect to a remote TCP server
+			@param server		String with IP or server name
+			@param port 		Remote port number
+			@param id_socket	Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		*/
+		int connectTCPClient(const char* server, int port, int id_socket);
+		
+		// Attention to parameter rewriting in ShieldV1
+		/** Write buffer information into a socket
+			@param buf			Buffer
+			@param size			Buffer size
+			@param idsocket		Socket
+		 */
+		void writeSocket(const uint8_t *buf, size_t size, int idsocket);
+		
+		// ShieldV1 will have two reading mechanisms:
+		// Mechanism 1: Call AT+QIRD for size bytes. Put them in the circular buffer,
+		// fill buf. Take care to xon/xoff effect, as we may copy just a part of the 
+		// incoming bytes.
+		/** Read socket and put information in a buffer
+			@param buf			Buffer
+			@param size			Buffer size
+			@param idsocket		Socket
+			@return
+		 */
+		int readSocket(uint8_t *buf, size_t size, int idsocket);
+		
+		// Mechanism 2 in ShieldV1:
+		// When called "available()" or "read()" reuse readSocket code to execute 
+		// QIRD SYNCHRONOUSLY. Ask the modem for 1500 bytes but do not copy them anywhere, 
+		// leave data in the circular buffer. Put buffer head at the start of received data.
+		// Peek() will get a character but will not advance the buffer head.
+		// Read() will get one character. XON/XOFF will take care of buffer filling
+		// If Read() gets to the end of the QIRD response, execute again QIRD SYNCHRONOUSLY 
+		// If the user executes flush(), execute read() until there is nothing more to read()
+		// (the modem gives no way to empty the socket of incoming data)
+		
+		/** Check if there are data to be read in socket.
+			@param idsocket	Local socket number
+			@return 0 if command running, 1 if there are data available, 4 if no data, otherwise error
+		*/
+		int availableSocket(int idsocket);
+		
+		/** Read data (get a character) available in socket
+			@param idsocket		Socket
+			@param advance		Determines if advance the buffer head
+			@return character
+		 */
+		int readSocket(int idsocket, bool advance=true);
+		
+		/** Flush socket
+			@param idsocket		Socket
+		 */
+		void flushSocket(int idsocket);
+		
+		// This is the same in ShieldV1
+		/** Close a socket
+			@param idsocket			Socket
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		int disconnectTCP(int idsocket);
+		
+		// TCP Server. Attention. Changing the int*&. We'll receive a buffer for the IP
+		// If the pointer ins NULL just forget it
+		// I think that opening a server does not occupy a socket. Is that true?
+		/** Establish a TCP connection
+			@param port				Port
+			@param localIP			IP address
+			@param localIPlength	IP address size in characters
+			@return	command error if exists
+		 */
+		int connectTCPServer(int port, char* localIP, int* localIPlength);
+		
+		// Modem sockets status. Return TRUE if the modem thinks the socket is occupied.
+		// This should be detected through an unrequisited response
+		/** Get modem status
+			@param s			Socket
+			@return modem status (true if connected)
+		 */
+		bool getSocketModemStatus(uint8_t s);
+
+
+};
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkProvider.cpp	(revision 175)
@@ -0,0 +1,71 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3MobileNetworkProvider.h>
+
+GSM3MobileNetworkProvider* theProvider;
+
+GSM3MobileNetworkProvider::GSM3MobileNetworkProvider()
+{
+	socketsAsServer=0x0000;
+};
+
+
+int GSM3MobileNetworkProvider::getNewOccupiedSocketAsServer()
+{
+	int i;
+	for(i=minSocketAsServer(); i<=maxSocketAsServer(); i++)
+	{
+		if ((!(socketsAsServer&(0x0001<<i))) && getSocketAsServerModemStatus(i))
+		{
+			socketsAsServer|=((0x0001)<<i);	
+			//SerialUSB.print("New occupied=");SerialUSB.println(i);
+			return i;
+		}
+	}
+	//SerialUSB.println("No new occupied");
+	return -1;
+}
+
+
+bool GSM3MobileNetworkProvider::getStatusSocketAsServer(uint8_t socket)
+{
+	if(socketsAsServer&(0x0001<<socket))
+		return 1;
+	else
+		return 0;
+};
+
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkProvider.h	(revision 175)
@@ -0,0 +1,136 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILENETWORKPROVIDER_
+#define _GSM3MOBILENETWORKPROVIDER_
+
+#include <GSM3MobileAccessProvider.h>
+#include <inttypes.h>
+#include <stddef.h>
+#include <IPAddress.h>
+		
+class GSM3MobileNetworkProvider 
+{
+	private:
+	
+		/** Restart hardware
+			@return 1 if successful
+		 */
+		int HWrestart();
+		
+		uint16_t socketsAsServer; // Server socket
+		
+		/** Get modem status
+			@param s			Socket
+			@return modem status (true if connected)
+		 */
+		virtual inline bool getSocketAsServerModemStatus(int s){return false;};
+		
+	public:
+		
+		/** minSocketAsServer
+			@return 0
+		 */
+		virtual inline int minSocketAsServer(){return 0;};
+		
+		/** maxSocketAsServer
+			@return 0
+		 */
+		virtual inline int maxSocketAsServer(){return 0;};
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		virtual int ready()=0;
+		
+		/** Constructor */
+		GSM3MobileNetworkProvider();
+		
+		/** Get network status
+			@return network status
+		 */
+		virtual inline GSM3_NetworkStatus_t getStatus(){return ERROR;};
+		
+		/** Get socket client status
+			@param socket		Socket
+			@return 1 if connected, 0 otherwise
+		 */
+		bool getStatusSocketClient(uint8_t socket);
+
+		/** Close a AT command
+			@param code			Close code
+		 */
+		virtual inline void closeCommand(int code){};
+		
+		/** Establish a TCP connection
+			@param port				Port
+			@param localIP			IP address
+			@param localIPlength	IP address size in characters
+			@return	command error if exists
+		 */
+		virtual inline int connectTCPServer(int port, char* localIP, int localIPlength){return 0;};
+		
+		/** Get local IP address
+			@param LocalIP			Buffer for save IP address
+			@param LocalIPlength	Buffer size
+		 */
+		virtual inline int getIP(char* LocalIP, int LocalIPlength){return 0;};
+			
+		/** Get new occupied socket
+			@return -1 if no new socket has been occupied
+		 */
+		int getNewOccupiedSocketAsServer();
+		
+		/** Get socket status as server
+			@param socket			Socket to get status
+			@return socket status
+		 */
+		bool getStatusSocketAsServer(uint8_t socket);
+		
+		/** Close a socket
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		int disconnectTCP(bool client1Server0, int idsocket){return 1;};
+		
+		/** Release socket
+			@param socket		Socket
+		 */
+		void releaseSocket(int socket){};
+
+};
+
+extern GSM3MobileNetworkProvider* theProvider;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkRegistry.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkRegistry.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkRegistry.cpp	(revision 175)
@@ -0,0 +1,51 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3MobileNetworkRegistry.h>
+
+GSM3MobileNetworkRegistry::GSM3MobileNetworkRegistry()
+{
+	theProvider=0;
+};
+
+void GSM3MobileNetworkRegistry::registerMobileNetworkProvider(GSM3MobileNetworkProvider* provider)
+{
+	theProvider=provider;
+}
+
+GSM3MobileNetworkProvider* GSM3MobileNetworkRegistry::getMobileNetworkProvider()
+{
+	return theProvider;
+}
+
+GSM3MobileNetworkRegistry theMobileNetworkRegistry;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkRegistry.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkRegistry.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileNetworkRegistry.h	(revision 175)
@@ -0,0 +1,63 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILENETWORKREGISTRY_
+#define _GSM3MOBILENETWORKREGISTRY_
+#include <GSM3MobileNetworkProvider.h>
+
+class GSM3MobileNetworkRegistry
+{
+	private:
+		
+		GSM3MobileNetworkProvider* theProvider; // Network provider
+
+	public:
+	
+		/** Constructor */
+		GSM3MobileNetworkRegistry();
+		
+		/** Register in mobile network provider
+			@param provider			Provider
+		 */
+		void registerMobileNetworkProvider(GSM3MobileNetworkProvider* provider);
+			
+		/** Returns network provider object pointer
+			@return mobile network provider
+		 */
+		GSM3MobileNetworkProvider* getMobileNetworkProvider();
+	
+};
+
+extern GSM3MobileNetworkRegistry theMobileNetworkRegistry;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileSMSProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileSMSProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileSMSProvider.cpp	(revision 175)
@@ -0,0 +1,3 @@
+#include <GSM3MobileSMSProvider.h>
+
+GSM3MobileSMSProvider* theGSM3SMSProvider;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileSMSProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileSMSProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileSMSProvider.h	(revision 175)
@@ -0,0 +1,91 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILESMSPROVIDER_
+#define _GSM3MOBILESMSPROVIDER_
+
+class GSM3MobileSMSProvider
+{
+	public:
+		
+		/** Begin a SMS to send it
+			@param to			Destination
+			@return error command if it exists
+		 */
+		virtual inline int beginSMS(const char* to){return 0;};
+		
+		/** Write a SMS character by character
+			@param c			Character
+		 */
+		virtual inline void writeSMS(const char c){};
+		
+		/** End SMS
+			@return error command if it exists
+		 */
+		virtual inline int endSMS(){return 0;};
+		
+		/** Check if SMS available and prepare it to be read
+			@return number of bytes in a received SMS
+		 */
+		virtual inline int availableSMS(){return 0;};
+		
+		/** Read a byte but do not advance the buffer header (circular buffer)
+			@return character
+		 */
+		virtual inline int peekSMS(){return 0;};
+		
+		/** Delete the SMS from Modem memory and proccess answer
+		 */
+		virtual inline void flushSMS(){return;};
+		
+		/** Read sender number phone
+			@param number		Buffer for save number phone
+			@param nlength		Buffer length
+			@return 1 success, >1 error
+		 */
+		virtual inline int remoteSMSNumber(char* number, int nlength){return 0;}; 
+		
+		/** Read one char for SMS buffer (advance circular buffer)
+			@return character
+		 */
+		virtual inline int readSMS(){return 0;};
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		virtual int ready()=0;
+};
+
+extern GSM3MobileSMSProvider* theGSM3SMSProvider;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerProvider.cpp	(revision 175)
@@ -0,0 +1,5 @@
+ #include <GSM3MobileServerProvider.h>
+ 
+ GSM3MobileServerProvider* theGSM3MobileServerProvider;
+ 
+ 
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerProvider.h	(revision 175)
@@ -0,0 +1,95 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_MOBILESERVERPROVIDER__
+#define __GSM3_MOBILESERVERPROVIDER__
+
+
+#include <GSM3MobileAccessProvider.h>
+#include <inttypes.h>
+#include <stddef.h>
+		
+
+class GSM3MobileServerProvider
+{	
+		/** Get socket status
+			@param s			Socket
+			@return modem status (true if connected)
+		 */
+		virtual bool getSocketAsServerModemStatus(int s)=0;
+		
+	public:
+		
+		/** minSocketAsServer
+			@return socket
+		 */
+		virtual int minSocketAsServer()=0;
+		
+		/** maxSocketAsServer
+			@return socket
+		 */
+		virtual int maxSocketAsServer()=0;
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		virtual int ready()=0;
+		
+		/** Constructor */
+		GSM3MobileServerProvider(){};
+						
+		/** Connect server to TCP port
+			@param port			TCP port
+			@return	command error if exists
+		 */
+		virtual  int connectTCPServer(int port)=0;
+		//virtual  int getIP(char* LocalIP, int LocalIPlength)=0;
+				
+		/** Get new occupied socket as server
+			@return return -1 if no new socket has been occupied
+		 */
+		virtual int getNewOccupiedSocketAsServer()=0;
+		
+		/** Get socket status
+			@param socket		Socket
+			@return socket status (true if connected)
+		 */
+		virtual bool getStatusSocketAsServer(uint8_t socket)=0;
+		
+		// virtual int disconnectTCP(bool client1Server0, int idsocket)=0;
+
+};
+
+extern GSM3MobileServerProvider* theGSM3MobileServerProvider;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerService.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerService.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerService.cpp	(revision 175)
@@ -0,0 +1,159 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3MobileServerService.h>
+#include <GSM3MobileServerProvider.h>
+#include <GSM3MobileClientProvider.h>
+
+
+#define __TOUTSERVER__ 10000
+#define BUFFERSIZETWEET 100
+
+#define GSM3MOBILESERVERSERVICE_SYNCH 0x01 // 1: TRUE, compatible with other clients 0: FALSE
+
+// While there is only a shield (ShieldV1) we will include it by default
+#include <GSM3ShieldV1ServerProvider.h>
+GSM3ShieldV1ServerProvider theShieldV1ServerProvider;
+
+
+GSM3MobileServerService::GSM3MobileServerService(uint8_t port, bool synch)
+{
+	mySocket=0;
+	_port=port;
+	flags = 0;
+	
+	// If synchronous
+	if(synch)
+		flags |= GSM3MOBILESERVERSERVICE_SYNCH;
+}
+
+// Returns 0 if last command is still executing
+// 1 if success
+// >1 if error 
+int GSM3MobileServerService::ready()
+{	
+	return theGSM3MobileServerProvider->ready();
+}
+
+void GSM3MobileServerService::begin()
+{	
+	if(theGSM3MobileServerProvider==0)
+		return;
+	theGSM3MobileServerProvider->connectTCPServer(_port);
+	
+	if(flags & GSM3MOBILESERVERSERVICE_SYNCH)
+		waitForAnswer();
+}
+
+GSM3MobileClientService GSM3MobileServerService::available(bool synch)
+{	
+	int newSocket;
+	// In case we are debugging, we'll need to force a look at the buffer
+	ready();
+	
+	newSocket=theGSM3MobileServerProvider->getNewOccupiedSocketAsServer();
+	
+	// Instatiate new client. If we are synch, the client is synchronous/blocking
+	GSM3MobileClientService client((uint8_t)(newSocket), (flags & GSM3MOBILESERVERSERVICE_SYNCH));
+
+	return client;
+}
+
+size_t GSM3MobileServerService::write(uint8_t c)
+{
+// Adapt to the new, lean implementation	
+//	theGSM3MobileServerProvider->writeSocket(c);
+	return 1;
+}
+
+void GSM3MobileServerService::beginWrite()
+{
+// Adapt to the new, lean implementation
+//	theGSM3MobileServerProvider->beginWriteSocket(local1Remote0, mySocket);
+}
+
+size_t GSM3MobileServerService::write(const uint8_t* buf)
+{
+// Adapt to the new, lean implementation
+//	theGSM3MobileServerProvider->writeSocket((const char*)(buf));
+	return strlen((const char*)buf);
+}
+
+size_t GSM3MobileServerService::write(const uint8_t* buf, size_t sz)
+{
+// Adapt to the new, lean implementation
+//	theGSM3MobileServerProvider->writeSocket((const char*)(buf));
+}
+
+void GSM3MobileServerService::endWrite()
+{
+// Adapt to the new, lean implementation
+//	theGSM3MobileServerProvider->endWriteSocket();
+}
+
+void GSM3MobileServerService::stop()
+{
+	
+	// Review, should be the server?
+	theGSM3MobileClientProvider->disconnectTCP(local1Remote0, mySocket);
+	if(flags & GSM3MOBILESERVERSERVICE_SYNCH)
+		waitForAnswer();
+	theGSM3MobileClientProvider->releaseSocket(mySocket);
+	mySocket = -1;
+}
+
+
+/*int GSM3MobileServerService::getIP(char* LocalIP, int LocalIPlength)
+{
+	return theGSM3MobileServerProvider->getIP(LocalIP, LocalIPlength);
+}*/
+
+int GSM3MobileServerService::waitForAnswer()
+{
+	unsigned long m;
+	m=millis();
+	int res;
+	
+	while(((millis()-m)< __TOUTSERVER__ )&&(ready()==0)) 
+		delay(10);
+	
+	res=ready();
+
+	// If we get something different from a 1, we are having a problem
+	if(res!=1)
+		res=0;
+
+	return res;
+}
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerService.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerService.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileServerService.h	(revision 175)
@@ -0,0 +1,124 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILESERVERSERVICE_
+#define _GSM3MOBILESERVERSERVICE_
+
+#include <GSM3MobileNetworkProvider.h>
+#include <GSM3MobileClientService.h>
+#include <Server.h>
+
+class GSM3MobileServerService : public Server
+{
+	private:
+	
+		uint8_t _port; // Port
+		uint8_t mySocket; // Actual socket
+		uint8_t flags;
+		bool local1Remote0;
+	
+		/** Internal utility, used in synchronous calls
+			@return operation result, 1 if success, 0 otherwise
+		 */
+		int waitForAnswer();
+
+	public:
+		
+		/** Constructor
+			@param port			Port
+			@param synch		True if the server acts synchronously
+		 */
+		GSM3MobileServerService(uint8_t port, bool synch=true);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready();
+		
+		/** Initialize server
+		 */
+		void begin();
+		
+		/** Check if there is an incoming client request
+		  @param synch			If true, the returned client is synchronous or
+								blocking.
+		  @return Client if successful, else error
+		*/
+		GSM3MobileClientService available(bool synch=true);
+		
+		// Just to keep in line with Ethernet.
+		// Write to every open socket...
+		//void write(uint8_t);
+		//void write(const uint8_t *buf, size_t size);
+		
+		/** Begin write in socket
+		 */
+		void beginWrite();
+		
+		/** Write character in socket
+			@param c			Character
+			@return size
+		 */
+		size_t write(uint8_t c);
+		
+		/** Write buffer in socket
+			@param buf			Buffer
+			@return size
+		 */
+		size_t write(const uint8_t *buf);
+		
+		/** Write buffer in socket with size
+			@param buf			Buffer		
+			@param sz			Buffer size
+			@return size
+		 */
+		size_t write(const uint8_t *buf, size_t sz);
+		
+		/** End write in socket
+		 */
+		void endWrite();
+
+		/** Stop server
+		 */
+		void stop();
+		
+		// we take this function out as IPAddress is complex to bring to
+		// version 1.
+		// inline int connect(IPAddress ip, uint16_t port){return 0;};
+		// Returns 2 if there are no resources
+		//int getIP(char* LocalIP, int LocalIPlength);
+		
+};
+
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileVoiceProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileVoiceProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileVoiceProvider.cpp	(revision 175)
@@ -0,0 +1,4 @@
+#include <GSM3MobileVoiceProvider.h>
+
+
+GSM3MobileVoiceProvider* theGSM3MobileVoiceProvider;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileVoiceProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileVoiceProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3MobileVoiceProvider.h	(revision 175)
@@ -0,0 +1,90 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3MOBILEVOICEPROVIDER_
+#define _GSM3MOBILEVOICEPROVIDER_
+
+enum GSM3_voiceCall_st { IDLE_CALL, CALLING, RECEIVINGCALL, TALKING};
+
+class GSM3MobileVoiceProvider
+{
+	public:
+		
+		/** Initialize the object relating it to the general infrastructure
+			@param
+			@return void
+		*/
+		virtual void initialize(){};
+		
+		/** Launch a voice call
+			@param number	 	Phone number to be called
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		*/
+		virtual int voiceCall(const char* number)=0;
+		
+		/** Answer a voice call
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		*/
+		virtual int answerCall()=0;
+		
+		/** Hang a voice call
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		*/
+		virtual int hangCall()=0;
+		
+		/** Retrieve phone number of caller
+			@param buffer		Buffer for copy phone number
+			@param bufsize		Buffer size
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		*/
+		virtual int retrieveCallingNumber(char* buffer, int bufsize)=0;
+
+		/** Returns voice call status
+			@return voice call status
+		*/
+		virtual GSM3_voiceCall_st getvoiceCallStatus()=0;
+		
+		/**	Set voice call status
+			@param status		New status for voice call
+		*/
+		virtual void setvoiceCallStatus(GSM3_voiceCall_st status)=0;
+
+		/** Get last command status
+			@return Returns 0 if last command is still executing, 1 success, >1 error
+		*/
+		virtual int ready()=0;
+};
+
+extern GSM3MobileVoiceProvider* theGSM3MobileVoiceProvider;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SMSService.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SMSService.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SMSService.cpp	(revision 175)
@@ -0,0 +1,126 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3SMSService.h>
+#include <GSM3MobileNetworkProvider.h>
+#include <Arduino.h>
+
+// While there is only a shield (ShieldV1) we will include it by default
+#include <GSM3ShieldV1SMSProvider.h>
+GSM3ShieldV1SMSProvider theShieldV1SMSProvider;
+
+#define GSM3SMSSERVICE_SYNCH 0x01 // 1: synchronous 0: asynchronous
+#define __TOUT__ 10000
+
+
+GSM3SMSService::GSM3SMSService(bool synch)
+{
+	if(synch)
+		flags |= GSM3SMSSERVICE_SYNCH;
+}
+
+// Returns 0 if last command is still executing
+// 1 if success
+// >1 if error 
+int GSM3SMSService::ready()
+{	
+	return theGSM3SMSProvider->ready();
+}
+
+int GSM3SMSService::beginSMS(const char *number)
+{	
+	return waitForAnswerIfNeeded(theGSM3SMSProvider->beginSMS(number));
+};
+
+int GSM3SMSService::endSMS()
+{
+	return waitForAnswerIfNeeded(theGSM3SMSProvider->endSMS());
+};
+
+size_t GSM3SMSService::write(uint8_t c)
+{
+	theGSM3SMSProvider->writeSMS(c);
+	return 1;
+}
+
+void GSM3SMSService::flush()
+{		
+	theGSM3SMSProvider->flushSMS();
+	waitForAnswerIfNeeded(1);
+};
+
+int GSM3SMSService::available()
+{
+	return waitForAnswerIfNeeded(theGSM3SMSProvider->availableSMS());
+};
+
+int GSM3SMSService::remoteNumber(char* number, int nlength)
+{
+	return theGSM3SMSProvider->remoteSMSNumber(number, nlength);
+
+}
+
+int GSM3SMSService::read()
+{
+	return theGSM3SMSProvider->readSMS();
+};
+int GSM3SMSService::peek()
+{		
+	return theGSM3SMSProvider->peekSMS();
+};
+
+int GSM3SMSService::waitForAnswerIfNeeded(int returnvalue)
+{
+	// If synchronous
+	if(flags & GSM3SMSSERVICE_SYNCH )
+	{
+		unsigned long m;
+		m=millis();
+		// Wait for __TOUT__
+		while(((millis()-m)< __TOUT__ )&&(ready()==0)) 
+			delay(100);
+		// If everything was OK, return 1
+		// else (timeout or error codes) return 0;
+		if(ready()==1)
+			return 1;
+		else
+			return 0;
+	}
+	// If not synchronous just kick ahead the coming result
+	return ready();
+}
+
+
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SMSService.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SMSService.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SMSService.h	(revision 175)
@@ -0,0 +1,110 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3SMSSERVICE_
+#define _GSM3SMSSERVICE_
+
+#include <GSM3MobileSMSProvider.h>
+#include <Stream.h>
+
+class GSM3SMSService : public Stream 
+{
+	private:
+	
+		uint8_t flags;
+		
+		/** Makes synchronous the functions, if needed
+			@param returnvalue	Return value
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int waitForAnswerIfNeeded(int returnvalue);
+		
+	public:
+	
+		/** Constructor
+			@param synch		Determines sync mode
+		 */
+		GSM3SMSService(bool synch=true);
+		
+		/** Write a character in SMS message
+			@param c			Character
+			@return size
+		 */
+		size_t write(uint8_t c);
+		
+		/** Begin a SMS to send it
+			@param to			Destination
+			@return error command if it exists
+		 */
+		int beginSMS(const char* to);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready();
+		
+		/** End SMS
+			@return error command if it exists
+		 */
+		int endSMS();
+		
+		/** Check if SMS available and prepare it to be read
+			@return number of bytes in a received SMS
+		 */
+		int available();
+		
+		/** Read sender number phone
+			@param number		Buffer for save number phone
+			@param nlength		Buffer length
+			@return 1 success, >1 error
+		 */
+		int remoteNumber(char* number, int nlength); 
+		
+		/** Read one char for SMS buffer (advance circular buffer)
+			@return byte
+		 */
+		int read();
+		
+		/** Read a byte but do not advance the buffer header (circular buffer)
+			@return byte
+		 */
+		int peek();
+		
+		/** Delete the SMS from Modem memory and proccess answer
+		 */
+		void flush();
+
+};
+
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1.cpp	(revision 175)
@@ -0,0 +1,96 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3ShieldV1.h>
+#include <HardwareSerial.h>
+#include <Arduino.h>
+
+#define __RESETPIN__ 7
+#define __TOUTLOCALCOMS__ 500
+#define __TOUTSHUTDOWN__ 5000
+#define __TOUTMODEMCONFIGURATION__ 5000//equivalent to 30000 because of time in interrupt routine.
+#define __TOUTAT__ 1000
+#define __TOUTSMS__ 7000
+#define __TOUTCALL__ 15000
+#define __TOUTGPRS__ 10000
+#define __NCLIENTS_MAX__ 3
+
+//Constructor.
+GSM3ShieldV1::GSM3ShieldV1(bool db) 
+{
+	theGSM3ShieldV1ModemCore.setCommandCounter(1);
+	socketsAccepted=0;
+	theGSM3ShieldV1ModemCore.registerUMProvider(this);
+	theProvider=this;
+}
+
+//Response management.
+void GSM3ShieldV1::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case NONE:
+			theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from);
+			break;
+
+	}
+}
+
+//Function for 2 sec delay inside an interruption.
+void GSM3ShieldV1::delayInsideInterrupt2seg()
+{
+	for (int k=0;k<280;k++)  theGSM3ShieldV1ModemCore.gss.tunedDelay(50000); 
+} 
+
+///////////////////////////////////////////////////////UNSOLICITED RESULT CODE (URC) FUNCTIONS///////////////////////////////////////////////////////////////////
+
+//URC recognize.
+bool GSM3ShieldV1::recognizeUnsolicitedEvent(byte oldTail)
+{
+
+int nlength;
+char auxLocate [15];
+	//POWER DOWN.
+	prepareAuxLocate(PSTR("POWER DOWN"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		return true;
+	}
+	
+	
+	return false;
+}
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1.h	(revision 175)
@@ -0,0 +1,137 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SHIELDV1__
+#define __GSM3_SHIELDV1__
+
+#include <GSM3MobileNetworkProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <GSM3ShieldV1BaseProvider.h>
+#include <Arduino.h>
+
+
+class GSM3ShieldV1 : public GSM3MobileNetworkProvider, public GSM3ShieldV1BaseProvider
+{
+	// General code, for modem management
+	private:
+
+		/** Delay inside an interrupt (2 seconds)
+		 */
+		void delayInsideInterrupt2seg(); 
+		
+	// Code for SMS Service
+	private:
+
+
+		long commandMillis;
+		bool commandSent;
+		
+		const char* pinConfig;		//PIN.
+		char* accessPoint;			//APN.					
+		char* userName;				//User.
+		char* passw;				//Password.
+		const char* remoteID;		//Server.
+		
+		char* dataSocket;			//Data socket.
+		int local_Port;				//Local Port.
+		char* local_IP;				//Local IP.
+		int local_IP_Length;		//Local IP length.
+				
+		
+		int socketDataSize; 		//Size of socket data to be read.
+		int socketDataSizeWritten;  //Number of socket data written in buffer not to overflow the buffer
+				
+		int socketsAccepted;		//Status for remote clients accepted of closed.
+			
+	public:
+	
+		/** Constructor **/
+		GSM3ShieldV1(bool debug=false);
+
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		*/
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		/** Parse modem response
+			@param rsp			Returns true if expected response exists
+			@param string1		Substring expected in response
+			@param string2		Second substring expected in response
+			@return true if parsed successful
+		*/
+		bool genericParse_rsp2(bool& rsp, char* string1, char* string2);
+		
+		/** Recognize URC
+			@param oldTail		
+			@return true if successful
+		*/		
+		bool recognizeUnsolicitedEvent(byte oldTail);
+		
+		/** Receive answer
+			@return true if successful
+		*/		
+		bool answerReceived();
+		
+		/** Receive socket
+			@param id_socket	Socket ID
+			@return true if successful
+		*/		
+		bool socketReceived(int id_socket);
+		
+		/** Update active ID sockets
+			@param active		Active sockets
+			@param ID			Id for update
+		*/		
+		void update_activeIDsockets (bool active, int ID);
+		
+		/** Assign ID to socket
+			@param ID			Id to assign to socket
+			@return true if successful
+		*/		
+		bool assignIDsocket (int& ID);
+		
+		/** Close data socket
+			@return true if successful
+		*/		
+		bool closedDataSocket(); //Flag closed current data socket. 
+		
+		//bool writeIncomingCalls(char* bufferForCallerId) If isn't zero, doesn't wait calls
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1AccessProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1AccessProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1AccessProvider.cpp	(revision 175)
@@ -0,0 +1,323 @@
+#include <GSM3ShieldV1AccessProvider.h>
+#include <Arduino.h>
+#include "GSM3IO.h"
+
+#define __TOUTSHUTDOWN__ 5000
+#define __TOUTMODEMCONFIGURATION__ 5000//equivalent to 30000 because of time in interrupt routine.
+#define __TOUTAT__ 1000
+
+const char _command_AT[] PROGMEM = "AT";
+const char _command_CGREG[] PROGMEM = "AT+CGREG?";
+
+
+GSM3ShieldV1AccessProvider::GSM3ShieldV1AccessProvider(bool debug)
+{
+	theGSM3ShieldV1ModemCore.setDebug(debug);
+
+}
+
+void GSM3ShieldV1AccessProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case MODEMCONFIG:
+			ModemConfigurationContinue();
+			break;
+		case ALIVETEST:
+			isModemAliveContinue();
+			break;
+	}
+}
+
+///////////////////////////////////////////////////////CONFIGURATION FUNCTIONS///////////////////////////////////////////////////////////////////
+
+// Begin
+// Restart or start the modem
+// May be synchronous
+GSM3_NetworkStatus_t GSM3ShieldV1AccessProvider::begin(char* pin, bool restart, bool synchronous)
+{	
+	pinMode(__RESETPIN__, OUTPUT);
+
+	#ifdef TTOPEN_V1
+	pinMode(__POWERPIN__, OUTPUT);
+	digitalWrite(__POWERPIN__, HIGH);
+	#endif
+	// If asked for modem restart, restart
+	if (restart) 
+		HWrestart();
+	else 
+ 		HWstart();
+  
+	theGSM3ShieldV1ModemCore.gss.begin(9600);
+         
+	// Launch modem configuration commands
+	ModemConfiguration(pin);
+	// If synchronous, wait till ModemConfiguration is over
+	if(synchronous)
+	{
+		// if we shorten this delay, the command fails
+		while(ready()==0) 
+			delay(1000);
+	}
+	return getStatus();
+}
+
+//HWrestart.
+int GSM3ShieldV1AccessProvider::HWrestart()
+{
+	#ifdef TTOPEN_V1
+	digitalWrite(__POWERPIN__, HIGH);
+	delay(1000);
+	#endif
+	
+	theGSM3ShieldV1ModemCore.setStatus(IDLE);
+	digitalWrite(__RESETPIN__, HIGH);
+	delay(12000);
+	digitalWrite(__RESETPIN__, LOW);
+	delay(1000);
+	return 1; //configandwait(pin);
+}
+
+//HWrestart.
+int GSM3ShieldV1AccessProvider::HWstart()
+{
+
+	theGSM3ShieldV1ModemCore.setStatus(IDLE);
+	digitalWrite(__RESETPIN__, HIGH);
+	delay(2000);
+	digitalWrite(__RESETPIN__, LOW);
+	//delay(1000);
+
+	return 1; //configandwait(pin);
+}
+
+//Initial configuration main function.
+int GSM3ShieldV1AccessProvider::ModemConfiguration(char* pin)
+{
+	theGSM3ShieldV1ModemCore.setPhoneNumber(pin);
+	theGSM3ShieldV1ModemCore.openCommand(this,MODEMCONFIG);
+	theGSM3ShieldV1ModemCore.setStatus(CONNECTING);
+	ModemConfigurationContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Initial configuration continue function.
+void GSM3ShieldV1AccessProvider::ModemConfigurationContinue()
+{
+	bool resp;
+
+	// 1: Send AT
+	// 2: Wait AT OK and SetPin or CGREG
+	// 3: Wait Pin OK and CGREG
+	// 4: Wait CGREG and Flow SW control or CGREG
+	// 5: Wait IFC OK and SMS Text Mode
+	// 6: Wait SMS text Mode OK and Calling line identification
+	// 7: Wait Calling Line Id OK and Echo off
+	// 8: Wait for OK and COLP command for connecting line identification.
+	// 9: Wait for OK.
+	int ct=theGSM3ShieldV1ModemCore.getCommandCounter();
+	if(ct==1)
+	{
+		// Launch AT	
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_AT);
+	}
+	else if(ct==2)
+	{
+		// Wait for AT - OK.
+	   if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	   {
+			if(resp)
+			{ 
+				// OK received
+				if(theGSM3ShieldV1ModemCore.getPhoneNumber() && (theGSM3ShieldV1ModemCore.getPhoneNumber()[0]!=0)) 
+					{
+						theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CPIN="), false);
+						theGSM3ShieldV1ModemCore.setCommandCounter(3);
+						theGSM3ShieldV1ModemCore.genericCommand_rqc(theGSM3ShieldV1ModemCore.getPhoneNumber());
+					}
+				else 
+					{
+						//DEBUG	
+						//SerialUSB.println("AT+CGREG?");	
+						theGSM3ShieldV1ModemCore.setCommandCounter(4);
+						theGSM3ShieldV1ModemCore.takeMilliseconds();
+						theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGREG);
+					}
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==3)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				theGSM3ShieldV1ModemCore.setCommandCounter(4);
+				theGSM3ShieldV1ModemCore.takeMilliseconds();
+				theGSM3ShieldV1ModemCore.delayInsideInterrupt(2000);
+				theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGREG);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+	    }
+	}
+	else if(ct==4)
+	{
+		char auxLocate1 [12];
+		char auxLocate2 [12];
+		prepareAuxLocate(PSTR("+CGREG: 0,1"), auxLocate1);
+		prepareAuxLocate(PSTR("+CGREG: 0,5"), auxLocate2);
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, auxLocate1, auxLocate2))
+		{
+			if(resp)
+			{
+				theGSM3ShieldV1ModemCore.setCommandCounter(5);
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+IFC=1,1"));
+			}
+			else
+			{
+				// If not, launch command again
+				if(theGSM3ShieldV1ModemCore.takeMilliseconds() > __TOUTMODEMCONFIGURATION__)
+				{
+					theGSM3ShieldV1ModemCore.closeCommand(3);
+				}
+				else 
+				{
+					theGSM3ShieldV1ModemCore.delayInsideInterrupt(2000);
+					theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGREG);
+				}
+			}
+		}	
+	}
+	else if(ct==5)
+	{
+		// 5: Wait IFC OK
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			//Delay for SW flow control being active.
+			theGSM3ShieldV1ModemCore.delayInsideInterrupt(2000);
+			// 9: SMS Text Mode
+			theGSM3ShieldV1ModemCore.setCommandCounter(6);
+			theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGF=1"));
+		}
+	}
+	else if(ct==6)
+	{
+		// 6: Wait SMS text Mode OK
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			//Calling line identification
+			theGSM3ShieldV1ModemCore.setCommandCounter(7);			
+			theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CLIP=1"));
+		}
+	}
+	else if(ct==7)
+	{
+		// 7: Wait Calling Line Id OK
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			// Echo off
+			theGSM3ShieldV1ModemCore.setCommandCounter(8);			
+			theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATE0"));
+		}
+	}
+	else if(ct==8)
+	{
+		// 8: Wait ATEO OK, send COLP
+		// In Arduino Mega, attention, take away the COLP step
+		// It looks as we can only have 8 steps
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			theGSM3ShieldV1ModemCore.setCommandCounter(9);
+			theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+COLP=1"));
+		}
+	}
+	else if(ct==9)
+	{
+		// 9: Wait ATCOLP OK
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			if (resp) 
+				{
+					theGSM3ShieldV1ModemCore.setStatus(GSM_READY);
+					theGSM3ShieldV1ModemCore.closeCommand(1);
+				}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+ 	}
+}
+
+//Alive Test main function.
+int GSM3ShieldV1AccessProvider::isAccessAlive()
+{
+	theGSM3ShieldV1ModemCore.setCommandError(0);
+	theGSM3ShieldV1ModemCore.setCommandCounter(1);
+	theGSM3ShieldV1ModemCore.openCommand(this,ALIVETEST);
+	isModemAliveContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Alive Test continue function.
+void GSM3ShieldV1AccessProvider::isModemAliveContinue()
+{
+bool rsp;
+switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_AT);
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+      break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(rsp))
+		{
+			if (rsp) theGSM3ShieldV1ModemCore.closeCommand(1);
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+      break;
+	}
+}
+
+//Shutdown.
+bool GSM3ShieldV1AccessProvider::shutdown()
+{
+	unsigned long m;
+	bool resp;
+	char auxLocate [18];
+	
+	// It makes no sense to have an asynchronous shutdown
+	pinMode(__RESETPIN__, OUTPUT);
+	digitalWrite(__RESETPIN__, HIGH);
+	delay(1500);
+	digitalWrite(__RESETPIN__, LOW);
+	theGSM3ShieldV1ModemCore.setStatus(IDLE);
+	theGSM3ShieldV1ModemCore.gss.close();
+	
+	m=millis();
+	prepareAuxLocate(PSTR("POWER DOWN"), auxLocate);
+	while((millis()-m) < __TOUTSHUTDOWN__)
+	{
+		delay(1);
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, auxLocate))
+			return resp;
+	}
+	return false;
+}
+
+//Secure shutdown.
+bool GSM3ShieldV1AccessProvider::secureShutdown()
+{
+	// It makes no sense to have an asynchronous shutdown
+	pinMode(__RESETPIN__, OUTPUT);
+	digitalWrite(__RESETPIN__, HIGH);
+	delay(900);
+	digitalWrite(__RESETPIN__, LOW);
+	theGSM3ShieldV1ModemCore.setStatus(OFF);
+	theGSM3ShieldV1ModemCore.gss.close();
+
+#ifdef TTOPEN_V1
+	_delay_ms(12000);
+	digitalWrite(__POWERPIN__, LOW);
+#endif
+	
+	return true;
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1AccessProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1AccessProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1AccessProvider.h	(revision 175)
@@ -0,0 +1,121 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3SHIELDV1ACCESSPROVIDER_
+#define _GSM3SHIELDV1ACCESSPROVIDER_
+
+#include <GSM3MobileAccessProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <GSM3ShieldV1BaseProvider.h>
+
+class GSM3ShieldV1AccessProvider : public GSM3MobileAccessProvider, public GSM3ShieldV1BaseProvider
+{
+	private:
+
+		/** Initialize main modem configuration
+			@param pin			PIN code
+			@return command error if exists
+		 */
+		int ModemConfiguration(char* pin);
+		
+		/** Continue to modem configuration function
+		 */
+		void ModemConfigurationContinue();
+		
+		/** Continue to check if modem alive function
+		 */
+		void isModemAliveContinue();
+		
+
+	public:
+	
+		/** Constructor
+			@param debug		Determines debug mode
+		 */
+		
+		GSM3ShieldV1AccessProvider(bool debug=false);
+		
+		/** Start the GSM/GPRS modem, attaching to the GSM network
+			@param pin 			SIM PIN number (4 digits in a string, example: "1234"). If 
+								NULL the SIM has no configured PIN.
+			@param restart		Restart the modem. Default is TRUE. The modem receives
+								a signal through the Ctrl/D7 pin. If it is shut down, it will
+								start-up. If it is running, it will restart. Takes up to 10 
+								seconds
+			@param synchronous	If TRUE the call only returns after the Start is complete 
+								or fails. If FALSE the call will return inmediately. You have
+								to call repeatedly ready() until you get a result. Default is TRUE.
+			@return If synchronous, GSM3_NetworkStatus_t. If asynchronous, returns 0.
+		*/
+		GSM3_NetworkStatus_t begin(char* pin=0,bool restart=true, bool synchronous=true);
+		
+		/** Check network access status
+			@return 1 if Alive, 0 if down
+		*/
+		int isAccessAlive();
+		
+		/** Shutdown the modem (power off really)
+			@return true if successful
+		*/
+		bool shutdown();
+		
+		/** Secure shutdown the modem (power off really)
+			@return true if successful
+		 */
+		bool secureShutdown();
+		
+		/** Returns 0 if last command is still executing
+			@return 1 if success, >1 if error 
+		*/
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		/** Returns modem status
+			@return modem network status 
+		*/
+		inline GSM3_NetworkStatus_t getStatus(){return theGSM3ShieldV1ModemCore.getStatus();};
+
+		void manageResponse(byte from, byte to);
+
+		/** Restart the modem (will shut down if running)
+			@return 1 if success, >1 if error 
+		*/		
+		int HWrestart();
+		
+		/** Start the modem (will not shut down if running)
+			@return 1 if success, >1 if error 
+		*/		
+		int HWstart();
+
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BandManagement.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BandManagement.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BandManagement.cpp	(revision 175)
@@ -0,0 +1,67 @@
+#include <GSM3ShieldV1BandManagement.h>
+
+GSM3ShieldV1BandManagement::GSM3ShieldV1BandManagement(bool trace): modem(trace)
+{
+	quectelStrings[UNDEFINED]="";
+	quectelStrings[EGSM_MODE]="\"EGSM_MODE\"";
+	quectelStrings[DCS_MODE]="\"DCS_MODE\"";
+	quectelStrings[PCS_MODE]="\"PCS_MODE\"";
+	quectelStrings[EGSM_DCS_MODE]="\"EGSM_DCS_MODE\"";
+	quectelStrings[GSM850_PCS_MODE]="\"GSM850_PCS_MODE\"";
+	quectelStrings[GSM850_EGSM_DCS_PCS_MODE]="\"GSM850_EGSM_DCS_PCS_MODE\"";	
+}
+
+GSM3_NetworkStatus_t GSM3ShieldV1BandManagement::begin()
+{
+	// check modem response
+	modem.begin();
+
+	// reset hardware
+	modem.restartModem();
+
+	return IDLE;
+}
+
+String GSM3ShieldV1BandManagement::getBand()
+{
+  String modemResponse=modem.writeModemCommand("AT+QBAND?", 2000);
+	
+  for(GSM3GSMBand i=GSM850_EGSM_DCS_PCS_MODE;i>UNDEFINED;i=(GSM3GSMBand)((int)i-1))
+  {
+    if(modemResponse.indexOf(quectelStrings[i])>=0)
+      return quectelStrings[i];
+  }
+
+  SerialUSB.print("Unrecognized modem answer:");
+  SerialUSB.println(modemResponse);
+  
+  return "";
+}
+
+bool GSM3ShieldV1BandManagement::setBand(String band)
+{
+	String command;
+	String modemResponse;
+	bool found=false;
+
+	command="AT+QBAND=";
+	for(GSM3GSMBand i=EGSM_MODE;((i<=GSM850_EGSM_DCS_PCS_MODE)&&(!found));i=(GSM3GSMBand)((int)i+1))
+	{
+		String aux=quectelStrings[i];
+		if(aux.indexOf(band)>=0)
+		{
+		    command+=aux;
+			found=true;
+		}
+	}
+	
+	if(!found)
+		return false;
+	// Quad-band takes an awful lot of time
+    modemResponse=modem.writeModemCommand(command, 15000);
+	
+	if(modemResponse.indexOf("QBAND")>=0)
+      return true;
+	else
+		return false;
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BandManagement.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BandManagement.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BandManagement.h	(revision 175)
@@ -0,0 +1,96 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3SHIELDV1BANDMANAGEMENT__
+#define __GSM3SHIELDV1BANDMANAGEMENT__
+
+// This class executes band management functions for the ShieldV1
+#include <GSM3ShieldV1DirectModemProvider.h>
+
+#define NUMBEROFBANDS 7
+#define GSM_MODE_UNDEFINED "UNDEFINED"
+#define GSM_MODE_EGSM "EGSM_MODE"
+#define GSM_MODE_DCS "DCS_MODE"
+#define GSM_MODE_PCS "PCS_MODE"
+#define GSM_MODE_EGSM_DCS "EGSM_DCS_MODE"
+#define GSM_MODE_GSM850_PCS "GSM850_PCS_MODE"
+#define GSM_MODE_GSM850_EGSM_DCS_PCS "GSM850_EGSM_DCS_PCS_MODE"
+
+typedef enum GSM3GSMBand {UNDEFINED, EGSM_MODE, DCS_MODE, PCS_MODE, EGSM_DCS_MODE, GSM850_PCS_MODE, GSM850_EGSM_DCS_PCS_MODE};
+
+// 
+// These are the bands and scopes:
+//
+//	E-GSM(900)
+//  DCS(1800)
+//  PCS(1900)
+//	E-GSM(900)+DCS(1800) ex: Europe
+//	GSM(850)+PCS(1900) Ex: USA, South Am.
+//	GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)
+
+class GSM3ShieldV1BandManagement
+{
+	private:
+	
+		GSM3ShieldV1DirectModemProvider modem; // Direct access to modem
+		
+		char* quectelStrings[NUMBEROFBANDS];// = {"\"EGSM_MODE\"", "\"DCS_MODE\"", "\"PCS_MODE\"",
+								//"\"EGSM_DCS_MODE\"", "\"GSM850_PCS_MODE\"", 
+								//"\"GSM850_EGSM_DCS_PCS_MODE\""};
+
+
+	public:
+	
+		/** Constructor
+			@param trace		If true, dumps all AT dialogue to Serial
+		 */
+		GSM3ShieldV1BandManagement(bool trace=false);
+		
+		/** Forces modem hardware restart, so we begin from scratch
+			@return always returns IDLE status
+		 */
+		GSM3_NetworkStatus_t begin();
+
+		/** Get current modem work band 
+			@return current modem work band
+		 */		
+		String getBand();
+
+		/** Changes the modem operating band 
+			@param band			Desired new band
+			@return true if success, false otherwise
+		 */			
+		bool setBand(String band);
+			
+};
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BaseProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BaseProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BaseProvider.cpp	(revision 175)
@@ -0,0 +1,27 @@
+#include <GSM3ShieldV1BaseProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <Arduino.h>
+
+// Returns 0 if last command is still executing
+// 1 if success
+// >1 if error 
+int GSM3ShieldV1BaseProvider::ready() 
+{
+	theGSM3ShieldV1ModemCore.manageReceivedData();
+
+	return theGSM3ShieldV1ModemCore.getCommandError();
+};
+
+void GSM3ShieldV1BaseProvider::prepareAuxLocate(PGM_P str, char auxLocate[])
+{
+	int i=0;
+	char c;
+
+	do
+	{	
+		c=pgm_read_byte_near(str + i); 
+		auxLocate[i]=c;
+		i++;
+	} while (c!=0);
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BaseProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BaseProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1BaseProvider.h	(revision 175)
@@ -0,0 +1,73 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3SHIELDV1BASEPROVIDER_
+#define _GSM3SHIELDV1BASEPROVIDER_
+
+#include <GSM3SoftSerial.h>
+
+enum GSM3_commandType_e { XON, NONE, MODEMCONFIG, ALIVETEST, BEGINSMS, ENDSMS, AVAILABLESMS, FLUSHSMS,
+	VOICECALL, ANSWERCALL, HANGCALL, RETRIEVECALLINGNUMBER, 
+	ATTACHGPRS, DETACHGPRS, CONNECTTCPCLIENT, DISCONNECTTCP, BEGINWRITESOCKET, ENDWRITESOCKET, 
+	AVAILABLESOCKET, FLUSHSOCKET, CONNECTSERVER, GETIP, GETCONNECTSTATUS, GETLOCATION, GETICCID}; 
+
+class GSM3ShieldV1BaseProvider
+{
+	public:
+
+	/** Get last command status
+		@return Returns 0 if last command is still executing, 1 success, >1 error
+	*/
+	int ready();
+
+	/** This function locates strings from PROGMEM in the buffer
+		@param str			PROGMEN
+		@param auxLocate	Buffer where to locate strings
+	*/
+	void prepareAuxLocate(PGM_P str, char auxLocate[]);
+
+	/** Manages modem response
+		@param from 		Initial byte of buffer
+		@param to 			Final byte of buffer
+	*/
+	virtual void manageResponse(byte from, byte to);
+	
+	/** Recognize URC
+		@param from		
+		@return true if successful (default: false)
+	*/		
+	virtual bool recognizeUnsolicitedEvent(byte from){return false;};
+
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1CellManagement.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1CellManagement.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1CellManagement.cpp	(revision 175)
@@ -0,0 +1,168 @@
+#include <GSM3ShieldV1CellManagement.h>
+
+GSM3ShieldV1CellManagement::GSM3ShieldV1CellManagement()
+{
+}
+
+bool GSM3ShieldV1CellManagement::parseQCCID_available(bool& rsp)
+{
+	char c;
+	bool iccidFound = false;
+	int i = 0;
+	
+	while(((c = theGSM3ShieldV1ModemCore.theBuffer().read()) != 0) & (i < 19))
+	{
+		if((c < 58) & (c > 47))
+			iccidFound = true;
+		
+		if(iccidFound)
+		{
+			bufferICCID[i] = c;
+			i++;
+		}
+	}
+	bufferICCID[i]=0;
+	
+	return true;
+}			
+
+bool GSM3ShieldV1CellManagement::parseQENG_available(bool& rsp)
+{
+	char c;
+	char location[50] = "";
+	int i = 0;
+	
+	if (!(theGSM3ShieldV1ModemCore.theBuffer().chopUntil("+QENG: ", true)))
+		rsp = false;
+	else 
+		rsp = true;
+	
+	if (!(theGSM3ShieldV1ModemCore.theBuffer().chopUntil("+QENG:", true)))
+		rsp = false;
+	else 
+		rsp = true;
+	
+	while(((c = theGSM3ShieldV1ModemCore.theBuffer().read()) != 0) & (i < 50))
+	{
+		location[i] = c;
+		i++;
+	}
+	location[i]=0;
+	
+	char* res_tok = strtok(location, ",");
+	res_tok=strtok(NULL, ",");
+	strcpy(countryCode, res_tok);
+	res_tok=strtok(NULL, ",");
+	strcpy(networkCode, res_tok);
+	res_tok=strtok(NULL, ",");
+	strcpy(locationArea, res_tok);
+	res_tok=strtok(NULL, ",");
+	strcpy(cellId, res_tok);
+	
+	return true;
+}			
+
+int GSM3ShieldV1CellManagement::getLocation(char *country, char *network, char *area, char *cell)
+{
+	if((theGSM3ShieldV1ModemCore.getStatus() != GSM_READY) && (theGSM3ShieldV1ModemCore.getStatus() != GPRS_READY))
+		return 2;
+	
+	countryCode=country;
+	networkCode=network;
+	locationArea=area;
+	cellId=cell;
+	
+	theGSM3ShieldV1ModemCore.openCommand(this,GETLOCATION);
+	getLocationContinue();
+	
+	unsigned long timeOut = millis();
+	while(((millis() - timeOut) < 5000) & (ready() == 0));
+
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+void GSM3ShieldV1CellManagement::getLocationContinue()
+{
+	bool resp;
+	
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		theGSM3ShieldV1ModemCore.gss.tunedDelay(21000);
+		delay(3000);
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QENG=1"), false);
+		theGSM3ShieldV1ModemCore.print("\r");
+		break;
+	case 2:
+		if (theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			theGSM3ShieldV1ModemCore.gss.tunedDelay(21000);
+			delay(3000);
+			theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QENG?"), false);
+			theGSM3ShieldV1ModemCore.print("\r");
+		}
+		else theGSM3ShieldV1ModemCore.closeCommand(1);
+		break;
+	case 3:
+		if (resp)
+		{
+			parseQENG_available(resp);
+			theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		else theGSM3ShieldV1ModemCore.closeCommand(2);
+		break;
+	}
+}
+
+int GSM3ShieldV1CellManagement::getICCID(char *iccid)
+{
+	if((theGSM3ShieldV1ModemCore.getStatus() != GSM_READY) && (theGSM3ShieldV1ModemCore.getStatus() != GPRS_READY))
+		return 2;
+	
+	bufferICCID=iccid;
+	theGSM3ShieldV1ModemCore.openCommand(this,GETICCID);
+	getICCIDContinue();
+	
+	unsigned long timeOut = millis();
+	while(((millis() - timeOut) < 5000) & (ready() == 0));
+		
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+void GSM3ShieldV1CellManagement::getICCIDContinue()
+{
+	bool resp;
+	
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QCCID"), false);
+		theGSM3ShieldV1ModemCore.print("\r");
+		break;
+	case 2:
+		if (theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			parseQCCID_available(resp);
+			theGSM3ShieldV1ModemCore.closeCommand(2);
+		}
+		else theGSM3ShieldV1ModemCore.closeCommand(1);
+		break;
+	}
+}
+
+void GSM3ShieldV1CellManagement::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case NONE:
+			theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from);
+			break;
+		case GETLOCATION:
+			getLocationContinue();
+			break;
+		case GETICCID:
+			getICCIDContinue();
+			break;
+	}
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1CellManagement.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1CellManagement.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1CellManagement.h	(revision 175)
@@ -0,0 +1,92 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SHIELDV1CELLMANAGEMENT__
+#define __GSM3_SHIELDV1CELLMANAGEMENT__
+
+#include <GSM3ShieldV1ModemCore.h>
+#include <GSM3MobileCellManagement.h>
+#include <GSM3ShieldV1CellManagement.h>
+
+class GSM3ShieldV1CellManagement : public GSM3MobileCellManagement, public GSM3ShieldV1BaseProvider
+{		
+	public:
+	
+		/** Constructor
+		*/
+		GSM3ShieldV1CellManagement();
+
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+		
+		/** getLocation
+		 @return current cell location
+		*/		
+		int getLocation(char *country, char *network, char *area, char *cell);
+		
+		/** getICCID
+		*/
+		int getICCID(char *iccid);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+
+	private:	
+	
+		char *countryCode;
+		char *networkCode;
+		char *locationArea;
+		char *cellId;
+		
+		char *bufferICCID;
+	
+		/** Continue to getLocation function
+		 */
+		void getLocationContinue();
+		
+		/** Continue to getICCID function
+		 */
+		void getICCIDContinue();
+		
+		bool parseQENG_available(bool& rsp);
+		
+		bool parseQCCID_available(bool& rsp);
+		
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ClientProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ClientProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ClientProvider.cpp	(revision 175)
@@ -0,0 +1,294 @@
+#include <GSM3ShieldV1ClientProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+
+GSM3ShieldV1ClientProvider::GSM3ShieldV1ClientProvider()
+{
+	theGSM3MobileClientProvider=this;
+};
+
+//Response management.
+void GSM3ShieldV1ClientProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case NONE:
+			theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from);
+			break;
+		case CONNECTTCPCLIENT:
+			connectTCPClientContinue();
+			break;
+		case FLUSHSOCKET:
+			flushSocketContinue();
+			break;	
+	}
+}
+
+//Connect TCP main function.
+int GSM3ShieldV1ClientProvider::connectTCPClient(const char* server, int port, int id_socket)
+{
+	theGSM3ShieldV1ModemCore.setPort(port);		
+	idSocket = id_socket;
+	
+	theGSM3ShieldV1ModemCore.setPhoneNumber((char*)server);
+	theGSM3ShieldV1ModemCore.openCommand(this,CONNECTTCPCLIENT);
+	theGSM3ShieldV1ModemCore.registerUMProvider(this);
+	connectTCPClientContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();	
+}
+
+int GSM3ShieldV1ClientProvider::connectTCPClient(IPAddress add, int port, int id_socket)
+{
+	remoteIP=add;
+	theGSM3ShieldV1ModemCore.setPhoneNumber(0);
+	return connectTCPClient(0, port, id_socket);
+}
+
+//Connect TCP continue function.
+void GSM3ShieldV1ClientProvider::connectTCPClientContinue()
+{
+	bool resp;
+	// 0: Dot or DNS notation activation
+	// 1: Disable SW flow control 
+	// 2: Waiting for IFC OK
+	// 3: Start-up TCP connection "AT+QIOPEN"
+	// 4: Wait for connection OK
+	// 5: Wait for CONNECT
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIDNSIP="), false);
+		if ((theGSM3ShieldV1ModemCore.getPhoneNumber()!=0)&&
+			((*(theGSM3ShieldV1ModemCore.getPhoneNumber())<'0')||((*(theGSM3ShieldV1ModemCore.getPhoneNumber())>'9'))))
+		{
+			theGSM3ShieldV1ModemCore.print('1');
+			theGSM3ShieldV1ModemCore.print('\r');
+		}
+		else 
+		{
+			theGSM3ShieldV1ModemCore.print('0');
+			theGSM3ShieldV1ModemCore.print('\r');
+		}
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			//Response received
+			if(resp)
+			{				
+				// AT+QIOPEN
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIOPEN="),false);
+				theGSM3ShieldV1ModemCore.print("\"TCP\",\"");
+				if(theGSM3ShieldV1ModemCore.getPhoneNumber()!=0)
+				{
+					theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber());
+				}
+				else
+				{
+					remoteIP.printTo(theGSM3ShieldV1ModemCore);
+				}
+				theGSM3ShieldV1ModemCore.print('"');
+				theGSM3ShieldV1ModemCore.print(',');
+				theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPort());
+				theGSM3ShieldV1ModemCore.print('\r');
+				theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;
+	
+	case 3:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			// Response received
+			if(resp)
+			{
+				// OK Received
+				// Great. Go for the next step
+				theGSM3ShieldV1ModemCore.setCommandCounter(4);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;
+	case 4:
+		char auxLocate [12];
+		prepareAuxLocate(PSTR("CONNECT\r\n"), auxLocate);
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp,auxLocate))
+	    {
+			// Response received
+			if(resp)
+			{
+				// Received CONNECT OK
+				// Great. We're done
+				theGSM3ShieldV1ModemCore.setStatus(TRANSPARENT_CONNECTED);
+				theGSM3ShieldV1ModemCore.theBuffer().chopUntil(auxLocate, true);
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			}
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}		
+		break;
+		
+	}
+}
+
+//Disconnect TCP main function.
+int GSM3ShieldV1ClientProvider::disconnectTCP(bool client1Server0, int id_socket)
+{		
+	// id Socket does not really mean anything, in this case we have
+	// only one socket running
+	theGSM3ShieldV1ModemCore.openCommand(this,DISCONNECTTCP);
+	
+	// If we are not closed, launch the command
+//[ZZ]	if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED)
+//	{
+		delay(1000);
+		theGSM3ShieldV1ModemCore.print("+++");
+		delay(1000);
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QICLOSE"));
+		theGSM3ShieldV1ModemCore.setStatus(GPRS_READY);
+//	}
+	// Looks like it runs everytime, so we simply flush to death and go on
+	do
+	{
+		// Empty the local buffer, and tell the modem to XON
+		// If meanwhile we receive a DISCONNECT we should detect it as URC.
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		// Give some time for the buffer to refill
+		delay(100);
+		theGSM3ShieldV1ModemCore.closeCommand(1);
+	}while(theGSM3ShieldV1ModemCore.theBuffer().storedBytes()>0);
+
+	theGSM3ShieldV1ModemCore.unRegisterUMProvider(this);
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+
+//Write socket first chain main function.
+void GSM3ShieldV1ClientProvider::beginWriteSocket(bool client1Server0, int id_socket)
+{
+}
+
+
+//Write socket next chain function.
+void GSM3ShieldV1ClientProvider::writeSocket(const char* buf)
+{
+	if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED)
+		theGSM3ShieldV1ModemCore.print(buf);
+}
+
+//Write socket character function.
+void GSM3ShieldV1ClientProvider::writeSocket(uint8_t c)
+{
+	if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED)
+		theGSM3ShieldV1ModemCore.print((char)c);
+}
+
+//Write socket last chain main function.
+void GSM3ShieldV1ClientProvider::endWriteSocket()
+{		
+}
+
+
+//Available socket main function.
+int GSM3ShieldV1ClientProvider::availableSocket(bool client1Server0, int id_socket)
+{
+		
+	if(!(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED))
+		theGSM3ShieldV1ModemCore.closeCommand(4);
+		
+	if(theGSM3ShieldV1ModemCore.theBuffer().storedBytes())
+		theGSM3ShieldV1ModemCore.closeCommand(1);
+	else
+		theGSM3ShieldV1ModemCore.closeCommand(4);
+		
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+int GSM3ShieldV1ClientProvider::readSocket()
+{
+	char charSocket;
+		
+	if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==0)
+	{
+		return 0;
+	}
+	
+	charSocket = theGSM3ShieldV1ModemCore.theBuffer().read(); 
+	
+	if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==100)
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+
+	return charSocket;
+
+}
+
+//Read socket main function.
+int GSM3ShieldV1ClientProvider::peekSocket()
+{
+	return theGSM3ShieldV1ModemCore.theBuffer().peek(0); 
+}
+
+
+//Flush SMS main function.
+void GSM3ShieldV1ClientProvider::flushSocket()
+{
+	theGSM3ShieldV1ModemCore.openCommand(this,FLUSHSOCKET);
+
+	flushSocketContinue();
+}
+
+//Send SMS continue function.
+void GSM3ShieldV1ClientProvider::flushSocketContinue()
+{
+	// If we have incomed data
+	if(theGSM3ShieldV1ModemCore.theBuffer().storedBytes()>0)
+	{
+		// Empty the local buffer, and tell the modem to XON
+		// If meanwhile we receive a DISCONNECT we should detect it as URC.
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+	}
+	else 
+	{
+		//We're done		
+		theGSM3ShieldV1ModemCore.closeCommand(1);
+	}
+}
+
+// URC recognize.
+// Yes, we recognize "closes" in client mode
+bool GSM3ShieldV1ClientProvider::recognizeUnsolicitedEvent(byte oldTail)
+{
+	char auxLocate [12];
+	prepareAuxLocate(PSTR("CLOSED"), auxLocate);
+
+	if((theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED) & theGSM3ShieldV1ModemCore.theBuffer().chopUntil(auxLocate, false, false))
+	{
+		theGSM3ShieldV1ModemCore.setStatus(GPRS_READY);
+		theGSM3ShieldV1ModemCore.unRegisterUMProvider(this);
+		return true;
+	}
+		
+	return false;
+}
+
+int GSM3ShieldV1ClientProvider::getSocket(int socket)
+{
+	return 0;
+}
+
+void GSM3ShieldV1ClientProvider::releaseSocket(int socket)
+{
+
+}
+
+bool GSM3ShieldV1ClientProvider::getStatusSocketClient(uint8_t socket)
+{
+	return (theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED);
+
+};
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ClientProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ClientProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ClientProvider.h	(revision 175)
@@ -0,0 +1,181 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SHIELDV1CLIENTPROVIDER__
+#define __GSM3_SHIELDV1CLIENTPROVIDER__
+
+#include <GSM3MobileClientProvider.h>
+#include <GSM3ShieldV1BaseProvider.h>
+
+class GSM3ShieldV1ClientProvider : public GSM3MobileClientProvider,  public GSM3ShieldV1BaseProvider
+{
+	private:
+	
+		int remotePort;				//Current operation remote port.
+		IPAddress remoteIP;        	// Remote IP address
+		int idSocket;				// Remote ID socket.
+
+
+		/** Continue to connect TCP client function
+		 */
+		void connectTCPClientContinue();
+		
+		/** Continue to available socket function
+		 */
+		void availableSocketContinue();
+		
+		/** Continue to flush socket function
+		 */
+		void flushSocketContinue();
+		
+	public:
+	
+		/** Constructor */
+		GSM3ShieldV1ClientProvider();
+		
+		/** minSocket
+			@return 0
+		 */
+		int minSocket(){return 0;};
+		
+		/** maxSocket
+			@return 0
+		 */
+		int maxSocket(){return 0;};
+		
+		/** Connect to a remote TCP server
+			@param server		String with IP or server name
+			@param port 		Remote port number
+			@param id_socket	Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		int connectTCPClient(const char* server, int port, int id_socket);
+		
+		/** Connect to a remote TCP server
+			@param add			Remote IP address
+			@param port 		Remote port number
+			@param id_socket	Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		int connectTCPClient(IPAddress add, int port, int id_socket);
+
+		/** Begin writing through a socket
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		void beginWriteSocket(bool client1Server0, int id_socket);
+
+		/** Write through a socket. MUST go after beginWriteSocket()
+			@param buf				characters to be written (final 0 will not be written)
+		 */
+		void writeSocket(const char* buf);
+
+		/** Write through a socket. MUST go after beginWriteSocket()
+			@param c 				character to be written
+		 */		
+		void writeSocket(uint8_t c);
+		
+		/** Finish current writing
+		 */	
+		void endWriteSocket();
+		
+		/** Check if there are data to be read in socket.
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if there are data available, 4 if no data, otherwise error
+		 */
+		int availableSocket(bool client, int id_socket); // With "available" and "readSocket" ask the modem for 1500 bytes.
+		
+		/** Read data (get a character) available in socket
+			@return character
+		 */
+		int readSocket(); //If Read() gets to the end of the QIRD response, execute again QIRD SYNCHRONOUSLY 
+		
+		/** Flush socket
+		 */
+		void flushSocket();
+		
+		/** Get a character but will not advance the buffer head
+			@return character
+		 */
+		int peekSocket();
+
+		/** Close a socket
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Socket
+			@return 0 if command running, 1 if success, otherwise error
+		 */
+		int disconnectTCP(bool client1Server0, int id_socket);
+		
+		/** Recognize unsolicited event
+			@param oldTail		
+			@return true if successful
+		 */
+		bool recognizeUnsolicitedEvent(byte from);
+		
+		/** Manages modem response
+			@param from 		Initial byte position
+			@param to 			Final byte position
+		 */
+		void manageResponse(byte from, byte to);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		// Client socket management, just to be compatible
+		// with the Multi option
+		
+		/** Get socket
+			@param socket		Socket		
+			@return socket
+		 */
+		int getSocket(int socket=-1);
+		
+		/** Release socket
+			@param socket		Socket
+		 */
+		void releaseSocket(int socket);
+		
+		/** Get socket client status
+			@param socket		Socket
+			@return 1 if connected, 0 otherwise
+		 */
+		bool getStatusSocketClient(uint8_t socket);
+		
+};
+
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.cpp	(revision 175)
@@ -0,0 +1,365 @@
+#include <GSM3ShieldV1DataNetworkProvider.h>
+#include <Arduino.h>
+
+const char _command_CGATT[] PROGMEM = "AT+CGATT=";
+const char _command_SEPARATOR[] PROGMEM = "\",\"";
+
+//Attach GPRS main function.	
+GSM3_NetworkStatus_t GSM3ShieldV1DataNetworkProvider::attachGPRS(char* apn, char* user_name, char* password, bool synchronous)
+{					
+	user = user_name;
+	passwd = password;
+	// A sad use of byte reuse
+	theGSM3ShieldV1ModemCore.setPhoneNumber(apn);
+
+	theGSM3ShieldV1ModemCore.openCommand(this,ATTACHGPRS);
+	theGSM3ShieldV1ModemCore.setStatus(CONNECTING);
+
+	attachGPRSContinue();
+
+	// If synchronous, wait till attach is over, or not.
+	if(synchronous)
+	{
+		// if we shorten this delay, the command fails
+		while(ready()==0) 
+			delay(100); 
+	}
+
+	return theGSM3ShieldV1ModemCore.getStatus();	
+}
+
+//Atthach GPRS continue function.
+void GSM3ShieldV1DataNetworkProvider::attachGPRSContinue()
+{
+	bool resp;
+	// 1: Attach to GPRS service "AT+CGATT=1"
+	// 2: Wait attach OK and Set the context 0 as FGCNT "AT+QIFGCNT=0"
+	// 3: Wait context OK and Set bearer type as GPRS, APN, user name and pasword "AT+QICSGP=1..."
+	// 4: Wait bearer OK and Enable the function of MUXIP "AT+QIMUX=1" 
+	// 5: Wait for disable MUXIP OK and Set the session mode as non transparent "AT+QIMODE=0"
+	// 6: Wait for session mode OK and Enable notification when data received "AT+QINDI=1"
+	// 8: Wait domain name OK and Register the TCP/IP stack "AT+QIREGAPP"
+	// 9: Wait for Register OK and Activate FGCNT "AT+QIACT"
+	// 10: Wait for activate OK
+	
+	int ct=theGSM3ShieldV1ModemCore.getCommandCounter();
+	if(ct==1)
+	{
+		//AT+CGATT	
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGATT,false);
+		theGSM3ShieldV1ModemCore.print(1);
+		theGSM3ShieldV1ModemCore.print('\r');
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+	}
+	else if(ct==2)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				//AT+QIFGCNT
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIFGCNT=0"));
+				theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==3)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				// Great. Go for the next step
+				//DEBUG
+				//SerialUSB.println("AT+QICSGP.");	
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QICSGP=1,\""),false);
+				theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber());
+				theGSM3ShieldV1ModemCore.genericCommand_rq(_command_SEPARATOR,false);
+				theGSM3ShieldV1ModemCore.print(user);
+				theGSM3ShieldV1ModemCore.genericCommand_rq(_command_SEPARATOR,false);
+				theGSM3ShieldV1ModemCore.print(passwd);
+				theGSM3ShieldV1ModemCore.print("\"\r");
+				theGSM3ShieldV1ModemCore.setCommandCounter(4);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==4)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				// AT+QIMUX=1 for multisocket
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIMUX=0"));
+				theGSM3ShieldV1ModemCore.setCommandCounter(5);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==5)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				//AT+QIMODE=0 for multisocket
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIMODE=1"));
+				theGSM3ShieldV1ModemCore.setCommandCounter(6);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==6)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				// AT+QINDI=1
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QINDI=1"));
+				theGSM3ShieldV1ModemCore.setCommandCounter(8);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==8)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				// AT+QIREGAPP
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIREGAPP"));
+				theGSM3ShieldV1ModemCore.setCommandCounter(9);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==9)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if(resp)
+			{
+				// AT+QIACT	
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIACT"));
+				theGSM3ShieldV1ModemCore.setCommandCounter(10);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+	else if(ct==10)
+	{
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			if (resp) 
+				{
+					theGSM3ShieldV1ModemCore.setStatus(GPRS_READY);
+					theGSM3ShieldV1ModemCore.closeCommand(1);
+				}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+	}
+}
+
+//Detach GPRS main function.
+GSM3_NetworkStatus_t GSM3ShieldV1DataNetworkProvider::detachGPRS(bool synchronous)
+{
+	theGSM3ShieldV1ModemCore.openCommand(this,DETACHGPRS);
+	theGSM3ShieldV1ModemCore.setStatus(CONNECTING);
+	detachGPRSContinue();
+	
+	if(synchronous)
+	{
+		while(ready()==0) 
+			delay(1); 
+	}
+	
+	return theGSM3ShieldV1ModemCore.getStatus();
+}
+
+void GSM3ShieldV1DataNetworkProvider::detachGPRSContinue()
+{
+	bool resp;
+	// 1: Detach to GPRS service "AT+CGATT=0"
+	// 2: Wait dettach +PDP DEACT 
+	// 3: Wait for OK
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		//AT+CGATT=0
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGATT,false);
+		theGSM3ShieldV1ModemCore.print(0);
+		theGSM3ShieldV1ModemCore.print('\r');
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		char auxLocate[12];
+		prepareAuxLocate(PSTR("+PDP DEACT"), auxLocate);
+		if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate))
+	    {
+			if(resp)
+			{
+				// Received +PDP DEACT;				
+				theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;
+	case 3:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			// OK received
+			if (resp) 
+				{
+					theGSM3ShieldV1ModemCore.setStatus(GSM_READY);
+					theGSM3ShieldV1ModemCore.closeCommand(1);
+				}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}		
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		break;	
+	}
+}
+
+//QILOCIP parse.
+bool GSM3ShieldV1DataNetworkProvider::parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp)
+{
+	if (!(theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("\r\n","\r\n", LocalIP, LocalIPlength)))
+		rsp = false;
+	else 
+		rsp = true;
+	return true;
+}
+
+//Get IP main function.
+int GSM3ShieldV1DataNetworkProvider::getIP(char* LocalIP, int LocalIPlength)
+{
+	theGSM3ShieldV1ModemCore.setPhoneNumber(LocalIP);
+	theGSM3ShieldV1ModemCore.setPort(LocalIPlength);
+	theGSM3ShieldV1ModemCore.openCommand(this,GETIP);
+	getIPContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+void GSM3ShieldV1DataNetworkProvider::getIPContinue()
+{
+
+	bool resp;
+	// 1: Read Local IP "AT+QILOCIP"
+	// 2: Waiting for IP.
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		//AT+QILOCIP
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILOCIP"));
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(parseQILOCIP_rsp(theGSM3ShieldV1ModemCore.getPhoneNumber(), theGSM3ShieldV1ModemCore.getPort(), resp))
+	    {
+			if (resp) 
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		break;	
+	}
+}
+
+//Get IP with IPAddress object
+IPAddress GSM3ShieldV1DataNetworkProvider::getIPAddress() {
+	char ip_temp[15]="";
+	getIP(ip_temp, 15);
+	unsigned long m=millis();
+
+	while((millis()-m)<10*1000 && (!ready())){
+		// wait for a response from the modem:
+		delay(100);
+	} 
+	IPAddress ip;
+	inet_aton(ip_temp, ip);
+	return ip;
+}
+
+int GSM3ShieldV1DataNetworkProvider::inet_aton(const char* aIPAddrString, IPAddress& aResult)
+{
+    // See if we've been given a valid IP address
+    const char* p =aIPAddrString;
+    while (*p &&
+           ( (*p == '.') || (*p >= '0') || (*p <= '9') ))
+    {
+        p++;
+    }
+
+    if (*p == '\0')
+    {
+        // It's looking promising, we haven't found any invalid characters
+        p = aIPAddrString;
+        int segment =0;
+        int segmentValue =0;
+        while (*p && (segment < 4))
+        {
+            if (*p == '.')
+            {
+                // We've reached the end of a segment
+                if (segmentValue > 255)
+                {
+                    // You can't have IP address segments that don't fit in a byte
+                    return 0;
+                }
+                else
+                {
+                    aResult[segment] = (byte)segmentValue;
+                    segment++;
+                    segmentValue = 0;
+                }
+            }
+            else
+            {
+                // Next digit
+                segmentValue = (segmentValue*10)+(*p - '0');
+            }
+            p++;
+        }
+        // We've reached the end of address, but there'll still be the last
+        // segment to deal with
+        if ((segmentValue > 255) || (segment > 3))
+        {
+            // You can't have IP address segments that don't fit in a byte,
+            // or more than four segments
+            return 0;
+        }
+        else
+        {
+            aResult[segment] = (byte)segmentValue;
+            return 1;
+        }
+    }
+    else
+    {
+        return 0;
+    }
+}
+
+//Response management.
+void GSM3ShieldV1DataNetworkProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case ATTACHGPRS:
+			attachGPRSContinue();
+			break;	
+		case DETACHGPRS:
+			detachGPRSContinue();
+			break;
+		case GETIP:
+			getIPContinue();
+			break;		
+	}
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.h	(revision 175)
@@ -0,0 +1,140 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3SHIELDV1DATANETWORKPROVIDER_
+#define _GSM3SHIELDV1DATANETWORKPROVIDER_
+
+#include <GSM3MobileDataNetworkProvider.h>
+#include <GSM3ShieldV1BaseProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <IPAddress.h>
+
+class GSM3ShieldV1DataNetworkProvider : public GSM3MobileDataNetworkProvider, public GSM3ShieldV1BaseProvider
+{
+	private:
+	
+		char* user; // Username for GPRS
+		char* passwd; // Password for GPRS
+	
+		/** Continue to attach GPRS function
+		 */
+		void attachGPRSContinue();
+		
+		/** Continue to detach GPRS function
+		 */
+		void detachGPRSContinue();
+		
+		/** Parse QILOCIP response
+			@param LocalIP			Buffer for save local IP address
+			@param LocalIPlength	Buffer size
+			@param rsp				Returns true if expected response exists
+			@return true if command executed correctly
+		 */
+		bool parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp);
+		
+		/** Continue to get IP function
+		 */
+		void getIPContinue();
+		
+		/** Implementation of inet_aton standard function
+			@param aIPAddrString	IP address in characters buffer
+			@param aResult			IP address in IPAddress format
+			@return 1 if the address is successfully converted, or 0 if the conversion failed
+		 */
+		int inet_aton(const char* aIPAddrString, IPAddress& aResult);
+	
+	public:
+	
+		/** Attach to GPRS/GSM network
+			@param networkId 	APN GPRS
+			@param user			Username
+			@param pass			Password
+			@return connection status
+		 */
+		GSM3_NetworkStatus_t networkAttach(char* networkId, char* user, char* pass)
+		{
+			return attachGPRS(networkId, user, pass);
+		};
+		
+		/** Detach GPRS/GSM network
+			@return connection status
+		 */
+		GSM3_NetworkStatus_t networkDetach(){ return detachGPRS();};
+		
+		/** Attach to GPRS service
+			@param apn			APN GPRS
+			@param user_name	Username
+			@param password		Password
+			@param synchronous	Sync mode
+			@return connection status
+		 */
+		GSM3_NetworkStatus_t attachGPRS(char* apn, char* user_name, char* password, bool synchronous=true);
+		
+		/** Detach GPRS service
+			@param synchronous	Sync mode
+			@return connection status
+		 */
+		GSM3_NetworkStatus_t detachGPRS(bool synchronous=true);
+		
+		/** Returns 0 if last command is still executing
+			@return 1 if success, >1 if error 
+		 */
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		/** Get network status (connection)
+			@return status
+		 */
+		inline GSM3_NetworkStatus_t getStatus(){return theGSM3ShieldV1ModemCore.getStatus();};
+
+		/** Get actual assigned IP address
+			@param LocalIP			Buffer for copy IP address
+			@param LocalIPlength	Buffer length
+			@return command error if exists
+		 */
+		int getIP(char* LocalIP, int LocalIPlength);
+		
+		/** Get actual assigned IP address in IPAddress format
+			@return IP address in IPAddress format
+		 */
+		IPAddress getIPAddress();
+		
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+
+
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DirectModemProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DirectModemProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DirectModemProvider.cpp	(revision 175)
@@ -0,0 +1,143 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3ShieldV1DirectModemProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <HardwareSerial.h>
+#include <Arduino.h>
+
+#define __RESETPIN__ 7
+
+//Constructor
+GSM3ShieldV1DirectModemProvider::GSM3ShieldV1DirectModemProvider(bool t)
+{
+	trace=t;
+};
+
+void GSM3ShieldV1DirectModemProvider::begin()
+{
+	theGSM3ShieldV1ModemCore.gss.begin(9600);
+}
+
+void GSM3ShieldV1DirectModemProvider::restartModem()
+{
+	pinMode(__RESETPIN__, OUTPUT);
+	digitalWrite(__RESETPIN__, HIGH);
+	delay(12000);
+	digitalWrite(__RESETPIN__, LOW);
+	delay(1000);
+
+}
+
+//To enable the debug process
+void GSM3ShieldV1DirectModemProvider::connect()
+{
+        theGSM3ShieldV1ModemCore.registerActiveProvider(this);
+}
+
+//To disable the debug process
+void GSM3ShieldV1DirectModemProvider::disconnect()
+{
+        theGSM3ShieldV1ModemCore.registerActiveProvider(0);
+}
+
+//Write to the modem by means of SoftSerial
+size_t GSM3ShieldV1DirectModemProvider::write(uint8_t c)
+{	
+        theGSM3ShieldV1ModemCore.write(c);
+}
+
+//Detect if data to be read
+int/*bool*/ GSM3ShieldV1DirectModemProvider::available()
+{
+	if (theGSM3ShieldV1ModemCore.gss.cb.peek(1)) return 1;
+	else return 0;
+} 
+
+//Read data
+int/*char*/ GSM3ShieldV1DirectModemProvider::read()
+{
+	int dataRead;
+	dataRead = theGSM3ShieldV1ModemCore.gss.cb.read();
+	//In case last char in xof mode.
+	if (!(theGSM3ShieldV1ModemCore.gss.cb.peek(0))) {
+			theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+			delay(100);
+		}
+	return dataRead;
+} 
+
+//Peek data
+int/*char*/ GSM3ShieldV1DirectModemProvider::peek()
+{
+	return theGSM3ShieldV1ModemCore.gss.cb.peek(0);
+} 
+
+//Flush data
+void GSM3ShieldV1DirectModemProvider::flush()
+{
+	return theGSM3ShieldV1ModemCore.gss.cb.flush();
+}
+
+String GSM3ShieldV1DirectModemProvider::writeModemCommand(String ATcommand, int responseDelay)
+{
+
+  if(trace)
+	SerialUSB.println(ATcommand);
+	
+  // Flush other texts
+  flush();
+  
+  //Enter debug mode.
+  connect();
+  //Send the AT command.
+  println(ATcommand);
+
+  delay(responseDelay);
+
+  //Get response data from modem.
+  String result = "";
+  if(trace)
+	theGSM3ShieldV1ModemCore.gss.cb.debugBuffer();
+
+  while (available())
+  {
+    char c = read();
+    result += c;
+  }
+  if(trace)
+	SerialUSB.println(result);
+  //Leave the debug mode.
+  disconnect();
+  return result;
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DirectModemProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DirectModemProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1DirectModemProvider.h	(revision 175)
@@ -0,0 +1,118 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+
+#ifndef __GSM3DIRECTMODEMPROVIDER__
+#define __GSM3DIRECTMODEMPROVIDER__
+
+#include <GSM3SoftSerial.h>
+#include <GSM3MobileNetworkProvider.h>
+#include <GSM3ShieldV1BaseProvider.h>
+#include <Stream.h>
+#include <Arduino.h>
+
+class GSM3ShieldV1DirectModemProvider : public GSM3ShieldV1BaseProvider, public Stream
+{			
+		private:
+			
+			bool trace;
+			
+        public:
+			
+			/** Constructor
+				@param trace if true, dumps all AT dialogue to Serial
+			*/
+			GSM3ShieldV1DirectModemProvider(bool trace=false);
+			
+			/**
+			 */
+			void begin();
+			
+			/**
+			 */
+			void restartModem();
+			
+			/** Enable the debug process.
+			 */
+			void connect();
+			
+			/** Disable the debug process.
+			 */
+			void disconnect();
+			
+			/** Debug write to modem by means of SoftSerial.
+				@param c			Character
+				@return size
+			 */
+			size_t write(uint8_t c);
+			
+			/** Check for incoming bytes in buffer
+				@return
+			 */
+			int available();
+			
+			/** Read from circular buffer
+				@return character
+			 */
+			int read();
+			
+			/** Read from circular buffer, but do not delete it
+				@return character
+			 */
+			int peek();
+			
+			/** Empty circular buffer
+			 */
+			void flush();
+			
+			/** Manages modem response
+				@param from 		Initial byte of buffer
+				@param to 			Final byte of buffer
+			 */
+			void manageResponse(byte from, byte to){};
+			
+			/** Recognize unsolicited event
+				@param from		
+				@return true if successful
+			 */
+			bool recognizeUnsolicitedEvent(byte from){return false;};
+			
+			/** Send AT command to modem
+				@param command		AT command
+				@param delay		Time to wait for response
+				@return response from modem
+			 */
+			String writeModemCommand(String command, int delay);
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemCore.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemCore.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemCore.cpp	(revision 175)
@@ -0,0 +1,198 @@
+#include <GSM3ShieldV1ModemCore.h>
+#include <Arduino.h>
+
+GSM3ShieldV1ModemCore theGSM3ShieldV1ModemCore;
+
+char* __ok__="OK";
+
+GSM3ShieldV1ModemCore::GSM3ShieldV1ModemCore() : gss()
+{
+	gss.registerMgr(this);
+	_dataInBufferFrom=0;
+	_dataInBufferTo=0;
+	commandError=1;
+	commandCounter=0;
+	ongoingCommand=NONE;
+	takeMilliseconds();
+	
+	for(int i=0;i<UMPROVIDERS;i++)
+		UMProvider[i]=0;
+}
+
+void GSM3ShieldV1ModemCore::registerUMProvider(GSM3ShieldV1BaseProvider* provider)
+{
+	for(int i=0;i<UMPROVIDERS;i++)
+	{
+		if(UMProvider[i]==0)
+		{
+			UMProvider[i]=provider;
+			break;
+		}
+
+	}
+
+}
+
+void GSM3ShieldV1ModemCore::unRegisterUMProvider(GSM3ShieldV1BaseProvider* provider)
+{
+	for(int i=0;i<UMPROVIDERS;i++)
+	{
+		if(UMProvider[i]==provider)
+		{
+			UMProvider[i]=0;
+			break;
+		}
+	}
+}
+
+
+//Response parse.
+bool GSM3ShieldV1ModemCore::genericParse_rsp(bool& rsp, char* string, char* string2)
+{
+	if((string==0) && (string2==0))
+		string=__ok__;
+	
+	rsp=theBuffer().locate(string);
+	
+	if((!rsp)&&(string2!=0))
+		rsp=theBuffer().locate(string2);
+		
+	return true;
+}
+
+void GSM3ShieldV1ModemCore::closeCommand(int code)
+{
+	// If we were configuring the modem,
+	// and there's been an error
+	// we don't know exactly where we are
+	if((code!=1)&&(theGSM3ShieldV1ModemCore.getOngoingCommand()==MODEMCONFIG))
+		theGSM3ShieldV1ModemCore.setStatus(ERROR);
+
+	setCommandError(code);
+	ongoingCommand=NONE;
+	activeProvider=0;
+	commandCounter=1;
+}
+
+//Generic command (stored in flash).
+void GSM3ShieldV1ModemCore::genericCommand_rq(PGM_P str, bool addCR)
+{
+	theBuffer().flush();
+	writePGM(str, addCR);
+}
+
+//Generic command (const string).
+void GSM3ShieldV1ModemCore::genericCommand_rqc(const char* str, bool addCR)
+{
+	theBuffer().flush();
+	print(str);
+	if(addCR)
+		print("\r");
+}
+
+// If we are not debugging, lets manage data in interrupt time
+// but if we are not, just take note.
+void GSM3ShieldV1ModemCore::manageMsg(byte from, byte to)
+{
+	if(_debug)
+	{
+		_dataInBufferFrom=from;
+		_dataInBufferTo=to;
+	}
+	else
+	{
+		manageMsgNow(from, to);
+	}
+}
+
+void GSM3ShieldV1ModemCore::manageReceivedData()
+{
+	if(_debug)
+	{
+/*		SerialUSB.print(theBuffer().getHead());
+		SerialUSB.print(" ");
+		SerialUSB.println(theBuffer().getTail());*/
+		if(_dataInBufferFrom != _dataInBufferTo)
+		{
+			theBuffer().debugBuffer();
+			manageMsgNow(_dataInBufferFrom, _dataInBufferTo);
+			_dataInBufferFrom=0;
+			_dataInBufferTo=0;
+		}
+	}
+	else
+	{
+		// Just debugging the non debugging
+//		SerialUSB.println();
+//		SerialUSB.print("Com:");
+//		SerialUSB.print(ongoingCommand);
+//		SerialUSB.print("   Step:");
+//		SerialUSB.print(commandCounter);
+	}
+}
+
+//Select between URC or response.
+void GSM3ShieldV1ModemCore::manageMsgNow(byte from, byte to)
+{
+	bool recognized=false;
+	
+	for(int i=0;(i<UMPROVIDERS)&&(!recognized);i++)
+	{
+		if(UMProvider[i])
+			recognized=UMProvider[i]->recognizeUnsolicitedEvent(from);
+	}
+	if((!recognized)&&(activeProvider))
+		activeProvider->manageResponse(from, to);
+}
+
+
+void GSM3ShieldV1ModemCore::openCommand(GSM3ShieldV1BaseProvider* provider, GSM3_commandType_e c)
+{	
+	activeProvider=provider;
+	commandError=0;
+	commandCounter=1;
+	ongoingCommand=c;
+	_dataInBufferFrom=0;
+	_dataInBufferTo=0;
+
+};
+
+size_t GSM3ShieldV1ModemCore::writePGM(PGM_P str, bool CR)
+{
+	int i=0;
+	char c;
+	
+	do
+	{	
+		c=pgm_read_byte_near(str + i); 
+		if(c!=0)
+			write(c);
+		i++;
+	} while (c!=0);
+	if(CR)
+		print("\r");
+		
+	return 1;
+}
+
+size_t GSM3ShieldV1ModemCore::write(uint8_t c)
+{
+	if(_debug)
+		GSM3CircularBuffer::printCharDebug(c);
+	return gss.write(c);
+}
+
+unsigned long GSM3ShieldV1ModemCore::takeMilliseconds()
+{
+	unsigned long now=millis();
+	unsigned long delta;
+	delta=now-milliseconds;
+	milliseconds=now;
+	return delta;
+}
+
+void GSM3ShieldV1ModemCore::delayInsideInterrupt(unsigned long milliseconds)
+{
+	for (unsigned long k=0;k<milliseconds;k++)  
+		theGSM3ShieldV1ModemCore.gss.tunedDelay(7000); 
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemCore.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemCore.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemCore.h	(revision 175)
@@ -0,0 +1,254 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+
+#ifndef __GSM3_SHIELDV1MODEMCORE__
+#define __GSM3_SHIELDV1MODEMCORE__
+
+#include <GSM3SoftSerial.h>
+#include <GSM3ShieldV1BaseProvider.h>
+#include <GSM3MobileAccessProvider.h>
+#include <Print.h>
+
+#define UMPROVIDERS 3
+
+class GSM3ShieldV1ModemCore : public GSM3SoftSerialMgr, public Print
+{
+	private:
+		
+		// Phone number, used when calling, sending SMS and reading calling numbers
+		// Also PIN in modem configuration
+		// Also APN
+		// Also remote server
+		char* phoneNumber;	
+		
+		// Working port. Port used in the ongoing command, while opening a server
+		// Also for IP address length
+		int port;
+
+		// 0 = ongoing
+		// 1 = OK
+		// 2 = Error. Incorrect state
+		// 3 = Unexpected modem message
+		// 4 = OK but not available data. 
+		uint8_t commandError;
+
+		// Counts the steps by the command
+		uint8_t commandCounter;
+		
+		// Presently ongoing command
+		GSM3_commandType_e ongoingCommand;
+		
+		// Enable/disable debug
+		bool _debug;
+		byte _dataInBufferFrom;
+		byte _dataInBufferTo;
+		
+		// This is the modem (known) status
+		GSM3_NetworkStatus_t _status;
+		
+		GSM3ShieldV1BaseProvider* UMProvider[UMPROVIDERS];
+		GSM3ShieldV1BaseProvider* activeProvider;
+		
+		// Private function for anage message
+		void manageMsgNow(byte from, byte to);
+		
+		unsigned long milliseconds;
+
+	public:
+	
+		/** Constructor */
+		GSM3ShieldV1ModemCore();
+		
+		GSM3SoftSerial gss; // Direct access to modem
+		
+		/** Get phone number
+			@return phone number
+		 */
+		char *getPhoneNumber(){return phoneNumber;};
+		
+		/** Establish a new phone number
+			@param n			Phone number
+		 */
+		void setPhoneNumber(char *n){phoneNumber=n;};
+
+		/** Get port used
+			@return port
+		 */
+		int getPort(){return port;};
+		
+		/** Establish a new port for use
+			@param p			Port
+		 */
+		void setPort(int p){port=p;};
+
+		/** Get command error
+			@return command error
+		 */
+		uint8_t getCommandError(){return commandError;};
+		
+		/** Establish a command error
+			@param n			Command error
+		 */
+		void setCommandError(uint8_t n){commandError=n;};
+		
+		/** Get command counter
+			@return command counter
+		 */
+		uint8_t getCommandCounter(){return commandCounter;};
+		
+		/** Set command counter
+			@param c			Initial value
+		 */
+		void setCommandCounter(uint8_t c){commandCounter=c;};
+
+		/** Get ongoing command
+			@return command
+		 */
+		GSM3_commandType_e getOngoingCommand(){return ongoingCommand;};
+		
+		/** Set ongoing command
+			@param c			 New ongoing command
+		 */
+		void setOngoingCommand(GSM3_commandType_e c){ongoingCommand=c;};
+		
+		/** Open command
+			@param activeProvider	Active provider
+			@param c				Command for open
+		 */
+		void openCommand(GSM3ShieldV1BaseProvider* activeProvider, GSM3_commandType_e c);
+		
+		/** Close command
+			@param code			Close code
+		 */
+		void closeCommand(int code);
+
+		// These functions allow writing to the SoftwareSerial
+		// If debug is set, dump to the console
+		
+		/** Write a character in serial
+			@param c			Character
+			@return size
+		 */
+		size_t write(uint8_t c);
+		
+		/** Write PGM
+			@param str			Buffer for write
+			@param CR			Carriadge return adding automatically
+			@return size
+		 */
+		virtual size_t writePGM(PGM_P str, bool CR=true);
+		
+		/** Establish debug mode
+			@param db			Boolean that indicates debug on or off
+		 */
+		void setDebug(bool db){_debug=db;};
+		
+		/** Generic response parser
+			@param rsp			Returns true if expected response exists
+			@param string		Substring expected in response
+			@param string2		Second substring expected in response
+			@return true if parsed correctly
+		 */		
+		bool genericParse_rsp(bool& rsp, char* string=0, char* string2=0);
+		
+		/** Generates a generic AT command request from PROGMEM buffer
+			@param str			Buffer with AT command
+			@param addCR		Carriadge return adding automatically
+		 */
+		void genericCommand_rq(PGM_P str, bool addCR=true);
+
+		/** Generates a generic AT command request from a simple char buffer
+			@param str			Buffer with AT command
+			@param addCR		Carriadge return adding automatically
+		 */
+		void genericCommand_rqc(const char* str, bool addCR=true);		
+		
+		/** Returns the circular buffer
+			@return circular buffer
+		 */
+		inline GSM3CircularBuffer& theBuffer(){return gss.cb;};
+
+		/** Establish a new network status
+			@param status		Network status
+		 */
+		inline void setStatus(GSM3_NetworkStatus_t status) { _status = status; };
+		
+		/** Returns actual network status
+			@return network status
+		 */
+		inline GSM3_NetworkStatus_t getStatus() { return _status; };
+		
+		/** Register provider as willing to receive unsolicited messages
+			@param provider	Pointer to provider able to receive unsolicited messages
+		*/
+		void registerUMProvider(GSM3ShieldV1BaseProvider* provider);		
+	
+		/** unegister provider as willing to receive unsolicited messages
+			@param provider	Pointer to provider able to receive unsolicited messages
+		*/
+		void unRegisterUMProvider(GSM3ShieldV1BaseProvider* provider);		
+
+		
+		/** Register a provider as "dialoguing" talking in facto with the modem
+			@param provider	Pointer to provider receiving responses
+		*/
+		void registerActiveProvider(GSM3ShieldV1BaseProvider* provider){activeProvider=provider;};
+		
+		/** Needed to manage the SoftSerial. Receives the call when received data
+			If _debugging, no code is called
+		@param from Starting byte to read
+		@param to Last byte to read
+		*/
+		void manageMsg(byte from, byte to);
+		
+		/** If _debugging, this call is assumed to be made out of interrupts
+			Prints incoming info and calls manageMsgNow
+		*/
+		void manageReceivedData();
+
+		/** Chronometer. Measure milliseconds from last call
+			@return milliseconds from las time function was called
+		*/		
+		unsigned long takeMilliseconds();
+		
+		/** Delay for interrupts
+			@param milliseconds		Delay time in milliseconds
+		 */
+		void delayInsideInterrupt(unsigned long milliseconds);
+
+};
+
+extern GSM3ShieldV1ModemCore theGSM3ShieldV1ModemCore;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemVerification.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemVerification.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemVerification.cpp	(revision 175)
@@ -0,0 +1,73 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+
+#include <GSM3ShieldV1ModemVerification.h>
+
+// constructor
+GSM3ShieldV1ModemVerification::GSM3ShieldV1ModemVerification()
+{
+};
+
+// reset the modem for direct access
+int GSM3ShieldV1ModemVerification::begin()
+{
+	int result=0;
+	String modemResponse;
+	
+	// check modem response
+	modemAccess.begin();
+
+	// reset hardware
+	modemAccess.restartModem();
+
+	modemResponse=modemAccess.writeModemCommand("AT", 1000);
+	if(modemResponse.indexOf("OK")>=0)
+		result=1;
+	modemResponse=modemAccess.writeModemCommand("ATE0", 1000);
+	return result;
+}
+
+// get IMEI
+String GSM3ShieldV1ModemVerification::getIMEI()
+{
+	String number(NULL);
+	// AT command for obtain IMEI
+	String modemResponse = modemAccess.writeModemCommand("AT+GSN", 2000);
+	// Parse and check response
+	char res_to_compare[modemResponse.length()];
+	modemResponse.toCharArray(res_to_compare, modemResponse.length());
+	if(strstr(res_to_compare,"OK") != NULL)
+		number = modemResponse.substring(1, 17);
+	return number;
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemVerification.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemVerification.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ModemVerification.h	(revision 175)
@@ -0,0 +1,64 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3SHIELDV1MODEMVERIFICATION_
+#define _GSM3SHIELDV1MODEMVERIFICATION_
+
+#include <GSM3ShieldV1AccessProvider.h>
+#include <GSM3ShieldV1DirectModemProvider.h>
+
+class GSM3ShieldV1ModemVerification
+{
+
+	private:
+		
+		GSM3ShieldV1DirectModemProvider modemAccess;
+		GSM3ShieldV1AccessProvider gsm; // Access provider to GSM/GPRS network
+		
+	public:
+
+		/** Constructor */
+		GSM3ShieldV1ModemVerification();
+	
+		/** Check modem response and restart it
+		 */
+		int begin();
+		
+		/** Obtain modem IMEI (command AT)
+			@return modem IMEI number
+		 */
+		String getIMEI();
+		
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiClientProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiClientProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiClientProvider.cpp	(revision 175)
@@ -0,0 +1,583 @@
+#include <GSM3ShieldV1MultiClientProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+
+const char _command_MultiQISRVC[] PROGMEM = "AT+QISRVC=";
+
+#define __TOUTFLUSH__ 10000
+
+GSM3ShieldV1MultiClientProvider::GSM3ShieldV1MultiClientProvider()
+{
+	theGSM3MobileClientProvider=this;
+	theGSM3ShieldV1ModemCore.registerUMProvider(this);
+};
+
+//Response management.
+void GSM3ShieldV1MultiClientProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case XON:
+			if (flagReadingSocket) 
+				{
+//					flagReadingSocket = 0;
+					fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3);
+				}
+			else theGSM3ShieldV1ModemCore.setOngoingCommand(NONE);
+			break;
+		case NONE:
+			theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from);
+			break;
+		case CONNECTTCPCLIENT:
+			connectTCPClientContinue();
+			break;
+		case DISCONNECTTCP:
+			disconnectTCPContinue();
+			break;	
+	 	case BEGINWRITESOCKET:
+			beginWriteSocketContinue();
+			break;
+		case ENDWRITESOCKET:
+			endWriteSocketContinue();
+			break;	
+		case AVAILABLESOCKET:
+			availableSocketContinue();
+			break;	
+		case FLUSHSOCKET:
+			fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3);
+			flushSocketContinue();
+			break;	
+	}
+}
+
+//Connect TCP main function.
+int GSM3ShieldV1MultiClientProvider::connectTCPClient(const char* server, int port, int id_socket)
+{
+	theGSM3ShieldV1ModemCore.setPort(port);		
+	idSocket = id_socket;
+	
+	theGSM3ShieldV1ModemCore.setPhoneNumber((char*)server);
+	theGSM3ShieldV1ModemCore.openCommand(this,CONNECTTCPCLIENT);
+	connectTCPClientContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();	
+}
+
+int GSM3ShieldV1MultiClientProvider::connectTCPClient(IPAddress add, int port, int id_socket)
+{
+	remoteIP=add;
+	theGSM3ShieldV1ModemCore.setPhoneNumber(0);
+	return connectTCPClient(0, port, id_socket);
+}
+
+//Connect TCP continue function.
+void GSM3ShieldV1MultiClientProvider::connectTCPClientContinue()
+{
+	bool resp;
+	// 0: Dot or DNS notation activation
+	// 1: Disable SW flow control 
+	// 2: Waiting for IFC OK
+	// 3: Start-up TCP connection "AT+QIOPEN"
+	// 4: Wait for connection OK
+	// 5: Wait for CONNECT
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIDNSIP="), false);
+		if ((theGSM3ShieldV1ModemCore.getPhoneNumber()!=0)&&
+			((*(theGSM3ShieldV1ModemCore.getPhoneNumber())<'0')||((*(theGSM3ShieldV1ModemCore.getPhoneNumber())>'9'))))
+		{
+			theGSM3ShieldV1ModemCore.print('1');
+			theGSM3ShieldV1ModemCore.print('\r');
+		}
+		else 
+		{
+			theGSM3ShieldV1ModemCore.print('0');
+			theGSM3ShieldV1ModemCore.print('\r');
+		}
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			//Response received
+			if(resp)
+			{				
+				// AT+QIOPEN
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIOPEN="),false);
+				theGSM3ShieldV1ModemCore.print(idSocket);
+				theGSM3ShieldV1ModemCore.print(",\"TCP\",\"");
+				if(theGSM3ShieldV1ModemCore.getPhoneNumber()!=0)
+				{
+					theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber());
+				}
+				else
+				{
+					remoteIP.printTo(theGSM3ShieldV1ModemCore);
+				}
+				theGSM3ShieldV1ModemCore.print('"');
+				theGSM3ShieldV1ModemCore.print(',');
+				theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPort());
+				theGSM3ShieldV1ModemCore.print('\r');
+				theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;
+	
+	case 3:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			// Response received
+			if(resp)
+			{
+				// OK Received
+				// Great. Go for the next step
+				theGSM3ShieldV1ModemCore.setCommandCounter(4);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;
+	case 4:
+		char auxLocate [12];
+		prepareAuxLocate(PSTR("CONNECT OK"), auxLocate);
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp,auxLocate))
+	    {
+			// Response received
+			if(resp)
+			{
+				// Received CONNECT OK
+				// Great. We're done
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			}
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}		
+		break;
+		
+	}
+}
+
+//Disconnect TCP main function.
+int GSM3ShieldV1MultiClientProvider::disconnectTCP(bool client1Server0, int id_socket)
+{		
+	idSocket = id_socket;
+	
+	// First of all, we will flush the socket synchronously
+	unsigned long m;
+	m=millis();
+	flushSocket();
+	while(((millis()-m)< __TOUTFLUSH__ )&&(ready()==0)) 
+		delay(10);
+		
+	// Could not flush the communications... strange
+	if(ready()==0)
+	{
+		theGSM3ShieldV1ModemCore.setCommandError(2);
+		return theGSM3ShieldV1ModemCore.getCommandError();
+	}
+		
+	// Set up the command
+	client1_server0 = client1Server0;
+	flagReadingSocket=0;
+	theGSM3ShieldV1ModemCore.openCommand(this,DISCONNECTTCP);
+	disconnectTCPContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Disconnect TCP continue function
+void GSM3ShieldV1MultiClientProvider::disconnectTCPContinue()
+{
+	bool resp;
+	// 1: Send AT+QISRVC
+	// 2: "AT+QICLOSE"
+	// 3: Wait for OK
+	
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_MultiQISRVC, false);
+		if (client1_server0) theGSM3ShieldV1ModemCore.print('1');
+		else theGSM3ShieldV1ModemCore.print('2');
+		theGSM3ShieldV1ModemCore.print('\r');
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		// Parse response to QISRVC
+		theGSM3ShieldV1ModemCore.genericParse_rsp(resp);
+		if(resp)
+		{
+			// Send QICLOSE command
+			theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QICLOSE="),false);
+			theGSM3ShieldV1ModemCore.print(idSocket);
+			theGSM3ShieldV1ModemCore.print('\r');
+			theGSM3ShieldV1ModemCore.setCommandCounter(3);
+		}
+		else 
+			theGSM3ShieldV1ModemCore.closeCommand(3);
+		break;
+	case 3:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {		
+			theGSM3ShieldV1ModemCore.setCommandCounter(0);
+			if (resp) 
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;
+	}
+}
+
+//Write socket first chain main function.
+void GSM3ShieldV1MultiClientProvider::beginWriteSocket(bool client1Server0, int id_socket)
+{
+	idSocket = id_socket;	
+	client1_server0 = client1Server0;
+	theGSM3ShieldV1ModemCore.openCommand(this,BEGINWRITESOCKET);
+	beginWriteSocketContinue();
+}
+
+//Write socket first chain continue function.
+void GSM3ShieldV1MultiClientProvider::beginWriteSocketContinue()
+{
+	bool resp;
+	// 1: Send AT+QISRVC
+	// 2: Send AT+QISEND
+	// 3: wait for > and Write text
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		// AT+QISRVC
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_MultiQISRVC, false);
+		if (client1_server0) 
+			theGSM3ShieldV1ModemCore.print('1');
+		else 
+			theGSM3ShieldV1ModemCore.print('2');
+		theGSM3ShieldV1ModemCore.print('\r');
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+    case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			// Response received
+			if(resp)
+			{
+				// AT+QISEND
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QISEND="), false);
+				theGSM3ShieldV1ModemCore.print(idSocket);
+				theGSM3ShieldV1ModemCore.print('\r');
+				theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			}
+			else
+			{
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+			}
+		}	
+		break;
+	case 3:
+		char aux[2];
+		aux[0]='>';
+		aux[1]=0;
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, aux))
+		{
+			if(resp)
+			{
+				// Received ">"
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			}
+			else
+			{
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+			}
+		}
+		break;
+	}
+}
+
+//Write socket next chain function.
+void GSM3ShieldV1MultiClientProvider::writeSocket(const char* buf)
+{
+	theGSM3ShieldV1ModemCore.print(buf);
+}
+
+//Write socket character function.
+void GSM3ShieldV1MultiClientProvider::writeSocket(char c)
+{
+	theGSM3ShieldV1ModemCore.print(c);
+}
+
+//Write socket last chain main function.
+void GSM3ShieldV1MultiClientProvider::endWriteSocket()
+{		
+	theGSM3ShieldV1ModemCore.openCommand(this,ENDWRITESOCKET);
+	endWriteSocketContinue();
+}
+
+//Write socket last chain continue function.
+void GSM3ShieldV1MultiClientProvider::endWriteSocketContinue()
+{
+	bool resp;
+	// 1: Write text (ctrl-Z)
+	// 2: Wait for OK
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		theGSM3ShieldV1ModemCore.write(26); // Ctrl-Z
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			// OK received
+			if (resp) theGSM3ShieldV1ModemCore.closeCommand(1);
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		break;
+	}
+}
+
+//Available socket main function.
+int GSM3ShieldV1MultiClientProvider::availableSocket(bool client1Server0, int id_socket)
+{
+	if(flagReadingSocket==1)
+	{
+		theGSM3ShieldV1ModemCore.setCommandError(1);
+		return 1;
+	}
+	client1_server0 = client1Server0;
+	idSocket = id_socket;	
+	theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESOCKET);
+	availableSocketContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Available socket continue function.
+void GSM3ShieldV1MultiClientProvider::availableSocketContinue()
+{
+	bool resp;
+	// 1: AT+QIRD
+	// 2: Wait for OK and Next necessary AT+QIRD
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIRD=0,"),false);
+		if (client1_server0) 
+			theGSM3ShieldV1ModemCore.print('1');
+		else 
+			theGSM3ShieldV1ModemCore.print('2');
+		theGSM3ShieldV1ModemCore.print(',');
+		theGSM3ShieldV1ModemCore.print(idSocket);
+		theGSM3ShieldV1ModemCore.print(",1500");
+		// theGSM3ShieldV1ModemCore.print(",120");
+		theGSM3ShieldV1ModemCore.print('\r');
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(parseQIRD_head(resp))
+		{
+			if (!resp)
+			{
+				theGSM3ShieldV1ModemCore.closeCommand(4);
+			}
+			else 
+			{
+				flagReadingSocket=1;
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			}
+		}
+		else 
+		{
+			theGSM3ShieldV1ModemCore.closeCommand(3);	
+		}
+		break;
+	}
+}
+	
+//Read Socket Parse head.
+bool GSM3ShieldV1MultiClientProvider::parseQIRD_head(bool& rsp)
+{
+	char _qird [8];
+	prepareAuxLocate(PSTR("+QIRD:"), _qird);
+	fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3);
+	if(theGSM3ShieldV1ModemCore.theBuffer().locate(_qird)) 
+	{		
+		theGSM3ShieldV1ModemCore.theBuffer().chopUntil(_qird, true);
+		// Saving more memory, reuse _qird
+		_qird[0]='\n';
+		_qird[1]=0;
+		theGSM3ShieldV1ModemCore.theBuffer().chopUntil(_qird, true);
+		rsp = true;			
+		return true;
+	}
+	else if(theGSM3ShieldV1ModemCore.theBuffer().locate("OK")) 
+	{
+		rsp = false;
+		return true;
+	}
+	else
+	{
+		rsp = false;
+		return false;
+	}
+}
+/*		
+//Read socket main function.
+int GSM3ShieldV1MultiClientProvider::readSocket()
+{
+	char charSocket;
+	charSocket = theGSM3ShieldV1ModemCore.theBuffer().read(); 
+	//Case buffer not full
+	if (!fullBufferSocket)
+	{	
+		//The last part of the buffer after data is CRLFOKCRLF
+		if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==125)
+		{
+			//Start again availableSocket function.
+			flagReadingSocket=0;
+			theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESOCKET);
+			availableSocketContinue();					
+		}
+	}
+	else if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==127)
+	{
+		// The buffer is full, no more action is possible until we have read()
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		flagReadingSocket = 1;
+		theGSM3ShieldV1ModemCore.openCommand(this,XON);
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		//A small delay to assure data received after xon.
+		delay(10);
+	}
+	//To distinguish the case no more available data in socket.			
+	if (ready()==1)	
+		return charSocket;
+	else 
+		return 0;
+}	
+*/
+int GSM3ShieldV1MultiClientProvider::readSocket()
+{
+	char charSocket;
+	
+	if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==0)
+	{
+		SerialUSB.println();SerialUSB.println("*");
+		return 0;
+	}
+		
+	charSocket = theGSM3ShieldV1ModemCore.theBuffer().read(); 
+	//Case buffer not full
+	if (!fullBufferSocket)
+	{	
+		//The last part of the buffer after data is CRLFOKCRLF
+		if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==125)
+		{
+			//Start again availableSocket function.
+			flagReadingSocket=0;
+			theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESOCKET);
+			availableSocketContinue();					
+		}
+	}
+	else if (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()>=100)
+	{
+		// The buffer was full, we have to let the data flow again
+		// theGSM3ShieldV1ModemCore.theBuffer().flush();
+		flagReadingSocket = 1;
+		theGSM3ShieldV1ModemCore.openCommand(this,XON);
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		//A small delay to assure data received after xon.
+		delay(100);
+		if(theGSM3ShieldV1ModemCore.theBuffer().availableBytes() >=6)
+			fullBufferSocket=false;
+	}
+
+	return charSocket;
+
+}
+
+//Read socket main function.
+int GSM3ShieldV1MultiClientProvider::peekSocket()
+{
+	return theGSM3ShieldV1ModemCore.theBuffer().peek(0); 
+}
+
+
+//Flush SMS main function.
+void GSM3ShieldV1MultiClientProvider::flushSocket()
+{
+	flagReadingSocket=0;
+	theGSM3ShieldV1ModemCore.openCommand(this,FLUSHSOCKET);
+	flushSocketContinue();
+}
+
+//Send SMS continue function.
+void GSM3ShieldV1MultiClientProvider::flushSocketContinue()
+{
+	bool resp;
+	// 1: Deleting SMS
+	// 2: wait for OK
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		//DEBUG
+		//SerialUSB.println("Flushing Socket.");	
+			theGSM3ShieldV1ModemCore.theBuffer().flush();
+			if (fullBufferSocket) 
+				{
+					//SerialUSB.println("Buffer flushed.");
+					theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+				}
+			else 
+				{
+					//SerialUSB.println("Socket flushed completely.");
+					theGSM3ShieldV1ModemCore.closeCommand(1);
+				}
+		break;
+	}
+}
+
+//URC recognize.
+// Momentarily, we will not recognize "closes" in client mode
+bool GSM3ShieldV1MultiClientProvider::recognizeUnsolicitedEvent(byte oldTail)
+{
+	return false;
+}
+
+int GSM3ShieldV1MultiClientProvider::getSocket(int socket)
+{
+	if(socket==-1)
+	{
+		int i;
+		for(i=minSocket(); i<=maxSocket(); i++)
+		{
+			if (!(sockets&(0x0001<<i)))
+			{
+				sockets|=((0x0001)<<i);
+				return i;
+			}	
+		}
+	}
+	else
+	{
+		if (!(sockets&(0x0001<<socket)))
+		{
+			sockets|=((0x0001)<<socket);
+			return socket;
+		}	
+	}
+	return -1;
+}
+
+void GSM3ShieldV1MultiClientProvider::releaseSocket(int socket)
+{
+	if (sockets&((0x0001)<<socket))
+		sockets^=((0x0001)<<socket);
+}
+
+bool GSM3ShieldV1MultiClientProvider::getStatusSocketClient(uint8_t socket)
+{
+	if(socket>8)
+		return 0;
+	if(sockets&(0x0001<<socket))
+		return 1;
+	else
+		return 0;
+};
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiClientProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiClientProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiClientProvider.h	(revision 175)
@@ -0,0 +1,202 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SHIELDV1CLIENTPROVIDER__
+#define __GSM3_SHIELDV1CLIENTPROVIDER__
+
+#include <GSM3MobileClientProvider.h>
+#include <GSM3ShieldV1BaseProvider.h>
+
+class GSM3ShieldV1MultiClientProvider : public GSM3MobileClientProvider,  public GSM3ShieldV1BaseProvider
+{
+	private:
+	
+		int remotePort;		// Current operation remote port
+		int idSocket; 		// Remote ID socket
+		IPAddress remoteIP; // Remote IP address
+		
+		uint16_t sockets;
+
+		/** Continue to connect TCP client function
+		 */
+		void connectTCPClientContinue();
+		
+		/** Continue to disconnect TCP client function
+		 */
+		void disconnectTCPContinue();
+		
+		/** Continue to begin socket for write function
+		 */
+		void beginWriteSocketContinue();
+		
+		/** Continue to end write socket function
+		 */
+		void endWriteSocketContinue();
+		
+		/** Continue to available socket function
+		 */
+		void availableSocketContinue();
+		
+		/** Continue to flush socket function
+		 */
+		void flushSocketContinue();
+		
+		// GATHER!
+		bool flagReadingSocket; //In case socket data being read, update fullBufferSocket in the next buffer.
+		bool fullBufferSocket;	//To detect if the socket data being read needs another buffer.
+		bool client1_server0;	//1 Client, 0 Server.
+		
+		/** Parse QIRD response
+			@param rsp		Returns true if expected response exists
+			@return true if command executed correctly
+		 */
+		bool parseQIRD_head(bool& rsp); 
+
+	public:
+	
+		/** Constructor */
+		GSM3ShieldV1MultiClientProvider();
+		
+		/** Minimum socket
+			@return 0
+		 */
+		int minSocket(){return 0;};
+		
+		/** Maximum socket
+			@return 5
+		 */
+		int maxSocket(){return 5;};
+		
+		/** Connect to a remote TCP server
+			@param server		String with IP or server name
+			@param port 		Remote port number
+			@param id_socket	Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		*/
+		int connectTCPClient(const char* server, int port, int id_socket);
+		
+		/** Connect to a remote TCP server
+			@param add			Remote IP address
+			@param port 		Remote port number
+			@param id_socket	Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		*/
+		int connectTCPClient(IPAddress add, int port, int id_socket);
+
+		/** Begin writing through a socket
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		*/
+		void beginWriteSocket(bool client1Server0, int id_socket);
+
+		/** Write through a socket. MUST go after beginWriteSocket()
+			@param buf			characters to be written (final 0 will not be written)
+		*/
+		void writeSocket(const char* buf);
+
+		/** Write through a socket. MUST go after beginWriteSocket()
+			@param c character to be written
+		*/		
+		void writeSocket(char c);
+		
+		/** Finish current writing
+		*/	
+		void endWriteSocket();
+		
+		/** Check if there are data to be read in socket.
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if there are data available, 4 if no data, otherwise error
+		*/
+		int availableSocket(bool client, int id_socket); // With "available" and "readSocket" ask the modem for 1500 bytes.
+		
+		/** Read a character from socket
+			@return socket
+		 */
+		int readSocket(); //If Read() gets to the end of the QIRD response, execute again QIRD SYNCHRONOUSLY 
+		
+		/** Flush socket
+		 */
+		void flushSocket();
+		
+		/** Get a character but will not advance the buffer head
+			@return character
+		 */
+		int peekSocket();
+
+		/** Close a socket
+			@param client1Server0	1 if modem acts as client, 0 if acts as server
+			@param id_socket		Local socket number
+			@return 0 if command running, 1 if success, otherwise error
+		*/
+		int disconnectTCP(bool client1Server0, int id_socket);
+		
+		/** Recognize unsolicited event
+			@param from		
+			@return true if successful
+		*/		
+		bool recognizeUnsolicitedEvent(byte from);
+	
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		*/
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		/** Get client socket
+			@param socket		
+			@return	socket
+		 */
+		int getSocket(int socket=-1);
+		
+		/** Release socket
+			@param socket		Socket for release
+		 */
+		void releaseSocket(int socket);
+		
+		/** Get socket client status
+			@param socket		Socket
+			@return socket client status
+		 */
+		bool getStatusSocketClient(uint8_t socket);
+		
+};
+
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiServerProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiServerProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiServerProvider.cpp	(revision 175)
@@ -0,0 +1,357 @@
+#include <GSM3ShieldV1MultiServerProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <Arduino.h>
+
+#define __NCLIENTS_MAX__ 3
+
+const char _command_QILOCIP[] PROGMEM = "AT+QILOCIP";
+
+GSM3ShieldV1MultiServerProvider::GSM3ShieldV1MultiServerProvider()
+{
+	theGSM3MobileServerProvider=this;
+	socketsAsServer=0;
+	socketsAccepted=0;
+	theGSM3ShieldV1ModemCore.registerUMProvider(this);
+};
+
+//Response management.
+void GSM3ShieldV1MultiServerProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case NONE:
+			theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from);
+			break;
+		case CONNECTSERVER:
+			connectTCPServerContinue();
+			break;	
+		case GETIP:
+			getIPContinue();
+			break;
+	}
+}
+
+//Connect Server main function.
+int GSM3ShieldV1MultiServerProvider::connectTCPServer(int port)
+{
+	// We forget about LocalIP as it has no real use, the modem does whatever it likes
+	theGSM3ShieldV1ModemCore.setPort(port);			
+	theGSM3ShieldV1ModemCore.openCommand(this,CONNECTSERVER);
+	connectTCPServerContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Connect Server continue function.
+void GSM3ShieldV1MultiServerProvider::connectTCPServerContinue()
+{
+
+	bool resp;
+	// 1: Read Local IP "AT+QILOCIP"
+	// 2: Waiting for IP and Set local port "AT+QILPORT"
+	// 3: Waiting for QILPOR OK andConfigure as server "AT+QISERVER"
+	// 4: Wait for SERVER OK
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		//"AT+QILOCIP."
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_QILOCIP);
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		//Not IP storing but the command is necessary.
+		//if(parseQILOCIP_rsp(local_IP, local_IP_Length, resp))
+		// This awful trick saves some RAM bytes
+		char aux[3];
+		aux[0]='\r';aux[1]='\n';aux[2]=0;
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, aux))
+	    {
+			//Response received
+			if(resp)
+			{
+				// Great. Go for the next step
+				// AT+QILPORT
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILPORT=\"TCP\","),false);
+				theGSM3ShieldV1ModemCore.print(	theGSM3ShieldV1ModemCore.getPort());
+				theGSM3ShieldV1ModemCore.print('\r');
+				theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;	
+	case 3:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			// Response received
+			if(resp)
+			{
+				// OK received
+				// Great. Go for the next step
+				// AT+QISERVER
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QISERVER=0,"),false);
+				theGSM3ShieldV1ModemCore.print(__NCLIENTS_MAX__);
+				theGSM3ShieldV1ModemCore.print('\r');
+				theGSM3ShieldV1ModemCore.setCommandCounter(4);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;	
+	case 4:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			// Response received
+			// OK received, kathapoon, chessespoon
+			if (resp) theGSM3ShieldV1ModemCore.closeCommand(1);
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}		
+		break;	
+	}
+}
+
+//QILOCIP parse.
+bool GSM3ShieldV1MultiServerProvider::parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp)
+{
+	if (!(theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("\r\n","\r\n", LocalIP, LocalIPlength)))
+		rsp = false;
+	else 
+		rsp = true;
+	return true;
+}
+
+//Get IP main function.
+int GSM3ShieldV1MultiServerProvider::getIP(char* LocalIP, int LocalIPlength)
+{
+	theGSM3ShieldV1ModemCore.setPhoneNumber(LocalIP);
+	theGSM3ShieldV1ModemCore.setPort(LocalIPlength);
+	theGSM3ShieldV1ModemCore.openCommand(this,GETIP);
+	getIPContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+void GSM3ShieldV1MultiServerProvider::getIPContinue()
+{
+
+	bool resp;
+	// 1: Read Local IP "AT+QILOCIP"
+	// 2: Waiting for IP.
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		//AT+QILOCIP
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_QILOCIP);
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(parseQILOCIP_rsp(theGSM3ShieldV1ModemCore.getPhoneNumber(), theGSM3ShieldV1ModemCore.getPort(), resp))
+	    {
+			if (resp) 
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;	
+	}
+}
+
+bool GSM3ShieldV1MultiServerProvider::getSocketAsServerModemStatus(int s)
+{
+	if (socketsAccepted&(0x0001<<s)) 
+		return true;
+	else return false;
+}
+
+
+//URC recognize.
+bool GSM3ShieldV1MultiServerProvider::recognizeUnsolicitedEvent(byte oldTail)
+{
+
+	int nlength;
+	char auxLocate [15];
+	
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("0, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(0);
+		socketsAccepted &= ~(0x0001);
+		//SerialUSB.println("JCR_DB REMOTE CLOSED");
+	}
+	
+	//REMOTE SOCKET CLOSED.
+	
+	prepareAuxLocate(PSTR("1, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(1);
+		socketsAccepted &= ~(0x0002);
+	}
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("2, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(2);
+		socketsAccepted &= ~(0x0004);
+	}
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("3, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(3);
+		socketsAccepted &= ~(0x0008);
+	}
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("4, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(4);
+		socketsAccepted &= ~(0x0010);
+	}
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("5, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(5);
+		socketsAccepted &= ~(0x0020);
+	}
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("6, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(6);
+		socketsAccepted &= ~(0x0040);
+	}
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("7, CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		releaseSocket(7);
+		socketsAccepted &= ~(0x0080);
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("0, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0001);
+		return true;
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("1, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0002);
+		return true;
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("2, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0004);
+		return true;
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("3, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0008);
+		return true;
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("4, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0010);
+		return true;
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("5, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0020);
+		return true;
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("6, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0040);
+		return true;
+	}
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("7, REMOTE IP"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.gss.cb.flush();
+		socketsAccepted |= (0x0080);
+		return true;
+	}
+	
+	
+	return false;
+}
+
+bool GSM3ShieldV1MultiServerProvider::getStatusSocketAsServer(uint8_t socket)
+{
+	if(socketsAsServer&(0x0001<<socket))
+		return 1;
+	else
+		return 0;
+};
+
+void GSM3ShieldV1MultiServerProvider::releaseSocket(int socket)
+{
+	if (socketsAsServer&((0x0001)<<socket))
+		socketsAsServer^=((0x0001)<<socket);
+}
+
+int GSM3ShieldV1MultiServerProvider::getNewOccupiedSocketAsServer()
+{
+	int i;
+	ready();
+	for(i=minSocketAsServer(); i<=maxSocketAsServer(); i++)
+	{
+		if ((!(socketsAsServer&(0x0001<<i))) && getSocketAsServerModemStatus(i))
+		{
+			socketsAsServer|=((0x0001)<<i);	
+			return i;
+		}
+	}
+	// No new occupied
+	return -1;
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiServerProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiServerProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1MultiServerProvider.h	(revision 175)
@@ -0,0 +1,136 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SHIELDV1SERVERPROVIDER__
+#define __GSM3_SHIELDV1SERVERPROVIDER__
+
+#include <GSM3MobileServerProvider.h>
+#include <GSM3ShieldV1BaseProvider.h>
+
+class GSM3ShieldV1MultiServerProvider : public GSM3MobileServerProvider,  public GSM3ShieldV1BaseProvider
+{
+	private:
+		
+		// Used sockets
+		uint8_t socketsAsServer;
+		uint8_t socketsAccepted;
+
+		/** Continue to connect TCP server function
+		 */
+		void connectTCPServerContinue();
+
+		/** Continue to get IP function
+		 */
+		void getIPContinue();
+		
+		/** Release socket
+			@param socket		Socket
+		 */
+		void releaseSocket(int socket);
+		
+		/** Parse QILOCIP response
+			@param LocalIP			Buffer for save local IP address
+			@param LocalIPlength	Buffer size
+			@param rsp				Returns if expected response exists
+			@return true if command executed correctly
+		 */
+		bool parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp);
+		
+	public:
+	
+		/** Constructor */
+		GSM3ShieldV1MultiServerProvider();
+		
+		/** minSocketAsServer
+			@return 0
+		 */
+		int minSocketAsServer(){return 0;};
+		
+		/** maxSocketAsServer
+			@return 0
+		 */
+		int maxSocketAsServer(){return 4;};
+		
+		/** Get modem status
+			@param s
+			@return modem status (true if connected)
+		 */
+		bool getSocketAsServerModemStatus(int s);
+		
+		/** Get new occupied socket as server
+			@return command error if exists
+		 */
+		int getNewOccupiedSocketAsServer();
+
+		/** Connect server to TCP port
+			@param port			TCP port
+			@return	command error if exists
+		 */
+		int connectTCPServer(int port);
+		
+		/** Get server IP address
+			@param LocalIP			Buffer for copy IP address
+			@param LocalIPlength	Length of buffer
+			@return command error if exists
+		 */
+		int getIP(char* LocalIP, int LocalIPlength);
+		
+//		int disconnectTCP(bool client1Server0, int id_socket);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		/** Get socket status as server
+			@param socket		Socket to get status
+			@return socket status
+		 */
+		bool getStatusSocketAsServer(uint8_t socket);
+		
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+		
+		/** Recognize unsolicited event
+			@param oldTail		
+			@return true if successful
+		 */		
+		bool recognizeUnsolicitedEvent(byte oldTail);
+
+	
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1PinManagement.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1PinManagement.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1PinManagement.cpp	(revision 175)
@@ -0,0 +1,201 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+
+#include <GSM3ShieldV1PinManagement.h>
+
+// constructor
+GSM3ShieldV1PinManagement::GSM3ShieldV1PinManagement()
+{
+};
+
+// reset the modem for direct access
+void GSM3ShieldV1PinManagement::begin()
+{
+	// reset hardware
+	gsm.HWrestart();
+
+	pin_used = false;
+	
+	// check modem response
+	modemAccess.writeModemCommand("AT", 1000);
+	modemAccess.writeModemCommand("ATE0", 1000);
+}
+
+/*
+  Check PIN status
+*/
+int GSM3ShieldV1PinManagement::isPIN()
+{
+  String res = modemAccess.writeModemCommand("AT+CPIN?",1000);
+  // Check response
+  char res_to_compare[res.length()];
+  res.toCharArray(res_to_compare, res.length());
+  if(strstr(res_to_compare, "READY") != NULL)
+    return 0;
+  else if(strstr(res_to_compare, "SIM PIN") != NULL)
+    return 1; 
+  else if(strstr(res_to_compare, "SIM PUK") != NULL)
+    return -1;
+  else
+    return -2;
+}
+
+/*
+  Check PIN code
+*/
+int GSM3ShieldV1PinManagement::checkPIN(String pin)
+{
+  String res = modemAccess.writeModemCommand("AT+CPIN=" + pin,1000);
+  // check response
+  char res_to_compare[res.length()];
+  res.toCharArray(res_to_compare, res.length());
+  if(strstr(res_to_compare, "OK") == NULL)
+    return -1;
+  else
+    return 0;
+}
+
+/*
+  Check PUK code
+*/
+int GSM3ShieldV1PinManagement::checkPUK(String puk, String pin)
+{
+  String res = modemAccess.writeModemCommand("AT+CPIN=\"" + puk + "\",\"" + pin + "\"",1000);
+  // check response
+  char res_to_compare[res.length()];
+  res.toCharArray(res_to_compare, res.length());
+  if(strstr(res_to_compare, "OK") == NULL)
+    return -1;
+  else
+    return 0;
+}
+
+/*
+  Change PIN code
+*/
+void GSM3ShieldV1PinManagement::changePIN(String old, String pin)
+{
+  String res = modemAccess.writeModemCommand("AT+CPWD=\"SC\",\"" + old + "\",\"" + pin + "\"",2000);
+  SerialUSB.println(res);
+  // check response
+  char res_to_compare[res.length()];
+  res.toCharArray(res_to_compare, res.length());
+  if(strstr(res_to_compare, "OK") != NULL)
+    SerialUSB.println("Pin changed succesfully.");
+  else
+    SerialUSB.println("ERROR");
+}
+
+/*
+  Switch PIN status
+*/
+void GSM3ShieldV1PinManagement::switchPIN(String pin)
+{
+  String res = modemAccess.writeModemCommand("AT+CLCK=\"SC\",2",1000);
+  // check response
+  char res_to_compare[res.length()];
+  res.toCharArray(res_to_compare, res.length());
+  if(strstr(res_to_compare, "0") != NULL)
+  {
+    res = modemAccess.writeModemCommand("AT+CLCK=\"SC\",1,\"" + pin + "\"",1000);
+    // check response
+    char res_to_compare[res.length()];
+    res.toCharArray(res_to_compare, res.length());
+    if(strstr(res_to_compare, "OK") == NULL)
+    {
+      SerialUSB.println("ERROR");
+      pin_used = false;
+    }
+    else
+    {
+      SerialUSB.println("OK. PIN lock on.");
+      pin_used = true;
+    }
+  }
+  else if(strstr(res_to_compare, "1") != NULL)
+  {
+    res = modemAccess.writeModemCommand("AT+CLCK=\"SC\",0,\"" + pin + "\"",1000);
+    // check response
+    char res_to_compare[res.length()];
+    res.toCharArray(res_to_compare, res.length());
+    if(strstr(res_to_compare, "OK") == NULL)
+    {
+      SerialUSB.println("ERROR");
+      pin_used = true;
+    }
+    else
+    {
+      SerialUSB.println("OK. PIN lock off.");
+      pin_used = false;
+    }
+  }
+  else
+  {
+    SerialUSB.println("ERROR");
+  }
+}
+
+/*
+  Check registrer
+*/
+int GSM3ShieldV1PinManagement::checkReg()
+{
+  delay(5000);
+  String res = modemAccess.writeModemCommand("AT+CREG?",1000);
+  // check response
+  char res_to_compare[res.length()];
+  res.toCharArray(res_to_compare, res.length());
+  if(strstr(res_to_compare, "1") != NULL)
+    return 0;
+  else if(strstr(res_to_compare, "5") != NULL)
+    return 1;
+  else
+    return -1; 
+}
+
+/*
+  Return if PIN lock is used
+*/
+bool GSM3ShieldV1PinManagement::getPINUsed()
+{
+	return pin_used;
+}
+
+/*
+  Set if PIN lock is used
+*/
+void GSM3ShieldV1PinManagement::setPINUsed(bool used)
+{
+	pin_used = used;
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1PinManagement.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1PinManagement.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1PinManagement.h	(revision 175)
@@ -0,0 +1,103 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3SHIELDV1PINMANAGEMENT_
+#define _GSM3SHIELDV1PINMANAGEMENT_
+
+#include <GSM3ShieldV1AccessProvider.h>
+#include <GSM3ShieldV1DirectModemProvider.h>
+
+class GSM3ShieldV1PinManagement
+{
+
+	private:
+	
+		GSM3ShieldV1AccessProvider gsm; // GSM access required for network register with PIN code     
+		GSM3ShieldV1DirectModemProvider modemAccess; 
+		bool pin_used; // determines if pin lock is activated 
+		
+	public:
+
+		/** Constructor */
+		GSM3ShieldV1PinManagement();
+		
+		/** Check modem response and restart it
+		 */
+		void begin();
+	
+		/** Check if PIN lock or PUK lock is activated
+			@return 0 if PIN lock is off, 1 if PIN lock is on, -1 if PUK lock is on, -2 if error exists
+		 */
+		int isPIN();
+		
+		/** Check if PIN code is correct and valid
+			@param pin			PIN code
+			@return 0 if is correct, -1 if is incorrect
+		 */
+		int checkPIN(String pin);
+		
+		/** Check if PUK code is correct and establish new PIN code
+			@param puk			PUK code
+			@param pin			New PIN code
+			@return 0 if successful, otherwise return -1
+		 */
+		int checkPUK(String puk, String pin);
+		
+		/** Change PIN code
+			@param old			Old PIN code
+			@param pin			New PIN code
+		 */
+		void changePIN(String old, String pin);
+		
+		/** Change PIN lock status
+			@param pin			PIN code
+		 */
+		void switchPIN(String pin);
+		
+		/** Check if modem was registered in GSM/GPRS network
+			@return 0 if modem was registered, 1 if modem was registered in roaming, -1 if error exists
+		 */
+		int checkReg();
+		
+		/** Return if PIN lock is used
+			@return true if PIN lock is used, otherwise, return false
+		 */
+		bool getPINUsed();
+		
+		/** Set PIN lock status
+			@param used			New PIN lock status
+		 */
+		void setPINUsed(bool used);
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1SMSProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1SMSProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1SMSProvider.cpp	(revision 175)
@@ -0,0 +1,294 @@
+#include <GSM3ShieldV1SMSProvider.h>
+#include <Arduino.h>
+	
+GSM3ShieldV1SMSProvider::GSM3ShieldV1SMSProvider()
+{
+	theGSM3SMSProvider=this;
+};
+
+//Send SMS begin function.
+int GSM3ShieldV1SMSProvider::beginSMS(const char* to)
+{
+	if((theGSM3ShieldV1ModemCore.getStatus() != GSM_READY)&&(theGSM3ShieldV1ModemCore.getStatus() != GPRS_READY))
+	  return 2;
+
+	theGSM3ShieldV1ModemCore.setPhoneNumber((char*)to);
+	theGSM3ShieldV1ModemCore.openCommand(this,BEGINSMS);
+	beginSMSContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Send SMS continue function.
+void GSM3ShieldV1SMSProvider::beginSMSContinue()
+{
+	bool resp;
+	// 1: Send AT
+	// 2: wait for > and write text
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGS=\""), false);
+		theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber());
+		theGSM3ShieldV1ModemCore.print("\"\r");
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, ">"))
+		{
+			if (resp) theGSM3ShieldV1ModemCore.closeCommand(1);
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		break;
+	}
+}
+
+//Send SMS write function.
+void GSM3ShieldV1SMSProvider::writeSMS(char c)
+{
+	theGSM3ShieldV1ModemCore.write(c);
+}
+
+//Send SMS begin function.
+int GSM3ShieldV1SMSProvider::endSMS()
+{
+	theGSM3ShieldV1ModemCore.openCommand(this,ENDSMS);
+	endSMSContinue();
+	while(ready()==0) delay(100);
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Send SMS continue function.
+void GSM3ShieldV1SMSProvider::endSMSContinue()
+{
+	bool resp;
+	// 1: Send #26
+	// 2: wait for OK
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		theGSM3ShieldV1ModemCore.write(26);
+		theGSM3ShieldV1ModemCore.print("\r");
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			if (resp) 
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		break;
+	}
+}
+
+//Available SMS main function.
+int GSM3ShieldV1SMSProvider::availableSMS()
+{
+	flagReadingSMS = 0;
+	theGSM3ShieldV1ModemCore.openCommand(this,AVAILABLESMS);
+	availableSMSContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Available SMS continue function.
+void GSM3ShieldV1SMSProvider::availableSMSContinue()
+{
+	// 1:  AT+CMGL="REC UNREAD",1
+	// 2: Receive +CMGL: _id_ ... READ","_numero_" ... \n_mensaje_\nOK
+	// 3: Send AT+CMGD= _id_
+	// 4: Receive OK
+	// 5: Remaining SMS text in case full buffer.
+	// This implementation really does not care much if the modem aswers trash to CMGL
+	bool resp;
+	//int msglength_aux;
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:	
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGL=\"REC UNREAD\",1"));
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(parseCMGL_available(resp))
+			{
+				if (!resp) theGSM3ShieldV1ModemCore.closeCommand(4);
+				else theGSM3ShieldV1ModemCore.closeCommand(1);
+			}
+		break;
+	}
+	  
+}	
+		
+//SMS available parse.
+bool GSM3ShieldV1SMSProvider::parseCMGL_available(bool& rsp)
+{
+	fullBufferSMS = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<=4);
+	if (!(theGSM3ShieldV1ModemCore.theBuffer().chopUntil("+CMGL:", true)))
+		rsp = false;
+	else 
+		rsp = true;
+	idSMS=theGSM3ShieldV1ModemCore.theBuffer().readInt();
+
+	//If there are 2 SMS in buffer, response is ...CRLFCRLF+CMGL
+	twoSMSinBuffer = theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\n+");
+
+	checkSecondBuffer = 0;
+	
+	return true;
+}
+
+//remoteNumber SMS function.
+int GSM3ShieldV1SMSProvider::remoteSMSNumber(char* number, int nlength)
+{
+	theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("READ\",\"", "\"", number, nlength);	
+	
+	return 1;
+}
+
+//remoteNumber SMS function.
+int GSM3ShieldV1SMSProvider::readSMS()
+{
+	char charSMS;
+	//First char.
+	if (!flagReadingSMS) 
+	{
+		flagReadingSMS = 1;
+		theGSM3ShieldV1ModemCore.theBuffer().chopUntil("\n", true);
+	}
+	charSMS = theGSM3ShieldV1ModemCore.theBuffer().read(); 
+	
+	//Second Buffer.
+	if (checkSecondBuffer)
+	{
+		checkSecondBuffer = 0;
+		twoSMSinBuffer = theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\n+");
+	}
+
+	//Case the last char in buffer.
+	if ((!twoSMSinBuffer)&&fullBufferSMS&&(theGSM3ShieldV1ModemCore.theBuffer().availableBytes()==127))
+	{
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		fullBufferSMS = 0;
+		checkSecondBuffer = 1;
+		theGSM3ShieldV1ModemCore.openCommand(this,XON);
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		delay(10);
+		
+		return charSMS;
+	}
+	//Case two SMS in buffer
+	else if (twoSMSinBuffer)
+	{
+		if (theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\n+")) 
+		{
+					return charSMS;
+		}
+		else 
+		{
+			theGSM3ShieldV1ModemCore.theBuffer().flush();
+			theGSM3ShieldV1ModemCore.openCommand(this,XON);
+			theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+			delay(10);
+			return 0;
+		}
+	}
+	//Case 1 SMS and buffer not full
+	else if (!fullBufferSMS)
+	{
+		if (theGSM3ShieldV1ModemCore.theBuffer().locate("\r\n\r\nOK")) 
+		{
+			return charSMS;
+		}
+		else 
+		{
+			theGSM3ShieldV1ModemCore.theBuffer().flush();
+			theGSM3ShieldV1ModemCore.openCommand(this,XON);
+			theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+			delay(10);
+			return 0;
+		}
+	}
+	//Case to read all the chars in buffer to the end.
+	else 
+	{
+		return charSMS;		
+	}
+}	
+
+//Read socket main function.
+int GSM3ShieldV1SMSProvider::peekSMS()
+{
+	if (!flagReadingSMS) 
+	{
+		flagReadingSMS = 1;
+		theGSM3ShieldV1ModemCore.theBuffer().chopUntil("\n", true);
+	}
+
+	return theGSM3ShieldV1ModemCore.theBuffer().peek(0); 
+}
+	
+//Flush SMS main function.
+void GSM3ShieldV1SMSProvider::flushSMS()
+{
+
+	//With this, sms data can fill up to 2x128+5x128 bytes.
+	for (int aux = 0;aux<5;aux++)
+	{
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		delay(10);
+	}
+		
+	theGSM3ShieldV1ModemCore.openCommand(this,FLUSHSMS);
+	flushSMSContinue();
+}
+
+//Send SMS continue function.
+void GSM3ShieldV1SMSProvider::flushSMSContinue()
+{
+	bool resp;
+	// 1: Deleting SMS
+	// 2: wait for OK
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CMGD="), false);
+		theGSM3ShieldV1ModemCore.print(idSMS);
+		theGSM3ShieldV1ModemCore.print("\r");
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+			if (resp) theGSM3ShieldV1ModemCore.closeCommand(1);
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		break;
+	}
+}
+
+void GSM3ShieldV1SMSProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+/*		case XON:
+			if (flagReadingSocket) 
+				{
+//					flagReadingSocket = 0;
+					fullBufferSocket = (theGSM3ShieldV1ModemCore.theBuffer().availableBytes()<3);
+				}
+			else theGSM3ShieldV1ModemCore.openCommand(this,NONE);
+			break;
+*/		case NONE:
+			theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from);
+			break;
+		case BEGINSMS:
+			beginSMSContinue();
+			break;
+		case ENDSMS:
+			endSMSContinue();
+			break;
+		case AVAILABLESMS:
+			availableSMSContinue();
+			break;
+		case FLUSHSMS:
+			flushSMSContinue();
+			break;
+	}
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1SMSProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1SMSProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1SMSProvider.h	(revision 175)
@@ -0,0 +1,130 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SHIELDV1SMSPROVIDER__
+#define __GSM3_SHIELDV1SMSPROVIDER__
+
+#include <GSM3ShieldV1ModemCore.h>
+#include <GSM3MobileSMSProvider.h>
+#include <GSM3ShieldV1SMSProvider.h>
+
+
+class GSM3ShieldV1SMSProvider : public GSM3MobileSMSProvider, public GSM3ShieldV1BaseProvider
+{		
+	public:
+		GSM3ShieldV1SMSProvider();
+	
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+	
+		/** Begin a SMS to send it
+			@param to			Destination
+			@return error command if it exists
+		 */
+		inline int beginSMS(const char* to);
+		
+		/** Write a SMS character by character
+			@param c			Character
+		 */
+		inline void writeSMS(char c);
+		
+		/** End SMS
+			@return error command if it exists
+		 */
+		inline int endSMS();
+		
+		/** Check if SMS available and prepare it to be read
+			@return number of bytes in a received SMS
+		 */
+		int availableSMS();
+		
+		/** Read a byte but do not advance the buffer header (circular buffer)
+			@return character
+		 */
+		int peekSMS();
+		
+		/** Delete the SMS from Modem memory and proccess answer
+		 */
+		void flushSMS();
+		
+		/** Read sender number phone
+			@param number		Buffer for save number phone
+			@param nlength		Buffer length
+			@return 1 success, >1 error
+		 */
+		int remoteSMSNumber(char* number, int nlength); //Before reading the SMS, read the phone number.
+		
+		/** Read one char for SMS buffer (advance circular buffer)
+			@return character
+		 */
+		int readSMS();
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+
+	private:	
+	
+		int idSMS; // Id from current SMS being read.
+		bool flagReadingSMS; // To detect first SMS char if not yet reading.
+		bool fullBufferSMS; // To detect if the SMS being read needs another buffer. 
+		bool twoSMSinBuffer; // To detect if the buffer has more than 1 SMS.
+		bool checkSecondBuffer; // Pending to detect if the second buffer has more than 1 SMS.
+
+		/** Continue to begin SMS function
+		 */
+		void beginSMSContinue();
+		
+		/** Continue to end SMS function
+		 */
+		void endSMSContinue();
+		
+		/** Continue to available SMS function
+		 */
+		void availableSMSContinue();
+		
+		/** Continue to flush SMS function
+		 */
+		void flushSMSContinue();
+		
+		/** Parse CMGL response
+			@param rsp			Returns true if expected response exists
+			@return	true if command executed correctly
+		 */
+		bool parseCMGL_available(bool& rsp);
+};
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ScanNetworks.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ScanNetworks.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ScanNetworks.cpp	(revision 175)
@@ -0,0 +1,126 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+
+#include <GSM3ShieldV1ScanNetworks.h>
+
+GSM3ShieldV1ScanNetworks::GSM3ShieldV1ScanNetworks(bool trace): modem(trace)
+{	
+}
+
+GSM3_NetworkStatus_t GSM3ShieldV1ScanNetworks::begin()
+{
+	modem.begin();
+	modem.restartModem();
+	// check modem response
+	modem.writeModemCommand("AT", 1000);
+	modem.writeModemCommand("ATE0", 1000);
+	return IDLE;
+}
+
+String GSM3ShieldV1ScanNetworks::getCurrentCarrier()
+{
+	String modemResponse = modem.writeModemCommand("AT+COPS?", 2000);
+	
+	// Parse and check response
+	char res_to_split[modemResponse.length()];
+	modemResponse.toCharArray(res_to_split, modemResponse.length());
+	if(strstr(res_to_split,"ERROR") == NULL){
+		// Tokenizer
+		char *ptr_token;
+		ptr_token = strtok(res_to_split, "\"");
+		ptr_token = strtok(NULL, "\"");
+		String final_result = ptr_token;
+		return final_result;
+	}else{
+		return String(NULL);
+	}
+}
+
+String GSM3ShieldV1ScanNetworks::getSignalStrength()
+{
+	String modemResponse = modem.writeModemCommand("AT+CSQ", 2000);
+	char res_to_split[modemResponse.length()];
+	modemResponse.toCharArray(res_to_split, modemResponse.length());
+	if((strstr(res_to_split,"ERROR") == NULL) | (strstr(res_to_split,"99") == NULL)){
+		// Tokenizer
+		char *ptr_token;
+		ptr_token = strtok(res_to_split, ":");
+		ptr_token = strtok(NULL, ":");
+		ptr_token = strtok(ptr_token, ",");
+		String final_result = ptr_token;
+		final_result.trim();
+		return final_result;
+	}else{
+		return String(NULL);
+	}
+}
+
+String GSM3ShieldV1ScanNetworks::readNetworks()
+{
+	String modemResponse = modem.writeModemCommand("AT+COPS=?",20000);
+	String result;
+	bool inQuotes=false;
+	int quoteCounter=0;
+	for(unsigned int i=0; i<modemResponse.length();i++)
+	{
+		if(modemResponse[i]=='"')
+		{
+			if(!inQuotes)
+			{
+				inQuotes=true;
+				quoteCounter++;
+				if(quoteCounter==1)
+					result+="> ";
+			}
+			else
+			{
+				inQuotes=false;
+				if(quoteCounter==3)
+					quoteCounter=0;
+				if(quoteCounter==1)
+					result+="\n";
+				
+			}
+		}
+		else
+		{
+			if(inQuotes&&(quoteCounter==1))
+			{
+				result+=modemResponse[i];
+			}
+		}
+	}
+	return result;
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ScanNetworks.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ScanNetworks.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ScanNetworks.h	(revision 175)
@@ -0,0 +1,75 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3SHIELDV1SCANNETWORKS__
+#define __GSM3SHIELDV1SCANNETWORKS__
+
+// This class executes band management functions for the ShieldV1
+#include <GSM3ShieldV1AccessProvider.h>
+#include <GSM3ShieldV1DirectModemProvider.h>
+
+class GSM3ShieldV1ScanNetworks
+{
+	private:
+		GSM3ShieldV1DirectModemProvider modem;
+				
+	public:
+	
+		/** Constructor
+			@param trace		if true, dumps all AT dialogue to Serial
+			@return - 
+		*/
+		GSM3ShieldV1ScanNetworks(bool trace=false);
+		
+		/** begin (forces modem hardware restart, so we begin from scratch)
+			@return Always returns IDLE status
+		*/
+		GSM3_NetworkStatus_t begin();
+
+		/**	Read current carrier
+			@return Current carrier
+		 */
+		String getCurrentCarrier();
+		
+		/** Obtain signal strength
+			@return Signal Strength
+		 */
+		String getSignalStrength();
+		
+		/** Search available carriers
+			@return A string with list of networks available
+		 */
+		String readNetworks();
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ServerProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ServerProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ServerProvider.cpp	(revision 175)
@@ -0,0 +1,205 @@
+#include <GSM3ShieldV1ServerProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <Arduino.h>
+
+GSM3ShieldV1ServerProvider::GSM3ShieldV1ServerProvider()
+{
+	theGSM3MobileServerProvider=this;
+};
+
+//Response management.
+void GSM3ShieldV1ServerProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case NONE:
+			theGSM3ShieldV1ModemCore.gss.cb.deleteToTheEnd(from);
+			break;
+		case CONNECTSERVER:
+			connectTCPServerContinue();
+			break;	
+		/*case GETIP:
+			getIPContinue();
+			break;*/
+	}
+}
+
+//Connect Server main function.
+int GSM3ShieldV1ServerProvider::connectTCPServer(int port)
+{
+	// We forget about LocalIP as it has no real use, the modem does whatever it likes
+	theGSM3ShieldV1ModemCore.setPort(port);			
+	theGSM3ShieldV1ModemCore.openCommand(this,CONNECTSERVER);
+	// From this moment on we wait for a call
+	connectTCPServerContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Connect Server continue function.
+void GSM3ShieldV1ServerProvider::connectTCPServerContinue()
+{
+
+	bool resp;
+	// 1: Read Local IP "AT+QILOCIP"
+	// 2: Waiting for IP and Set local port "AT+QILPORT"
+	// 3: Waiting for QILPOR OK andConfigure as server "AT+QISERVER"
+	// 4: Wait for SERVER OK
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		//"AT+QILOCIP."
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILOCIP"));
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		//Not IP storing but the command is necessary.
+		//if(parseQILOCIP_rsp(local_IP, local_IP_Length, resp))
+		// This awful trick saves some RAM bytes
+		char aux[3];
+		aux[0]='\r';aux[1]='\n';aux[2]=0;
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp, aux))
+	    {
+			//Response received
+			if(resp)
+			{
+				// Great. Go for the next step
+				// AT+QILPORT
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILPORT=\"TCP\","),false);
+				theGSM3ShieldV1ModemCore.print(	theGSM3ShieldV1ModemCore.getPort());
+				theGSM3ShieldV1ModemCore.print('\r');
+				theGSM3ShieldV1ModemCore.setCommandCounter(3);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;	
+	case 3:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			// Response received
+			if(resp)
+			{
+				// OK received
+				// Great. Go for the next step
+				// AT+QISERVER
+				theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QISERVER"),true);
+				theGSM3ShieldV1ModemCore.setCommandCounter(4);
+			}
+			else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}	
+		break;	
+	case 4:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+	    {
+			// Response received
+			// OK received, kathapoon, chessespoon
+			if (resp) 
+			{
+				theGSM3ShieldV1ModemCore.registerUMProvider(this);
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			}
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}		
+		break;	
+	}
+}
+
+//QILOCIP parse.
+/*bool GSM3ShieldV1ServerProvider::parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp)
+{
+	if (!(theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("\r\n","\r\n", LocalIP, LocalIPlength)))
+		rsp = false;
+	else 
+		rsp = true;
+	return true;
+}
+
+//Get IP main function.
+int GSM3ShieldV1ServerProvider::getIP(char* LocalIP, int LocalIPlength)
+{
+	theGSM3ShieldV1ModemCore.setPhoneNumber(LocalIP);
+	theGSM3ShieldV1ModemCore.setPort(LocalIPlength);
+	theGSM3ShieldV1ModemCore.openCommand(this,GETIP);
+	getIPContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+void GSM3ShieldV1ServerProvider::getIPContinue()
+{
+
+	bool resp;
+	// 1: Read Local IP "AT+QILOCIP"
+	// 2: Waiting for IP.
+
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+	case 1:
+		//AT+QILOCIP
+		theGSM3ShieldV1ModemCore.genericCommand_rq(_command_MonoQILOCIP);
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(parseQILOCIP_rsp(theGSM3ShieldV1ModemCore.getPhoneNumber(), theGSM3ShieldV1ModemCore.getPort(), resp))
+	    {
+			if (resp) 
+				theGSM3ShieldV1ModemCore.closeCommand(1);
+			else 
+				theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		break;	
+	}
+}*/
+
+bool GSM3ShieldV1ServerProvider::getSocketAsServerModemStatus(int s)
+{
+	if(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED)
+		return true;
+	else 
+		return false;
+}
+
+
+//URC recognize.
+bool GSM3ShieldV1ServerProvider::recognizeUnsolicitedEvent(byte oldTail)
+{
+
+	int nlength;
+	char auxLocate [15];
+	
+	//REMOTE SOCKET CLOSED.
+	prepareAuxLocate(PSTR("CLOSED\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.setStatus(GPRS_READY);
+	}
+	
+	
+	//REMOTE SOCKET ACCEPTED.
+	prepareAuxLocate(PSTR("CONNECT\r\n"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.gss.cb.locate(auxLocate))
+	{
+		//To detect remote socket closed for example inside socket data.
+		theGSM3ShieldV1ModemCore.theBuffer().chopUntil(auxLocate, true);
+		theGSM3ShieldV1ModemCore.gss.spaceAvailable();
+		theGSM3ShieldV1ModemCore.setStatus(TRANSPARENT_CONNECTED);
+		return true;
+	}
+	
+	return false;
+}
+
+bool GSM3ShieldV1ServerProvider::getStatusSocketAsServer(uint8_t socket)
+{
+	return(theGSM3ShieldV1ModemCore.getStatus()==TRANSPARENT_CONNECTED);
+};
+
+void GSM3ShieldV1ServerProvider::releaseSocket(int socket)
+{
+}
+
+int GSM3ShieldV1ServerProvider::getNewOccupiedSocketAsServer()
+{
+	return 0;
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ServerProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ServerProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1ServerProvider.h	(revision 175)
@@ -0,0 +1,126 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SHIELDV1SERVERPROVIDER__
+#define __GSM3_SHIELDV1SERVERPROVIDER__
+
+#include <GSM3MobileServerProvider.h>
+#include <GSM3ShieldV1BaseProvider.h>
+
+class GSM3ShieldV1ServerProvider : public GSM3MobileServerProvider,  public GSM3ShieldV1BaseProvider
+{
+	private:
+		
+		/** Continue to connect to server with TCP protocol function
+		 */
+		void connectTCPServerContinue();
+		
+		/** Continue to get IP address function
+		 */
+		//void getIPContinue();
+		
+		/** Parse QILOCIP response
+			@param LocalIP			Buffer for save local IP address
+			@param LocalIPlength	Buffer size
+			@param rsp				Returns if expected response exists
+			@return true if command executed correctly
+		 */
+		//bool parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp);
+		
+		/** Release socket
+			@param socket		Socket
+		 */
+		void releaseSocket(int socket);
+
+	public:
+	
+		/** Constructor */
+		GSM3ShieldV1ServerProvider();
+		
+		/** minSocketAsServer
+			@return 0
+		 */
+		int minSocketAsServer(){return 0;};
+		
+		/** maxSocketAsServer
+			@return 0
+		 */
+		int maxSocketAsServer(){return 0;};
+		
+		/** Get modem status
+			@param s			Socket
+			@return modem status (true if connected)
+		 */
+		bool getSocketAsServerModemStatus(int s);
+		
+		/** Get new occupied socket as server
+			@return return -1 if no new socket has been occupied
+		 */
+		int getNewOccupiedSocketAsServer();
+
+		/** Connect server to TCP port
+			@param port			TCP port
+			@return	command error if exists
+		 */
+		int connectTCPServer(int port);
+		
+		//int getIP(char* LocalIP, int LocalIPlength);
+//		int disconnectTCP(bool client1Server0, int id_socket);
+		
+		/** Get last command status
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		/** Get socket status as server
+			@param socket		Socket to get status
+			@return socket status
+		 */
+		bool getStatusSocketAsServer(uint8_t socket);
+		
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+		
+		/** Recognize unsolicited event
+			@param oldTail		
+			@return true if successful
+		 */
+		bool recognizeUnsolicitedEvent(byte oldTail);
+
+	
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1VoiceProvider.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1VoiceProvider.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1VoiceProvider.cpp	(revision 175)
@@ -0,0 +1,215 @@
+#include <GSM3ShieldV1VoiceProvider.h>
+#include <Arduino.h>
+
+GSM3ShieldV1VoiceProvider::GSM3ShieldV1VoiceProvider()
+ {
+	phonelength=0;
+	theGSM3MobileVoiceProvider=this;
+ }
+ 
+ void GSM3ShieldV1VoiceProvider::initialize()
+ {
+ 	theGSM3ShieldV1ModemCore.registerUMProvider(this);
+ }
+ 
+//Voice Call main function.
+int GSM3ShieldV1VoiceProvider::voiceCall(const char* to)
+{
+	theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATD"),false);
+	theGSM3ShieldV1ModemCore.print(to);
+	theGSM3ShieldV1ModemCore.print(";\r");
+	setvoiceCallStatus(CALLING);
+	return 1;
+}
+
+//Retrieve calling number main function.
+int GSM3ShieldV1VoiceProvider::retrieveCallingNumber (char* buffer, int bufsize)
+{
+	theGSM3ShieldV1ModemCore.setPhoneNumber(buffer);
+	phonelength = bufsize;
+	theGSM3ShieldV1ModemCore.setCommandError(0);
+	theGSM3ShieldV1ModemCore.setCommandCounter(1);
+	theGSM3ShieldV1ModemCore.openCommand(this,RETRIEVECALLINGNUMBER);
+	retrieveCallingNumberContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Retrieve calling number Continue function.
+void GSM3ShieldV1VoiceProvider::retrieveCallingNumberContinue()
+{
+	// 1:  AT+CLCC
+	// 2: Receive +CLCC: 1,1,4,0,0,"num",129,""
+	// This implementation really does not care much if the modem aswers trash to CMGL
+	bool resp;
+	//int msglength_aux;
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:	
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+CLCC"));
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(parseCLCC(theGSM3ShieldV1ModemCore.getPhoneNumber(), phonelength))
+		{
+			theGSM3ShieldV1ModemCore.closeCommand(1);
+		}
+		break;
+	}	
+}	
+
+//CLCC parse.	
+bool GSM3ShieldV1VoiceProvider::parseCLCC(char* number, int nlength)
+{
+	theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("+CLCC: 1,1,4,0,0,\"","\"", number, nlength);
+	theGSM3ShieldV1ModemCore.theBuffer().flush();
+	return true;
+}	
+
+//Answer Call main function.
+int GSM3ShieldV1VoiceProvider::answerCall()
+{
+	theGSM3ShieldV1ModemCore.setCommandError(0);
+	theGSM3ShieldV1ModemCore.setCommandCounter(1);
+	theGSM3ShieldV1ModemCore.openCommand(this,ANSWERCALL);
+	answerCallContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Answer Call continue function.
+void GSM3ShieldV1VoiceProvider::answerCallContinue()
+{
+	// 1: ATA
+	// 2: Waiting for OK
+	
+	// This implementation really does not care much if the modem aswers trash to CMGL
+	bool resp;
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		// ATA ;
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATA"));
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		   {
+			   setvoiceCallStatus(TALKING);
+			   if (resp) theGSM3ShieldV1ModemCore.closeCommand(1);
+			   else theGSM3ShieldV1ModemCore.closeCommand(3);
+			}
+		break;
+	}
+}
+		
+//Hang Call main function.		
+int GSM3ShieldV1VoiceProvider::hangCall()
+{
+	theGSM3ShieldV1ModemCore.setCommandError(0);
+	theGSM3ShieldV1ModemCore.setCommandCounter(1);
+	theGSM3ShieldV1ModemCore.openCommand(this,HANGCALL);
+	hangCallContinue();
+	return theGSM3ShieldV1ModemCore.getCommandError();
+}
+
+//Hang Call continue function.
+void GSM3ShieldV1VoiceProvider::hangCallContinue()
+{
+	// 1: ATH
+	// 2: Waiting for OK
+	
+	bool resp;
+	switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
+    case 1:
+		//ATH
+		theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("ATH"));
+		theGSM3ShieldV1ModemCore.setCommandCounter(2);
+		break;
+	case 2:
+		if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
+		{
+		   setvoiceCallStatus(IDLE_CALL);
+		   if (resp) theGSM3ShieldV1ModemCore.closeCommand(1);
+		   else theGSM3ShieldV1ModemCore.closeCommand(3);
+		}
+		break;
+	}
+}		
+
+//Response management.
+void GSM3ShieldV1VoiceProvider::manageResponse(byte from, byte to)
+{
+	switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
+	{
+		case ANSWERCALL:
+			answerCallContinue();
+			break;
+		case HANGCALL:
+			hangCallContinue();
+			break;
+		case RETRIEVECALLINGNUMBER:
+			retrieveCallingNumberContinue();
+			break;	
+
+	}
+}
+
+//URC recognize.
+bool GSM3ShieldV1VoiceProvider::recognizeUnsolicitedEvent(byte oldTail)
+{
+
+	int nlength;
+	char auxLocate [15];
+	//RING.
+	prepareAuxLocate(PSTR("RING"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate))
+	{
+		// RING
+		setvoiceCallStatus(RECEIVINGCALL);
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		return true;
+	}
+	
+	//CALL ACEPTED.
+	prepareAuxLocate(PSTR("+COLP:"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate))
+	{
+		//DEBUG
+		//SerialUSB.println("Call Accepted.");
+		setvoiceCallStatus(TALKING);
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		return true;
+	}	
+	
+	//NO CARRIER.
+	prepareAuxLocate(PSTR("NO CARRIER"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate))
+	{
+		//DEBUG
+		//SerialUSB.println("NO CARRIER received.");
+		setvoiceCallStatus(IDLE_CALL);
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		return true;
+	}
+	
+	//BUSY.
+	prepareAuxLocate(PSTR("BUSY"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate))
+	{
+		//DEBUG	
+		//SerialUSB.println("BUSY received.");
+		setvoiceCallStatus(IDLE_CALL);
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		return true;
+	}	
+	
+	//CALL RECEPTION.
+	prepareAuxLocate(PSTR("+CLIP:"), auxLocate);
+	if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate))
+	{
+		theGSM3ShieldV1ModemCore.theBuffer().flush();
+		setvoiceCallStatus(RECEIVINGCALL);
+		return true;
+	}
+	
+	return false;
+}
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1VoiceProvider.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1VoiceProvider.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV1VoiceProvider.h	(revision 175)
@@ -0,0 +1,137 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+
+#ifndef _GSM3SHIELDV1VOICEPROVIDER_
+#define _GSM3SHIELDV1VOICEPROVIDER_
+
+#include <GSM3MobileVoiceProvider.h>
+#include <GSM3ShieldV1ModemCore.h>
+#include <GSM3ShieldV1BaseProvider.h>
+
+class GSM3ShieldV1VoiceProvider : public GSM3MobileVoiceProvider, public GSM3ShieldV1BaseProvider
+{
+	public:
+		
+		/** Constructor */
+		GSM3ShieldV1VoiceProvider();
+		
+		/** initilizer, links with modem provider */
+		void initialize();
+
+		
+		/** Manages modem response
+			@param from 		Initial byte of buffer
+			@param to 			Final byte of buffer
+		 */
+		void manageResponse(byte from, byte to);
+
+		//Call functions.
+		
+		/** Launch a voice call
+			@param number	 	Phone number to be called
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		int voiceCall(const char* number);
+		
+		/** Answer a voice call
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		int answerCall();
+		
+		/** Hang a voice call
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		int hangCall();
+		
+		/** Retrieve phone number of caller
+			@param buffer		Buffer for copy phone number
+			@param bufsize		Buffer size
+			@return If asynchronous, returns 0. If synchronous, 1 if success, other if error
+		 */
+		int retrieveCallingNumber(char* buffer, int bufsize);
+		
+		/** Get last command status
+			@return Returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int ready(){return GSM3ShieldV1BaseProvider::ready();};
+		
+		/** Recognize URC
+			@param oldTail		
+			@return true if successful
+		 */		
+		bool recognizeUnsolicitedEvent(byte oldTail);
+		
+		/** Returns voice call status
+			@return voice call status
+		 */
+		GSM3_voiceCall_st getvoiceCallStatus(){ready(); return _voiceCallstatus;};
+		
+		/**	Set voice call status
+			@param status		New status for voice call
+		 */
+		void setvoiceCallStatus(GSM3_voiceCall_st status) { _voiceCallstatus = status; };
+
+		
+	private:
+		
+		int phonelength; // Phone number length
+		
+		GSM3_voiceCall_st _voiceCallstatus; // The voiceCall status
+
+		/** Continue to voice call function
+		 */
+		void voiceCallContinue();
+		
+		/** Continue to answer call function
+		 */
+		void answerCallContinue();
+		
+		/** Continue to hang call function
+		 */
+		void hangCallContinue();
+		
+		/** Continue to retrieve calling number function
+		 */
+		void retrieveCallingNumberContinue();
+		
+		/** Parse CLCC response from buffer
+			@param number		Number initial for extract substring of response
+			@param nlength		Substring length
+			@return true if successful
+		 */
+		bool parseCLCC(char* number, int nlength);
+
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV2.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV2.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV2.cpp	(revision 175)
@@ -0,0 +1,255 @@
+/*
+This file is part of GSM3ShieldV2 library developed by Arduino.org (http://arduino.org).
+
+    GSM3ShieldV2 library is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    GSM3ShieldV2 library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with GSM3ShieldV2 library.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <GSM3ShieldV1ModemVerification.h>
+#include <GSM3ShieldV2.h>
+
+
+// constructor
+GSM3ShieldV2::GSM3ShieldV2(bool db)
+{
+	 debug=db;
+}
+
+GSM3ShieldV2::GSM3ShieldV2()
+{
+}	
+
+// get position (longitude and latitude)
+String GSM3ShieldV2::getPosition()
+{
+	String Result = "";
+	String number;
+	// AT command for obtain the current Location
+	String modemResponse = modemAccess.writeModemCommand("AT+QCELLLOC=1", 1000);
+	// Parse and check response
+	char res_to_compare[modemResponse.length()];
+	modemResponse.toCharArray(res_to_compare, modemResponse.length());
+	if(strstr(res_to_compare,"OK") == NULL)
+	{	
+		if(debug==true) SerialUSB.println(modemResponse);
+		Result =" Position not lock ";
+	}
+	else
+	{
+		if(debug==true) SerialUSB.println(modemResponse);
+		Result = modemResponse.substring(12, 33);
+		
+	}
+	return Result;	
+}
+// set speaker loudness (this command have not effect. Refer to Quectel M10 datasheet for further informaions  )
+String GSM3ShieldV2::speakerLoudness(int level) 				// set the speaker Volume
+	                                           					// 0: Low speaker volume
+                                           						// 1: Low speaker volume
+                                           						// 2: Medium speaker volume
+                                            					// 3: High speaker volume
+{
+	String Result ="", modemResponse;
+	// Send the AT command for set the speaker volume
+	switch(level) 
+		{
+		case	0: 
+				modemResponse = modemAccess.writeModemCommand("ATL0",300);	// set low volume
+				break;
+		
+		case	1: 
+				modemResponse = modemAccess.writeModemCommand("ATL1",300);	// set low volume
+				break;
+		
+		case	2: 
+				modemResponse = modemAccess.writeModemCommand("ATL2",300);	// set medium volume
+				break;
+		
+		case	3: 
+				modemResponse = modemAccess.writeModemCommand("ATL3",300);	// set High volume
+				break;
+		}		
+
+	char res_to_compare[modemResponse.length()];
+	modemResponse.toCharArray(res_to_compare, modemResponse.length());
+	if(strstr(res_to_compare,"OK") == NULL)
+	{	
+		Result =" Error !";
+		if(debug==true) SerialUSB.println(Result);
+	}
+	else
+	{
+		Result = modemResponse.substring(1, 45);
+		if(debug==true) SerialUSB.println(Result);
+		return Result;
+	}	
+}
+// set speaker mode    
+String GSM3ShieldV2::speakerMode(int mode)       				// Set the speaker on mode
+                                            					// 0: Speaker is always off
+                                            					// 1: Speaker is on until TA inform TE that carrier has been detected
+                                            					// 2: Speaker is always on when TA is off-hook
+{
+	int spkMode=0;
+	char Mode[2],command[5];
+	
+	Mode[1]='\0';
+	command[4]='\0';
+
+	spkMode=mode;
+	if((spkMode < 0) || (spkMode > 2)) spkMode=DEFAULT_speakerMode;
+	strcpy(command,"ATM");
+	itoa(spkMode,Mode,10);
+	strcat(command,Mode);
+	String modemResponse=modemAccess.writeModemCommand(command,300);
+	if(debug==true) SerialUSB.println(modemResponse);
+
+	return modemResponse;
+
+}
+// set alert sound mode
+String GSM3ShieldV2::alertSoundMode(int mode)					// silent the alert sound
+        														// 0: Normal mode
+        														// 1: Silent mode
+{
+	int soundMode=0;
+	char Mode[2],command[10];
+	
+	Mode[1]='\0';
+	command[9]='\0';
+
+	soundMode=mode;
+	if((soundMode < 0) || (soundMode > 1)) soundMode=DEFAULT_AlertSoundMode;
+	strcpy(command,"AT+CALM=");
+	itoa(soundMode,Mode,10);
+	strcat(command,Mode);
+	String modemResponse=modemAccess.writeModemCommand(command,300);
+	if(debug==true) SerialUSB.println(modemResponse);
+
+	return modemResponse;
+}
+// set ringer sound level
+String GSM3ShieldV2::ringerSoundLevel(int level)				// Set the ringer volume (0-100)
+{
+	char command[12], lev[4];
+	int ringLevel=level;
+	if((ringLevel < 0) || (ringLevel > 100)) ringLevel=DEFAULT_RingerSoundLevel;
+
+	command[11]='\0';
+	lev[3]='\0';
+	strcpy(command,"AT+CRSL=");
+	itoa(ringLevel,lev,10);
+	strcat(command,lev);
+	String modemResponse=modemAccess.writeModemCommand(command,300);
+	if(debug==true) SerialUSB.println(modemResponse);
+	return modemResponse;	
+
+	
+}
+// set lodspeaker volume level
+String GSM3ShieldV2::loudSpeakerVolumeLevel(int level)			// Set the Speaker volume (0-100)
+{
+	char command[12], lev[4];
+	int speakerLevel=level;
+	if((speakerLevel < 0) || (speakerLevel > 100)) speakerLevel=DEFAULT_LoudSpeakerVolumeLevel;
+
+	command[11]='\0';
+	lev[3]='\0';
+	strcpy(command,"AT+CLVL=");
+	itoa(speakerLevel,lev,10);
+	strcat(command,lev);
+	String modemResponse=modemAccess.writeModemCommand(command,300);
+	if(debug==true) SerialUSB.println(modemResponse);
+	return modemResponse;	
+}
+// set mute control
+String GSM3ShieldV2::muteControl(int mode)						// switch on or off mute
+        														// 0: Mute off
+        														// 1: Mute on
+{
+	char command[10], mod[2];
+	int muteCtrl=mode;
+	if((muteCtrl < 0) || (muteCtrl > 1)) muteCtrl=DEFAULT_muteControl;  //operazione non permessa
+
+	command[9]='\0';
+	mod[1]='\0';
+	strcpy(command,"AT+CMUT=");
+	itoa(muteCtrl,mod,10);
+	strcat(command,mod);
+	String modemResponse=modemAccess.writeModemCommand(command,300);
+	if(debug==true) SerialUSB.println(modemResponse);
+	return modemResponse;
+}
+// set microphone gain
+String GSM3ShieldV2::microphoneGainLevel(int channel, int gain)	// Set the microphone channel and level
+        														// Channel:
+        														//			0: Normal Microphone
+        														//			1: Headset Microphone
+        														//			2: Loudspeaker Microphone
+        														// Gain: (0-15)
+{
+	char chn[2], gn[3],command[13];
+
+	chn[1]='\0';
+	gn[2]='\0';
+	command[12]='\0';
+
+	if((channel < 0) || (channel > 2)) itoa(DEFAULT_Channel,chn,10);
+	else itoa(channel,chn,10);
+
+	if((gain < 0) || (gain > 15)) itoa(DEFAULT_MicrophoneGainLevel,gn,10);
+	else itoa(gain,gn,10);
+
+	strcpy(command,"AT+QMIC=");
+	strcat(command,chn);
+	strcat(command,",");
+	strcat(command,gn);
+	String modemResponse=modemAccess.writeModemCommand(command,300);
+	if(debug==true) SerialUSB.println(modemResponse);
+	return modemResponse;
+	
+}
+// set audio channel
+String GSM3ShieldV2::swapAudioChannel(int channel)				// Set the audio channel
+        														// 0: Normal audio channel
+        														// 1: headset audio channel
+        														// 2: Loudspeaker audio chanel
+{
+	 char chn[2], command[12];
+
+	 chn[1]='\0';
+	 command[11]='\0';
+
+	 if((channel < 0) || (channel > 2)) itoa(DEFAULT_Channel,chn,10);
+	 else itoa(channel,chn,10);
+	 strcpy(command,"AT+QAUDCH=");
+	 strcat(command,chn);
+	 String modemResponse=modemAccess.writeModemCommand(command,300);
+	 if(debug==true) SerialUSB.println(modemResponse);
+	 return modemResponse;
+}
+// set the module echo mode (Refer Quectel M10 datasheet for further informaions)
+void GSM3ShieldV2::CommandEcho(int value)
+{
+	switch(value)
+	{
+		case 0: modemAccess.writeModemCommand("ATE0",300);
+				break;
+
+		case 1: modemAccess.writeModemCommand("ATE1",300);		
+				break;
+
+		default:
+				break;
+	}
+}						
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV2.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV2.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3ShieldV2.h	(revision 175)
@@ -0,0 +1,89 @@
+/*
+This file is part of GSM3ShieldV2 library developed by Arduino.org (http://arduino.org).
+
+    GSM3ShieldV2 library is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    GSM3ShieldV2 library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with GSM3ShieldV2 library.  If not, see <http://www.gnu.org/licenses/>.
+*/
+    
+#ifndef _GSM3SHIELDV2_
+#define _GSM3SHIELDV2_
+
+#include <GSM3ShieldV1AccessProvider.h>
+#include <GSM3ShieldV1DirectModemProvider.h>
+#include <GSM.h>
+#include <Arduino.h>
+#include <stdlib.h>
+#include <string.h>
+#include <DEFAULT.h>
+#include <GSM3ShieldV1ModemCore.h>
+
+class GSM3ShieldV2
+{
+
+	private:
+		
+		GSM3ShieldV1DirectModemProvider modemAccess;
+		GSM3ShieldV1AccessProvider gsm; // Access provider to GSM/GPRS network
+		
+	public:
+
+		/** Constructor */
+		GSM3ShieldV2();
+        GSM3ShieldV2(bool db);
+
+        bool debug=false;
+		
+        String getPosition(); 									// Get Current Location
+    
+        // Aded for voice call debug
+        String speakerLoudness(int level); 					// set the speaker Volume
+                                            					// 0: Low speaker volume
+                                           						// 1: Low speaker volume
+                                           						// 2: Medium speaker volume
+                                            					// 3: High speaker volume
+    
+        String speakerMode(int mode);       					// Set the speaker on mode
+                                            					// 0: Speaker is always off
+                                            					// 1: Speaker is on until TA inform TE that carrier has been detected
+                                            					// 2: Speaker is always on when TA is off-hook
+    
+        String alertSoundMode(int mode);						// silent the alert sound
+        														// 0: Normal mode
+        														// 1: Silent mode
+
+        String ringerSoundLevel(int level);						// Set the ringer volume (0-100)
+
+        String loudSpeakerVolumeLevel(int level);				// Set the Speaker volume (0-100)
+
+        String muteControl(int mode);							// switch on or off mute
+        														// 0: Mute off
+        														// 1: Mute on
+
+        String microphoneGainLevel(int channel, int gain);		// Set the microphone channel and level
+        														// Channel:
+        														//			0: Normal Microphone
+        														//			1: Headset Microphone
+        														//			2: Loudspeaker Microphone
+        														// Gain: (0-15)
+
+        String swapAudioChannel(int channel);					// Set the audio channel
+        														// 0: Normal audio channel
+        														// 1: headset audio channel
+        														// 2: Loudspeaker audio chanel
+
+       void CommandEcho(int value);                             // 0: command echo OFF 
+                                                                // 1: command echo ON    
+
+};
+
+#endif;
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SoftSerial.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SoftSerial.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SoftSerial.cpp	(revision 175)
@@ -0,0 +1,398 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include "GSM3SoftSerial.h"
+#include <WInterrupts.h>
+#include <HardwareSerial.h>
+#include <Arduino.h>
+
+#define __XON__ 0x11
+#define __XOFF__ 0x13
+
+#define _GSMSOFTSERIALFLAGS_ESCAPED_ 0x01
+#define _GSMSOFTSERIALFLAGS_SENTXOFF_ 0x02
+
+//
+// Lookup table
+//
+#define __PARAGRAPHGUARD__ 50
+typedef struct _DELAY_TABLE
+{
+  long baud;
+  unsigned short rx_delay_centering;
+  unsigned short rx_delay_intrabit;
+  unsigned short rx_delay_stopbit;
+  unsigned short tx_delay;
+} DELAY_TABLE;
+
+
+static const DELAY_TABLE PROGMEM table[] = 
+{
+  //  baud    rxcenter   rxintra    rxstop    tx
+  { 115200,   2,         6,         8,        8,     },
+  { 57600,    6,         15,        17,       17,    },
+  { 38400,    11,        24,        26,       26,    },
+  { 31250,    14,        30,        32,       32,    },
+  { 28800,    15,        32,        34,       34,    },
+  { 19200,    24,        50,        52,       52,    },
+  { 14400,    32,        67,        69,       69,    },
+  { 9600,     50,        102,       104,      104,   },
+  { 4800,     102,       206,       208,      208,   },
+  { 2400,     206,       414,       416,      416,   },
+  { 1200,     414,       831,       833,      833,   },
+  { 300,      1664,      3331,      3333,     3333,  },
+};
+
+//const int XMIT_START_ADJUSTMENT = 5;
+
+
+GSM3SoftSerial* GSM3SoftSerial::_activeObject=0;
+
+GSM3SoftSerial::GSM3SoftSerial():
+	_rx_delay_centering(0),
+	_rx_delay_intrabit(0),
+	_rx_delay_stopbit(0),
+	_tx_delay(0),
+	cb(this)
+{
+	
+	//comStatus=0;
+	//waitingAnswer=false;
+}
+
+int GSM3SoftSerial::begin(long speed)
+{
+  _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;
+        setTX();
+	setRX();
+  for (unsigned i=0; i<sizeof(table)/sizeof(table[0]); ++i)
+  {
+    long baud = pgm_read_dword(&table[i].baud);
+    if (baud == speed)
+    {
+      _rx_delay_centering = pgm_read_word(&table[i].rx_delay_centering);
+      _rx_delay_intrabit = pgm_read_word(&table[i].rx_delay_intrabit);
+      _rx_delay_stopbit = pgm_read_word(&table[i].rx_delay_stopbit);
+      _tx_delay = pgm_read_word(&table[i].tx_delay);
+      break;
+    }
+  }
+  
+  if (_rx_delay_stopbit)
+  {
+    if (digitalPinToInterrupt(4))
+    {
+     attachInterrupt(4, handle_interrupt, FALLING);
+    }
+    delayMicroseconds(_tx_delay); // if we were low this establishes the end
+  }
+  
+  _activeObject=this;
+
+}
+
+void GSM3SoftSerial::close()
+ {
+	_activeObject=0;
+ }
+
+size_t GSM3SoftSerial::write(uint8_t c)
+{
+	if (_tx_delay == 0)
+		return 0;
+
+	// Characters to be escaped under XON/XOFF control with Quectel
+	if(c==0x11)
+	{
+		this->finalWrite(0x77);
+		return this->finalWrite(0xEE);
+	}
+
+	if(c==0x13)
+	{
+		this->finalWrite(0x77);
+		return this->finalWrite(0xEC);
+	}
+
+	if(c==0x77)
+	{
+		this->finalWrite(0x77);
+		return this->finalWrite(0x88);
+	}
+	
+	return this->finalWrite(c);
+}
+
+size_t GSM3SoftSerial::finalWrite(uint8_t c)
+{
+	
+        // turn off interrupts for a clean txmit
+       EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT( 1 << digitalPinToInterrupt( 4 ));
+
+
+	// Write the start bit
+	tx_pin_write(LOW);
+	delayMicroseconds(_tx_delay);// + XMIT_START_ADJUSTMENT);
+
+	// Write each of the 8 bits
+	for (byte mask = 0x01; mask; mask <<= 1)
+	{
+		if (c & mask) // choose bit
+			tx_pin_write(HIGH); // send 1
+		else
+			tx_pin_write(LOW); // send 0
+		delayMicroseconds(_tx_delay);
+	}
+
+	tx_pin_write(HIGH); // restore pin to natural state
+	
+	// turn interrupts back on
+        EIC->INTENSET.reg = EIC_INTENSET_EXTINT( 1 << digitalPinToInterrupt( 4 ));
+	delayMicroseconds(_tx_delay);
+				
+	return 1;
+}
+
+  /*inline*/ void GSM3SoftSerial::tunedDelay(uint16_t delay) { 
+	__asm__ __volatile__(
+    "1:              \n"
+    "   sub %0, #1   \n" // substract 1 from %0 (n)
+    "   bne 1b       \n" // if result is not 0 jump to 1
+    : "+r" (delay)           // '%0' is n variable with RW constraints
+    :                    // no input
+    :                    // no clobber
+  );
+  }
+
+void GSM3SoftSerial::tx_pin_write(uint8_t pin_state)
+{
+  // Direct port manipulation is faster than digitalWrite/Read
+  if (pin_state == LOW)
+    _transmitPortRegister->reg &= ~_transmitBitMask;
+  else
+    _transmitPortRegister->reg |= _transmitBitMask;
+}
+
+void GSM3SoftSerial::setTX()
+{
+  pinMode(3, OUTPUT);
+  digitalWrite(3, HIGH);
+  // For digital port direct manipulation
+  _transmitBitMask = digitalPinToBitMask(3);
+  PortGroup * port = digitalPinToPort(3);
+  _transmitPortRegister = portOutputRegister(port);
+}
+
+void GSM3SoftSerial::setRX()
+{
+  pinMode(4, INPUT);
+  digitalWrite(4, HIGH);  // pullup for normal logic!
+  // For digital port direct manipulation
+  _receiveBitMask = digitalPinToBitMask(4);
+  PortGroup * port = digitalPinToPort(4);
+  _receivePortRegister = portInputRegister(port);
+}
+
+void GSM3SoftSerial::handle_interrupt()
+{
+	if(_activeObject)
+		_activeObject->recv();
+}
+
+uint32_t GSM3SoftSerial::rx_pin_read()
+{
+  // Digital port manipulation
+  return _receivePortRegister->reg & digitalPinToBitMask(4);
+}
+
+void GSM3SoftSerial::recv()
+{
+
+  bool firstByte=true;
+  byte thisHead;
+  
+  uint8_t d = 0;
+  bool morebytes=false;
+  //bool fullbuffer=(cb.availableBytes()<3);
+  bool fullbuffer;
+  bool capturado_fullbuffer = 0;
+  int i;
+  byte oldTail;
+
+  // If RX line is high, then we don't see any start bit
+  // so interrupt is probably not for us
+  if (!rx_pin_read())
+  {
+ 	do
+	{
+		oldTail=cb.getTail();
+		// Wait approximately 1/2 of a bit width to "center" the sample
+		delayMicroseconds(_rx_delay_centering);
+		
+		fullbuffer=(cb.availableBytes()<6);
+
+		
+		if(fullbuffer&&(!capturado_fullbuffer))
+			tx_pin_write(LOW);
+
+		
+		// Read each of the 8 bits
+		for (uint8_t i=0x1; i; i <<= 1)
+		{
+			delayMicroseconds(_rx_delay_intrabit);
+			uint8_t noti = ~i;
+			if (rx_pin_read())
+				d |= i;
+			else // else clause added to ensure function timing is ~balanced
+				d &= noti;
+			if(fullbuffer&&(!capturado_fullbuffer))
+			{
+			  if((uint8_t)__XOFF__ & i)
+				tx_pin_write(HIGH);
+			  else
+				tx_pin_write(LOW);
+			}
+		}
+
+		if(fullbuffer&&(!capturado_fullbuffer))
+		{
+			delayMicroseconds(_rx_delay_intrabit);
+			tx_pin_write(HIGH);	
+		}
+		
+		// So, we know the buffer is full, and we have sent a XOFF
+		if (fullbuffer) 
+		{
+			capturado_fullbuffer =1;
+			_flags |=_GSMSOFTSERIALFLAGS_SENTXOFF_;
+		}
+
+
+		// skip the stop bit
+		if (!fullbuffer) delayMicroseconds(_rx_delay_stopbit);		
+		if(keepThisChar(&d))
+		{
+			cb.write(d);
+			if(firstByte)
+			{
+				firstByte=false;
+				thisHead=cb.getTail();
+			}
+		}
+		
+		
+		// This part is new. It is used to detect the end of a "paragraph"
+		// Caveat: the old fashion would let processor a bit of time between bytes, 
+		// that here is lost
+		// This active waiting avoids drifting
+		morebytes=false;
+		// TO-DO. This PARAGRAPHGUARD is empyric. We should test it for every speed
+		for(i=0;i<__PARAGRAPHGUARD__;i++)
+		{	
+			delayMicroseconds(1);
+			if(!rx_pin_read())
+			{
+				morebytes=true;
+				break;
+			}
+		}
+	}while(morebytes);
+	// If we find a line feed, we are at the end of a paragraph
+	// check!
+	
+	if (fullbuffer)
+	{
+		// And... go handle it!
+		if(mgr)
+			mgr->manageMsg(thisHead, cb.getTail());
+	}
+	else if(d==10)
+	{
+		// And... go handle it!
+		if(mgr)
+			mgr->manageMsg(thisHead, cb.getTail());
+	}
+	else if (d==32)
+	{
+		// And... go handle it!
+		if(mgr)
+			mgr->manageMsg(thisHead, cb.getTail());
+	}
+  }
+
+}
+
+bool GSM3SoftSerial::keepThisChar(uint8_t* c)
+{
+	// Horrible things for Quectel XON/XOFF
+	// 255 is the answer to a XOFF
+	// It comes just once
+	if((*c==255)&&(_flags & _GSMSOFTSERIALFLAGS_SENTXOFF_))
+	{
+		_flags ^= _GSMSOFTSERIALFLAGS_SENTXOFF_;
+		return false;
+	}
+
+	// 0x77, w, is the escape character
+	if(*c==0x77)
+	{
+		_flags |= _GSMSOFTSERIALFLAGS_ESCAPED_;
+		return false;
+	}
+	
+	// and these are the escaped codes
+	if(_flags & _GSMSOFTSERIALFLAGS_ESCAPED_)
+	{
+		if(*c==0xEE)
+			*c=0x11;
+		else if(*c==0xEC)
+			*c=0x13;
+		else if(*c==0x88)
+			*c=0x77;
+			
+		_flags ^= _GSMSOFTSERIALFLAGS_ESCAPED_;
+		return true;
+	}
+	
+	return true;
+}
+
+void GSM3SoftSerial::spaceAvailable()
+{
+	// If there is spaceAvailable in the buffer, lets send a XON
+	finalWrite((byte)__XON__);
+}
+
+
+// This is here to avoid problems with Arduino compiler
+void GSM3SoftSerialMgr::manageMsg(byte from, byte to){};
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SoftSerial.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SoftSerial.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3SoftSerial.h	(revision 175)
@@ -0,0 +1,174 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef __GSM3_SOFTSERIAL__
+#define __GSM3_SOFTSERIAL__
+
+// An adaptation of NewSoftSerial for Modem Shields
+// Assumes directly that Serial is attached to Pins 2 and 3, not inverse
+// We are implementing it because NewSoftSerial does not deal correctly with floods
+// of data
+#include "GSM3CircularBuffer.h"
+
+#include <variant.h>
+/*
+#define _COMSTATUS_ANSWERRECEIVED_ 0x100
+#define _COMSTATUS_SMSRECEIVED_ 0x80
+#define _COMSTATUS_CALLRECEIVED_ 0x40
+
+// PLEASE, when accessing the sockets use "for" and >> (bitwise operator)
+#define _COMSTATUS_SOCKET6RECEIVED_ 0x20
+#define _COMSTATUS_SOCKET5RECEIVED_ 0x10
+#define _COMSTATUS_SOCKET4RECEIVED_ 0x08
+#define _COMSTATUS_SOCKET3RECEIVED_ 0x04
+#define _COMSTATUS_SOCKET2RECEIVED_ 0x02
+#define _COMSTATUS_SOCKET1RECEIVED_ 0x01
+
+#define __CALLTABLEMASK__ 0x3
+*/
+
+class GSM3SoftSerialMgr
+{
+	public:
+	
+		/** Manages soft serial message
+			@param from			Initial byte
+			@param to			Final byte
+		 */
+		virtual void manageMsg(byte from, byte to);
+};
+
+// This class manages software serial communications
+// Changing it so it doesn't know about modems or whatever
+
+class GSM3SoftSerial : public GSM3CircularBufferManager
+{
+	private:
+	
+		uint32_t _receiveBitMask;
+		volatile PORT_IN_Type *_receivePortRegister;
+		uint32_t _transmitBitMask;
+		volatile PORT_OUT_Type *_transmitPortRegister;
+	  
+		static GSM3SoftSerial* _activeObject;
+		GSM3SoftSerialMgr* mgr;
+	  
+		uint16_t _rx_delay_centering;
+		uint16_t _rx_delay_intrabit;
+		uint16_t _rx_delay_stopbit;
+		uint16_t _tx_delay;
+		uint8_t _flags;
+	  
+		/** Write in tx_pin
+			@param pin_state		Pin state
+		 */
+		void tx_pin_write(uint8_t pin_state);
+		
+		/** Set transmission
+		 */
+		void setTX();
+		
+		/** Set receiver
+		 */
+		void setRX();
+		
+		/** Receive
+		 */
+		void recv();
+		
+		/** Read from rx_pin
+			@return receive bit mask
+		 */
+		uint32_t rx_pin_read();
+		
+		void setComsReceived();
+		
+		/** Write a character in serial connection, final action after escaping
+			@param c			Character
+			@return	1 if succesful, 0 if transmission delay = 0
+		 */
+		virtual size_t finalWrite(uint8_t);
+
+		/** Decide, attending to escapes, if the received character should we
+		    kept, forgotten, or changed
+			@param c			Character, may be changed
+			@return	1 if shall be kept, 0 if forgotten
+		 */
+		bool keepThisChar(uint8_t* c);
+		  
+		// Checks the buffer for well-known events. 
+		//bool recognizeUnsolicitedEvent(byte oldTail);
+	  
+	  public:
+	  
+		/** Tuned delay in microcontroller
+			@param delay		Time to delay
+		 */
+		static /*inline */void tunedDelay(uint16_t delay);
+		
+		GSM3CircularBuffer cb; // Circular buffer
+		
+		/** Register serial manager
+			@param manager		Serial manager
+		 */
+		inline void registerMgr(GSM3SoftSerialMgr* manager){mgr=manager;};
+		
+		/** If there is spaceAvailable in the buffer, lets send a XON
+		 */
+		void spaceAvailable();
+		
+		/** Write a character in serial connection
+			@param c			Character
+			@return	1 if succesful, 0 if transmission delay = 0
+		 */
+		virtual size_t write(uint8_t);
+		
+		/** Constructor */
+		GSM3SoftSerial();
+		
+		/** Establish serial connection
+			@param speed		Baudrate
+			@return
+		 */
+		int begin(long speed);
+		
+		/** Manage interruptions
+		 */
+		static inline void handle_interrupt();
+		
+		/** Close serial connection
+		 */
+		void close();
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3VoiceCallService.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3VoiceCallService.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3VoiceCallService.cpp	(revision 175)
@@ -0,0 +1,146 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#include <GSM3VoiceCallService.h>
+#include <Arduino.h>
+
+#include <GSM3ShieldV1VoiceProvider.h>
+GSM3ShieldV1VoiceProvider theShieldV1VoiceProvider;
+
+// While there is only a shield (ShieldV1) we will include it by default
+
+#define GSM3VOICECALLSERVICE_SYNCH 0x01 // 1: synchronous 0: asynchronous
+#define __TOUT__ 10000
+
+
+
+
+GSM3VoiceCallService::GSM3VoiceCallService(bool synch)
+{
+    GSM3ShieldV1VoiceProvider theShieldV1VoiceProvider; //needed to avoid hard fault in M0
+ 	if(synch)
+ 		flags |= GSM3VOICECALLSERVICE_SYNCH;
+	theGSM3MobileVoiceProvider->initialize();
+}
+
+GSM3_voiceCall_st GSM3VoiceCallService::getvoiceCallStatus()
+{
+	if(theGSM3MobileVoiceProvider==0)
+		return IDLE_CALL;
+        theShieldV1VoiceProvider.recognizeUnsolicitedEvent(1) ;
+	return theGSM3MobileVoiceProvider->getvoiceCallStatus();
+}
+
+int GSM3VoiceCallService::ready()
+{
+	if(theGSM3MobileVoiceProvider==0)
+		return 0;
+	
+	return theGSM3MobileVoiceProvider->ready();
+}
+
+int GSM3VoiceCallService::voiceCall(const char* to, unsigned long timeout)
+{
+	if(theGSM3MobileVoiceProvider==0){
+		return 0;
+        }
+		
+	if(flags & GSM3VOICECALLSERVICE_SYNCH )
+	{
+		theGSM3MobileVoiceProvider->voiceCall(to);
+		unsigned long m;
+		m=millis();
+		// Wait an answer for timeout
+		while(((millis()-m)< timeout )&&(getvoiceCallStatus()==CALLING)){
+			delay(100);
+                }
+		if(getvoiceCallStatus()==TALKING)
+			return 1;
+		else
+			return 0;
+	}
+	else
+	{ 
+		return theGSM3MobileVoiceProvider->voiceCall(to);
+	}
+		
+}
+
+int GSM3VoiceCallService::answerCall()
+{
+	if(theGSM3MobileVoiceProvider==0)
+		return 0;
+	
+	return waitForAnswerIfNeeded(theGSM3MobileVoiceProvider->answerCall());
+}
+
+int GSM3VoiceCallService::hangCall()
+{
+	if(theGSM3MobileVoiceProvider==0)
+		return 0;
+	
+	return waitForAnswerIfNeeded(theGSM3MobileVoiceProvider->hangCall());
+}
+
+int GSM3VoiceCallService::retrieveCallingNumber(char* buffer, int bufsize)
+{
+	if(theGSM3MobileVoiceProvider==0)
+		return 0;
+	
+	return waitForAnswerIfNeeded(theGSM3MobileVoiceProvider->retrieveCallingNumber(buffer, bufsize));
+}
+
+int GSM3VoiceCallService::waitForAnswerIfNeeded(int returnvalue)
+{
+	// If synchronous
+	if(flags & GSM3VOICECALLSERVICE_SYNCH )
+	{
+		unsigned long m;
+		m=millis();
+		// Wait for __TOUT__
+		while(((millis()-m)< __TOUT__ )&&(ready()==0)) 
+			delay(100);
+		// If everything was OK, return 1
+		// else (timeout or error codes) return 0;
+		if(ready()==1)
+			return 1;
+		else
+			return 0;
+	}
+	// If not synchronous just kick ahead the coming result
+	return ready();
+}
+
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3VoiceCallService.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3VoiceCallService.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/GSM/src/GSM3VoiceCallService.h	(revision 175)
@@ -0,0 +1,102 @@
+/*
+This file is part of the GSM3 communications library for Arduino
+-- Multi-transport communications platform
+-- Fully asynchronous
+-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
+-- Voice calls
+-- SMS
+-- TCP/IP connections
+-- HTTP basic clients
+
+This library has been developed by Telefónica Digital - PDI -
+- Physical Internet Lab, as part as its collaboration with
+Arduino and the Open Hardware Community. 
+
+September-December 2012
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+The latest version of this library can always be found at
+https://github.com/BlueVia/Official-Arduino
+*/
+#ifndef _GSM3VOICECALLSERVICE_
+#define _GSM3VOICECALLSERVICE_
+
+#include <GSM3MobileNetworkProvider.h>
+#include <GSM3MobileVoiceProvider.h>
+
+class GSM3VoiceCallService
+{
+	private:
+		uint8_t flags;
+		
+		/** Make synchronous the functions, if needed
+			@param returnvalue	Return value
+			@return returns 0 if last command is still executing, 1 success, >1 error
+		 */
+		int waitForAnswerIfNeeded(int returnvalue);
+		
+	public:
+		/** Service creation
+			@param synch		If true, the service calls are synchronois
+		*/
+		GSM3VoiceCallService(bool synch=true);
+
+		/** Voice call status
+			@return Status of the voice call, as described in GSM3MobileVoiceProvider.h
+		          { IDLE_CALL, CALLING, RECEIVINGCALL, TALKING};
+		*/
+		GSM3_voiceCall_st getvoiceCallStatus();
+
+		/** Get last command status
+			@return Returns 0 if last command is still executing, 1 success, >1 error
+		*/
+		int ready();
+		
+		/** Place a voice call. If asynchronous, returns while ringing. If synchronous
+			returns if the call is stablished or cancelled.
+			@param to			Receiver number. Country extension can be used or not.
+								Char buffer should not be released or used until command is over
+			@param timeout		In millisecods. Time ringing before closing the call. 
+								Only used in synchronous mode.
+								If zero, ring undefinitely
+			@return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error
+					In synchronous mode returns 1 if the call is placed, 0 if not.
+		*/		
+		int voiceCall(const char* to, unsigned long timeout=30000);
+		
+		/** Accept an incoming voice call
+			@return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error
+					In synchronous mode returns 1 if the call is answered, 0 if not.
+		*/		
+		int answerCall();
+		
+		/** Hang a stablished call or an incoming ring
+			@return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error
+					In synchronous mode returns 1 if the call is answered, 0 if not.
+		*/		
+		int hangCall();
+
+		/** Retrieve the calling number, put it in buffer
+			@param buffer		pointer to the buffer memory
+			@param bufsize		size of available memory area, at least should be 10 characters
+			@return In asynchronous mode returns 0 if last command is still executing, 1 success, >1 error
+					In synchronous mode returns 1 if the number is correcty taken 0 if not
+		*/		
+		int retrieveCallingNumber(char* buffer, int bufsize);
+};
+
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/LCD_m0.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/LCD_m0.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/LCD_m0.cpp	(revision 175)
@@ -0,0 +1,365 @@
+//   Versione 1.0 By Mario Mottula
+
+#include "Arduino.h"
+#include "LCD_m0.h"
+#define H HIGH 
+#define L LOW 
+
+
+//************************************************************
+//* Funzione di inizializzazione display
+//* 4 bit di dati
+//* 2 righe e font Standard 5x8
+//************************************************************
+void LCD_m0::Inizializza_LCD(int pin_RS, int pin_EN,int pin_D4,int pin_D5, int pin_D6, int pin_D7)
+
+{
+  _pin_RS = pin_RS;
+  _pin_EN = pin_EN;
+  _pin_D7 = pin_D7;
+  _pin_D6 = pin_D6;
+  _pin_D5 = pin_D5;
+  _pin_D4 = pin_D4;
+
+  
+  //ritardo per stabilizzazione Vdc
+  delay(250);
+  pinMode(pin_RS, OUTPUT);
+  pinMode(pin_EN, OUTPUT);
+  pinMode(pin_D7, OUTPUT);
+  pinMode(pin_D6, OUTPUT);
+  pinMode(pin_D5, OUTPUT);
+  pinMode(pin_D4, OUTPUT);
+ 
+  delay(50);
+  SetCommandPin(0,0,1,1); 
+  delay(10);
+  SetCommandPin(0,0,1,1); 
+  delay(1);
+  SetCommandPin(0,0,1,1); 
+   delay(50);
+//impostazione interfaccia 4 bit
+  SetCommandPin(0,0,1,0);
+  delay(5);
+   
+//impostazione font e righe (2 righe Font 5x8)
+   
+  SetCommandPin(0,0,1,0);
+  SetCommandPin(1,0,0,0);
+  delay(5);
+	
+// impostazione Off display
+
+   SetCommandPin(0,0,0,0); 
+   SetCommandPin(1,0,0,0); 
+   delay(5);
+
+   
+// impostazione On display cursore OFF
+   
+   SetCommandPin(0,0,0,0); 
+   SetCommandPin(1,1,0,0); 
+   delay(5);
+
+// pulizia display
+   
+   SetCommandPin(0,0,0,0); 
+   SetCommandPin(0,0,0,0); 
+   delay(5);
+
+  
+//shift a sinistra cursore (Entry mode da SX a DX)
+  
+   SetCommandPin(0,0,0,0); 
+   SetCommandPin(0,1,1,0); 
+   
+
+
+
+  
+   }
+
+
+//************************************************************
+//*	Funzione di invio Comandi
+//************************************************************
+void LCD_m0::SetCommandPin(int D7,int D6,int D5, int D4)
+{
+  digitalWrite(_pin_RS, L); 
+
+  digitalWrite(_pin_D7, D7); 
+  digitalWrite(_pin_D6, D6); 
+  digitalWrite(_pin_D5, D5); 
+  digitalWrite(_pin_D4, D4);  
+  digitalWrite(_pin_EN, H);
+  delay(1); 
+  digitalWrite(_pin_EN, L);  
+
+
+}
+
+//************************************************************
+//*	Funzione di invio Dati primi 4 bit
+//************************************************************
+
+void LCD_m0::SetDataPin1(int D7,int D6,int D5, int D4)
+{
+  
+ 
+  digitalWrite(_pin_EN, H);
+  delay(1);
+  digitalWrite(_pin_RS , H); 
+
+  digitalWrite(_pin_D7, D7); 
+  digitalWrite(_pin_D6, D6); 
+  digitalWrite(_pin_D5, D5); 
+  digitalWrite(_pin_D4, D4);  
+
+  
+  digitalWrite(_pin_EN, L);
+  delay(1);
+  digitalWrite(12, H); 
+
+}
+//************************************************************
+//*	Funzione di invio Dati secondi 4 bit
+//************************************************************
+
+void LCD_m0::SetDataPin2(int D7,int D6,int D5, int D4)
+{
+  
+  digitalWrite(_pin_EN, H);
+  delay(1);
+  digitalWrite(_pin_RS , H); 
+
+  digitalWrite(_pin_D7, D7); 
+  digitalWrite(_pin_D6, D6); 
+  digitalWrite(_pin_D5, D5); 
+  digitalWrite(_pin_D4, D4);  
+
+
+  digitalWrite(_pin_EN, L);
+  delay(1);
+  digitalWrite(_pin_RS , L); 
+
+
+}
+
+
+
+
+//************************************************************
+//* Funzione di attivazione Cursore
+//************************************************************
+void LCD_m0::Cursore_ON()
+
+{
+   SetCommandPin(0,0,0,0); 
+   SetCommandPin(1,1,1,0); 
+}
+
+
+
+//************************************************************
+//* Funzione di disattivazione Cursore
+//************************************************************
+
+void LCD_m0::Cursore_OFF()
+{
+	SetCommandPin(0,0,0,0); 
+  	SetCommandPin(1,1,0,0); 
+   
+}
+
+
+
+//************************************************************
+//* Funzione di scrittura carattere in posizione corrente
+//* c = carattere da scrivere in posizione corrente
+//************************************************************
+
+void LCD_m0::Scrivi_Car_PC(char c)
+{
+ carattere = c;
+  
+ for(i=0;i<8;i++) 
+	{
+  	bin[i]=((c>>i)&1);
+	}
+
+ for(i=0;i<8;i++) 
+     {
+      bin_inv[i]=bin[7-i];
+	}
+ SetDataPin1(bin_inv[0],bin_inv[1],bin_inv[2],bin_inv[3]);
+   delay(50);
+ SetDataPin2(bin_inv[4],bin_inv[5],bin_inv[6],bin_inv[7]);
+
+}
+
+
+//************************************************************
+//* Funzione di scrittura di un carattere su riga e posizione
+//* desiderate.
+//* c = carttere da scrivere 
+//* rig = intero con il numero di riga
+//* pos = intero con il numero della posizione 
+//************************************************************
+void LCD_m0::Scrivi_Car_PS(char c,int rig,int pos)
+{
+ carattere = c;
+ //SerialUSB.begin(9600);
+ //SerialUSB.println(carattere);
+ if(rig==1){ 
+ 			SetCommandPin(1,0,0,0);//selezione riga1
+			Posizione(pos);
+		}
+ if(rig==2){
+			SetCommandPin(1,1,0,0);//selezione riga 2
+			Posizione(pos);
+		}
+ 
+ for(i=0;i<8;i++) 
+	{
+  	bin[i]=((c>>i)&1);
+     
+	}
+ for(i=0;i<8;i++) 
+     {
+     
+  	bin_inv[i]=bin[7-i];
+     
+	}
+ SetDataPin1(bin_inv[0],bin_inv[1],bin_inv[2],bin_inv[3]);
+   delay(50);
+ SetDataPin2(bin_inv[4],bin_inv[5],bin_inv[6],bin_inv[7]);
+
+}
+
+
+void LCD_m0::Posizione(int pos)
+{
+ switch (pos)  
+  {  
+  case 0:  
+  SetCommandPin(0,0,0,0);   
+  break;  
+
+  case 1:  
+  SetCommandPin(0,0,0,0);    
+  break;  
+  
+  case 2:  
+  SetCommandPin(0,0,0,1);    
+  break;  
+  
+  case 3:  
+  SetCommandPin(0,0,1,0);   
+  break;  
+
+  case 4:  
+  SetCommandPin(0,0,1,1);    
+  break;  
+  
+  case 5:  
+  SetCommandPin(0,1,0,0);    
+  break;  
+  
+  case 6:  
+  SetCommandPin(0,1,0,1);    
+  break;  
+
+  case 7:  
+  SetCommandPin(0,1,1,0);    
+  break;  
+
+  case 8:  
+  SetCommandPin(0,1,1,1);    
+  break; 
+  
+  case 9:  
+  SetCommandPin(1,0,0,0);   
+  break;  
+
+  case 10:  
+  SetCommandPin(1,0,0,1);    
+  break;  
+  
+  case 11:  
+  SetCommandPin(1,0,1,0);    
+  break;  
+  
+  case 12:  
+  SetCommandPin(1,0,1,1);    
+  break;  
+
+  case 13:  
+  SetCommandPin(1,1,0,0);    
+  break;  
+  
+  case 14:  
+  SetCommandPin(1,1,0,1);   
+  break;  
+  
+  case 15:  
+  SetCommandPin(1,1,1,0);   
+  break;  
+
+  case 16: 
+  SetCommandPin(1,1,1,1);   
+  break;  
+
+
+  }  
+}
+
+
+
+//*********************************************************
+//*Permette di scrivere un 'intera riga di testo
+//*stringa = Testo da scrivere  Formato String
+//*rig = riga sulla quale scrivere il testo  Formato int
+//*********************************************************
+
+void LCD_m0::Scrivi_Testo(String stringa,int rig)
+{
+ 
+n = stringa.length();
+
+
+ if(rig==1){ 
+ 			SetCommandPin(1,0,0,0);
+			SetCommandPin(0,0,0,0);
+
+			for(m=0; m<=n-1; m++){
+		               			c = stringa[m];	  
+		     					
+ 							Scrivi_Car_PC(c);
+ 							}
+		  }
+
+
+ if(rig==2){ 
+                SetCommandPin(1,1,0,0);//selezione riga1
+			SetCommandPin(0,0,0,0);//offset
+
+ 			for(m=0; m<=n-1; m++){
+		               			c = stringa[m];	  
+		     					
+ 							Scrivi_Car_PC(c);
+
+ 							}
+		  }
+
+}
+
+
+
+void LCD_m0::Pulisci()
+{
+
+   SetCommandPin(0,0,0,0); 
+   SetCommandPin(0,0,0,1); 
+
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/LCD_m0.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/LCD_m0.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/LCD_m0.h	(revision 175)
@@ -0,0 +1,60 @@
+/* File: LCD_m0.h 1.0  */
+
+// Libreria Scritta per Arduino m0 Pro Ver. 1.0
+// Funzioni base implementate:
+// - Inizializzazione a 4 Bit 					inizializza_LCD()
+// - Pulizia Display						Pulisci()
+// - Scrittura carattere in posizione desiderata 		Scrivi_Car_PS()
+// - Scrittura carattere in posizione corrente			Scrivi_Car_PC();
+// - Scrittura testo con scelta della riga			Scrivi_Testo()
+// - Attivazione / Disattivazione cursore			cursore_ON();
+//								cursore_OFF();
+
+//				BUON LAVORO MARIO MOTTULA						
+#ifndef LCD_m0_h
+#define LCD_m0_h
+
+
+#include "Arduino.h"
+       
+
+
+class LCD_m0
+{
+
+public:
+	
+	void Inizializza_LCD(int pin_RS,int pin_EN,int pin_D4,int pin_D5,int pin_D6,int pin_D7);
+	void Cursore_ON();
+	void Cursore_OFF();
+        void SetCommandPin(int D7,int D6,int D5,int D4);   //Funzione interna
+        void SetDataPin1(int D7, int D6, int D5, int D4);  //Funzione interna
+        void SetDataPin2(int D7, int D6, int D5, int D4);  //Funzione Interna
+        void Scrivi_Car_PC(char c);  		           //Scrive carattere nella posizione corrente		
+        void Scrivi_Car_PS(char c, int rig, int pos);      //Scrive carattere nella posizione Scelta rig=riga pos = colon.
+        void Scrivi_Testo(String stringa, int rig);	   //Scrive del testo specificando la riga
+        void Pulisci();					   //Pulisce il Display
+        void Posizione(int pos);			   //Funzione Interna				
+private:					
+	int pin_RS;
+	int pin_EN;
+	int pin_D4;
+	int pin_D5;
+	int pin_D6;
+	int pin_D7;
+        int _pin_RS, _pin_EN,_pin_D4,_pin_D5,_pin_D6,_pin_D7;
+        int i,bin[8],bin_inv[8],n,m;
+        int D7;
+	int D6;
+	int D5;
+	int D4;
+	char c,carattere;
+        String stringa;
+	int rig;
+	int pos;
+	
+};
+
+#endif
+
+	
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/examples/Esempio_LCD_Hitachi/Esempio_LCD_Hitachi.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/examples/Esempio_LCD_Hitachi/Esempio_LCD_Hitachi.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/examples/Esempio_LCD_Hitachi/Esempio_LCD_Hitachi.ino	(revision 175)
@@ -0,0 +1,69 @@
+
+/*Programma di esempio per la gestione di un display LCD a duer righe con controller Hitachi HD44780
+
+VerrÃ  visualizzata sullaprima riga la Scritta Ciao con il cursore ON
+Mentre nella seconda riga verrÃ  visualizzata la scritta Mondo !! con cursore OFF
+Dopo 3 secondi si vedranno lampeggiare i simboli * 
+
+Buon Lavoro !! Mario Mottula
+
+Per info: mmottula@hotmail.com
+
+Di seguito la Configurazione dei pin Standard:
+
+ * LCD RS pin to digital pin 12
+ * LCD Enable pin to digital pin 11
+ * LCD D4 pin to digital pin 5
+ * LCD D5 pin to digital pin 4
+ * LCD D6 pin to digital pin 3
+ * LCD D7 pin to digital pin 2
+ * LCD R/W pin to ground */
+
+//Inserisco la libreria LCD_m0 nel programma
+#include <LCD_m0.h>
+
+//Rinomino per comoditÃ  la libreria LCD_m0 in LCD
+LCD_m0 LCD;
+void setup() {
+//Attendo 50ms per la stabilizzazione della tensione di alimentazione
+delay(50);
+//Richiamo la Routine di Inizializzazione passando come parametri i pin di Reset , Enable e di Dati
+LCD.Inizializza_LCD(12,11,5,4,3,2); //D4,D5,D6,D7
+
+}
+
+void loop() {
+  //Ad ogni ciclo posso eseguire la pulizia del display
+  LCD.Pulisci();
+  delay(1000);
+  //Accendo il cursore
+  LCD.Cursore_ON();
+  delay(1000);
+  //Scrivo il Testo desiderato
+  LCD.Scrivi_Testo("     Ciao       ",1);
+  //Spengo il cursore
+  LCD.Cursore_OFF();
+  LCD.Scrivi_Testo("    Mondo !!    ",2);
+  delay(3000);
+  //Scrive il carattere * nella posizione desiderata
+  LCD.Scrivi_Car_PS('*',1,4);
+  LCD.Scrivi_Car_PS('*',1,11);
+  delay(500);
+  LCD.Scrivi_Car_PS(' ',1,4);
+  LCD.Scrivi_Car_PS(' ',1,11);
+  delay(500);
+  LCD.Scrivi_Car_PS('*',1,4);
+  LCD.Scrivi_Car_PS('*',1,11);
+  delay(2000);
+  Blink();      //Lampeggio che indica la fine della routine
+}
+
+void Blink()
+
+{
+  digitalWrite(13,HIGH);
+  delay(250);
+  digitalWrite(13,LOW);
+  delay(250);
+  }
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/keywords.txt
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/keywords.txt	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/LCD/keywords.txt	(revision 175)
@@ -0,0 +1,14 @@
+#######################################
+# Syntax Coloring Map For LEDLIB
+#######################################
+
+LCD_m0	KEYWORD1
+
+Inizializza_LCD	KEYWORD2
+Cursore_ON      KEYWORD2
+Cursore_OFF	KEYWORD2
+Scrivi_Car_PC 	KEYWORD2
+Scrivi_Car_PS 	KEYWORD2
+Posizione	KEYWORD2
+Scrivi_Testo	KEYWORD2
+Pulisci		KEYWORD2
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/examples/MasterSend/MasterSend.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/examples/MasterSend/MasterSend.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/examples/MasterSend/MasterSend.ino	(revision 175)
@@ -0,0 +1,36 @@
+/* Connection
+MASTER           SLAVE
+MISO      ->     MOSI
+MOSI      ->     MISO
+SCK       ->     SCK
+D10       ->     D10
+GND       ->     GND
+*/
+
+#include <SPI.h>
+
+#define SS 10
+#define DIM 11
+
+void setup() {
+
+  pinMode (SS, OUTPUT);
+  digitalWrite(SS, HIGH);
+  Serial.begin(9600);
+  //
+  SPI.begin();
+  
+}
+
+void loop() {
+  String x ="hello world";
+  digitalWrite(SS, LOW);
+  for (int i=0;i<DIM;i++){
+    SPI.transfer(x[i]);
+    delay(1);
+  } 
+  digitalWrite(SS,HIGH);
+  delay(1000);
+}
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/examples/SlaveReceive/SlaveReceive.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/examples/SlaveReceive/SlaveReceive.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SPI/examples/SlaveReceive/SlaveReceive.ino	(revision 175)
@@ -0,0 +1,36 @@
+/* Connection
+MASTER           SLAVE
+MISO      ->     MOSI
+MOSI      ->     MISO
+SCK       ->     SCK
+D10       ->     D10
+GND       ->     GND
+*/
+
+#include <SPI.h>
+
+#define SS 10
+#define DIM 11
+        
+uint8_t data[11];
+  
+void setup() {
+
+  SerialUSB.begin(9600);
+  pinMode (SS, INPUT);
+  while(!SerialUSB); 
+   SPI.beginSlave(); 
+}
+
+void loop() {
+  while(digitalRead(SS)==LOW){
+    for (int i=0;i<DIM;i++){
+      data[i] = SPI.read();
+      SerialUSB.print((char)data[i]);
+   }
+    SerialUSB.println("");
+  }    
+}
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/SoftwareSerial.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/SoftwareSerial.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/SoftwareSerial.cpp	(revision 175)
@@ -0,0 +1,323 @@
+/*
+  SoftwareSerial.cpp - library for Arduino M0/M0 pro
+  Copyright (c) 2016 Arduino Srl. All rights reserved.
+  Written by Chiara Ruggeri (chiara@arduino.org)
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ 
+  Enjoy!
+*/ 
+ 
+ 
+#include <Arduino.h>
+#include <SoftwareSerial.h>
+#include <variant.h>
+#include <WInterrupts.h>
+
+SoftwareSerial *SoftwareSerial::active_object = 0;
+char SoftwareSerial::_receive_buffer[_SS_MAX_RX_BUFF]; 
+volatile uint8_t SoftwareSerial::_receive_buffer_tail = 0;
+volatile uint8_t SoftwareSerial::_receive_buffer_head = 0;
+
+
+bool SoftwareSerial::listen()
+{
+  if (!_rx_delay_stopbit)
+    return false;
+
+  if (active_object != this)
+  {
+    if (active_object)
+      active_object->stopListening();
+
+    _buffer_overflow = false;
+    _receive_buffer_head = _receive_buffer_tail = 0;
+    active_object = this;
+
+    if(_inverse_logic)
+        //Start bit high
+        attachInterrupt(_receivePin, handle_interrupt, RISING);
+    else
+        //Start bit low
+        attachInterrupt(_receivePin, handle_interrupt, FALLING);
+    
+    
+    return true;
+  }
+ return false;
+}
+  
+bool SoftwareSerial::stopListening()
+{
+   if (active_object == this)
+   {  
+        EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT( 1 << digitalPinToInterrupt( _receivePin )) ;
+     active_object = NULL;
+     return true;
+   }
+  return false;
+}
+
+
+void SoftwareSerial::recv()
+{
+    
+  uint8_t d = 0;
+   
+  // If RX line is high, then we don't see any start bit
+  // so interrupt is probably not for us
+  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
+  {
+
+       EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT( 1 << digitalPinToInterrupt(_receivePin));
+   
+    // Wait approximately 1/2 of a bit width to "center" the sample
+       delayMicroseconds(_rx_delay_centering);
+   
+    // Read each of the 8 bits
+    for (uint8_t i=8; i > 0; --i)
+    {
+        
+     delayMicroseconds(_rx_delay_intrabit);
+      d >>= 1;
+      if (rx_pin_read()){
+        d |= 0x80;                  
+       }
+     
+    }
+    if (_inverse_logic){
+      d = ~d;
+    }
+    
+    // if buffer full, set the overflow flag and return
+    uint8_t next = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
+    if (next != _receive_buffer_head)
+    {
+      // save new data in buffer: tail points to where byte goes
+      _receive_buffer[_receive_buffer_tail] = d; // save new byte
+      _receive_buffer_tail = next;
+    } 
+    else 
+    {
+      _buffer_overflow = true;
+    }
+
+    // skip the stop bit
+   delayMicroseconds(_rx_delay_stopbit); 
+
+     EIC->INTENSET.reg = EIC_INTENSET_EXTINT( 1 << digitalPinToInterrupt(_receivePin));
+  }
+}
+
+
+uint32_t SoftwareSerial::rx_pin_read()
+{ 
+  return _receivePortRegister->reg & digitalPinToBitMask(_receivePin);
+}
+
+/* static */
+inline void SoftwareSerial::handle_interrupt()
+{
+   if (active_object)
+   {
+     active_object->recv();
+   }
+}
+
+
+// Constructor
+SoftwareSerial::SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) : 
+  _rx_delay_centering(0),
+  _rx_delay_intrabit(0),
+  _rx_delay_stopbit(0),
+  _tx_delay(0),
+  _buffer_overflow(false),
+  _inverse_logic(inverse_logic)
+{   
+  _receivePin = receivePin;
+  _transmitPin = transmitPin;
+}
+
+// Destructor
+SoftwareSerial::~SoftwareSerial()
+{
+  end();
+}
+
+void SoftwareSerial::setTX(uint8_t tx)
+{
+  // First write, then set output. If we do this the other way around,
+  // the pin would be output low for a short while before switching to
+  // output hihg. Now, it is input with pullup for a short while, which
+  // is fine. With inverse logic, either order is fine.
+  digitalWrite(tx, _inverse_logic ? LOW : HIGH);
+  pinMode(tx, OUTPUT);
+  _transmitBitMask = digitalPinToBitMask(tx);
+  PortGroup * port = digitalPinToPort(tx);
+  _transmitPortRegister = portOutputRegister(port);
+ 
+}
+
+void SoftwareSerial::setRX(uint8_t rx)
+{
+  pinMode(rx, INPUT);
+  if (!_inverse_logic)
+    digitalWrite(rx, HIGH);  // pullup for normal logic!
+  _receivePin = rx;
+  _receiveBitMask = digitalPinToBitMask(rx);
+  PortGroup * port = digitalPinToPort(rx);
+  _receivePortRegister = portInputRegister(port);
+
+}
+
+
+void SoftwareSerial::begin(long speed)
+{   
+    setTX(_transmitPin);
+    setRX(_receivePin);
+    // Precalculate the various delays
+    //Calculate the distance between bit in micro seconds
+  uint32_t bit_delay = (float(1)/speed)*1000000;
+ 
+  _tx_delay = bit_delay;
+  
+  // Only setup rx when we have a valid PCINT for this pin
+  if (digitalPinToInterrupt(_receivePin)!=NOT_AN_INTERRUPT) {
+      //Wait 1/2 bit - 2 micro seconds (time for interrupt to be served)
+       _rx_delay_centering = (bit_delay/2) - 2;
+      //Wait 1 bit - 2 micro seconds (time in each loop iteration)
+       _rx_delay_intrabit = bit_delay - 2;
+      //Wait 1 bit (the stop one) 
+       _rx_delay_stopbit = bit_delay; 
+
+       
+      delayMicroseconds(_tx_delay);
+      }
+      listen();
+}
+
+void SoftwareSerial::end()
+{
+  stopListening();
+}
+  
+int SoftwareSerial::read()
+{
+  if (!isListening()){
+    return -1;}
+
+
+  // Empty buffer?
+  if (_receive_buffer_head == _receive_buffer_tail){
+    return -1;}
+
+  // Read from "head"
+  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
+  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
+  return d;
+}  
+
+
+int SoftwareSerial::available()
+{
+  if (!isListening())
+    return 0;
+  
+  return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
+}
+
+
+size_t SoftwareSerial::write(uint8_t b)
+{
+  if (_tx_delay == 0) {
+    setWriteError();
+    return 0;
+  }
+
+  // By declaring these as local variables, the compiler will put them
+  // in registers _before_ disabling interrupts and entering the
+  // critical timing sections below, which makes it a lot easier to
+  // verify the cycle timings
+  volatile PORT_OUT_Type *reg = _transmitPortRegister;
+  uint32_t reg_mask = _transmitBitMask;
+  uint32_t inv_mask = ~_transmitBitMask;
+  bool inv = _inverse_logic;
+  uint16_t delay = _tx_delay;
+  
+  if (inv)
+    b = ~b;
+ // turn off interrupts for a clean txmit
+   EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT( 1 << digitalPinToInterrupt( _receivePin ));
+
+  // Write the start bit
+  if (inv)
+    reg->reg |= reg_mask;
+  else
+    reg->reg &= inv_mask;
+
+  delayMicroseconds(delay);
+
+
+  // Write each of the 8 bits
+  for (uint8_t i = 8; i > 0; --i)
+  {
+    if (b & 1) // choose bit
+      reg->reg |= reg_mask; // send 1
+    else
+      reg->reg &= inv_mask; // send 0
+
+  delayMicroseconds(delay); 
+    b >>= 1;
+  }
+
+  // restore pin to natural state
+  if (inv)
+    reg->reg &= inv_mask;
+  else
+    reg->reg |= reg_mask;
+  
+
+   EIC->INTENSET.reg = EIC_INTENSET_EXTINT( 1 << digitalPinToInterrupt( _receivePin ) ) ;
+  
+  delayMicroseconds(delay);  
+  
+  return 1;
+}
+
+void SoftwareSerial::flush()
+{
+  if (!isListening())
+    return;
+
+  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT( 1 << digitalPinToInterrupt( _receivePin ) ) ;
+  
+  _receive_buffer_head = _receive_buffer_tail = 0;
+
+   EIC->INTENSET.reg = EIC_INTENSET_EXTINT( 1 << digitalPinToInterrupt( _receivePin ) ) ;
+  
+}
+
+int SoftwareSerial::peek()
+{
+  if (!isListening())
+    return -1;
+
+  // Empty buffer?
+  if (_receive_buffer_head == _receive_buffer_tail)
+    return -1;
+
+  // Read from "head"
+  return _receive_buffer[_receive_buffer_head];
+}
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/SoftwareSerial.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/SoftwareSerial.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/SoftwareSerial.h	(revision 175)
@@ -0,0 +1,108 @@
+/*
+  SoftwareSerial.cpp - library for Arduino M0/M0 pro
+  Copyright (c) 2016 Arduino Srl. All rights reserved.
+  Written by Chiara Ruggeri (chiara@arduino.org)
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ 
+  Enjoy!
+*/ 
+
+#ifndef SoftwareSerial_h
+#define SoftwareSerial_h
+
+#include <inttypes.h>
+#include <Stream.h>
+#include <variant.h>
+
+/******************************************************************************
+* Definitions
+******************************************************************************/
+
+#define _SS_MAX_RX_BUFF 64 // RX buffer size
+#ifndef GCC_VERSION
+#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
+#endif
+
+class SoftwareSerial : public Stream
+{
+private:
+  // per object data
+  uint8_t _transmitPin;
+  uint8_t _receivePin;
+  uint32_t _receiveBitMask;
+  volatile PORT_IN_Type *_receivePortRegister;
+  uint32_t _transmitBitMask;
+  volatile PORT_OUT_Type *_transmitPortRegister;
+
+  // Expressed as 4-cycle delays (must never be 0!)
+  uint16_t _rx_delay_centering;
+  uint16_t _rx_delay_intrabit;
+  uint16_t _rx_delay_stopbit;
+  uint16_t _tx_delay;
+
+  uint16_t _buffer_overflow:1;
+  uint16_t _inverse_logic:1;
+
+  // static data
+  static char _receive_buffer[_SS_MAX_RX_BUFF]; 
+  static volatile uint8_t _receive_buffer_tail;
+  static volatile uint8_t _receive_buffer_head;
+  static SoftwareSerial *active_object;
+
+  // private methods
+  void recv() __attribute__((__always_inline__));
+  uint32_t rx_pin_read();
+  void tx_pin_write(uint8_t pin_state) __attribute__((__always_inline__));
+  void setTX(uint8_t transmitPin);
+  void setRX(uint8_t receivePin);
+  void setRxIntMsk(bool enable) __attribute__((__always_inline__));
+
+
+public:
+  // public methods
+  SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);
+  ~SoftwareSerial();
+  void begin(long speed);
+  bool listen();
+  void end();
+  bool isListening() { return this == active_object; }
+  bool stopListening();
+  bool overflow() { bool ret = _buffer_overflow; if (ret) _buffer_overflow = false; return ret; }
+  int peek();
+
+  virtual size_t write(uint8_t byte);
+  virtual int read();
+  virtual int available();
+  virtual void flush();
+  operator bool() { return true; }
+  
+  using Print::write;
+
+  // public only for easy access by interrupt handlers
+  static inline void handle_interrupt() __attribute__((__always_inline__));
+};
+
+// Arduino 0012 workaround
+#undef int
+#undef char
+#undef long
+#undef byte
+#undef float
+#undef abs
+#undef round
+
+#endif
+ 
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/examples/SoftwareSerialExample/SoftwareSerialExample.ino	(revision 175)
@@ -0,0 +1,41 @@
+/*
+  Software serial multiple serial test
+
+ Receives from the hardware serial, sends to software serial.
+ Receives from software serial, sends to hardware serial.
+
+ The circuit:
+ * RX is digital pin 9 (connect to TX of other device)
+ * TX is digital pin 10 (connect to RX of other device)
+ 
+ Note:
+ You shouldn't use pin 2
+ 
+ This example code is in the public domain.
+
+ */
+
+#include <SoftwareSerial.h>
+
+SoftwareSerial mySerial(9, 10); // RX, TX
+
+void setup()
+{
+  // Open serial communications and wait for port to open:
+  SerialUSB.begin(115200);
+  SerialUSB.println("Goodnight moon!");
+
+  // set the data rate for the SoftwareSerial port
+  mySerial.begin(9600);
+  mySerial.println("Hello, world?");
+}
+
+void loop() // run over and over//
+{
+  if (mySerial.available()) 
+    SerialUSB.write(mySerial.read());
+
+  if (SerialUSB.available())
+    mySerial.write(SerialUSB.read());
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/SoftwareSerial/examples/TwoPortReceive/TwoPortReceive.ino	(revision 175)
@@ -0,0 +1,71 @@
+/*
+  Software serial multple serial test
+
+ Receives from the two software serial ports,
+ sends to the hardware serial port.
+
+ In order to listen on a software port, you call port.listen().
+ When using two software serial ports, you have to switch ports
+ by listen()ing on each one in turn. Pick a logical time to switch
+ ports, like the end of an expected transmission, or when the
+ buffer is empty. This example switches ports when there is nothing
+ more to read from a port
+
+ The circuit:
+ Two devices which communicate serially are needed.
+ * First serial device's TX attached to digital pin 9, RX to pin 11
+ * Second serial device's TX attached to digital pin 8, RX to pin 10
+
+ This example code is in the public domain.
+
+ */
+
+#include <SoftwareSerial.h>
+// software serial #1: TX = digital pin 11, RX = digital pin 9
+SoftwareSerial portOne(9, 11);
+
+// software serial #2: TX = digital pin 10, RX = digital pin 8
+SoftwareSerial portTwo(8, 10);
+
+void setup()
+{
+  // Open serial communications and wait for port to open:
+  SerialUSB.begin(115200);
+
+  // Start each software serial port
+  portOne.begin(9600);
+  portTwo.begin(9600);
+}
+
+void loop()
+{
+  // By default, the last intialized port is listening.
+  // when you want to listen on a port, explicitly select it:
+  portOne.listen();
+
+  SerialUSB.println("Data from port one:");
+  // while there is data coming in, read it
+  // and send to the hardware serial port:
+  while (portOne.available() > 0) {
+    char inByte = portOne.read();
+    SerialUSB.write(inByte);
+  }
+
+  // blank line to separate data from the two ports:
+  SerialUSB.println("");
+
+  // Now listen on the second port
+  portTwo.listen();
+  // while there is data coming in, read it
+  // and send to the hardware serial port:
+
+  SerialUSB.println("Data from port two:");
+  while (portTwo.available() > 0) {
+    char inByte = portTwo.read();
+    SerialUSB.write(inByte);
+  }
+
+  // blank line to separate data from the two ports:
+  SerialUSB.println();
+}
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/Wire.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/Wire.cpp	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/Wire.cpp	(revision 175)
@@ -1,7 +1,5 @@
 /*
- * TwoWire.h - TWI/I2C library for Arduino Zero
- * based on Copyright (c) 2011 Cristian Maglie <c.maglie@bug.st>.
- * Copyright (c) 2014 Arduino.
- * All rights reserved.
+ * TWI/I2C library for Arduino Zero
+ * Copyright (c) 2015 Arduino LLC. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
@@ -24,31 +22,47 @@
 }
 
+#include <Arduino.h>
+#include <wiring_private.h>
+
 #include "Wire.h"
-#include "variant.h"
-#include "wiring_digital.h"
-
-TwoWire::TwoWire(SERCOM * s)
-{
-	this->sercom = s;
-	transmissionBegun = false;
+
+TwoWire::TwoWire(SERCOM * s, uint8_t pinSDA, uint8_t pinSCL)
+{
+  this->sercom = s;
+  this->_uc_pinSDA=pinSDA;
+  this->_uc_pinSCL=pinSCL;
+  transmissionBegun = false;
 }
 
 void TwoWire::begin(void) {
-	//Master Mode
-	sercom->initMasterWIRE(TWI_CLOCK);
-	sercom->enableWIRE();
-
-  pinPeripheral(PIN_WIRE_SDA, g_APinDescription[PIN_WIRE_SDA].ulPinType);
-  pinPeripheral(PIN_WIRE_SCL, g_APinDescription[PIN_WIRE_SCL].ulPinType);
+  //Master Mode
+  sercom->initMasterWIRE(TWI_CLOCK);
+  sercom->enableWIRE();
+
+  pinPeripheral(_uc_pinSDA, g_APinDescription[_uc_pinSDA].ulPinType);
+  pinPeripheral(_uc_pinSCL, g_APinDescription[_uc_pinSCL].ulPinType);
 }
 
 void TwoWire::begin(uint8_t address) {
-	//Slave mode
-	sercom->initSlaveWIRE(address);
-	sercom->enableWIRE();
+  //Slave mode
+  sercom->initSlaveWIRE(address);
+  sercom->enableWIRE();
+
+  pinPeripheral(_uc_pinSDA, g_APinDescription[_uc_pinSDA].ulPinType);
+  pinPeripheral(_uc_pinSCL, g_APinDescription[_uc_pinSCL].ulPinType);
+}
+
+void TwoWire::setClock(uint32_t baudrate) {
+  sercom->disableWIRE();
+  sercom->initMasterWIRE(baudrate);
+  sercom->enableWIRE();
+}
+
+void TwoWire::end() {
+  sercom->disableWIRE();
 }
 
 uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit)
-{ 
+{
   if(quantity == 0)
   {
@@ -56,302 +70,261 @@
   }
 
-
   size_t byteRead = 0;
 
   if(sercom->startTransmissionWIRE(address, WIRE_READ_FLAG))
   {
-  
     // Read first data
     rxBuffer.store_char(sercom->readDataWIRE());
 
     // Connected to slave
-    //while(toRead--)
-    for(byteRead = 0; byteRead < quantity; ++byteRead)
-    {
-      if( byteRead == quantity - 1)  // Stop transmission
+    for (byteRead = 1; byteRead < quantity; ++byteRead)
+    {
+      sercom->prepareAckBitWIRE();                          // Prepare Acknowledge
+      sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_READ); // Prepare the ACK command for the slave
+      rxBuffer.store_char(sercom->readDataWIRE());          // Read data and send the ACK
+    }
+    sercom->prepareNackBitWIRE();                           // Prepare NACK to stop slave transmission
+    //sercom->readDataWIRE();                               // Clear data register to send NACK
+
+    if (stopBit)
+    {
+      sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP);   // Send Stop
+    }
+  }
+
+  return byteRead;
+}
+
+uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity)
+{
+  return requestFrom(address, quantity, true);
+}
+
+void TwoWire::beginTransmission(uint8_t address) {
+  // save address of target and clear buffer
+  txAddress = address;
+  txBuffer.clear();
+
+  transmissionBegun = true;
+}
+
+// Errors:
+//  0 : Success
+//  1 : Data too long
+//  2 : NACK on transmit of address
+//  3 : NACK on transmit of data
+//  4 : Other error
+uint8_t TwoWire::endTransmission(bool stopBit)
+{
+  transmissionBegun = false ;
+
+  // Start I2C transmission
+  if ( !sercom->startTransmissionWIRE( txAddress, WIRE_WRITE_FLAG ) )
+  {
+    sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP);
+    return 2 ;  // Address error
+  }
+
+  // Send all buffer
+  while( txBuffer.available() )
+  {
+    // Trying to send data
+    if ( !sercom->sendDataMasterWIRE( txBuffer.read_char() ) )
+    {
+      sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP);
+      return 3 ;  // Nack or error
+    }
+  }
+  
+  if (stopBit)
+  {
+    sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP);
+  }   
+
+  return 0;
+}
+
+uint8_t TwoWire::endTransmission()
+{
+  return endTransmission(true);
+}
+
+size_t TwoWire::write(uint8_t ucData)
+{
+  if(sercom->isMasterWIRE())
+  {
+    // No writing, without begun transmission or a full buffer
+    if ( !transmissionBegun || txBuffer.isFull() )
+    {
+      return 0 ;
+    }
+
+    txBuffer.store_char( ucData ) ;
+
+    return 1 ;
+  }
+  else
+  {
+    if(sercom->sendDataSlaveWIRE( ucData ))
+    {
+      return 1;
+    }
+  }
+
+  return 0;
+}
+
+size_t TwoWire::write(const uint8_t *data, size_t quantity)
+{
+  //Try to store all data
+  for(size_t i = 0; i < quantity; ++i)
+  {
+    //Return the number of data stored, when the buffer is full (if write return 0)
+    if(!write(data[i]))
+      return i;
+  }
+
+  //All data stored
+  return quantity;
+}
+
+int TwoWire::available(void)
+{
+  return rxBuffer.available();
+}
+
+int TwoWire::read(void)
+{
+  return rxBuffer.read_char();
+}
+
+int TwoWire::peek(void)
+{
+  return rxBuffer.peek();
+}
+
+void TwoWire::flush(void)
+{
+  // Do nothing, use endTransmission(..) to force
+  // data transfer.
+}
+
+void TwoWire::onReceive(void(*function)(int))
+{
+  onReceiveCallback = function;
+}
+
+void TwoWire::onRequest(void(*function)(void))
+{
+  onRequestCallback = function;
+}
+
+void TwoWire::onService(void)
+{
+  if ( sercom->isSlaveWIRE() )
+  {
+    if(sercom->isStopDetectedWIRE() || 
+        (sercom->isAddressMatch() && sercom->isRestartDetectedWIRE() && !sercom->isMasterReadOperationWIRE())) //Stop or Restart detected
+    {
+      sercom->prepareAckBitWIRE();
+      sercom->prepareCommandBitsWire(0x03);
+
+      //Calling onReceiveCallback, if exists
+      if(onReceiveCallback)
       {
-        sercom->prepareNackBitWIRE(); // Prepare NACK to stop slave transmission
-        //sercom->readDataWIRE(); // Clear data register to send NACK
-        sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); // Send Stop 
+        onReceiveCallback(available());
       }
-      else // Continue transmission
+      
+      rxBuffer.clear();
+    }
+    else if(sercom->isAddressMatch())  //Address Match
+    {
+      sercom->prepareAckBitWIRE();
+      sercom->prepareCommandBitsWire(0x03);
+
+      if(sercom->isMasterReadOperationWIRE()) //Is a request ?
       {
-        sercom->prepareAckBitWIRE();  // Prepare Acknowledge
-        sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_READ); // Prepare the ACK command for the slave
-        rxBuffer.store_char( sercom->readDataWIRE() );  // Read data and send the ACK
+        // wait for data ready flag,
+        // before calling request callback
+        while(!sercom->isDataReadyWIRE());
+
+        //Calling onRequestCallback, if exists
+        if(onRequestCallback)
+        {
+          onRequestCallback();
+        }
       }
     }
-  }
-
-  return byteRead;
-}
-
-uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity)
-{
-	return requestFrom(address, quantity, true);
-}
-
-void TwoWire::beginTransmission(uint8_t address) {
-	// save address of target and clear buffer
-	txAddress = address;
-	txBuffer.clear();
-
-	transmissionBegun = true;
-}
-
-// Errors:
-//	0 : Success
-//	1 : Data too long
-//	2 : NACK on transmit of address
-//	3 : NACK on transmit of data
-//	4 : Other error
-uint8_t TwoWire::endTransmission(bool stopBit)
-{
-	transmissionBegun = false ;
-
-	// Check if there are data to send
-	if ( txBuffer.available() == 0)
-  {
-		return 4 ;
-  }
-
-	// Start I2C transmission
-	if ( !sercom->startTransmissionWIRE( txAddress, WIRE_WRITE_FLAG ) )
-  {
-    sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP);
-		return 2 ;	// Address error
-  }
-
-	// Send all buffer
-	while( txBuffer.available() )
-	{
-
-		// Trying to send data
-		if ( !sercom->sendDataMasterWIRE( txBuffer.read_char() ) )
-    {
-      sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP);
-			return 3 ;	// Nack or error
-    }
-
-    
-    if(txBuffer.available() == 0)
-    {
-      sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP);
-    }
-	}
-
-	return 0;
-}
-
-uint8_t TwoWire::endTransmission()
-{
-	return endTransmission(true);
-}
-
-size_t TwoWire::write(uint8_t ucData)
-{
-	if(sercom->isMasterWIRE())
-	{
-		// No writing, without begun transmission or a full buffer
-		if ( !transmissionBegun || txBuffer.isFull() )
-    {
-      return 0 ;
-    }
-
-		txBuffer.store_char( ucData ) ;
-
-		return 1 ;
-	}
-	else
-	{
-		if(sercom->sendDataSlaveWIRE( ucData ))
-    {
-			return 1;
-    }
-	}
-
-	return 0;
-}
-
-size_t TwoWire::write(const uint8_t *data, size_t quantity)
-{
-	//Try to store all data
-	for(size_t i = 0; i < quantity; ++i)
-	{
-		//Return the number of data stored, when the buffer is full (if write return 0)
-		if(!write(data[i]))
-			return i;
-	}
-
-	//All data stored
-	return quantity;
-}
-
-int TwoWire::available(void)
-{
-	return rxBuffer.available();
-}
-
-int TwoWire::read(void)
-{
-	return rxBuffer.read_char();
-}
-
-int TwoWire::peek(void)
-{
-	return rxBuffer.peek();
-}
-
-void TwoWire::flush(void)
-{
-	// Do nothing, use endTransmission(..) to force
-	// data transfer.
-}
-
-void TwoWire::onReceive(void(*function)(int))
-{
-	onReceiveCallback = function;
-}
-
-void TwoWire::onRequest(void(*function)(void))
-{
-	onRequestCallback = function;
-}
-
-
-void TwoWire::onService(void)
-{
-	if ( sercom->isSlaveWIRE() )
-	{
-		//Received data
-		if(sercom->isDataReadyWIRE())
-		{
-			//Store data
-			rxBuffer.store_char(sercom->readDataWIRE());
-
-			//Stop or Restart detected
-			if(sercom->isStopDetectedWIRE() || sercom->isRestartDetectedWIRE())
-			{
-				//Calling onReceiveCallback, if exists
-				if(onReceiveCallback)
-				{
-					onReceiveCallback(available());
-				}
-			}
-		}
-
-		//Address Match
-		if(sercom->isAddressMatch())
-		{
-			//Is a request ?
-			if(sercom->isMasterReadOperationWIRE())
-			{
-				//Calling onRequestCallback, if exists
-				if(onRequestCallback)
-				{
-					onRequestCallback();
-				}
-			}
-		}
-	}
-}
-
-/*
-void TwoWire::onService(void)
-{
-	// Retrieve interrupt status
-	uint32_t sr = TWI_GetStatus(twi);
-
-	if (status == SLAVE_IDLE && TWI_STATUS_SVACC(sr)) {
-		TWI_DisableIt(twi, TWI_IDR_SVACC);
-		TWI_EnableIt(twi, TWI_IER_RXRDY | TWI_IER_GACC | TWI_IER_NACK
-				| TWI_IER_EOSACC | TWI_IER_SCL_WS | TWI_IER_TXCOMP);
-
-		srvBufferLength = 0;
-		srvBufferIndex = 0;
-
-		// Detect if we should go into RECV or SEND status
-		// SVREAD==1 means *master* reading -> SLAVE_SEND
-		if (!TWI_STATUS_SVREAD(sr)) {
-			status = SLAVE_RECV;
-		} else {
-			status = SLAVE_SEND;
-
-			// Alert calling program to generate a response ASAP
-			if (onRequestCallback)
-				onRequestCallback();
-			else
-				// create a default 1-byte response
-				write((uint8_t) 0);
-		}
-	}
-
-	if (status != SLAVE_IDLE) {
-		if (TWI_STATUS_TXCOMP(sr) && TWI_STATUS_EOSACC(sr)) {
-			if (status == SLAVE_RECV && onReceiveCallback) {
-				// Copy data into rxBuffer
-				// (allows to receive another packet while the
-				// user program reads actual data)
-				for (uint8_t i = 0; i < srvBufferLength; ++i)
-					rxBuffer[i] = srvBuffer[i];
-				rxBufferIndex = 0;
-				rxBufferLength = srvBufferLength;
-
-				// Alert calling program
-				onReceiveCallback( rxBufferLength);
-			}
-
-			// Transfer completed
-			TWI_EnableIt(twi, TWI_SR_SVACC);
-			TWI_DisableIt(twi, TWI_IDR_RXRDY | TWI_IDR_GACC | TWI_IDR_NACK
-					| TWI_IDR_EOSACC | TWI_IDR_SCL_WS | TWI_IER_TXCOMP);
-			status = SLAVE_IDLE;
-		}
-	}
-
-	if (status == SLAVE_RECV) {
-		if (TWI_STATUS_RXRDY(sr)) {
-			if (srvBufferLength < BUFFER_LENGTH)
-				srvBuffer[srvBufferLength++] = TWI_ReadByte(twi);
-		}
-	}
-
-	if (status == SLAVE_SEND) {
-		if (TWI_STATUS_TXRDY(sr) && !TWI_STATUS_NACK(sr)) {
-			uint8_t c = 'x';
-			if (srvBufferIndex < srvBufferLength)
-				c = srvBuffer[srvBufferIndex++];
-			TWI_WriteByte(twi, c);
-		}
-	}
-}
-*/
+    else if(sercom->isDataReadyWIRE()) //Received data
+    {
+      if (rxBuffer.isFull()) {
+        sercom->prepareNackBitWIRE(); 
+      } else {
+        //Store data
+        rxBuffer.store_char(sercom->readDataWIRE());
+
+        sercom->prepareAckBitWIRE(); 
+      }
+
+      sercom->prepareCommandBitsWire(0x03);
+    }
+  }
+}
 
 #if WIRE_INTERFACES_COUNT > 0
-/*static void Wire_Init(void) {
-	pmc_enable_periph_clk(WIRE_INTERFACE_ID);
-	PIO_Configure(
-			g_APinDescription[PIN_WIRE_SDA].pPort,
-			g_APinDescription[PIN_WIRE_SDA].ulPinType,
-			g_APinDescription[PIN_WIRE_SDA].ulPin,
-			g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration);
-	PIO_Configure(
-			g_APinDescription[PIN_WIRE_SCL].pPort,
-			g_APinDescription[PIN_WIRE_SCL].ulPinType,
-			g_APinDescription[PIN_WIRE_SCL].ulPin,
-			g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration);
-
-	NVIC_DisableIRQ(WIRE_ISR_ID);
-	NVIC_ClearPendingIRQ(WIRE_ISR_ID);
-	NVIC_SetPriority(WIRE_ISR_ID, 0);
-	NVIC_EnableIRQ(WIRE_ISR_ID);
-}*/
-
-
-TwoWire Wire(&sercom3);
-
-void SERCOM3_Handler(void) {
-	Wire.onService();
-}
-
-#endif
+  /* In case new variant doesn't define these macros,
+   * we put here the ones for Arduino Zero.
+   *
+   * These values should be different on some variants!
+   */
+  #ifndef PERIPH_WIRE
+    #define PERIPH_WIRE          sercom3
+    #define WIRE_IT_HANDLER      SERCOM3_Handler
+  #endif // PERIPH_WIRE
+  TwoWire Wire(&PERIPH_WIRE, PIN_WIRE_SDA, PIN_WIRE_SCL);
+
+  void WIRE_IT_HANDLER(void) {
+    Wire.onService();
+  }
+#endif
+
+#if WIRE_INTERFACES_COUNT > 1
+  TwoWire Wire1(&PERIPH_WIRE1, PIN_WIRE1_SDA, PIN_WIRE1_SCL);
+
+  void WIRE1_IT_HANDLER(void) {
+    Wire1.onService();
+  }
+#endif
+
+#if WIRE_INTERFACES_COUNT > 2
+  TwoWire Wire2(&PERIPH_WIRE2, PIN_WIRE2_SDA, PIN_WIRE2_SCL);
+
+  void WIRE2_IT_HANDLER(void) {
+    Wire2.onService();
+  }
+#endif
+
+#if WIRE_INTERFACES_COUNT > 3
+  TwoWire Wire3(&PERIPH_WIRE3, PIN_WIRE3_SDA, PIN_WIRE3_SCL);
+
+  void WIRE3_IT_HANDLER(void) {
+    Wire3.onService();
+  }
+#endif
+
+#if WIRE_INTERFACES_COUNT > 4
+  TwoWire Wire4(&PERIPH_WIRE4, PIN_WIRE4_SDA, PIN_WIRE4_SCL);
+
+  void WIRE4_IT_HANDLER(void) {
+    Wire4.onService();
+  }
+#endif
+
+#if WIRE_INTERFACES_COUNT > 5
+  TwoWire Wire5(&PERIPH_WIRE5, PIN_WIRE5_SDA, PIN_WIRE5_SCL);
+
+  void WIRE5_IT_HANDLER(void) {
+    Wire5.onService();
+  }
+#endif
+
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/Wire.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/Wire.h	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/Wire.h	(revision 175)
@@ -1,6 +1,5 @@
 /*
- * TwoWire.h - TWI/I2C library for Arduino Due
- * Copyright (c) 2011 Cristian Maglie <c.maglie@bug.st>.
- * All rights reserved.
+ * TWI/I2C library for Arduino Zero
+ * Copyright (c) 2015 Arduino LLC. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
@@ -22,6 +21,4 @@
 #define TwoWire_h
 
-//#include <include/twi.h>
-
 #include "Stream.h"
 #include "variant.h"
@@ -32,76 +29,100 @@
 #define BUFFER_LENGTH 32
 
+ // WIRE_HAS_END means Wire has end()
+#define WIRE_HAS_END 1
 
 class TwoWire : public Stream
 {
-	public:
-		TwoWire(SERCOM *s);
-		void begin();
-		void begin(uint8_t);
+  public:
+    TwoWire(SERCOM *s, uint8_t pinSDA, uint8_t pinSCL);
+    void begin();
+    void begin(uint8_t);
+    void end();
+    void setClock(uint32_t);
 
-		void beginTransmission(uint8_t);
-		uint8_t endTransmission(bool stopBit);
-		uint8_t endTransmission(void);
+    void beginTransmission(uint8_t);
+    uint8_t endTransmission(bool stopBit);
+    uint8_t endTransmission(void);
 
-		uint8_t requestFrom(uint8_t address, size_t quantity, bool stopBit);
-		uint8_t requestFrom(uint8_t address, size_t quantity);
+    uint8_t requestFrom(uint8_t address, size_t quantity, bool stopBit);
+    uint8_t requestFrom(uint8_t address, size_t quantity);
 
-		size_t write(uint8_t data);
-		size_t write(const uint8_t * data, size_t quantity);
+    size_t write(uint8_t data);
+    size_t write(const uint8_t * data, size_t quantity);
 
-		virtual int available(void);
-		virtual int read(void);
-		virtual int peek(void);
-		virtual void flush(void);
-		void onReceive(void(*)(int));
-		void onRequest(void(*)(void));
+    virtual int available(void);
+    virtual int read(void);
+    virtual int peek(void);
+    virtual void flush(void);
+    void onReceive(void(*)(int));
+    void onRequest(void(*)(void));
 
-		using Print::write;
+    using Print::write;
 
-		void onService(void);
+    void onService(void);
 
-	private:
-		SERCOM * sercom;
-		bool transmissionBegun;
+  private:
+    SERCOM * sercom;
+    uint8_t _uc_pinSDA;
+    uint8_t _uc_pinSCL;
 
-		// RX Buffer
-		RingBuffer rxBuffer;
+    bool transmissionBegun;
 
-		//TX buffer
-		RingBuffer txBuffer;
-		uint8_t txAddress;
+    // RX Buffer
+    RingBuffer rxBuffer;
+
+    //TX buffer
+    RingBuffer txBuffer;
+    uint8_t txAddress;
 
 
-		// Service buffer
-		//uint8_t srvBuffer[BUFFER_LENGTH];
-		//uint8_t srvBufferIndex;
-		//uint8_t srvBufferLength;
+    // Service buffer
+    //uint8_t srvBuffer[BUFFER_LENGTH];
+    //uint8_t srvBufferIndex;
+    //uint8_t srvBufferLength;
 
-		// Callback user functions
-		void (*onRequestCallback)(void);
-		void (*onReceiveCallback)(int);
+    // Callback user functions
+    void (*onRequestCallback)(void);
+    void (*onReceiveCallback)(int);
 
-		// TWI state
-		//enum TwoWireStatus
+    // TWI state
+    //enum TwoWireStatus
     //{
-		//	UNINITIALIZED,
-		//	MASTER_IDLE,
-		//	MASTER_SEND,
-		//	MASTER_RECV,
-		//	SLAVE_IDLE,
-		//	SLAVE_RECV,
-		//	SLAVE_SEND
-		//};
-		//TwoWireStatus status;
+    //  UNINITIALIZED,
+    //  MASTER_IDLE,
+    //  MASTER_SEND,
+    //  MASTER_RECV,
+    //  SLAVE_IDLE,
+    //  SLAVE_RECV,
+    //  SLAVE_SEND
+    //};
+    //TwoWireStatus status;
 
-		// TWI clock frequency
-		static const uint32_t TWI_CLOCK = 100000;
+    // TWI clock frequency
+    static const uint32_t TWI_CLOCK = 100000;
 
-		// Timeouts
-		//static const uint32_t RECV_TIMEOUT = 100000;
-		//static const uint32_t XMIT_TIMEOUT = 100000;
+    // Timeouts
+    //static const uint32_t RECV_TIMEOUT = 100000;
+    //static const uint32_t XMIT_TIMEOUT = 100000;
 };
 
-extern TwoWire Wire;
+#if WIRE_INTERFACES_COUNT > 0
+  extern TwoWire Wire;
+#endif
+#if WIRE_INTERFACES_COUNT > 1
+  extern TwoWire Wire1;
+#endif
+#if WIRE_INTERFACES_COUNT > 2
+  extern TwoWire Wire2;
+#endif
+#if WIRE_INTERFACES_COUNT > 3
+  extern TwoWire Wire3;
+#endif
+#if WIRE_INTERFACES_COUNT > 4
+  extern TwoWire Wire4;
+#endif
+#if WIRE_INTERFACES_COUNT > 5
+  extern TwoWire Wire5;
+#endif
 
 #endif
Index: /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/library.properties
===================================================================
--- /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/library.properties	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/hardware/arduino/samd/libraries/Wire/library.properties	(revision 175)
@@ -0,0 +1,9 @@
+name=Wire
+version=1.0
+author=Jonathan BAUDIN, Thibaut VIARD, Arduino
+maintainer=Arduino <info@arduino.cc>
+sentence=Allows the communication between devices or sensors connected via Two Wire Interface Bus. Specific implementation for Arduino Zero.
+paragraph=
+category=Communication
+url=http://www.arduino.cc/en/Reference/Wire
+architectures=samd
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/README.adoc
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/README.adoc	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/README.adoc	(revision 175)
@@ -0,0 +1,24 @@
+= Braccio Library for Arduino =
+
+The library offers easy access to the data from the onboard Arduino Braccio, and provides moves the Arduino Braccio.
+
+For more information about this library please visit us at
+http://www.arduino.org/products/tinkerkit/17-arduino-tinkerkit/arduino-tinkerkit-braccio
+
+== License ==
+
+Copyright (c) Medea-Solutions. All right reserved.
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/ciaoBraccio/ciaoBraccio.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/ciaoBraccio/ciaoBraccio.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/ciaoBraccio/ciaoBraccio.ino	(revision 175)
@@ -0,0 +1,236 @@
+/*
+
+ This sketch uses the rest connector to receive command for the MCU from a rest client.
+ Each command received will fire an action for the Braccio.
+ Run the sketch with Arduino Braccio - Web Examples to move your Braccio via web page.
+ Visit the Demo section of the Braccio's page.
+ http://www.arduino.org/products/tinkerkit/17-arduino-tinkerkit/arduino-tinkerkit-braccio
+ 
+
+
+REST command example:
+
+ * "ledon"             -> turn on led 13
+ * "ledoff"            -> turn off led 13
+
+ example: http://arduino.local/arduino/ledon
+
+ NOTE: be sure to activate and configure rest connector on Linino OS
+       http://labs.arduino.org/Ciao
+
+ created March 2016
+ by andrea[at]arduino[dot]org and a.ferrante[at]arduino[dot]org
+
+ */
+
+#include <Ciao.h>
+#include <Servo.h>
+#include <Braccio.h>
+
+//Initial Value for each Motor
+int m1 = 0;
+int m2 = 45;
+int m3 = 180;
+int m4 = 180;
+int m5 = 90;
+int m6 = 0;
+
+boolean moveBraccio = false;
+
+Servo base;
+Servo shoulder;
+Servo elbow;
+Servo wrist_rot;
+Servo wrist_ver;
+Servo gripper;
+
+void setup() {
+  //Initialization functions for Ciao
+  Ciao.begin();
+  //Initialization functions for Braccio
+  Braccio.begin();
+}
+
+/**
+Parse Command from REST
+It parse a command like: /arduino/base/value:45
+Giving "base" it return the value
+@param command: The message to parse
+@param type: the key for parsing
+*/
+int parseCommand(String command, String type) {
+  int typeIndex = command.indexOf(type);
+  int dotsIndex = command.indexOf(':', typeIndex + type.length());
+
+  int idxtmp = dotsIndex + 4;
+  if ((dotsIndex + 4) > command.length()) idxtmp = command.length();
+  String tmp = command.substring(dotsIndex + 1, idxtmp);
+
+  return tmp.toInt();
+}
+
+void loop() {
+
+  //Select REST connector
+  CiaoData data = Ciao.read("restserver");
+  //If data is not empry
+  if (!data.isEmpty()) {
+    //ID of the command
+    String id = data.get(0);
+    //Sender ID
+    String sender = data.get(1);
+    //The message from sender
+    String message = data.get(2);
+
+    message.toUpperCase();
+
+    /*
+    For each message do the proper command
+    */
+    if (message == "LEDON") {
+      //Turn OFF Led 13
+      digitalWrite(13, HIGH);
+      //Return message to the sender (Eg: the browser)
+      Ciao.writeResponse("restserver", id, "Led D13 ON");
+    }
+    else if (message == "LEDOFF") {
+      digitalWrite(13, LOW);
+      Ciao.writeResponse("restserver", id, "Led D13 OFF");
+    }
+    //This command allow you to move a desired servo motor giving the
+    //PWM pin where is connected
+    else if (message.startsWith("SERVO")) {
+      //Parse the message to retrive what is the servo to move
+      int servo = parseCommand(message, "SERVO");
+      //Parse the message to retrive what is the value for the servo
+      int value = parseCommand(message, "VALUE");
+
+      Ciao.writeResponse("restserver", id, "Message:" + String(message) + "SERVO: " + String(servo) + " " + String(value));
+    }
+    //Command for the base of the braccio (M1)
+    else if (message.startsWith("BASE")) {
+      m1 = parseCommand(message, "VALUE");
+      moveBraccio = true;
+      Ciao.writeResponse("restserver", id, "BASE: " + String(m1));
+    }
+    //Command for the shoulder of the braccio (M2)
+    else if (message.startsWith("SHOULDER")) {
+      m2 = parseCommand(message, "VALUE");
+      moveBraccio = true;
+      Ciao.writeResponse("restserver", id, "SHOULDER: " + String(m2));
+    }
+    //Command for the elbow of the braccio (M3)
+    else if (message.startsWith("ELBOW")) {
+      m3 = parseCommand(message, "VALUE");
+      moveBraccio = true;
+      Ciao.writeResponse("restserver", id, "ELBOW: " + String(m3));
+    }
+    //Command for the wrist of the braccio to move it up and down (M4)
+    else if (message.startsWith("WRISTV")) {
+      m4 = parseCommand(message, "VALUE");
+      moveBraccio = true;
+      Ciao.writeResponse("restserver", id, "WRISTV: " + String(m4));
+    }
+    //Command for the wrist of the braccio to rotate it  (M5)
+    else if (message.startsWith("WRISTR")) {
+      m5 = parseCommand(message, "VALUE");
+      moveBraccio = true;
+      Ciao.writeResponse("restserver", id, "WRISTR: " + String(m5));
+    }
+    //Command for the gripper of the braccio to open and close it (M6)
+    else if (message.startsWith("GRIPPER")) {
+      m6 = parseCommand(message, "VALUE");
+      moveBraccio = true;
+      Ciao.writeResponse("restserver", id, "GRIPPER: " + String(m6));
+    }
+    //Command to say "Ciao"
+    else if (message.startsWith("SAYCIAO")) {
+      sayCiao();
+      Ciao.writeResponse("restserver", id, "SAYCIAO: " + String(m6));
+    }
+    //Command for take the sponge
+    else if (message.startsWith("TAKESPONGE")) {
+      takesponge();
+      Ciao.writeResponse("restserver", id, "TAKESPONGE: " + String(m6));
+    }
+   //Command for show the sponge
+    else if (message.startsWith("SHOWSPONGE")) {
+      showsponge();
+      Ciao.writeResponse("restserver", id, "SHOWSPONGE: " + String(m6));
+    }
+    //Command for throw away the sponge
+    else if (message.startsWith("THROWSPONGE")) {
+      throwsponge();
+      Ciao.writeResponse("restserver", id, "THROWSPONGE: " + String(m6));
+    }
+
+    else
+      Ciao.writeResponse("restserver", id, "command error");
+
+    //if flag moveBraccio is true fire the movement
+    if (moveBraccio) {
+      Braccio.ServoMovement(20, m1, m2, m3, m4, m5, m6);
+      moveBraccio = false;
+    }
+  }
+}
+
+/**
+The braccio Say 'Ciao' with the Tongue
+*/
+void sayCiao() {
+
+  Braccio.ServoMovement(20,           90,  0, 180, 160,  0,  15);
+
+  for (int i = 0; i < 5; i++) {
+    Braccio.ServoMovement(10,           90,  0, 180, 160,  0,  15);
+    delay(500);
+
+    Braccio.ServoMovement(10,     90,  0,   180,   160,  0,   73);
+    delay(500);
+  }
+}
+
+/**
+Braccio take the Sponge
+*/
+void takesponge() {
+  //starting position
+                      //(step delay  M1 , M2 , M3 , M4 , M5 , M6);
+  Braccio.ServoMovement(20,           0,  45, 180, 180,  90,  0);
+
+  //I move arm towards the sponge
+  Braccio.ServoMovement(20,           0,  90, 180, 180,  90,   0);
+
+  //the gripper takes the sponge
+  Braccio.ServoMovement(20,           0,  90, 180, 180,  90,  60 );
+
+  //up the sponge
+  Braccio.ServoMovement(20,         0,   45, 180,  45,  0, 60);
+}
+
+
+/**
+Braccio show the sponge to the user
+*/
+void showsponge() {
+  for (int i = 0; i < 2; i++) {
+
+                          //(step delay  M1 , M2 , M3 , M4 , M5 , M6 );
+    Braccio.ServoMovement(10,         0,   45, 180,  45,  180, 60);
+
+    Braccio.ServoMovement(10,         0,   45, 180,  45,  0, 60);
+  }
+}
+
+/**
+Braccio throw away the sponge
+*/
+void throwsponge() {
+                      //(step delay  M1 , M2 , M3 , M4 , M5 , M6 );
+  Braccio.ServoMovement(20,         0,   45, 90,  45,  90, 60);
+
+  Braccio.ServoMovement(5,         0,   45, 135,  90,  90, 60);
+
+  Braccio.ServoMovement(5,         0,   90, 150,  90,  90, 0);
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/simpleMovements/simpleMovements.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/simpleMovements/simpleMovements.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/simpleMovements/simpleMovements.ino	(revision 175)
@@ -0,0 +1,56 @@
+
+/*
+  simpleMovements.ino
+
+ This  sketch simpleMovements shows how they move each servo motor of Braccio
+
+ Created on 18 Nov 2015
+ by Andrea Martino
+
+ This example is in the public domain.
+ */
+
+#include <Braccio.h>
+#include <Servo.h>
+
+Servo base;
+Servo shoulder;
+Servo elbow;
+Servo wrist_rot;
+Servo wrist_ver;
+Servo gripper;
+
+void setup() {
+  //Initialization functions and set up the initial position for Braccio
+  //All the servo motors will be positioned in the "safety" position:
+  //Base (M1):90 degrees
+  //Shoulder (M2): 45 degrees
+  //Elbow (M3): 180 degrees
+  //Wrist vertical (M4): 180 degrees
+  //Wrist rotation (M5): 90 degrees
+  //gripper (M6): 10 degrees
+  Braccio.begin();
+}
+
+void loop() {
+   /*
+   Step Delay: a milliseconds delay between the movement of each servo.  Allowed values from 10 to 30 msec.
+   M1=base degrees. Allowed values from 0 to 180 degrees
+   M2=shoulder degrees. Allowed values from 15 to 165 degrees
+   M3=elbow degrees. Allowed values from 0 to 180 degrees
+   M4=wrist vertical degrees. Allowed values from 0 to 180 degrees
+   M5=wrist rotation degrees. Allowed values from 0 to 180 degrees
+   M6=gripper degrees. Allowed values from 10 to 73 degrees. 10: the toungue is open, 73: the gripper is closed.
+  */
+  
+                       //(step delay, M1, M2, M3, M4, M5, M6);
+  Braccio.ServoMovement(20,           0,  15, 180, 170, 0,  73);  
+
+  //Wait 1 second
+  delay(1000);
+
+  Braccio.ServoMovement(20,           180,  165, 0, 0, 180,  10);  
+
+  //Wait 1 second
+  delay(1000);
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/takethesponge/takethesponge.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/takethesponge/takethesponge.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/takethesponge/takethesponge.ino	(revision 175)
@@ -0,0 +1,73 @@
+/*
+  takethesponge.ino
+
+ This example commands to the Braccio to take a sponge from the table and it shows to the user
+
+ Created on 18 Nov 2015
+ by Andrea Martino
+
+ This example is in the public domain.
+*/
+
+#include <Braccio.h>
+#include <Servo.h>
+
+
+Servo base;
+Servo shoulder;
+Servo elbow;
+Servo wrist_rot;
+Servo wrist_ver;
+Servo gripper;
+
+
+void setup() {  
+  //Initialization functions and set up the initial position for Braccio
+  //All the servo motors will be positioned in the "safety" position:
+  //Base (M1):90 degrees
+  //Shoulder (M2): 45 degrees
+  //Elbow (M3): 180 degrees
+  //Wrist vertical (M4): 180 degrees
+  //Wrist rotation (M5): 90 degrees
+  //gripper (M6): 10 degrees
+  Braccio.begin();
+}
+
+void loop() {
+  /*
+  Step Delay: a milliseconds delay between the movement of each servo.  Allowed values from 10 to 30 msec.
+  M1=base degrees. Allowed values from 0 to 180 degrees
+  M2=shoulder degrees. Allowed values from 15 to 165 degrees
+  M3=elbow degrees. Allowed values from 0 to 180 degrees
+  M4=wrist vertical degrees. Allowed values from 0 to 180 degrees
+  M5=wrist rotation degrees. Allowed values from 0 to 180 degrees
+  M6=gripper degrees. Allowed values from 10 to 73 degrees. 10: the toungue is open, 73: the gripper is closed.
+  */
+
+  //Starting position
+                      //(step delay  M1 , M2 , M3 , M4 , M5 , M6);
+  Braccio.ServoMovement(20,           0,  45, 180, 180,  90,  10);
+  
+  //Wait 1 second
+  delay(1000);
+
+  //The braccio moves to the sponge. Only the M2 servo will moves
+  Braccio.ServoMovement(20,           0,  90, 180, 180,  90,   10);
+
+  //Close the gripper to take the sponge. Only the M6 servo will moves
+  Braccio.ServoMovement(10,           0,  90, 180, 180,  90,  60 );
+
+  //Brings the sponge upwards.
+  Braccio.ServoMovement(20,         0,   45, 180,  45,  0, 60);
+
+  //Show the sponge. Only the M1 servo will moves
+  Braccio.ServoMovement(20,         180,  45, 180,   45,   0,  60);
+
+  //Return to the start position.
+  Braccio.ServoMovement(20,         0,   90, 180,  180,  90, 60);
+
+  //Open the gripper
+  Braccio.ServoMovement(20,         0,   90, 180,  180,  90, 10 );
+
+
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/testBraccio90/testBraccio90.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/testBraccio90/testBraccio90.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/examples/testBraccio90/testBraccio90.ino	(revision 175)
@@ -0,0 +1,53 @@
+ /*
+  testBraccio90.ino
+
+ testBraccio90 is a setup sketch to check the alignment of all the servo motors
+ This is the first sketch you need to run on Braccio
+ When you start this sketch Braccio will be positioned perpendicular to the base
+ If you can't see the Braccio in this exact position you need to reallign the servo motors position
+
+ Created on 18 Nov 2015
+ by Andrea Martino
+
+ This example is in the public domain.
+ */
+
+#include <Braccio.h>
+#include <Servo.h>
+
+
+Servo base;
+Servo shoulder;
+Servo elbow;
+Servo wrist_rot;
+Servo wrist_ver;
+Servo gripper;
+
+void setup() {  
+  //Initialization functions and set up the initial position for Braccio
+  //All the servo motors will be positioned in the "safety" position:
+  //Base (M1):90 degrees
+  //Shoulder (M2): 45 degrees
+  //Elbow (M3): 180 degrees
+  //Wrist vertical (M4): 180 degrees
+  //Wrist rotation (M5): 90 degrees
+  //gripper (M6): 10 degrees
+  Braccio.begin();
+}
+
+void loop() {
+  /*
+   Step Delay: a milliseconds delay between the movement of each servo.  Allowed values from 10 to 30 msec.
+   M1=base degrees. Allowed values from 0 to 180 degrees
+   M2=shoulder degrees. Allowed values from 15 to 165 degrees
+   M3=elbow degrees. Allowed values from 0 to 180 degrees
+   M4=wrist vertical degrees. Allowed values from 0 to 180 degrees
+   M5=wrist rotation degrees. Allowed values from 0 to 180 degrees
+   M6=gripper degrees. Allowed values from 10 to 73 degrees. 10: the toungue is open, 73: the gripper is closed.
+  */
+  
+  // the arm is aligned upwards  and the gripper is closed
+                     //(step delay, M1, M2, M3, M4, M5, M6);
+  Braccio.ServoMovement(20,         90, 90, 90, 90, 90,  73);  
+	 
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/keywords.txt
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/keywords.txt	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/keywords.txt	(revision 175)
@@ -0,0 +1,34 @@
+#######################################
+# Syntax Coloring Map For Braccio
+####################################### 
+# Class
+#######################################
+
+Braccio	KEYWORD3
+
+#######################################
+# Methods and Functions 
+#######################################	
+
+begin	KEYWORD2
+ServoMovement	KEYWORD2
+
+
+
+#######################################
+# Constants
+#######################################
+ 
+shoulder	LITERAL1
+elbow	LITERAL1
+wrist_rot	LITERAL1
+wrist_ver	LITERAL1
+gripper	LITERAL1
+base	LITERAL1
+
+step_base	LITERAL1
+step_shoulder	LITERAL1
+step_elbow	LITERAL1
+step_wrist_rot	LITERAL1
+step_wrist_ver	LITERAL1
+step_gripper	LITERAL1
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/library.properties
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/library.properties	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/library.properties	(revision 175)
@@ -0,0 +1,9 @@
+name=Braccio
+version=1.0
+author=Andrea Martino
+maintainer=Andrea <a.martino@arduino.org>
+sentence=For Arduino braccio only.
+paragraph= Arm robot , Braccio robotico
+category=Device Control
+url=www.bracciorobotico.com
+architectures=avr
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/src/Braccio.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/src/Braccio.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/src/Braccio.cpp	(revision 175)
@@ -0,0 +1,218 @@
+/*
+ Braccio.cpp - board library Version 1.1
+ Written by Andrea Martino
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#include "Braccio.h"
+
+extern Servo base;
+extern Servo shoulder;
+extern Servo elbow;
+extern Servo wrist_rot;
+extern Servo wrist_ver;
+extern Servo gripper;
+
+extern int step_base = 0;
+extern int step_shoulder = 45;
+extern int step_elbow = 180;
+extern int step_wrist_rot = 180;
+extern int step_wrist_ver = 90;
+extern int step_gripper = 10;
+
+_Braccio Braccio;
+
+//Initialize Braccio object
+_Braccio::_Braccio() {
+}
+
+/**
+ * Braccio initialization and set intial position
+ * Modifing this function you can set up the initial position of all the
+ * servo motors of the Braccio
+ */
+unsigned int _Braccio::begin() {
+	// initialization pin Servo motors
+	#if defined(ARDUINO_ARCH_SAMD)
+		base.attach(11);
+		shoulder.attach(7);
+		elbow.attach(9);
+		wrist_rot.attach(6);
+		wrist_ver.attach(8);
+		gripper.attach(3);
+	#else
+		base.attach(11);
+		shoulder.attach(10);
+		elbow.attach(9);
+		wrist_rot.attach(6);
+		wrist_ver.attach(5);
+		gripper.attach(3);
+	#endif	
+
+	//For each step motor this set up the initial degree
+	base.write(90);
+	shoulder.write(45);
+	elbow.write(180);
+        wrist_ver.write(180);
+        wrist_rot.write(90);
+        gripper.write(10);
+	//Previous step motor position
+	step_base = 90;
+	step_shoulder = 45;
+	step_elbow = 180;
+	step_wrist_ver = 180;
+	step_wrist_rot = 90;
+	step_gripper = 10;
+	return 1;
+}
+
+/**
+ * This functions allow you to control all the servo motors in the Braccio setting the funcion parameters.
+ * 
+ * @param stepDelay The delay between each servo movement
+ * @param vBase next base servo motor degree
+ * @param vShoulder next shoulder servo motor degree
+ * @param vElbow next elbow servo motor degree
+ * @param vWrist_ver next wrist rotation servo motor degree
+ * @param vWrist_rot next wrist vertical servo motor degree
+ * @param vgripper next gripper servo motor degree
+ */
+int _Braccio::ServoMovement(int stepDelay, int vBase, int vShoulder, int vElbow,int vWrist_ver, int vWrist_rot, int vgripper) {
+
+        // Check values
+        if (stepDelay > 30) stepDelay = 30;
+	if (stepDelay < 10) stepDelay = 10;
+	if (vBase < 0) vBase=0;
+	if (vBase > 180) vBase=180;
+	if (vShoulder < 15) vShoulder=15;
+	if (vShoulder > 165) vShoulder=165;
+	if (vElbow < 0) vElbow=0;
+	if (vElbow > 180) vElbow=180;
+	if (vWrist_ver < 0) vWrist_ver=0;
+	if (vWrist_ver > 180) vWrist_ver=180;
+	if (vWrist_rot > 180) vWrist_rot=180;
+	if (vWrist_rot < 0) vWrist_rot=0;
+        if (vgripper < 10) vgripper = 10;
+	if (vgripper > 73) vgripper = 73;
+
+	int exit = 1;
+
+	//Until the all motors are in the desired position
+	while (exit) 
+	{			
+		//For each servo motor if next degree is not the same of the previuos than do the movement		
+		if (vBase != step_base) 
+		{			
+			base.write(step_base);
+			//One step ahead
+			if (vBase > step_base) {
+				step_base++;
+			}
+			//One step beyond
+			if (vBase < step_base) {
+				step_base--;
+			}
+		}
+
+		if (vShoulder != step_shoulder)  
+		{
+			shoulder.write(step_shoulder);
+			//One step ahead
+			if (vShoulder > step_shoulder) {
+				step_shoulder++;
+			}
+			//One step beyond
+			if (vShoulder < step_shoulder) {
+				step_shoulder--;
+			}
+
+		}
+
+		if (vElbow != step_elbow)  
+		{
+			elbow.write(step_elbow);
+			//One step ahead
+			if (vElbow > step_elbow) {
+				step_elbow++;
+			}
+			//One step beyond
+			if (vElbow < step_elbow) {
+				step_elbow--;
+			}
+
+		}
+
+		if (vWrist_ver != step_wrist_rot) 
+		{
+			wrist_rot.write(step_wrist_rot);
+			//One step ahead
+			if (vWrist_ver > step_wrist_rot) {
+				step_wrist_rot++;				
+			}
+			//One step beyond
+			if (vWrist_ver < step_wrist_rot) {
+				step_wrist_rot--;
+			}
+
+		}
+
+		if (vWrist_rot != step_wrist_ver)
+		{
+			wrist_ver.write(step_wrist_ver);
+			//One step ahead
+			if (vWrist_rot > step_wrist_ver) {
+				step_wrist_ver++;
+			}
+			//One step beyond
+			if (vWrist_rot < step_wrist_ver) {
+				step_wrist_ver--;
+			}
+		}
+
+		if (vgripper != step_gripper)
+		{
+			gripper.write(step_gripper);
+			if (vgripper > step_gripper) {
+				step_gripper++;
+			}
+			//One step beyond
+			if (vgripper < step_gripper) {
+				step_gripper--;
+			}
+		}
+
+		
+		//The delay between each movement
+		delay(stepDelay);
+		
+		//It checks if all the servo motors are in the desired position 
+		if ((vBase == step_base) && (vShoulder == step_shoulder)
+				&& (vElbow == step_elbow) && (vWrist_ver == step_wrist_rot)
+				&& (vWrist_rot == step_wrist_ver) && (vgripper == step_gripper)) {
+			step_base = vBase;
+			step_shoulder = vShoulder;
+			step_elbow = vElbow;
+			step_wrist_rot = vWrist_ver;
+			step_wrist_ver = vWrist_rot;
+			step_gripper = vgripper;
+			exit = 0;
+		} else {
+			exit = 1;
+		}
+
+	}
+
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Braccio/src/Braccio.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Braccio/src/Braccio.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Braccio/src/Braccio.h	(revision 175)
@@ -0,0 +1,48 @@
+/*
+  Braccio.h - board library Version 1.1
+  Written by Andrea Martino
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+#ifndef BRACCIO_H_
+#define BRACCIO_H_
+
+#include <Arduino.h>
+#include <Servo.h>
+
+class _Braccio {
+
+public:
+  _Braccio();
+  
+  /**
+   * Braccio initializations and set intial position
+   * Modifing this function you can set up the initial position of all the
+   * servo motors of the Braccio
+   */
+  unsigned int begin(); 
+  
+  /**
+   * This functions allow you to control all the servo motors in the Braccio
+   */
+  int ServoMovement(int delay, int Vbase,int Vshoulder, int Velbow, int Vwrist_ver, int Vwrist_rot, int Vgripper); 
+
+
+};
+
+extern _Braccio Braccio;
+
+#endif // BRACCIO_H_
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/LICENSE
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/LICENSE	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/LICENSE	(revision 175)
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Arduino.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/README.md
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/README.md	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/README.md	(revision 175)
@@ -0,0 +1,20 @@
+##Arduino Ciao (MCU side)
+Simple library in C to make MCU communicate with "outside World" through Ciao Core.
+
+###What is Arduino Ciao?
+
+**Arduino Ciao** is a easy-to-use and powerful technology that enables Arduino sketches to communicate intuitively with the "outside World". It aims to simplify interaction between microcontroller and Linino OS allowing a variety of connections with most common protocols, third-party services and social networks.
+
+Arduino Ciao is open-source and distributed under MIT license: feel free to read it, suggest improvements, provide feedbacks and develop new features.
+
+More information about Arduino Ciao project can be found at http://labs.arduino.org/Ciao
+
+###Arduino Ciao (MCU side) - Ciao Library
+
+Arduino Ciao is made of two main parts:
+ * the **Ciao Library** - usable inside *sketches*, it's written in C.
+ * the [Ciao Core](http://labs.arduino.org/Ciao+CPU) - a library developed in python that runs on the CPU/MIPS side of the board.(source code available [here](https://github.com/arduino-org/Ciao+CPU))
+
+**Ciao Library**  allows you to send and receive data outside the microcontroller, through a serial communication, in a simple and intuitive way.
+
+Details about **Ciao Library** architecture are available in the [Arduino wiki](http://labs.arduino.org/Ciao+MCU)
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoArduinoXMPP/CiaoArduinoXMPP.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoArduinoXMPP/CiaoArduinoXMPP.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoArduinoXMPP/CiaoArduinoXMPP.ino	(revision 175)
@@ -0,0 +1,43 @@
+/*
+  Arduino Ciao example
+  
+ This sketch uses ciao xmpp connector. It sends back âhello worldâ message to the xmpp client when receives âciaoâ from it. 
+  
+ Be sure to set the xmpp client in the "USER" field used to receive the response by MCU.
+
+ Possible commands to send from the xmpp client:
+ * "ciao"               -> random answers in 5 different languages
+ 
+ created September 2015
+ by andrea[at]arduino[dot]org
+ 
+ 
+  NOTE: be sure to activate and configure xmpp connector on Linino OS
+       http://labs.arduino.org/Ciao
+   
+ */
+ 
+#include <Ciao.h>
+
+String USER="user@domain";
+String mess[5]={"Hi, I am MCU :-P","hallo , ik ben MCU :-P","bonjour, je suis MCU :-P","Ciao, io sono MCU :-P","Kon'nichiwa, watashi wa MCU yo :-P" };
+
+void setup() {
+  Ciao.begin(); 
+}
+
+void loop() {
+    
+  CiaoData data = Ciao.read("xmpp");  
+  
+  if(!data.isEmpty()){
+    String id = data.get(0);
+    String sender = data.get(1);
+    String message = data.get(2);
+    
+    message.toLowerCase();
+    if(message == "ciao" )
+      Ciao.write("xmpp", USER,mess[random(0,5)]);
+  }
+}
+
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoBluemixMQTT/CiaoBluemixMQTT.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoBluemixMQTT/CiaoBluemixMQTT.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoBluemixMQTT/CiaoBluemixMQTT.ino	(revision 175)
@@ -0,0 +1,46 @@
+/*
+  Arduino Ciao example
+  
+ This sketch uses Ciao mqtt connector. Sketch sends via MQTT brightness and temperature information that will be shown graphically in the blueMix IBM system.
+ Upload your sketch an than connect to the webpage:  
+ https://quickstart.internetofthings.ibmcloud.com/#/device/BlueMixTest902345/sensor/
+ 
+  NOTE: be sure to activate and configure mqtt connector on Linino OS.
+       http://labs.arduino.org/Ciao
+
+ created September 2015
+ by andrea[at]arduino[dot]org
+   
+ */
+
+#include <Ciao.h>
+
+int ctrl=0;
+void setup()
+{
+  Ciao.begin();  //Start the serial connection with the computer
+                       //to view the result open the serial monitor 
+  pinMode(9,OUTPUT);
+}
+ 
+void loop()                     // run over and over again
+{
+   //getting the voltage reading from the temperature sensor
+   int readingTemp = analogRead(A0);   
+   // converting readingTemp to voltage
+   float voltage = readingTemp * 4.56;
+   voltage /= 1024; 
+   // now print out the temperature
+   float temperatureC = (voltage - 0.5) * 100 ; 
+   int readingLum = analogRead(A2);
+
+   analogWrite(9,map(readingLum,0,1023,0,255)); 
+   
+   if (ctrl>=10){
+     Ciao.write("mqtt","iot-2/evt/status/fmt/json","{\"d\": {\"temperature\":"+String(temperatureC)+",\"luminosity\":"+String(readingLum)+"}}");
+     ctrl=0;
+   }
+   ctrl++;
+   delay(100);
+ 
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-TalkBackRecv/CiaoRestClient-TalkBackRecv.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-TalkBackRecv/CiaoRestClient-TalkBackRecv.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-TalkBackRecv/CiaoRestClient-TalkBackRecv.ino	(revision 175)
@@ -0,0 +1,53 @@
+#include <Wire.h>
+#include <Ciao.h>
+
+/* 
+
+This example show the interaction between the Ciao Library and the Thingspeak Cloud. 
+To run the example you need to register an account on thingspeak.com.
+After that, you need to create a new channel and a new talkback app.
+To create a new channel click the "Channels" section in the website (Channels -> My Channels -> New Channel).
+To create a new talkback click the "Apps" section in the website (Apps -> TalkBack -> New TalkBack). 
+Replace the APIKEY_TALKBACK and ID_TALKBACK values with the values reported in the API section of the site. 
+
+*/
+
+#define CONNECTOR     "rest" 
+#define SERVER_ADDR   "api.thingspeak.com"
+
+#define APIKEY_TALKBACK    "XXXXXXXXXXXXX"
+#define ID_TALKBACK      "XXXX"
+
+
+void setup() {
+
+  Ciao.begin(); // CIAO INIT
+
+}
+
+void loop() {
+  
+
+      String request = "/talkbacks/";  
+          request +=  ID_TALKBACK;
+          request +=  "/commands/execute?api_key=";
+          request +=  APIKEY_TALKBACK;
+    
+      Ciao.println("Read cmd from TalkBack Queue"); 
+      CiaoData data = Ciao.read(CONNECTOR, SERVER_ADDR, request);
+ 
+      String state = data.get(1);
+      String response = data.get(2);
+      
+      if (!data.isEmpty()){
+          Ciao.println( "State: " + String (data.get(1)) );
+          Ciao.println( "Response: " + String (data.get(2)) );
+        }
+        else{ 
+          Ciao.println ("Read Error OR EmptyQueue");
+        }
+ 
+  delay(30000); // Thinkspeak policy
+
+}  
+    
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-TalkBackSend/CiaoRestClient-TalkBackSend.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-TalkBackSend/CiaoRestClient-TalkBackSend.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-TalkBackSend/CiaoRestClient-TalkBackSend.ino	(revision 175)
@@ -0,0 +1,51 @@
+#include <Wire.h>
+#include <Ciao.h>
+
+/* 
+
+This example show the interaction between the Ciao Library and the Thingspeak Cloud. 
+To run the example you need to register an account on thingspeak.com.
+After that, you need to create a new channel and a new talkback app.
+To create a new channel click the "Channels" section in the website (Channels -> My Channels -> New Channel).
+To create a new talkback click the "Apps" section in the website (Apps -> TalkBack -> New TalkBack). 
+Replace the APIKEY_TALKBACK and ID_TALKBACK values with the values reported in the API section of the site. 
+
+*/
+
+#define CONNECTOR     "rest" 
+#define SERVER_ADDR   "api.thingspeak.com"
+
+#define APIKEY_TALKBACK     "XXXXXXXXXXXXXX"
+#define ID_TALKBACK         "XXXX"
+
+String cmd = "D13_ON";
+
+void setup() {
+
+  Ciao.begin(); // CIAO INIT
+}
+
+void loop() {
+      
+      String uri = "/talkbacks/";
+    	uri += ID_TALKBACK;
+    	uri += "/commands?api_key=";
+    	uri += APIKEY_TALKBACK;
+    	uri += "&command_string=";
+    	uri += cmd;
+
+      Ciao.println("Write cmd on TalkBack Queue"); 
+      CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, uri,"POST");
+  
+      if (!data.isEmpty()){
+          Ciao.println( "State: " + String (data.get(1)) );
+          Ciao.println( "Response: " + String (data.get(2)) );
+        }
+        else{ 
+          Ciao.println ("Write Error");
+        }
+ 
+  delay(30000); // Thinkspeak policy
+
+}  
+    
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-ThingSpeak/CiaoRestClient-ThingSpeak.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-ThingSpeak/CiaoRestClient-ThingSpeak.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient-ThingSpeak/CiaoRestClient-ThingSpeak.ino	(revision 175)
@@ -0,0 +1,50 @@
+#include <Wire.h>
+#include <Ciao.h>
+
+/* 
+
+This example show the interaction between the Ciao Library and the Thingspeak Cloud. 
+To run the example you need to register an account on thingspeak.com and create a 
+new channel by clicking "Channels" section in the website (Channels -> My Channels -> New Channel). 
+In the new channel you need to add two fields. The first one refers to the humidity data and the second one to the temperature value.
+After that, replace the "XXXXXXXXX" value of APIKEY_THINGSPEAK with "Write API key" value reported in the API Keys section of the channel. 
+
+*/
+
+#define CONNECTOR     "rest" 
+#define SERVER_ADDR   "api.thingspeak.com"
+
+#define APIKEY_THINGSPEAK  "XXXXXXXXXXXXX"
+
+short hum = 60;
+short temp = 22;
+
+void setup() {
+
+  Ciao.begin(); // CIAO INIT
+}
+
+void loop() {
+      
+    String uri = "/update?api_key=";
+    uri += APIKEY_THINGSPEAK;
+    uri += "&field1=";
+    uri += String(hum);
+    uri += "&field2=";
+    uri += String(temp);
+
+    Ciao.println("Send data on ThingSpeak Channel"); 
+      
+    CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, uri);
+
+    if (!data.isEmpty()){
+      Ciao.println( "State: " + String (data.get(1)) );
+      Ciao.println( "Response: " + String (data.get(2)) );
+    }
+    else{ 
+      Ciao.println("Write Error");
+    }    
+ 
+  delay(30000); // Thinkspeak policy
+
+}  
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient/CiaoRestClient.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient/CiaoRestClient.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestClient/CiaoRestClient.ino	(revision 175)
@@ -0,0 +1,51 @@
+#include <Wire.h>
+#include <Ciao.h>
+
+#define CONNECTOR     "rest" 
+#define SERVER_ADDR   "192.168.0.100" // change ip address with your server ip address
+
+int buttonState = LOW; //this variable tracks the state of the button, low if not pressed, high if pressed
+int ledState = -1; //this variable tracks the state of the LED, negative if off, positive if on
+long lastDebounceTime = 0;  // the last time the output pin was toggled
+long debounceDelay = 50;    // the debounce time; increase if the output flickers
+
+void setup() {
+  Ciao.begin();
+  pinMode(2, INPUT);
+  
+}
+ 
+void loop() {
+ 
+  //sample the state of the button - is it pressed or not?
+  buttonState = digitalRead(2);
+ 
+  //filter out any noise by setting a time buffer
+  if ( (millis() - lastDebounceTime) > debounceDelay) {
+ 
+    //if the button has been pressed, lets toggle the LED from "off to on" or "on to off"
+    if ( (buttonState == HIGH) && (ledState < 0) ) {
+ 
+      CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, "/arduino/digital/12/1"); //turn LED on
+      ledState = -ledState; //now the LED is on, we need to change the state
+      lastDebounceTime = millis(); //set the current time
+    }
+    else if ( (buttonState == HIGH) && (ledState > 0) ) {
+ 
+      CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, "/arduino/digital/12/0"); //turn LED off
+      ledState = -ledState; //now the LED is off, we need to change the state
+      lastDebounceTime = millis(); //set the current time
+        
+      if (!data.isEmpty()){
+        Ciao.println( "State: " + String (data.get(1)) );
+        Ciao.println( "Response: " + String (data.get(2)) );
+      }
+      else{ 
+        Ciao.println ("Write Error");
+      }
+              
+    }
+ 
+  }
+ 
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestServer/CiaoRestServer.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestServer/CiaoRestServer.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/examples/CiaoRestServer/CiaoRestServer.ino	(revision 175)
@@ -0,0 +1,142 @@
+/*
+
+ This sketch uses the xmpp connector to receive command for the MCU from a xmpp client.
+
+ Possible commands to send from the xmpp client:
+
+ * "digital/PIN"        -> to read a digital PIN
+ * "digital/PIN/VALUE"  -> to write a digital PIN (VALUE: 1/0)
+ * "analog/PIN/VALUE"   -> to write in a PWM PIN(VALUE range: 0 - 255);
+ * "analog/PIN"         -> to read a analog PIN
+ * "servo/PIN/VALUE"	  -> to write angle in a SERVO PIN(VALUE range: 0 - 180);
+ * "mode/PIN/VALUE"     -> to set the PIN mode (VALUE: input / output)
+ * "ledon"              -> turn on led 13
+ * "ledoff"             -> turn off led 13
+ * "ciao"               -> random answers in 5 different languages
+ 
+ NOTE: be sure to activate and configure xmpp connector on Linino OS
+       http://labs.arduino.org/Ciao
+   
+ created September 2015
+ by andrea[at]arduino[dot]org
+ 
+ */
+ 
+#include <Ciao.h>
+#include <Servo.h>
+
+Servo servo;
+
+void setup() {
+
+  Ciao.begin();
+}
+
+void loop() {
+
+  CiaoData data = Ciao.read("restserver");   
+  if(!data.isEmpty()){  
+    String id = data.get(0);
+    String sender = data.get(1);
+    String message = data.get(2);
+    
+    message.toUpperCase();
+    
+    String command[3];
+          
+    splitString(message,"/",command,3);
+    execute(command,id);
+
+  }
+}
+
+void execute(String cmd[], String id) {
+
+  if (cmd[0] == "DIGITAL") {
+    digitalCommand(cmd,id);
+  }
+  else if (cmd[0] == "ANALOG") {
+    analogCommand(cmd,id);
+  }
+  else if (cmd[0] == "SERVO") {
+    servoCommand(cmd,id);
+  }
+  else if (cmd[0] == "MODE") {
+    setMode(cmd,id);
+  }
+  else
+    Ciao.writeResponse("restserver",id,"sorry, i don't understand :(");
+}
+
+void servoCommand(String cmd[], String id){
+   int pin, value;
+  
+  pin = (cmd[1]).toInt();
+  
+  if (cmd[2] != "-1") {
+    value = (cmd[2]).toInt();
+    if(value <= 180 && value >=0){
+      servo.attach(pin);
+      servo.write(value);
+      Ciao.writeResponse("restserver",id,"Servo D"+String(pin)+" set to "+String(value)+" degrees");
+    }
+    else
+      Ciao.writeResponse("restserver",id,"Invalid angle value");
+  }
+  else
+    Ciao.writeResponse("restserver",id,"Invalid command");  
+}
+
+void digitalCommand(String cmd[], String id) {
+  int pin, value;
+  
+  pin = (cmd[1]).toInt();
+  
+  if (cmd[2] != "-1") {
+    value = (cmd[2]).toInt();
+    digitalWrite(pin, value);
+    if (value == 1)
+      Ciao.writeResponse("restserver",id,"Pin D"+String(pin)+" ON");
+    else if(value == 0)
+      Ciao.writeResponse("restserver",id,"Pin D"+String(pin)+" OFF");   
+  }
+  else if (cmd[2] == "-1") {
+    value = digitalRead(pin);
+    Ciao.writeResponse("restserver",id,"D"+String(pin)+" value = "+String(value));
+  }
+}
+
+void analogCommand(String cmd[], String id) {
+  int pin, value;
+
+  pin = (cmd[1]).toInt();
+  
+  if (cmd[2] != "-1") {
+    value =(cmd[2]).toInt();
+    analogWrite(pin, value);
+    Ciao.writeResponse("restserver",id,"D"+String(pin)+" set to analog");
+  }
+  else if (cmd[2] == "-1") {
+    value = analogRead(pin);
+    Ciao.writeResponse("restserver",id,"A"+String(pin)+" value = "+String(value));
+  }
+}
+
+void setMode(String cmd[], String id) {
+  int pin;
+
+  pin = (cmd[1]).toInt();
+  
+  if (cmd[2] == "INPUT") {
+    pinMode(pin, INPUT);
+    Ciao.writeResponse("restserver",id," pin D"+String(pin)+" set in INPUT mode");
+    return;
+  }
+
+  if (cmd[2] == "OUTPUT") {
+    pinMode(pin, OUTPUT);
+    Ciao.writeResponse("restserver",id," pin D"+String(pin)+" set in OUTPUT mode");
+    return;
+  }
+  Ciao.writeResponse("restserver",id,"invalid mode");
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/keywords.txt
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/keywords.txt	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/keywords.txt	(revision 175)
@@ -0,0 +1,24 @@
+#######################################
+# Syntax Coloring Map For Ciao
+#######################################
+
+#######################################
+# Class (KEYWORD3)
+#######################################
+
+Ciao		KEYWORD3
+CiaoData	KEYWORD3
+Wifi		KEYWORD3
+WifiData	KEYWORD3
+
+#######################################
+# Methods and Functions (KEYWORD2)
+#######################################
+
+begin			KEYWORD2
+writeResponse	KEYWORD2
+available		KEYWORD2
+read			KEYWORD2
+write			KEYWORD2
+bool			KEYWORD2
+
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/library.properties
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/library.properties	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/library.properties	(revision 175)
@@ -0,0 +1,9 @@
+name=Ciao
+version=1.0
+author=Arduino srl
+maintainer=Arduino srl<info@arduino.org>
+sentence=Enables the communication between the Linux processor and the AVR. For Arduino Y炭n, Y炭n Mini, Linino One, Arduino Tian and Arduino Industrial.
+paragraph=
+category=Communication
+url=http://labs.arduino.org/Ciao
+architectures=*
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/Ciao.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/Ciao.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/Ciao.h	(revision 175)
@@ -0,0 +1,136 @@
+/*
+****************************************************************************
+* Copyright (c) 2015 Arduino srl. All right reserved.
+*
+* File : Ciao.h
+* Date : 2016/02/16
+* Revision : 0.0.2 $
+* Author: andrea[at]arduino[dot]org
+* Author: adriano[at]arduino[dot]org
+*
+****************************************************************************
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#ifndef CIAO_H_
+#define CIAO_H_
+
+#include <Arduino.h>
+#include "lib/CiaoData.h"
+#if defined(__AVR_ATmega328P__)
+#include "lib/rest.h"
+#include "lib/SC16IS750.h"
+#include "lib/espduino.h"
+#else
+#include <Stream.h>
+#endif
+
+#if defined(__AVR_ATmega32U4__) || defined(ARDUINO_ARCH_SAMD)
+
+#if defined(__AVR_ATmega32U4__)
+#define BAUDRATE 250000
+#elif defined(ARDUINO_ARCH_SAMD)
+#define BAUDRATE 115200
+#endif
+
+class CiaoClass {
+	public:
+		void begin();
+		CiaoData read( String protocol, String param1 = "", String param2 = "", String param3 = "");
+		CiaoData write( String protocol, String param1, String param2 = "", String param3 = "");
+		CiaoData writeResponse( String protocol, String id, String param1="", String param2 = "", String param3 = "");
+		CiaoData parse( String, String);
+		void println(String log){};
+		#if defined(__AVR_ATmega32U4__) 
+		CiaoClass(Stream &_stream);
+		#elif defined(ARDUINO_ARCH_SAMD)
+		CiaoClass(Serial_ stream);
+		#endif
+
+	private:
+		void dropAll();
+		bool started;
+		#if defined(__AVR_ATmega32U4__)
+		Stream &stream;
+		#elif defined(ARDUINO_ARCH_SAMD)
+		Serial_ stream;
+		#endif
+};
+
+// This subclass uses a serial port Stream
+class SerialCiaoClass : public CiaoClass {
+	public:
+		#if defined(__AVR_ATmega32U4__)
+		SerialCiaoClass(HardwareSerial &_serial)
+			: CiaoClass(_serial), serial(_serial) {
+			// Empty
+		}
+		#elif defined(ARDUINO_ARCH_SAMD)
+		SerialCiaoClass(Serial_ serial)
+			: CiaoClass(serial){
+			// Empty	
+		}
+		#endif
+		void begin( unsigned long baudrate = BAUDRATE) {
+			serial.begin(baudrate);
+			CiaoClass::begin();
+		}
+	private:
+		#if defined(__AVR_ATmega32U4__)
+		HardwareSerial &serial;
+		#elif defined(ARDUINO_ARCH_SAMD)
+		Serial_ serial;
+		#endif
+};
+
+void splitString(String, String, String[], int size);
+
+extern SerialCiaoClass Ciao;
+
+#else
+
+// class CiaoData {
+// 	public:
+		
+// 		char* get(int index){
+// 			return msg_split[index];
+// 		}
+  
+// 	public:
+// 		char* msg_split[3];
+		
+// };
+
+class CiaoClass {
+	public:
+		void begin();
+
+		CiaoData read( char*, char*, String );            // ârestâ, âhostnameâ, âStringoneâ,		
+		CiaoData read( char*, char*, String, char*);      // ârestâ, âhostnameâ, âStringoneâ, âmethodâ
+
+		CiaoData write( char*, char*, String );            // ârestâ, âhostnameâ, âStringoneâ,		
+		CiaoData write( char*, char*, String, char*);      // ârestâ, âhostnameâ, âStringoneâ, âmethodâ
+		
+		void print(String str);
+		void println(String str);
+	
+};
+extern CiaoClass Ciao;
+
+#endif
+
+
+#endif /* CIAO_H_ */
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/Ciao.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/Ciao.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/Ciao.cpp	(revision 175)
@@ -0,0 +1,190 @@
+/*
+****************************************************************************
+* Copyright (c) 2015 Arduino srl. All right reserved.
+*
+* File : Ciao.cpp
+* Date : 2016/02/16
+* Revision : 0.0.2 $
+* Author: andrea[at]arduino[dot]org
+*
+****************************************************************************
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#include "Ciao.h"
+
+#if defined(__AVR_ATmega32U4__) || defined(ARDUINO_ARCH_SAMD)
+
+#if defined(__AVR_ATmega32U4__)
+CiaoClass::CiaoClass(Stream &_stream) :
+	stream(_stream), started(false) {
+  // Empty
+}
+#elif defined(ARDUINO_ARCH_SAMD)
+CiaoClass::CiaoClass(Serial_ stream){
+  // Empty
+}
+#endif
+
+void CiaoClass::begin() {
+	
+	String start;
+	String stop;
+
+  	// Wait for U-boot to finish startup
+	do {
+		dropAll();
+		delay(1000);
+	}while (stream.available() > 0);
+
+	stream.println("ciao;r;status");					//check the bridge python status	
+	String status = stream.readStringUntil(END_TX_CHAR);
+	if(status == "1;running"){						
+	 	do{												//kill a istance of the bridge.py
+	 		stream.println("ciao;w;quit");
+	 		stop = stream.readStringUntil(END_TX_CHAR);
+	 		delay(3000);
+	 	}while(stop != "1;done");
+    }
+	do{ 
+		#if defined(__AVR_ATmega32U4__)
+		stream.print(F("run-ciao\n"));				//start bridge python
+		stream.readStringUntil(END_TX_CHAR);
+		#endif
+		delay(3000);
+		stream.println("ciao;r;status");				//check if bridge python is running
+		start = stream.readStringUntil(END_TX_CHAR);
+	}while (start != "1;running");
+}
+
+CiaoData CiaoClass::read( String connector, String param1, String param2 , String param3 ) {
+	
+	CiaoData data;
+	stream.print(connector + ";r");					// send read request 
+	if (param1 != ""){
+		stream.print(";"+param1);
+	}
+	if (param2 != ""){
+		stream.print(DATA_SPLIT_CHAR);
+		stream.print(param2);
+	}
+	if (param3 != ""){
+		stream.print(DATA_SPLIT_CHAR);
+		stream.print(param3);
+	}
+	stream.println();
+	String message = stream.readStringUntil(END_TX_CHAR);
+	data = parse(message, ";");
+	return data;
+}
+
+CiaoData CiaoClass::write( String connector, String param1, String param2 , String param3 ) {
+
+	CiaoData data;
+	if (param1 != ""){
+		stream.print(connector+";w;");
+		stream.print(param1);
+	}
+	if (param2 != ""){
+		stream.print(DATA_SPLIT_CHAR);
+		stream.print(param2);
+	}
+	if (param3 != ""){
+		stream.print(DATA_SPLIT_CHAR);
+		stream.print(param3);
+	}
+	stream.println();
+	String mess_receive = stream.readStringUntil(END_TX_CHAR);
+	data = parse(mess_receive, ";");
+	return data;
+	
+}
+
+CiaoData CiaoClass::writeResponse( String connector, String id, String param1, String param2 , String param3) {
+
+	CiaoData data;
+	if(id.length()> ID_SIZE_TX){
+		if (param1 != ""){
+			stream.print(connector+";wr;");
+			stream.print(id+";");
+			stream.print(param1);
+		}
+		if (param2 != ""){
+			stream.print(DATA_SPLIT_CHAR);
+			stream.print(param2);
+		}
+		if (param3 != ""){
+			stream.print(DATA_SPLIT_CHAR);
+			stream.print(param3);
+		}
+		stream.println();
+		String mess_receive = stream.readStringUntil(END_TX_CHAR);
+		data = parse(mess_receive, ";");
+	}
+	return data;
+}
+
+CiaoData CiaoClass::parse(String message, String split){
+	String status;
+	CiaoData data;
+	int statusIndex = message.indexOf(split);
+	int messIndex = message.indexOf(split, statusIndex+1);
+	status = message.substring(0, statusIndex);				//message status (0: no message; 1:data ready; -1:error)
+
+	if(status == ID_READY && message.substring(statusIndex+1, messIndex) != "done"){
+		data.msg_split[0]=message.substring(statusIndex+1, messIndex);
+		data.parseMessage(message.substring(messIndex+1));	//parsing data received
+	}
+	else{
+		data.msg_split[0] = status;
+		data.msg_split[2] = message.substring(statusIndex+1, messIndex);
+	}
+	return data;
+}
+
+void CiaoClass::dropAll() {
+  while (stream.available() > 0) {
+    stream.read();
+  }
+}
+
+//fuction to split command (ex: digital/13/1)
+void splitString(String command, String split, String msg[], int size){		
+	  
+	for(int a=0;a< size ;a++)		//initialize array element to -1
+		msg[a]= ID_ERROR;
+	char buf[command.length()+1];
+	command.toCharArray(buf, command.length()+1);
+	char* array;
+	const char splt[1]= {split.charAt(0)};
+	int i=0;
+	array = strtok (buf,splt);
+	while (array != NULL){  
+		msg[i]=String(array);
+		array = strtok (NULL, splt);
+		i++; 
+	}
+}
+
+// Ciao instance
+#ifdef __AVR_ATmega32U4__ 
+// Yun variants (where HardwareSerial is Serial1)
+SerialCiaoClass Ciao(Serial1);
+#elif defined ARDUINO_ARCH_SAMD
+// Tian variants (where Serial_ is SerialUSB)
+SerialCiaoClass Ciao(SerialUSB);
+#endif
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/CiaoData.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/CiaoData.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/CiaoData.h	(revision 175)
@@ -0,0 +1,89 @@
+/*
+****************************************************************************
+* Copyright (c) 2015 Arduino srl. All right reserved.
+*
+* File : CiaoData.h
+* Date : 2016/02/16
+* Revision : 0.0.2 $
+* Author: andrea[at]arduino[dot]org
+*
+****************************************************************************
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#include <Arduino.h>
+
+#define ID_ERROR		String(-1)
+#define ID_EMPTY		String(0)
+#define ID_READY		String(1)
+#define END_TX_CHAR		(char)4
+#define DATA_SPLIT_CHAR	(char)30
+#define ID_SIZE_TX		25
+
+#if defined(__AVR_ATmega32U4__) || defined(ARDUINO_ARCH_SAMD)
+class CiaoData {
+	public:
+		
+		String get(int index){
+			return msg_split[index];
+		}
+		
+		void parseMessage(String command){
+			int statusIndex = command.indexOf(DATA_SPLIT_CHAR);
+			msg_split[1] = command.substring(0, statusIndex);
+			msg_split[2] = command.substring(statusIndex+1);
+		}
+  
+		bool isError(){		//check for an error in data received
+			if(get(0) == ID_ERROR)
+				return true;
+			else
+				return false;			
+		}
+		
+		bool isEmpty(){		//check if data received is empty
+			if(get(0) == ID_EMPTY)
+				return true;
+			else
+				return false;	
+		}
+		
+	public:
+		String msg_split[3];
+};
+
+#elif defined(__AVR_ATmega328P__)
+
+class CiaoData {
+	public:
+
+		char* get(int index){
+			return msg_split[index];
+		}
+
+		bool isEmpty(){	
+			if (atoi( get(1) ) > 0)
+				return false;
+			else
+				return true;	
+		}
+		
+	public:
+		char* msg_split[3];
+};
+
+#endif
+
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/FP.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/FP.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/FP.cpp	(revision 175)
@@ -0,0 +1,600 @@
+/**
+ * @file    FP.cpp
+ * @brief   Core Utility - Templated Function Pointer Class
+ * @author  sam grove
+ * @version 1.0
+ * @see     
+ *
+ * Copyright (c) 2013
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "FP.h"
+#include <stdint.h>
+
+template<class retT, class argT>
+FP<retT, argT>::FP()
+{
+    obj_callback = 0;
+    c_callback = 0;
+}
+
+template<class retT, class argT>
+bool FP<retT, argT>::attached()
+{
+    return obj_callback || c_callback;
+}
+
+
+template<class retT, class argT>
+void FP<retT, argT>::detach()
+{
+    obj_callback = 0;
+    c_callback = 0;
+}
+
+
+template<class retT, class argT>
+void FP<retT, argT>::attach(retT (*function)(argT))
+{
+    c_callback = function;
+}
+
+template<class retT, class argT>
+retT FP<retT, argT>::operator()(argT arg) const
+{
+    if( 0 != c_callback )
+    {
+        return obj_callback ? (obj_callback->*method_callback)(arg) : (*c_callback)(arg);
+    }
+    return (retT)0;
+}
+
+// pre-define the types for the linker
+template class FP<void,char>;
+template class FP<void,char*>;
+template class FP<void,int8_t>;
+template class FP<void,int8_t*>;
+template class FP<void,uint8_t>;
+template class FP<void,uint8_t*>;
+template class FP<void,int16_t>;
+template class FP<void,int16_t*>;
+template class FP<void,uint16_t>;
+template class FP<void,uint16_t*>;
+template class FP<void,int32_t>;
+template class FP<void,int32_t*>;
+template class FP<void,uint32_t>;
+template class FP<void,uint32_t*>;
+template class FP<void,int64_t>;
+template class FP<void,int64_t*>;
+template class FP<void,uint64_t>;
+template class FP<void,uint64_t*>;
+template class FP<void,bool>;
+template class FP<void,bool*>;
+template class FP<void,float>;
+template class FP<void,float*>;
+template class FP<void,double>;
+template class FP<void,double*>;
+template class FP<void,void*>;
+
+template class FP<int8_t,char>;
+template class FP<int8_t,char*>;
+template class FP<int8_t,int8_t>;
+template class FP<int8_t,int8_t*>;
+template class FP<int8_t,uint8_t>;
+template class FP<int8_t,uint8_t*>;
+template class FP<int8_t,int16_t>;
+template class FP<int8_t,int16_t*>;
+template class FP<int8_t,uint16_t>;
+template class FP<int8_t,uint16_t*>;
+template class FP<int8_t,int32_t>;
+template class FP<int8_t,int32_t*>;
+template class FP<int8_t,uint32_t>;
+template class FP<int8_t,uint32_t*>;
+template class FP<int8_t,int64_t>;
+template class FP<int8_t,int64_t*>;
+template class FP<int8_t,uint64_t>;
+template class FP<int8_t,uint64_t*>;
+template class FP<int8_t,bool>;
+template class FP<int8_t,bool*>;
+template class FP<int8_t,float>;
+template class FP<int8_t,float*>;
+template class FP<int8_t,double>;
+template class FP<int8_t,double*>;
+
+template class FP<int8_t*,char>;
+template class FP<int8_t*,char*>;
+template class FP<int8_t*,int8_t>;
+template class FP<int8_t*,int8_t*>;
+template class FP<int8_t*,uint8_t>;
+template class FP<int8_t*,uint8_t*>;
+template class FP<int8_t*,int16_t>;
+template class FP<int8_t*,int16_t*>;
+template class FP<int8_t*,uint16_t>;
+template class FP<int8_t*,uint16_t*>;
+template class FP<int8_t*,int32_t>;
+template class FP<int8_t*,int32_t*>;
+template class FP<int8_t*,uint32_t>;
+template class FP<int8_t*,uint32_t*>;
+template class FP<int8_t*,int64_t>;
+template class FP<int8_t*,int64_t*>;
+template class FP<int8_t*,uint64_t>;
+template class FP<int8_t*,uint64_t*>;
+template class FP<int8_t*,bool>;
+template class FP<int8_t*,bool*>;
+template class FP<int8_t*,float>;
+template class FP<int8_t*,float*>;
+template class FP<int8_t*,double>;
+template class FP<int8_t*,double*>;
+
+template class FP<uint8_t,char>;
+template class FP<uint8_t,char*>;
+template class FP<uint8_t,int8_t>;
+template class FP<uint8_t,int8_t*>;
+template class FP<uint8_t,uint8_t>;
+template class FP<uint8_t,uint8_t*>;
+template class FP<uint8_t,int16_t>;
+template class FP<uint8_t,int16_t*>;
+template class FP<uint8_t,uint16_t>;
+template class FP<uint8_t,uint16_t*>;
+template class FP<uint8_t,int32_t>;
+template class FP<uint8_t,int32_t*>;
+template class FP<uint8_t,uint32_t>;
+template class FP<uint8_t,uint32_t*>;
+template class FP<uint8_t,int64_t>;
+template class FP<uint8_t,int64_t*>;
+template class FP<uint8_t,uint64_t>;
+template class FP<uint8_t,uint64_t*>;
+template class FP<uint8_t,bool>;
+template class FP<uint8_t,bool*>;
+template class FP<uint8_t,float>;
+template class FP<uint8_t,float*>;
+template class FP<uint8_t,double>;
+template class FP<uint8_t,double*>;
+
+template class FP<uint8_t*,char>;
+template class FP<uint8_t*,char*>;
+template class FP<uint8_t*,int8_t>;
+template class FP<uint8_t*,int8_t*>;
+template class FP<uint8_t*,uint8_t>;
+template class FP<uint8_t*,uint8_t*>;
+template class FP<uint8_t*,int16_t>;
+template class FP<uint8_t*,int16_t*>;
+template class FP<uint8_t*,uint16_t>;
+template class FP<uint8_t*,uint16_t*>;
+template class FP<uint8_t*,int32_t>;
+template class FP<uint8_t*,int32_t*>;
+template class FP<uint8_t*,uint32_t>;
+template class FP<uint8_t*,uint32_t*>;
+template class FP<uint8_t*,int64_t>;
+template class FP<uint8_t*,int64_t*>;
+template class FP<uint8_t*,uint64_t>;
+template class FP<uint8_t*,uint64_t*>;
+template class FP<uint8_t*,bool>;
+template class FP<uint8_t*,bool*>;
+template class FP<uint8_t*,float>;
+template class FP<uint8_t*,float*>;
+template class FP<uint8_t*,double>;
+template class FP<uint8_t*,double*>;
+
+template class FP<int16_t,char>;
+template class FP<int16_t,char*>;
+template class FP<int16_t,int8_t>;
+template class FP<int16_t,int8_t*>;
+template class FP<int16_t,uint8_t>;
+template class FP<int16_t,uint8_t*>;
+template class FP<int16_t,int16_t>;
+template class FP<int16_t,int16_t*>;
+template class FP<int16_t,uint16_t>;
+template class FP<int16_t,uint16_t*>;
+template class FP<int16_t,int32_t>;
+template class FP<int16_t,int32_t*>;
+template class FP<int16_t,uint32_t>;
+template class FP<int16_t,uint32_t*>;
+template class FP<int16_t,int64_t>;
+template class FP<int16_t,int64_t*>;
+template class FP<int16_t,uint64_t>;
+template class FP<int16_t,uint64_t*>;
+template class FP<int16_t,bool>;
+template class FP<int16_t,bool*>;
+template class FP<int16_t,float>;
+template class FP<int16_t,float*>;
+template class FP<int16_t,double>;
+template class FP<int16_t,double*>;
+
+template class FP<int16_t*,char>;
+template class FP<int16_t*,char*>;
+template class FP<int16_t*,int8_t>;
+template class FP<int16_t*,int8_t*>;
+template class FP<int16_t*,uint8_t>;
+template class FP<int16_t*,uint8_t*>;
+template class FP<int16_t*,int16_t>;
+template class FP<int16_t*,int16_t*>;
+template class FP<int16_t*,uint16_t>;
+template class FP<int16_t*,uint16_t*>;
+template class FP<int16_t*,int32_t>;
+template class FP<int16_t*,int32_t*>;
+template class FP<int16_t*,uint32_t>;
+template class FP<int16_t*,uint32_t*>;
+template class FP<int16_t*,int64_t>;
+template class FP<int16_t*,int64_t*>;
+template class FP<int16_t*,uint64_t>;
+template class FP<int16_t*,uint64_t*>;
+template class FP<int16_t*,bool>;
+template class FP<int16_t*,bool*>;
+template class FP<int16_t*,float>;
+template class FP<int16_t*,float*>;
+template class FP<int16_t*,double>;
+template class FP<int16_t*,double*>;
+
+template class FP<uint16_t,char>;
+template class FP<uint16_t,char*>;
+template class FP<uint16_t,int8_t>;
+template class FP<uint16_t,int8_t*>;
+template class FP<uint16_t,uint8_t>;
+template class FP<uint16_t,uint8_t*>;
+template class FP<uint16_t,int16_t>;
+template class FP<uint16_t,int16_t*>;
+template class FP<uint16_t,uint16_t>;
+template class FP<uint16_t,uint16_t*>;
+template class FP<uint16_t,int32_t>;
+template class FP<uint16_t,int32_t*>;
+template class FP<uint16_t,uint32_t>;
+template class FP<uint16_t,uint32_t*>;
+template class FP<uint16_t,int64_t>;
+template class FP<uint16_t,int64_t*>;
+template class FP<uint16_t,uint64_t>;
+template class FP<uint16_t,uint64_t*>;
+template class FP<uint16_t,bool>;
+template class FP<uint16_t,bool*>;
+template class FP<uint16_t,float>;
+template class FP<uint16_t,float*>;
+template class FP<uint16_t,double>;
+template class FP<uint16_t,double*>;
+
+template class FP<uint16_t*,char>;
+template class FP<uint16_t*,char*>;
+template class FP<uint16_t*,int8_t>;
+template class FP<uint16_t*,int8_t*>;
+template class FP<uint16_t*,uint8_t>;
+template class FP<uint16_t*,uint8_t*>;
+template class FP<uint16_t*,int16_t>;
+template class FP<uint16_t*,int16_t*>;
+template class FP<uint16_t*,uint16_t>;
+template class FP<uint16_t*,uint16_t*>;
+template class FP<uint16_t*,int32_t>;
+template class FP<uint16_t*,int32_t*>;
+template class FP<uint16_t*,uint32_t>;
+template class FP<uint16_t*,uint32_t*>;
+template class FP<uint16_t*,int64_t>;
+template class FP<uint16_t*,int64_t*>;
+template class FP<uint16_t*,uint64_t>;
+template class FP<uint16_t*,uint64_t*>;
+template class FP<uint16_t*,bool>;
+template class FP<uint16_t*,bool*>;
+template class FP<uint16_t*,float>;
+template class FP<uint16_t*,float*>;
+template class FP<uint16_t*,double>;
+template class FP<uint16_t*,double*>;
+
+template class FP<int32_t,char>;
+template class FP<int32_t,char*>;
+template class FP<int32_t,int8_t>;
+template class FP<int32_t,int8_t*>;
+template class FP<int32_t,uint8_t>;
+template class FP<int32_t,uint8_t*>;
+template class FP<int32_t,int16_t>;
+template class FP<int32_t,int16_t*>;
+template class FP<int32_t,uint16_t>;
+template class FP<int32_t,uint16_t*>;
+template class FP<int32_t,int32_t>;
+template class FP<int32_t,int32_t*>;
+template class FP<int32_t,uint32_t>;
+template class FP<int32_t,uint32_t*>;
+template class FP<int32_t,int64_t>;
+template class FP<int32_t,int64_t*>;
+template class FP<int32_t,uint64_t>;
+template class FP<int32_t,uint64_t*>;
+template class FP<int32_t,bool>;
+template class FP<int32_t,bool*>;
+template class FP<int32_t,float>;
+template class FP<int32_t,float*>;
+template class FP<int32_t,double>;
+template class FP<int32_t,double*>;
+
+template class FP<int32_t*,char>;
+template class FP<int32_t*,char*>;
+template class FP<int32_t*,int8_t>;
+template class FP<int32_t*,int8_t*>;
+template class FP<int32_t*,uint8_t>;
+template class FP<int32_t*,uint8_t*>;
+template class FP<int32_t*,int16_t>;
+template class FP<int32_t*,int16_t*>;
+template class FP<int32_t*,uint16_t>;
+template class FP<int32_t*,uint16_t*>;
+template class FP<int32_t*,int32_t>;
+template class FP<int32_t*,int32_t*>;
+template class FP<int32_t*,uint32_t>;
+template class FP<int32_t*,uint32_t*>;
+template class FP<int32_t*,int64_t>;
+template class FP<int32_t*,int64_t*>;
+template class FP<int32_t*,uint64_t>;
+template class FP<int32_t*,uint64_t*>;
+template class FP<int32_t*,bool>;
+template class FP<int32_t*,bool*>;
+template class FP<int32_t*,float>;
+template class FP<int32_t*,float*>;
+template class FP<int32_t*,double>;
+template class FP<int32_t*,double*>;
+
+template class FP<uint32_t,char>;
+template class FP<uint32_t,char*>;
+template class FP<uint32_t,int8_t>;
+template class FP<uint32_t,int8_t*>;
+template class FP<uint32_t,uint8_t>;
+template class FP<uint32_t,uint8_t*>;
+template class FP<uint32_t,int16_t>;
+template class FP<uint32_t,int16_t*>;
+template class FP<uint32_t,uint16_t>;
+template class FP<uint32_t,uint16_t*>;
+template class FP<uint32_t,int32_t>;
+template class FP<uint32_t,int32_t*>;
+template class FP<uint32_t,uint32_t>;
+template class FP<uint32_t,uint32_t*>;
+template class FP<uint32_t,int64_t>;
+template class FP<uint32_t,int64_t*>;
+template class FP<uint32_t,uint64_t>;
+template class FP<uint32_t,uint64_t*>;
+template class FP<uint32_t,bool>;
+template class FP<uint32_t,bool*>;
+template class FP<uint32_t,float>;
+template class FP<uint32_t,float*>;
+template class FP<uint32_t,double>;
+template class FP<uint32_t,double*>;
+
+template class FP<uint32_t*,char>;
+template class FP<uint32_t*,char*>;
+template class FP<uint32_t*,int8_t>;
+template class FP<uint32_t*,int8_t*>;
+template class FP<uint32_t*,uint8_t>;
+template class FP<uint32_t*,uint8_t*>;
+template class FP<uint32_t*,int16_t>;
+template class FP<uint32_t*,int16_t*>;
+template class FP<uint32_t*,uint16_t>;
+template class FP<uint32_t*,uint16_t*>;
+template class FP<uint32_t*,int32_t>;
+template class FP<uint32_t*,int32_t*>;
+template class FP<uint32_t*,uint32_t>;
+template class FP<uint32_t*,uint32_t*>;
+template class FP<uint32_t*,int64_t>;
+template class FP<uint32_t*,int64_t*>;
+template class FP<uint32_t*,uint64_t>;
+template class FP<uint32_t*,uint64_t*>;
+template class FP<uint32_t*,bool>;
+template class FP<uint32_t*,bool*>;
+template class FP<uint32_t*,float>;
+template class FP<uint32_t*,float*>;
+template class FP<uint32_t*,double>;
+template class FP<uint32_t*,double*>;
+
+template class FP<int64_t,char>;
+template class FP<int64_t,char*>;
+template class FP<int64_t,int8_t>;
+template class FP<int64_t,int8_t*>;
+template class FP<int64_t,uint8_t>;
+template class FP<int64_t,uint8_t*>;
+template class FP<int64_t,int16_t>;
+template class FP<int64_t,int16_t*>;
+template class FP<int64_t,uint16_t>;
+template class FP<int64_t,uint16_t*>;
+template class FP<int64_t,int32_t>;
+template class FP<int64_t,int32_t*>;
+template class FP<int64_t,uint32_t>;
+template class FP<int64_t,uint32_t*>;
+template class FP<int64_t,int64_t>;
+template class FP<int64_t,int64_t*>;
+template class FP<int64_t,uint64_t>;
+template class FP<int64_t,uint64_t*>;
+template class FP<int64_t,bool>;
+template class FP<int64_t,bool*>;
+template class FP<int64_t,float>;
+template class FP<int64_t,float*>;
+template class FP<int64_t,double>;
+template class FP<int64_t,double*>;
+
+template class FP<int64_t*,char>;
+template class FP<int64_t*,char*>;
+template class FP<int64_t*,int8_t>;
+template class FP<int64_t*,int8_t*>;
+template class FP<int64_t*,uint8_t>;
+template class FP<int64_t*,uint8_t*>;
+template class FP<int64_t*,int16_t>;
+template class FP<int64_t*,int16_t*>;
+template class FP<int64_t*,uint16_t>;
+template class FP<int64_t*,uint16_t*>;
+template class FP<int64_t*,int32_t>;
+template class FP<int64_t*,int32_t*>;
+template class FP<int64_t*,uint32_t>;
+template class FP<int64_t*,uint32_t*>;
+template class FP<int64_t*,int64_t>;
+template class FP<int64_t*,int64_t*>;
+template class FP<int64_t*,uint64_t>;
+template class FP<int64_t*,uint64_t*>;
+template class FP<int64_t*,bool>;
+template class FP<int64_t*,bool*>;
+template class FP<int64_t*,float>;
+template class FP<int64_t*,float*>;
+template class FP<int64_t*,double>;
+template class FP<int64_t*,double*>;
+
+template class FP<uint64_t,char>;
+template class FP<uint64_t,char*>;
+template class FP<uint64_t,int8_t>;
+template class FP<uint64_t,int8_t*>;
+template class FP<uint64_t,uint8_t>;
+template class FP<uint64_t,uint8_t*>;
+template class FP<uint64_t,int16_t>;
+template class FP<uint64_t,int16_t*>;
+template class FP<uint64_t,uint16_t>;
+template class FP<uint64_t,uint16_t*>;
+template class FP<uint64_t,int32_t>;
+template class FP<uint64_t,int32_t*>;
+template class FP<uint64_t,uint32_t>;
+template class FP<uint64_t,uint32_t*>;
+template class FP<uint64_t,int64_t>;
+template class FP<uint64_t,int64_t*>;
+template class FP<uint64_t,uint64_t>;
+template class FP<uint64_t,uint64_t*>;
+template class FP<uint64_t,bool>;
+template class FP<uint64_t,bool*>;
+template class FP<uint64_t,float>;
+template class FP<uint64_t,float*>;
+template class FP<uint64_t,double>;
+template class FP<uint64_t,double*>;
+
+template class FP<uint64_t*,char>;
+template class FP<uint64_t*,char*>;
+template class FP<uint64_t*,int8_t>;
+template class FP<uint64_t*,int8_t*>;
+template class FP<uint64_t*,uint8_t>;
+template class FP<uint64_t*,uint8_t*>;
+template class FP<uint64_t*,int16_t>;
+template class FP<uint64_t*,int16_t*>;
+template class FP<uint64_t*,uint16_t>;
+template class FP<uint64_t*,uint16_t*>;
+template class FP<uint64_t*,int32_t>;
+template class FP<uint64_t*,int32_t*>;
+template class FP<uint64_t*,uint32_t>;
+template class FP<uint64_t*,uint32_t*>;
+template class FP<uint64_t*,int64_t>;
+template class FP<uint64_t*,int64_t*>;
+template class FP<uint64_t*,uint64_t>;
+template class FP<uint64_t*,uint64_t*>;
+template class FP<uint64_t*,bool>;
+template class FP<uint64_t*,bool*>;
+template class FP<uint64_t*,float>;
+template class FP<uint64_t*,float*>;
+template class FP<uint64_t*,double>;
+template class FP<uint64_t*,double*>;
+
+template class FP<float,char>;
+template class FP<float,char*>;
+template class FP<float,int8_t>;
+template class FP<float,int8_t*>;
+template class FP<float,uint8_t>;
+template class FP<float,uint8_t*>;
+template class FP<float,int16_t>;
+template class FP<float,int16_t*>;
+template class FP<float,uint16_t>;
+template class FP<float,uint16_t*>;
+template class FP<float,int32_t>;
+template class FP<float,int32_t*>;
+template class FP<float,uint32_t>;
+template class FP<float,uint32_t*>;
+template class FP<float,int64_t>;
+template class FP<float,int64_t*>;
+template class FP<float,uint64_t>;
+template class FP<float,uint64_t*>;
+template class FP<float,bool>;
+template class FP<float,bool*>;
+template class FP<float,float>;
+template class FP<float,float*>;
+template class FP<float,double>;
+template class FP<float,double*>;
+
+template class FP<float*,char>;
+template class FP<float*,char*>;
+template class FP<float*,int8_t>;
+template class FP<float*,int8_t*>;
+template class FP<float*,uint8_t>;
+template class FP<float*,uint8_t*>;
+template class FP<float*,int16_t>;
+template class FP<float*,int16_t*>;
+template class FP<float*,uint16_t>;
+template class FP<float*,uint16_t*>;
+template class FP<float*,int32_t>;
+template class FP<float*,int32_t*>;
+template class FP<float*,uint32_t>;
+template class FP<float*,uint32_t*>;
+template class FP<float*,int64_t>;
+template class FP<float*,int64_t*>;
+template class FP<float*,uint64_t>;
+template class FP<float*,uint64_t*>;
+template class FP<float*,bool>;
+template class FP<float*,bool*>;
+template class FP<float*,float>;
+template class FP<float*,float*>;
+template class FP<float*,double>;
+template class FP<float*,double*>;
+
+template class FP<double,char>;
+template class FP<double,char*>;
+template class FP<double,int8_t>;
+template class FP<double,int8_t*>;
+template class FP<double,uint8_t>;
+template class FP<double,uint8_t*>;
+template class FP<double,int16_t>;
+template class FP<double,int16_t*>;
+template class FP<double,uint16_t>;
+template class FP<double,uint16_t*>;
+template class FP<double,int32_t>;
+template class FP<double,int32_t*>;
+template class FP<double,uint32_t>;
+template class FP<double,uint32_t*>;
+template class FP<double,int64_t>;
+template class FP<double,int64_t*>;
+template class FP<double,uint64_t>;
+template class FP<double,uint64_t*>;
+template class FP<double,bool>;
+template class FP<double,bool*>;
+template class FP<double,float>;
+template class FP<double,float*>;
+template class FP<double,double>;
+template class FP<double,double*>;
+
+template class FP<double*,char>;
+template class FP<double*,char*>;
+template class FP<double*,int8_t>;
+template class FP<double*,int8_t*>;
+template class FP<double*,uint8_t>;
+template class FP<double*,uint8_t*>;
+template class FP<double*,int16_t>;
+template class FP<double*,int16_t*>;
+template class FP<double*,uint16_t>;
+template class FP<double*,uint16_t*>;
+template class FP<double*,int32_t>;
+template class FP<double*,int32_t*>;
+template class FP<double*,uint32_t>;
+template class FP<double*,uint32_t*>;
+template class FP<double*,int64_t>;
+template class FP<double*,int64_t*>;
+template class FP<double*,uint64_t>;
+template class FP<double*,uint64_t*>;
+template class FP<double*,bool>;
+template class FP<double*,bool*>;
+template class FP<double*,float>;
+template class FP<double*,float*>;
+template class FP<double*,double>;
+template class FP<double*,double*>;
+
+template class FP<char, char>;
+template class FP<char, char*>;
+template class FP<char, const char*>;
+
+template class FP<char*, char>;
+template class FP<char*, char*>;
+template class FP<char*, const char*>;
+
+
+
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/FP.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/FP.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/FP.h	(revision 175)
@@ -0,0 +1,188 @@
+/**
+ * @file    FP.h
+ * @brief   Core Utility - Templated Function Pointer Class
+ * @author  sam grove
+ * @version 1.0
+ * @see     
+ *
+ * Copyright (c) 2013
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FP_H
+#define FP_H
+
+/** Example using the FP Class with global functions
+ * @code
+ *  #include "mbed.h"
+ *  #include "FP.h"
+ *  
+ *  FP<void,bool>fp;
+ *  DigitalOut myled(LED1);
+ *  
+ *  void handler(bool value)
+ *  {
+ *      myled = value;
+ *      return;
+ *  }
+ *  
+ *  int main()
+ *  {
+ *      fp.attach(&handler);
+ *      
+ *      while(1) 
+ *      {
+ *          fp(1);
+ *          wait(0.2);
+ *          fp(0);
+ *          wait(0.2);
+ *      }
+ *  }
+ * @endcode
+ */
+ 
+/** Example using the FP Class with different class member functions
+ * @code
+ *  #include "mbed.h"
+ *  #include "FP.h"
+ *  
+ *  FP<void,bool>fp;
+ *  DigitalOut myled(LED4);
+ *  
+ *  class Wrapper
+ *  {
+ *  public:
+ *      Wrapper(){}
+ *  
+ *      void handler(bool value)
+ *      {
+ *          myled = value;
+ *          return;
+ *      }
+ *  };
+ *  
+ *  int main()
+ *  {
+ *      Wrapper wrapped;
+ *      fp.attach(&wrapped, &Wrapper::handler);
+ *      
+ *      while(1) 
+ *      {
+ *          fp(1);
+ *          wait(0.2);
+ *          fp(0);
+ *          wait(0.2);
+ *      }
+ *  }
+ * @endcode
+ */
+ 
+ /** Example using the FP Class with member FP and member function
+ * @code
+ *  #include "mbed.h"
+ *  #include "FP.h"
+ *  
+ *  DigitalOut myled(LED2);
+ *  
+ *  class Wrapper
+ *  {
+ *  public:
+ *      Wrapper()
+ *      {
+ *          fp.attach(this, &Wrapper::handler);
+ *      }
+ *  
+ *      void handler(bool value)
+ *      {
+ *          myled = value;
+ *          return;
+ *      }
+ *      
+ *      FP<void,bool>fp;
+ *  };
+ *  
+ *  int main()
+ *  {
+ *      Wrapper wrapped;
+ *      
+ *      while(1) 
+ *      {
+ *          wrapped.fp(1);
+ *          wait(0.2);
+ *          wrapped.fp(0);
+ *          wait(0.2);
+ *      }
+ *  }
+ * @endcode
+ */
+
+/**
+ *  @class FP
+ *  @brief API abstraction for a Function Pointers
+ */ 
+template<class retT, class argT>
+class FP
+{
+public:
+    /** Create the FP object
+     */ 
+    FP();
+
+    /** Add a callback function to the class
+     *  @param item - Address of the initialized class
+     *  @param member - Address of the member function (dont forget the scope that the function is defined in)
+     */
+    template<class T>
+    void attach(T *item, retT (T::*method)(argT))
+    {
+        obj_callback = (FPtrDummy *)(item);
+        method_callback = (retT (FPtrDummy::*)(argT))(method);
+        return;
+    }
+
+    /** Add a callback function to the class
+     *  @param function - The address of a globally defined function
+     */
+    void attach(retT (*function)(argT));
+    
+    /** Invoke the function attached to the class
+     *  @param arg - An argument that is passed into the function handler that is called
+     *  @return The return from the function hanlder called by this class
+     */
+    retT operator()(argT arg) const;
+    
+    bool attached();
+    
+    void detach();
+
+private:
+    
+    // empty type used for casting
+    class FPtrDummy;
+    
+    FPtrDummy *obj_callback;
+    
+    /**
+     *  @union Funciton
+     *  @brief Member or global callback function
+     */ 
+    union
+    {
+        retT (*c_callback)(argT);                   /*!< Footprint for a global function */
+        retT (FPtrDummy::*method_callback)(argT);   /*!< Footprint for a member function */
+    };
+};
+
+#endif
+
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.cpp	(revision 175)
@@ -0,0 +1,494 @@
+/* 
+Description:
+This is a example code for Sandbox Electronics' I2C/SPI to UART bridge module.
+You can get one of those products on 
+http://sandboxelectronics.com
+
+Version:
+V0.1
+
+Release Date:
+2014-02-16
+
+Author:
+Tiequan Shao          info@sandboxelectronics.com
+
+Lisence:
+CC BY-NC-SA 3.0
+
+Please keep the above information when you use this code in your project. 
+*/
+
+#if defined(__AVR_ATmega328P__)
+
+#include "SC16IS750.h"
+#include <Wire.h>
+
+#define WIRE Wire
+
+
+WifiData::WifiData(uint8_t prtcl, uint8_t addr_sspin)
+{
+    protocol = prtcl;
+    if ( protocol == SC16IS750_PROTOCOL_I2C ) {
+        device_address_sspin = (addr_sspin>>1);
+    } else {
+        device_address_sspin = addr_sspin;
+    }
+    peek_flag = 0;
+}
+
+void WifiData::begin(uint32_t baud)
+{
+    //Serial.println("1111111111111111");
+    if ( protocol == SC16IS750_PROTOCOL_I2C) {
+    //Serial.println("22222222222222");
+        WIRE.begin();
+    } 
+    ResetDevice();
+    FIFOEnable(1);
+    SetBaudrate(baud);
+    SetLine(8,0,1);
+}
+
+int WifiData::available(void)
+{
+    return FIFOAvailableData();
+}
+
+int WifiData::read(void)
+{
+    if ( peek_flag == 0) {
+        return ReadByte();
+    } else {
+        peek_flag = 0;
+        return peek_buf;
+    }
+}
+
+size_t WifiData::write(uint8_t val)
+{
+    WriteByte(val);
+}
+
+void WifiData::pinMode(uint8_t pin, uint8_t i_o)
+{
+    GPIOSetPinMode(pin, i_o);
+}
+
+void WifiData::digitalWrite(uint8_t pin, uint8_t value)
+{
+    GPIOSetPinState(pin, value);
+}
+
+uint8_t WifiData::digitalRead(uint8_t pin)
+{
+   return GPIOGetPinState(pin);
+}
+
+
+uint8_t WifiData::ReadRegister(uint8_t reg_addr)
+{
+    uint8_t result;
+    if ( protocol == SC16IS750_PROTOCOL_I2C ) {  // register read operation via I2C
+
+        WIRE.beginTransmission(device_address_sspin);
+        WIRE.write((reg_addr<<3));
+        WIRE.endTransmission(0);
+        WIRE.requestFrom(device_address_sspin,(uint8_t)1);
+        result = WIRE.read();
+    } 
+
+    return result;
+
+}
+
+void WifiData::WriteRegister(uint8_t reg_addr, uint8_t val)
+{
+    if ( protocol == SC16IS750_PROTOCOL_I2C ) {  // register read operation via I2C
+        WIRE.beginTransmission(device_address_sspin);
+        WIRE.write((reg_addr<<3));
+        WIRE.write(val);
+        WIRE.endTransmission(1);
+    } 
+
+
+    return ;
+}
+
+int16_t WifiData::SetBaudrate(uint32_t baudrate) //return error of baudrate parts per thousand
+{
+    uint16_t divisor;
+    uint8_t prescaler;
+    uint32_t actual_baudrate;
+    int16_t error;
+    uint8_t temp_lcr;
+    if ( (ReadRegister(SC16IS750_REG_MCR)&0x80) == 0) { //if prescaler==1
+        prescaler = 1;
+    } else {
+        prescaler = 4;
+    }
+
+    divisor = (SC16IS750_CRYSTCAL_FREQ/prescaler)/(baudrate*16);
+
+    temp_lcr = ReadRegister(SC16IS750_REG_LCR);
+    temp_lcr |= 0x80;
+    WriteRegister(SC16IS750_REG_LCR,temp_lcr);
+    //write to DLL
+    WriteRegister(SC16IS750_REG_DLL,(uint8_t)divisor);
+    //write to DLH
+    WriteRegister(SC16IS750_REG_DLH,(uint8_t)(divisor>>8));
+    temp_lcr &= 0x7F;
+    WriteRegister(SC16IS750_REG_LCR,temp_lcr);
+
+
+    actual_baudrate = (SC16IS750_CRYSTCAL_FREQ/prescaler)/(16*divisor);
+    error = ((float)actual_baudrate-baudrate)*1000/baudrate;
+
+    return error;
+
+}
+
+void WifiData::SetLine(uint8_t data_length, uint8_t parity_select, uint8_t stop_length )
+{
+    uint8_t temp_lcr;
+    temp_lcr = ReadRegister(SC16IS750_REG_LCR);
+    temp_lcr &= 0xC0; //Clear the lower six bit of LCR (LCR[0] to LCR[5]
+
+    switch (data_length) {            //data length settings
+        case 5:
+            break;
+        case 6:
+            temp_lcr |= 0x01;
+            break;
+        case 7:
+            temp_lcr |= 0x02;
+            break;
+        case 8:
+            temp_lcr |= 0x03;
+            break;
+        default:
+            temp_lcr |= 0x03;
+            break;
+    }
+
+    if ( stop_length == 2 ) {
+        temp_lcr |= 0x04;
+    }
+
+    switch (parity_select) {            //parity selection length settings
+        case 0:                         //no parity
+             break;
+        case 1:                         //odd parity
+            temp_lcr |= 0x08;
+            break;
+        case 2:                         //even parity
+            temp_lcr |= 0x18;
+            break;
+        case 3:                         //force '1' parity
+            temp_lcr |= 0x03;
+            break;
+        case 4:                         //force '0' parity
+            break;
+        default:
+            break;
+    }
+
+    WriteRegister(SC16IS750_REG_LCR,temp_lcr);
+}
+
+void WifiData::GPIOSetPinMode(uint8_t pin_number, uint8_t i_o)
+{
+    uint8_t temp_iodir;
+
+    temp_iodir = ReadRegister(SC16IS750_REG_IODIR);
+    if ( i_o == OUTPUT ) {
+      temp_iodir |= (0x01 << pin_number);
+    } else {
+      temp_iodir &= (uint8_t)~(0x01 << pin_number);
+    }
+
+    WriteRegister(SC16IS750_REG_IODIR, temp_iodir);
+    return;
+}
+
+void WifiData::GPIOSetPinState(uint8_t pin_number, uint8_t pin_state)
+{
+    uint8_t temp_iostate;
+
+    temp_iostate = ReadRegister(SC16IS750_REG_IOSTATE);
+    if ( pin_state == 1 ) {
+      temp_iostate |= (0x01 << pin_number);
+    } else {
+      temp_iostate &= (uint8_t)~(0x01 << pin_number);
+    }
+
+    WriteRegister(SC16IS750_REG_IOSTATE, temp_iostate);
+    return;
+}
+
+
+uint8_t WifiData::GPIOGetPinState(uint8_t pin_number)
+{
+    uint8_t temp_iostate;
+
+    temp_iostate = ReadRegister(SC16IS750_REG_IOSTATE);
+    if ( temp_iostate & (0x01 << pin_number)== 0 ) {
+      return 0;
+    }
+    return 1;
+}
+
+uint8_t WifiData::GPIOGetPortState(void)
+{
+
+    return ReadRegister(SC16IS750_REG_IOSTATE);
+
+}
+
+void WifiData::GPIOSetPortMode(uint8_t port_io)
+{
+    WriteRegister(SC16IS750_REG_IODIR, port_io);
+    return;
+}
+
+void WifiData::GPIOSetPortState(uint8_t port_state)
+{
+    WriteRegister(SC16IS750_REG_IOSTATE, port_state);
+    return;
+}
+
+void WifiData::SetPinInterrupt(uint8_t io_int_ena)
+{
+    WriteRegister(SC16IS750_REG_IOINTENA, io_int_ena);
+    return;
+}
+
+void WifiData::ResetDevice(void)
+{
+    uint8_t reg;
+
+    reg = ReadRegister(SC16IS750_REG_IOCONTROL);
+    reg |= 0x08;
+    WriteRegister(SC16IS750_REG_IOCONTROL, reg);
+
+    return;
+}
+
+void WifiData::ModemPin(uint8_t gpio) //gpio == 0, gpio[7:4] are modem pins, gpio == 1 gpio[7:4] are gpios
+{
+    uint8_t temp_iocontrol;
+
+    temp_iocontrol = ReadRegister(SC16IS750_REG_IOCONTROL);
+    if ( gpio == 0 ) {
+        temp_iocontrol |= 0x02;
+    } else {
+        temp_iocontrol &= 0xFD;
+    }
+    WriteRegister(SC16IS750_REG_IOCONTROL, temp_iocontrol);
+
+    return;
+}
+
+void WifiData::GPIOLatch(uint8_t latch)
+{
+    uint8_t temp_iocontrol;
+
+    temp_iocontrol = ReadRegister(SC16IS750_REG_IOCONTROL);
+    if ( latch == 0 ) {
+        temp_iocontrol &= 0xFE;
+    } else {
+        temp_iocontrol |= 0x01;
+    }
+    WriteRegister(SC16IS750_REG_IOCONTROL, temp_iocontrol);
+
+    return;
+}
+
+void WifiData::InterruptControl(uint8_t int_ena)
+{
+    WriteRegister(SC16IS750_REG_IER, int_ena);
+}
+
+uint8_t WifiData::InterruptPendingTest(void)
+{
+    return (ReadRegister(SC16IS750_REG_IIR) & 0x01);
+}
+
+void WifiData::__isr(void)
+{
+    uint8_t irq_src;
+
+    irq_src = ReadRegister(SC16IS750_REG_IIR);
+    irq_src = (irq_src >> 1);
+    irq_src &= 0x3F;
+
+    switch (irq_src) {
+        case 0x06:                  //Receiver Line Status Error
+            break;
+        case 0x0c:               //Receiver time-out interrupt
+            break;
+        case 0x04:               //RHR interrupt
+            break;
+        case 0x02:               //THR interrupt
+            break;
+        case 0x00:                  //modem interrupt;
+            break;
+        case 0x30:                  //input pin change of state
+            break;
+        case 0x10:                  //XOFF
+            break;
+        case 0x20:                  //CTS,RTS
+            break;
+        default:
+            break;
+    }
+    return;
+}
+
+void WifiData::FIFOEnable(uint8_t fifo_enable)
+{
+    uint8_t temp_fcr;
+
+    temp_fcr = ReadRegister(SC16IS750_REG_FCR);
+
+    if (fifo_enable == 0){
+        temp_fcr &= 0xFE;
+    } else {
+        temp_fcr |= 0x01;
+    }
+    WriteRegister(SC16IS750_REG_FCR,temp_fcr);
+
+    return;
+}
+
+void WifiData::FIFOReset(uint8_t rx_fifo)
+{
+     uint8_t temp_fcr;
+
+    temp_fcr = ReadRegister(SC16IS750_REG_FCR);
+
+    if (rx_fifo == 0){
+        temp_fcr |= 0x04;
+    } else {
+        temp_fcr |= 0x02;
+    }
+    WriteRegister(SC16IS750_REG_FCR,temp_fcr);
+
+    return;
+
+}
+
+void WifiData::FIFOSetTriggerLevel(uint8_t rx_fifo, uint8_t length)
+{
+    uint8_t temp_reg;
+
+    temp_reg = ReadRegister(SC16IS750_REG_MCR);
+    temp_reg |= 0x04;
+    WriteRegister(SC16IS750_REG_MCR,temp_reg); //SET MCR[2] to '1' to use TLR register or trigger level control in FCR register
+
+    temp_reg = ReadRegister(SC16IS750_REG_EFR);
+    WriteRegister(SC16IS750_REG_EFR, temp_reg|0x10); //set ERF[4] to '1' to use the  enhanced features
+    if (rx_fifo == 0) {
+        WriteRegister(SC16IS750_REG_TLR, length<<4); //Tx FIFO trigger level setting
+    } else {
+        WriteRegister(SC16IS750_REG_TLR, length);    //Rx FIFO Trigger level setting
+    }
+    WriteRegister(SC16IS750_REG_EFR, temp_reg); //restore EFR register
+
+    return;
+}
+
+uint8_t WifiData::FIFOAvailableData(void)
+{
+   return ReadRegister(SC16IS750_REG_RXLVL);
+
+}
+
+uint8_t WifiData::FIFOAvailableSpace(void)
+{
+   return ReadRegister(SC16IS750_REG_TXLVL);
+
+}
+
+void WifiData::WriteByte(uint8_t val)
+{
+    uint8_t tmp_lsr;
+    do {
+        tmp_lsr = ReadRegister(SC16IS750_REG_LSR);
+    } while ((tmp_lsr&0x20) ==0);
+
+    WriteRegister(SC16IS750_REG_THR,val);
+
+}
+
+int WifiData::ReadByte(void)
+{
+    volatile uint8_t val;
+    if (FIFOAvailableData() == 0) {
+
+        return -1;
+
+    } else {
+
+      val = ReadRegister(SC16IS750_REG_RHR);
+      return val;
+    }
+
+}
+
+void WifiData::EnableTransmit(uint8_t tx_enable)
+{
+    uint8_t temp_efcr;
+    temp_efcr = ReadRegister(SC16IS750_REG_EFCR);
+    if ( tx_enable == 0) {
+        temp_efcr |= 0x04;
+    } else {
+        temp_efcr &= 0xFB;
+    }
+    WriteRegister(SC16IS750_REG_EFCR,temp_efcr);
+
+    return;
+}
+
+uint8_t WifiData::ping()
+{
+    WriteRegister(SC16IS750_REG_SPR,0x55);
+    if (ReadRegister(SC16IS750_REG_SPR) !=0x55) {
+        return 0;
+    }
+
+    WriteRegister(SC16IS750_REG_SPR,0xAA);
+    if (ReadRegister(SC16IS750_REG_SPR) !=0xAA) {
+        return 0;
+    }
+
+    return 1;
+
+}
+
+void WifiData::flush()
+{
+    uint8_t tmp_lsr;
+
+    do {
+        tmp_lsr = ReadRegister(SC16IS750_REG_LSR);
+    } while ((tmp_lsr&0x20) ==0);
+
+
+}
+
+int WifiData::peek()
+{
+    if ( peek_flag == 0 ) {
+        peek_buf =ReadByte();
+        if (  peek_buf >= 0 ) {
+            peek_flag = 1;
+        }
+    }
+
+    return peek_buf;
+
+}
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/SC16IS750.h	(revision 175)
@@ -0,0 +1,163 @@
+/* 
+Description:
+This is a example code for Sandbox Electronics' I2C/SPI to UART bridge module.
+You can get one of those products on 
+http://sandboxelectronics.com
+
+Version:
+V0.1
+
+Release Date:
+2014-02-16
+
+Author:
+Tiequan Shao          info@sandboxelectronics.com
+
+Lisence:
+CC BY-NC-SA 3.0
+
+Please keep the above information when you use this code in your project. 
+*/
+
+
+#ifndef _SC16IS750_H_
+#define _SC16IS750_H_
+
+#if ARDUINO >= 100
+ #include "Arduino.h"
+#else
+ #include "WProgram.h"
+#endif
+
+//Device Address
+
+//A:VDD
+//B:GND
+//C:SCL
+//D:SDA
+#define     SC16IS750_ADDRESS_AA     (0X90)
+#define     SC16IS750_ADDRESS_AB     (0X92)
+#define     SC16IS750_ADDRESS_AC     (0X94)
+#define     SC16IS750_ADDRESS_AD     (0X96)
+#define     SC16IS750_ADDRESS_BA     (0X98)
+#define     SC16IS750_ADDRESS_BB     (0X9A)
+#define     SC16IS750_ADDRESS_BC     (0X9C)
+#define     SC16IS750_ADDRESS_BD     (0X9E)
+#define     SC16IS750_ADDRESS_CA     (0XA0)
+#define     SC16IS750_ADDRESS_CB     (0XA2)
+#define     SC16IS750_ADDRESS_CC     (0XA4)
+#define     SC16IS750_ADDRESS_CD     (0XA6)
+#define     SC16IS750_ADDRESS_DA     (0XA8)
+#define     SC16IS750_ADDRESS_DB     (0XAA)
+#define     SC16IS750_ADDRESS_DC     (0XAC)
+#define     SC16IS750_ADDRESS_DD     (0XAE)
+
+
+//General Registers
+#define     SC16IS750_REG_RHR        (0x00)
+#define     SC16IS750_REG_THR        (0X00)
+#define     SC16IS750_REG_IER        (0X01)
+#define     SC16IS750_REG_FCR        (0X02)
+#define     SC16IS750_REG_IIR        (0X02)
+#define     SC16IS750_REG_LCR        (0X03)
+#define     SC16IS750_REG_MCR        (0X04)
+#define     SC16IS750_REG_LSR        (0X05)
+#define     SC16IS750_REG_MSR        (0X06)
+#define     SC16IS750_REG_SPR        (0X07)
+#define     SC16IS750_REG_TCR        (0X06)
+#define     SC16IS750_REG_TLR        (0X07)
+#define     SC16IS750_REG_TXLVL      (0X08)
+#define     SC16IS750_REG_RXLVL      (0X09)
+#define     SC16IS750_REG_IODIR      (0X0A)
+#define     SC16IS750_REG_IOSTATE    (0X0B)
+#define     SC16IS750_REG_IOINTENA   (0X0C)
+#define     SC16IS750_REG_IOCONTROL  (0X0E)
+#define     SC16IS750_REG_EFCR       (0X0F)
+
+//Special Registers
+#define     SC16IS750_REG_DLL        (0x00)
+#define     SC16IS750_REG_DLH        (0X01)
+
+//Enhanced Registers
+#define     SC16IS750_REG_EFR        (0X02)
+#define     SC16IS750_REG_XON1       (0X04)
+#define     SC16IS750_REG_XON2       (0X05)
+#define     SC16IS750_REG_XOFF1      (0X06)
+#define     SC16IS750_REG_XOFF2      (0X07)
+
+//
+#define     SC16IS750_INT_CTS        (0X80)
+#define     SC16IS750_INT_RTS        (0X40)
+#define     SC16IS750_INT_XOFF       (0X20)
+#define     SC16IS750_INT_SLEEP      (0X10)
+#define     SC16IS750_INT_MODEM      (0X08)
+#define     SC16IS750_INT_LINE       (0X04)
+#define     SC16IS750_INT_THR        (0X02)
+#define     SC16IS750_INT_RHR        (0X01)
+
+//Application Related 
+
+#define     SC16IS750_CRYSTCAL_FREQ (14745600UL) 
+//#define   SC16IS750_CRYSTCAL_FREQ (1843200UL)   
+//#define     SC16IS750_CRYSTCAL_FREQ (16000000UL)    
+//#define     SC16IS750_DEBUG_PRINT   (0)
+#define     SC16IS750_PROTOCOL_I2C  (0)
+#define     SC16IS750_PROTOCOL_I2C  (0)
+#define     END     "<!--~-->"
+
+class WifiData : public Stream
+{ 
+    public:
+        WifiData(uint8_t prtcl = SC16IS750_PROTOCOL_I2C, uint8_t addr = SC16IS750_ADDRESS_AD);
+        void begin(uint32_t baud);                               
+        int read();
+        size_t write(uint8_t val);
+        int available();
+        void pinMode(uint8_t pin, uint8_t io);
+        void digitalWrite(uint8_t pin, uint8_t value);
+        uint8_t digitalRead(uint8_t pin);
+        uint8_t ping();
+        int peek();
+        void flush();
+        uint8_t GPIOGetPortState(void);
+        uint8_t InterruptPendingTest(void);
+        void    SetPinInterrupt(uint8_t io_int_ena);
+        void    InterruptControl(uint8_t int_ena);
+        void    ModemPin(uint8_t gpio); //gpio == 0, gpio[7:4] are modem pins, gpio == 1 gpio[7:4] are gpios
+        void    GPIOLatch(uint8_t latch);
+        
+    
+    private:
+        uint8_t device_address_sspin;
+        uint8_t protocol;
+    //  uint32_t timeout;
+        int16_t SetBaudrate(uint32_t baudrate);
+        uint8_t ReadRegister(uint8_t reg_addr);
+        void    WriteRegister(uint8_t reg_addr, uint8_t val);
+        void    SetLine(uint8_t data_length, uint8_t parity_select, uint8_t stop_length );
+        void    GPIOSetPinMode(uint8_t pin_number, uint8_t i_o);
+        void    GPIOSetPinState(uint8_t pin_number, uint8_t pin_state);
+        
+        uint8_t GPIOGetPinState(uint8_t pin_number);
+        void    GPIOSetPortMode(uint8_t port_io);
+        void    GPIOSetPortState(uint8_t port_state);
+        void    ResetDevice(void);
+        
+        
+        
+        void    __isr(void);
+        void    FIFOEnable(uint8_t fifo_enable);
+        void    FIFOReset(uint8_t rx_fifo);
+        void    FIFOSetTriggerLevel(uint8_t rx_fifo, uint8_t length);
+        uint8_t FIFOAvailableData(void);
+        uint8_t FIFOAvailableSpace(void);
+        void    WriteByte(uint8_t val);
+        int     ReadByte(void);
+        void    EnableTransmit(uint8_t tx_enable);
+    //  int16_t readwithtimeout();
+        int     peek_buf;
+        uint8_t peek_flag;
+        
+};
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/UnowifiCiao.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/UnowifiCiao.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/UnowifiCiao.cpp	(revision 175)
@@ -0,0 +1,207 @@
+/*
+****************************************************************************
+* Copyright (c) 2015 Arduino srl. All right reserved.
+*
+* File : UnowifiCiao.cpp
+* Date : 2016/02/16
+* Revision : 0.0.1 $
+* Author: adriano[at]arduino[dot]org
+*
+****************************************************************************
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#include "Ciao.h"
+#include "Wifi.h"
+
+#if defined(__AVR_ATmega328P__)
+
+#include <stdarg.h>
+#include <stdio.h>
+
+WifiData espSerial = WifiData(SC16IS750_PROTOCOL_I2C,SC16IS750_ADDRESS_AA);
+ESP esp(&espSerial, 4);
+REST rest(&esp);
+
+CiaoClass Ciao;
+WifiClass Wifi;
+
+boolean wifiConnected = false;
+
+void wifiCb(void* response)
+{
+	uint32_t status;
+	RESPONSE res(response);
+
+	if(res.getArgc() == 1) {
+		res.popArgs((uint8_t*)&status, 4);
+		if(status == STATION_GOT_IP){
+			espSerial.println("DBG: Internet Connected");
+			wifiConnected = true;
+		}
+		else {
+			wifiConnected = false;
+		}
+	}
+}
+
+void WifiClass::powerON(){ 	
+	
+}
+void WifiClass::powerOFF(){ 	
+	
+}
+
+WifiData WifiClass::stream(){
+	return espSerial;
+}
+int WifiClass::read(){
+	return espSerial.read();
+}
+void WifiClass::print(String str){
+	espSerial.print(str);
+}
+void WifiClass::println(String str){
+	espSerial.println(str);
+}
+void CiaoClass::print(String str){
+	espSerial.print(str);
+}
+void CiaoClass::println(String str){
+	espSerial.println(str);
+}
+boolean WifiClass::available(){
+	return espSerial.available();
+}
+void WifiClass::connect(char* ssid,char* pwd){
+	esp.wifiConnect(ssid, pwd);
+}
+boolean WifiClass::connected(){
+	return wifiConnected;
+}
+
+void WifiBegin() {
+	Serial.begin(9600);
+	espSerial.begin(9600);
+	if(espSerial.ping()!=1) {
+		espSerial.println("DBG: esp not found");
+		while(1);
+	}
+	else {
+		//espSerial.println("device found");
+	}
+	//metti GPIO control here !!!
+	esp.enable();
+	delay(1000);
+	esp.reset();
+	delay(1000);
+	while(!esp.ready());
+	esp.wifiCb.attach(&wifiCb);
+	espSerial.println("\nDBG: UnoWiFi Start");
+}
+void WifiClass::begin() {
+	WifiBegin();
+}
+void CiaoClass::begin() {
+
+	WifiBegin();
+	espSerial.println("DBG: Ciao start");
+	rest.begin("google.com");
+	rest.get("/");
+	delay(3000);
+}
+
+CiaoData responseREAD(){
+	CiaoData data;
+	delay(400);
+	char response[64] = "";
+	char cstr[8] = "";
+
+	int ret = rest.getResponse(response, 64);
+	//espSerial.println(ret);
+
+	snprintf(cstr,8,"%d",ret);
+
+		data.msg_split[0]="id";
+		data.msg_split[1]=cstr;
+		data.msg_split[2]=response;
+				
+	return data;
+}
+CiaoData requestPOST(char* hostname, String stringone){
+	rest.begin(hostname);
+	//delay(1000);	fix
+	//esp.process(); 
+	rest.post((const char*) stringone.c_str(),0);
+	return responseREAD(); 
+}
+
+CiaoData requestGET(char* hostname, String stringone){
+
+	rest.begin(hostname);
+	//delay(1000);   fix
+	//esp.process(); 
+	rest.get((const char*) stringone.c_str());
+	return responseREAD(); 
+}
+
+CiaoData PassThroughM(char* connector,char* hostname, String stringone, char* method){
+  
+	short mode = 0;
+	if (!strcmp(connector, "rest")){
+		mode = 0;
+	}
+	else if (!strcmp(connector, "mqtt")){
+		mode = 1;
+	}
+	else {
+		CiaoData data;				
+		data.msg_split[0]="";
+		data.msg_split[1]="";
+		data.msg_split[2]="Protocol Error";
+		return data;
+	}
+	
+	if (mode == 0){ 
+		if (!strcmp(method, "GET")){
+			return requestGET(hostname, stringone); 
+		}
+		else if (!strcmp(method, "POST")){
+			return requestPOST(hostname, stringone); 
+		}
+		else{
+			CiaoData data;				
+			data.msg_split[0]="";
+			data.msg_split[1]="";
+			data.msg_split[2]="Method Error";
+			return data;
+		}   
+	}
+}
+
+CiaoData CiaoClass::write(char* connector,char* hostname, String stringone, char* method) {
+	return PassThroughM(connector, hostname, stringone, method);
+}
+CiaoData CiaoClass::read(char* connector,char* hostname, String stringone, char* method) {
+	return PassThroughM(connector, hostname, stringone, method);
+}
+CiaoData CiaoClass::write(char* connector,char* hostname, String stringone) {
+	return PassThroughM(connector, hostname, stringone, "GET");
+}
+CiaoData CiaoClass::read(char* connector,char* hostname, String stringone) {
+	return PassThroughM(connector, hostname, stringone, "GET");
+}
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/Wifi.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/Wifi.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/Wifi.h	(revision 175)
@@ -0,0 +1,47 @@
+#ifndef WIFI_H_
+#define WIFI_H_
+
+#include <Arduino.h>
+
+#include <Stream.h>
+#include "crc16.h"
+//#include <mqtt.h>
+#include "rest.h"
+#include "espduino.h"
+#include "ringbuf.h"
+#include "FP.h"
+#include <string.h>
+
+#ifdef __AVR_ATmega328P__
+
+//#else
+
+#include "SC16IS750.h"
+
+class WifiClass {
+
+	public:
+		void begin();
+
+		void print(String str);
+		void println(String str);
+		int read();		
+
+		WifiData stream();
+
+		boolean available();
+		boolean connected();
+
+		void connect(char* , char*);
+
+		void powerON();
+		void powerOFF();
+
+};
+
+extern WifiClass Wifi;
+
+#endif
+
+
+#endif /* WIFI_H_ */
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/crc16.c
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/crc16.c	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/crc16.c	(revision 175)
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2005, Swedish Institute of Computer Science
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the Contiki operating system.
+ *
+ */
+
+/** \addtogroup crc16
+ * @{ */
+
+/**
+ * \file
+ *         Implementation of the CRC16 calculcation
+ * \author
+ *         Adam Dunkels <adam@sics.se>
+ *
+ */
+
+/* CITT CRC16 polynomial ^16 + ^12 + ^5 + 1 */
+/*---------------------------------------------------------------------------*/
+unsigned short
+crc16_add(unsigned char b, unsigned short acc)
+{
+  /*
+    acc  = (unsigned char)(acc >> 8) | (acc << 8);
+    acc ^= b;
+    acc ^= (unsigned char)(acc & 0xff) >> 4;
+    acc ^= (acc << 8) << 4;
+    acc ^= ((acc & 0xff) << 4) << 1;
+  */
+
+  acc ^= b;
+  acc  = (acc >> 8) | (acc << 8);
+  acc ^= (acc & 0xff00) << 4;
+  acc ^= (acc >> 8) >> 4;
+  acc ^= (acc & 0xff00) >> 5;
+  return acc;
+}
+/*---------------------------------------------------------------------------*/
+unsigned short
+crc16_data(const unsigned char *data, int len, unsigned short acc)
+{
+  int i;
+  
+  for(i = 0; i < len; ++i) {
+    acc = crc16_add(*data, acc);
+    ++data;
+  }
+  return acc;
+}
+/*---------------------------------------------------------------------------*/
+
+/** @} */
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/crc16.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/crc16.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/crc16.h	(revision 175)
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2005, Swedish Institute of Computer Science
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the Contiki operating system.
+ *
+ */
+
+/**
+ * \file
+ *         Header file for the CRC16 calculcation
+ * \author
+ *         Adam Dunkels <adam@sics.se>
+ *
+ */
+
+/** \addtogroup lib
+ * @{ */
+
+/**
+ * \defgroup crc16 Cyclic Redundancy Check 16 (CRC16) calculation
+ *
+ * The Cyclic Redundancy Check 16 is a hash function that produces a
+ * checksum that is used to detect errors in transmissions. The CRC16
+ * calculation module is an iterative CRC calculator that can be used
+ * to cumulatively update a CRC checksum for every incoming byte.
+ *
+ * @{
+ */
+
+#ifndef CRC16_H_
+#define CRC16_H_
+#ifdef	__cplusplus
+extern "C" {
+#endif
+/**
+ * \brief      Update an accumulated CRC16 checksum with one byte.
+ * \param b    The byte to be added to the checksum
+ * \param crc  The accumulated CRC that is to be updated.
+ * \return     The updated CRC checksum.
+ *
+ *             This function updates an accumulated CRC16 checksum
+ *             with one byte. It can be used as a running checksum, or
+ *             to checksum an entire data block.
+ *
+ *             \note The algorithm used in this implementation is
+ *             tailored for a running checksum and does not perform as
+ *             well as a table-driven algorithm when checksumming an
+ *             entire data block.
+ *
+ */
+unsigned short crc16_add(unsigned char b, unsigned short crc);
+
+/**
+ * \brief      Calculate the CRC16 over a data area
+ * \param data Pointer to the data
+ * \param datalen The length of the data
+ * \param acc  The accumulated CRC that is to be updated (or zero).
+ * \return     The CRC16 checksum.
+ *
+ *             This function calculates the CRC16 checksum of a data area.
+ *
+ *             \note The algorithm used in this implementation is
+ *             tailored for a running checksum and does not perform as
+ *             well as a table-driven algorithm when checksumming an
+ *             entire data block.
+ */
+unsigned short crc16_data(const unsigned char *data, int datalen,
+			  unsigned short acc);
+#ifdef	__cplusplus
+}
+#endif
+#endif /* CRC16_H_ */
+
+/** @} */
+/** @} */
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.cpp	(revision 175)
@@ -0,0 +1,297 @@
+/**
+ * \file
+ *       ESP8266 bridge arduino library 
+ * \author
+ *       Tuan PM <tuanpm@live.com>
+ */
+#include "espduino.h"
+
+RESPONSE::RESPONSE(void * response)
+{
+  cmd = (PACKET_CMD*)response;
+  arg_ptr = (uint8_t*)&cmd->args;
+  arg_num = 0;
+}
+
+uint16_t RESPONSE::getArgc()
+{
+  return cmd->argc;
+}
+uint16_t RESPONSE::argLen()
+{
+  return *(uint16_t*)arg_ptr;
+}
+int32_t RESPONSE::popArgs(uint8_t *data, uint16_t maxLen)
+{
+  uint16_t length, len, incLen = 0;
+
+   if(arg_num >= cmd->argc)
+     return -1;
+ 
+  length = *(uint16_t*)arg_ptr;
+  len = length;
+  arg_ptr += 2;
+
+  while(length --){
+    *data ++ = *arg_ptr ++;
+    incLen ++;
+    if(incLen > maxLen){
+      arg_num ++;
+      return maxLen;
+    }
+      
+  }
+  arg_num ++;
+  return len;
+}
+
+String RESPONSE::popString()
+{
+  String ret;
+  uint16_t len = *(uint16_t*)arg_ptr;
+  arg_ptr += 2;
+  while(len --)
+    ret += (char)*arg_ptr ++;
+  arg_num ++;
+  return ret;
+}
+void RESPONSE::popString(String* data)
+{
+  uint16_t len = *(uint16_t*)arg_ptr;
+  arg_ptr += 2;
+  while(len --)
+    data->concat( (char)*arg_ptr ++);
+  arg_num ++;
+}
+
+void ESP::protoCompletedCb(void)
+{
+  PACKET_CMD *cmd = (PACKET_CMD*)_proto.buf;
+  uint16_t crc = 0, argc, len, resp_crc;
+  uint8_t *data_ptr;
+  argc = cmd->argc;
+  data_ptr = (uint8_t*)&cmd->args ;
+  crc = crc16_data((uint8_t*)&cmd->cmd, 12, crc);
+  while(argc--){
+    len = *((uint16_t*)data_ptr);
+    crc = crc16_data(data_ptr, 2, crc);
+    data_ptr += 2;
+    while(len --){
+      crc = crc16_data(data_ptr, 1, crc);
+      data_ptr ++;
+    }
+  }
+  resp_crc =  *(uint16_t*)data_ptr;
+  if(crc != resp_crc) {
+      INFO("ARDUINO: Invalid CRC");
+    return;
+  }
+
+  FP<void, void*> *fp;
+  if(cmd->callback != 0){
+    fp = (FP<void, void*>*)cmd->callback;
+
+    return_cmd = cmd->cmd;
+    return_value = cmd->_return;
+
+    if(fp->attached())
+      (*fp)((void*)cmd);
+  } else {
+    if(cmd->argc == 0) {
+      is_return = true;
+      return_cmd = cmd->cmd;
+      return_value = cmd->_return;
+    }
+    
+  }
+}
+
+void ESP::wifiConnect(const char* ssid, const char* password)
+{
+  uint16_t crc;
+  crc = request(CMD_WIFI_CONNECT, (uint32_t)&wifiCb, 0, 2);
+  crc = request(crc,(uint8_t*)ssid, strlen(ssid));
+  crc = request(crc,(uint8_t*)password, strlen(password));
+  request(crc);
+}
+void ESP::write(uint8_t data)
+{
+  switch(data){
+  case SLIP_START:
+  case SLIP_END:
+  case SLIP_REPL:
+    _serial->write(SLIP_REPL);
+    _serial->write(SLIP_ESC(data));
+    break;
+  default:
+    _serial->write(data);
+  }
+}
+void ESP::write(uint8_t* data, uint16_t len)
+{
+  while(len --)
+    write(*data ++);
+}
+uint16_t ESP::request(uint16_t cmd, uint32_t callback, uint32_t _return, uint16_t argc)
+{
+  uint16_t crc = 0;
+  _serial->write(0x7E);
+  write((uint8_t*)&cmd, 2);
+  crc = crc16_data((uint8_t*)&cmd, 2, crc);
+
+  write((uint8_t*)&callback, 4);
+  crc = crc16_data((uint8_t*)&callback, 4, crc);
+
+  write((uint8_t*)&_return, 4);
+  crc = crc16_data((uint8_t*)&_return, 4, crc);
+
+  write((uint8_t*)&argc, 2);
+  crc = crc16_data((uint8_t*)&argc, 2, crc);
+  return crc;
+}
+
+uint16_t ESP::request(uint16_t crc_in, uint8_t* data, uint16_t len)
+{
+  uint8_t temp = 0;
+  uint16_t pad_len = len;
+  while(pad_len % 4 != 0)
+    pad_len++;
+  write((uint8_t*)&pad_len, 2);
+  crc_in = crc16_data((uint8_t*)&pad_len, 2, crc_in);
+  while(len --){
+    write(*data);
+    crc_in = crc16_data((uint8_t*)data, 1, crc_in);
+    data ++;
+    if(pad_len > 0) pad_len --;
+  }
+  
+  while(pad_len --){
+    write(temp);
+    crc_in = crc16_data((uint8_t*)&temp, 1, crc_in);
+  }
+  return crc_in;
+}
+uint16_t ESP::request(uint16_t crc)
+{
+  write((uint8_t*)&crc, 2);
+  _serial->write(0x7F);
+}
+
+void ESP::init()
+{
+  _proto.buf = _protoBuf;
+  _proto.bufSize = sizeof(_protoBuf);
+  _proto.dataLen = 0;
+  _proto.isEsc = 0;
+  pinMode(_chip_pd, OUTPUT);
+
+}
+
+ESP::ESP(Stream *serial, int chip_pd):
+_serial(serial), _chip_pd(chip_pd)
+{
+  _debugEn = false;
+  init();
+}
+
+ESP::ESP(Stream *serial, Stream* debug, int chip_pd):
+_serial(serial), _debug(debug), _chip_pd(chip_pd)
+{
+    _debugEn = true;
+    //_serial = _debug;
+    init();
+}
+void ESP::enable()
+{
+  digitalWrite(_chip_pd, HIGH);
+}
+void ESP::disable()
+{
+  digitalWrite(_chip_pd, LOW);
+}
+void ESP::INFO(String info)
+{
+  if(_debugEn)
+    _debug->println(info);
+}
+
+void ESP::reset()
+{
+  uint16_t crc = request(CMD_RESET, 0, 0, 0);
+  request(crc);
+}
+
+boolean ESP::ready()
+{
+  uint32_t wait;
+
+  for(uint8_t wait_time=5; wait_time>0; wait_time--){
+    is_return = false;
+    return_value = 0;
+    uint16_t crc = request(CMD_IS_READY, 0, 1, 0);
+    request(crc);
+    wait = millis();
+    while(is_return == false && (millis() - wait < 1000)) {
+      process();
+    }
+    if(is_return && return_value)
+      return true;
+  }
+  return false;
+  
+}
+boolean ESP::waitReturn(uint32_t timeout)
+{
+  is_return = false;
+  return_value = 0;
+  return_cmd = 0;
+  uint32_t wait = millis();
+  while(is_return == false && (millis() - wait < timeout)) {
+    process();
+  }
+  return is_return;
+}
+boolean ESP::waitReturn()
+{
+  return waitReturn(ESP_TIMEOUT);
+}
+void ESP::process()
+{
+  char value;
+  while(_serial->available()) {
+    value = _serial->read();
+    switch(value){
+    case 0x7D:
+      _proto.isEsc = 1;
+      break;
+    
+    case 0x7E:
+      _proto.dataLen = 0;
+      _proto.isEsc = 0;
+      _proto.isBegin = 1;
+      break;
+    
+    case 0x7F:
+      protoCompletedCb();
+      _proto.isBegin = 0;
+      break;
+    
+    default:
+      if(_proto.isBegin == 0) {
+        if(_debugEn) {
+            _debug->write(value);
+        }
+        break;
+      }
+      if(_proto.isEsc){
+        value ^= 0x20;
+        _proto.isEsc = 0;
+      }
+        
+      if(_proto.dataLen < _proto.bufSize)
+        _proto.buf[_proto.dataLen++] = value;
+        
+      break;
+    }
+  }
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/espduino.h	(revision 175)
@@ -0,0 +1,130 @@
+/**
+ * \file
+ *       ESP8266 bridge arduino library 
+ * \author
+ *       Tuan PM <tuanpm@live.com>
+ */
+#ifndef _ARDUINO_WIFI_H_
+#define _ARDUINO_WIFI_H_
+#include <stdint.h>
+//#include <HardwareSerial.h>
+#include <Arduino.h>
+#include "FP.h"
+#include "crc16.h"
+#include "ringbuf.h"
+
+#define ESP_TIMEOUT 2000
+
+#define SLIP_START 0x7E
+#define SLIP_END  0x7F
+#define SLIP_REPL 0x7D
+#define SLIP_ESC(x) (x ^ 0x20)
+
+typedef enum
+{
+  CMD_NULL = 0,
+  CMD_RESET,
+  CMD_IS_READY,
+  CMD_WIFI_CONNECT,
+  CMD_MQTT_SETUP,
+  CMD_MQTT_CONNECT,
+  CMD_MQTT_DISCONNECT,
+  CMD_MQTT_PUBLISH, 
+  CMD_MQTT_SUBSCRIBE,
+  CMD_MQTT_LWT,
+  CMD_MQTT_EVENTS,
+  CMD_REST_SETUP,
+  CMD_REST_REQUEST,
+  CMD_REST_SETHEADER,
+  CMD_REST_EVENTS
+}CMD_NAME;
+
+enum WIFI_STATUS{
+  STATION_IDLE = 0,
+  STATION_CONNECTING,
+  STATION_WRONG_PASSWORD,
+  STATION_NO_AP_FOUND,
+  STATION_CONNECT_FAIL,
+  STATION_GOT_IP
+};
+
+typedef struct{
+  uint8_t *buf;
+  uint16_t bufSize;
+  uint16_t dataLen;
+  uint8_t isEsc;
+  uint8_t isBegin;
+}PROTO;
+
+typedef struct __attribute((__packed__)) {
+  uint16_t len;
+  uint8_t data;
+} ARGS;
+
+typedef struct __attribute((__packed__)) {
+  uint16_t cmd;
+  uint32_t callback;
+  uint32_t _return;
+  uint16_t argc;
+  ARGS args;
+}PACKET_CMD;
+
+class ESP;
+class RESPONSE;
+class MQTT;
+
+class RESPONSE {
+private:
+  uint16_t arg_num;
+  uint8_t *arg_ptr;
+  PACKET_CMD* cmd;
+public:
+  RESPONSE(void *response);
+  uint16_t getArgc();
+  int32_t popArgs(uint8_t *data, uint16_t maxLen);
+  uint16_t argLen();
+  String popString();
+  void popString(String* data);
+};
+
+
+class ESP
+{
+public:
+  ESP(Stream *serial, Stream* debug, int chip_pd);
+  ESP(Stream *serial, int chip_pd);
+  Stream *_debug;
+
+  FP<void, void*> wifiCb;
+  uint32_t return_value;
+  uint16_t return_cmd;
+  boolean is_return;
+
+  void wifiConnect(const char* ssid, const char* password);
+  void process();
+  uint16_t request(uint16_t cmd, uint32_t callback, uint32_t _return, uint16_t argc);
+  uint16_t request(uint16_t crc_in, uint8_t* data, uint16_t len);
+  uint16_t request(uint16_t crc);
+  void reset();
+  boolean ready();
+  void enable();
+  void disable();
+  boolean waitReturn(uint32_t timeout);
+  boolean waitReturn();
+
+private:
+  Stream *_serial;
+  
+  boolean _debugEn;
+  PROTO _proto;
+  uint8_t _protoBuf[512];
+  int _chip_pd;
+  
+
+  void init();
+  void INFO(String info);
+  void protoCompletedCb(void);
+  void write(uint8_t data);
+  void write(uint8_t* data, uint16_t len);
+};
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/rest.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/rest.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/rest.cpp	(revision 175)
@@ -0,0 +1,138 @@
+/**
+ * \file
+ *       ESP8266 RESTful Bridge
+ * \author
+ *       Tuan PM <tuanpm@live.com>
+ */
+#include "rest.h"
+REST::REST(ESP *e)
+{
+  esp = e;
+  remote_instance = 0;
+  timeout = DEFAULT_REST_TIMEOUT;
+}
+void REST::restCallback(void *resp)
+{
+  response = true;
+  res = resp;
+}
+
+boolean REST::begin(const char* host, uint16_t port, boolean security)
+{
+  uint8_t sec = 0;
+  if(security)
+    sec = 1;
+  restCb.attach(this, &REST::restCallback);
+  
+  uint16_t crc = esp->request(CMD_REST_SETUP, (uint32_t)&restCb, 1, 3);
+  crc = esp->request(crc,(uint8_t*)host, strlen(host));
+  crc = esp->request(crc,(uint8_t*)&port, 2);
+  crc = esp->request(crc,(uint8_t*)&sec, 1);
+  esp->request(crc);
+
+  if(esp->waitReturn(timeout) && esp->return_value != 0){
+    remote_instance = esp->return_value;
+    return true;
+  }
+  return false;
+}
+
+boolean REST::begin(const char* host)
+{
+  return begin(host, 80, false);
+}
+void REST::request(const char* path, const char* method, const char* data, int len)
+{
+  if(remote_instance == 0)
+    return;
+  uint16_t crc;
+  if(len > 0)
+    crc = esp->request(CMD_REST_REQUEST, 0, 0, 5);
+  else
+    crc = esp->request(CMD_REST_REQUEST, 0, 0, 3);
+  crc = esp->request(crc,(uint8_t*)&remote_instance, 4);
+  crc = esp->request(crc,(uint8_t*)method, strlen(method));
+  crc = esp->request(crc,(uint8_t*)path, strlen(path));
+  if(len > 0){
+    crc = esp->request(crc,(uint8_t*)&len, 2);
+    crc = esp->request(crc,(uint8_t*)data, len);
+  }
+    
+  esp->request(crc);
+}
+void REST::request(const char* path, const char* method, const char* data)
+{
+  request(path, method, data, strlen(data));
+}
+void REST::get(const char* path, const char* data)
+{
+  request(path, "GET", data);
+}
+void REST::get(const char* path)
+{
+  request(path, "GET", 0, 0);
+}
+void REST::post(const char* path, const char* data)
+{
+  request(path, "POST", data);
+}
+void REST::put(const char* path, const char* data)
+{
+  request(path, "PUT", data);
+}
+void REST::del(const char* path, const char* data)
+{
+  request(path, "DELETE", data);
+}
+
+/*
+void REST::setHeader(const char* value)
+{
+  uint8_t header_index = HEADER_GENERIC;
+  uint16_t crc = esp->request(CMD_REST_SETHEADER, 0, 0, 3);
+  crc = esp->request(crc,(uint8_t*)&remote_instance, 4);
+  crc = esp->request(crc,(uint8_t*)&header_index, 1);
+  crc = esp->request(crc,(uint8_t*)value, strlen(value));
+  esp->request(crc);
+}
+void REST::setContentType(const char* value)
+{
+  uint8_t header_index = HEADER_CONTENT_TYPE;
+  uint16_t crc = esp->request(CMD_REST_SETHEADER, 0, 0, 3);
+  crc = esp->request(crc,(uint8_t*)&remote_instance, 4);
+  crc = esp->request(crc,(uint8_t*)&header_index, 1);
+  crc = esp->request(crc,(uint8_t*)value, strlen(value));
+  esp->request(crc);
+}
+void REST::setUserAgent(const char* value)
+{
+  uint8_t header_index = HEADER_USER_AGENT;
+  uint16_t crc = esp->request(CMD_REST_SETHEADER, 0, 0, 3);
+  crc = esp->request(crc,(uint8_t*)&remote_instance, 4);
+  crc = esp->request(crc,(uint8_t*)&header_index, 1);
+  crc = esp->request(crc,(uint8_t*)value, strlen(value));
+  esp->request(crc);
+}
+void REST::setTimeout(uint32_t ms)
+{
+  timeout = ms;
+}
+*/
+
+uint16_t REST::getResponse(char* data, uint16_t maxLen)
+{
+  response = false;
+  uint32_t wait = millis();
+  while(response == false && (millis() - wait < timeout)) {
+    esp->process();
+  }
+  if(response){
+    RESPONSE resp(res);
+
+    resp.popArgs((uint8_t*)data, maxLen);
+    return esp->return_value;
+  }
+    
+  
+  return 0;
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/rest.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/rest.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/rest.h	(revision 175)
@@ -0,0 +1,57 @@
+/**
+ * \file
+ *       ESP8266 RESTful Bridge
+ * \author
+ *       Tuan PM <tuanpm@live.com>
+ */
+#ifndef _REST_H_
+#define _REST_H_
+
+#include <stdint.h>
+#include <Arduino.h>
+#include "FP.h"
+#include "espduino.h"
+
+#define DEFAULT_REST_TIMEOUT  7000
+
+typedef enum {
+  HEADER_GENERIC = 0,
+  HEADER_CONTENT_TYPE,
+  HEADER_USER_AGENT
+} HEADER_TYPE;
+
+typedef enum {
+  HTTP_STATUS_OK = 200
+} HTTP_STATUS;
+
+class REST {
+private:
+  uint32_t remote_instance, timeout;
+  ESP *esp;
+  void restCallback(void* resp);
+  FP<void, void*> restCb;
+  boolean response;
+  void *res;
+
+public:
+  
+  REST(ESP *e);
+  boolean begin(const char* host, uint16_t port, boolean security);
+  boolean begin(const char* host);
+  void request(const char* path, const char* method, const char* data);
+  void request(const char* path, const char* method, const char* data, int len);
+  void get(const char* path, const char* data);
+  void get(const char* path);
+  void post(const char* path, const char* data);
+  void put(const char* path, const char* data);
+  void del(const char* path, const char* data);
+
+ // void setTimeout(uint32_t ms);
+  uint16_t getResponse(char* data, uint16_t maxLen);
+ // void setUserAgent(const char* value);
+ // Set Content-Type Header
+ // void setContentType(const char* value);
+ // void setHeader(const char* value);
+
+};
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/ringbuf.c
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/ringbuf.c	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/ringbuf.c	(revision 175)
@@ -0,0 +1,67 @@
+/**
+* \file
+*		Ring Buffer library
+*/
+
+#include "ringbuf.h"
+
+
+/**
+* \brief init a RINGBUF object
+* \param r pointer to a RINGBUF object
+* \param buf pointer to a byte array
+* \param size size of buf
+* \return 0 if successfull, otherwise failed
+*/
+int16_t RINGBUF_Init(RINGBUF *r, uint8_t* buf, int32_t size)
+{
+	if(r == NULL || buf == NULL || size < 2) return -1;
+	
+	r->p_o = r->p_r = r->p_w = buf;
+	r->fill_cnt = 0;
+	r->size = size;
+	
+	return 0;
+}
+/**
+* \brief put a character into ring buffer
+* \param r pointer to a ringbuf object
+* \param c character to be put
+* \return 0 if successfull, otherwise failed
+*/
+int16_t RINGBUF_Put(RINGBUF *r, uint8_t c)
+{
+	if(r->fill_cnt>=r->size)return -1;		// ring buffer is full, this should be atomic operation
+	
+
+	r->fill_cnt++;							// increase filled slots count, this should be atomic operation
+
+	
+	*r->p_w++ = c;							// put character into buffer
+	
+	if(r->p_w >= r->p_o + r->size)			// rollback if write pointer go pass
+		r->p_w = r->p_o;					// the physical boundary
+	
+	return 0;
+}
+/**
+* \brief get a character from ring buffer
+* \param r pointer to a ringbuf object
+* \param c read character
+* \return 0 if successfull, otherwise failed
+*/
+int16_t RINGBUF_Get(RINGBUF *r, uint8_t* c)
+{
+	if(r->fill_cnt<=0)return -1;				// ring buffer is empty, this should be atomic operation
+	
+
+	r->fill_cnt--;								// decrease filled slots count
+
+	
+	*c = *r->p_r++;								// get the character out
+	
+	if(r->p_r >= r->p_o + r->size)				// rollback if write pointer go pass
+		r->p_r = r->p_o;						// the physical boundary
+	
+	return 0;
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/ringbuf.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/ringbuf.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Ciao/src/lib/ringbuf.h	(revision 175)
@@ -0,0 +1,25 @@
+#ifndef _RING_BUF_H_
+#define _RING_BUF_H_
+
+#include <stdint.h>
+#include <stdlib.h>
+#ifdef	__cplusplus
+extern "C" {
+#endif
+
+typedef struct{
+	uint8_t* p_o;				/**< Original pointer */
+	uint8_t* volatile p_r;		/**< Read pointer */
+	uint8_t* volatile p_w;		/**< Write pointer */
+	volatile int32_t fill_cnt;	/**< Number of filled slots */
+	int32_t size;				/**< Buffer size */
+}RINGBUF;
+
+int16_t RINGBUF_Init(RINGBUF *r, uint8_t* buf, int32_t size);
+int16_t RINGBUF_Put(RINGBUF *r, uint8_t c);
+int16_t RINGBUF_Get(RINGBUF *r, uint8_t* c);
+
+#ifdef	__cplusplus
+}
+#endif
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/README.md
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/README.md	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/README.md	(revision 175)
@@ -0,0 +1,2 @@
+# arduino-library-lucky-shield
+Arduino Lucky Shield Library
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/LuckyTest/LuckyTest.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/LuckyTest/LuckyTest.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/LuckyTest/LuckyTest.ino	(revision 175)
@@ -0,0 +1,109 @@
+/*
+test_lucky
+
+A simple Arduino sketch that reads data from the on-board sensors of the Lucky Shield and checks all gpios.
+It prints sensors data via the Serial Monitor.
+
+The following pin are defined in the Lucky Shield library and directly map the digitals
+of the Lucky Shield.
+
+created Mar 2016
+by  andrea@arduino.org,
+    sergio@arduino.org
+*/
+
+#include <Lucky.h>
+#include <Wire.h>
+
+
+//set the sea level pressure
+#define SEALEVELPRESSURE_HPA 1008
+
+void setup() {
+
+  lucky.begin();
+  Serial.begin(9600);
+  while(!Serial);
+}
+
+void loop() {
+
+  //print on the oled
+  lucky.oled().setTextSize(2);
+  lucky.oled().setTextColor(WHITE);
+  lucky.oled().setCursor(3,23);
+  lucky.oled().clearDisplay();
+  lucky.oled().print("Arduino");
+  lucky.oled().display();
+
+  //write gpio
+  lucky.gpio().digitalWrite(LED1,HIGH);
+  lucky.gpio().digitalWrite(REL1,HIGH);
+  lucky.gpio().digitalWrite(LED2,LOW);
+  lucky.gpio().digitalWrite(REL2,LOW);
+  delay(1000);
+  lucky.gpio().digitalWrite(LED2,HIGH);
+  lucky.gpio().digitalWrite(REL2,HIGH);
+  lucky.gpio().digitalWrite(LED1,LOW);
+  lucky.gpio().digitalWrite(REL1,LOW);
+  delay(1000);
+
+  //read gpios value
+  Serial.print("LED1: ");
+  Serial.print(lucky.gpio().digitalRead(LED1));
+  Serial.print(" LED2: ");
+  Serial.print(lucky.gpio().digitalRead(LED2));
+  Serial.print(" REL1: ");
+  Serial.print(lucky.gpio().digitalRead(REL1));
+  Serial.print(" REL2: ");
+  Serial.println(lucky.gpio().digitalRead(REL2));
+  Serial.print(" joy-D: ");
+  Serial.print(lucky.gpio().digitalRead(JOYD));
+  Serial.print(" joy-R: ");
+  Serial.print(lucky.gpio().digitalRead(JOYR));
+  Serial.print(" joy-L: ");
+  Serial.print(lucky.gpio().digitalRead(JOYL));
+  Serial.print("  joy-U: ");
+  Serial.print(lucky.gpio().digitalRead(JOYU));
+  Serial.print("  joy-C: ");
+  Serial.println(lucky.gpio().digitalRead(JOYC));
+
+  //read accelerometer sensor
+  lucky.accelerometer().read();
+  Serial.print("x: ");
+  Serial.print(lucky.accelerometer().x());
+  Serial.print("  y: ");
+  Serial.print(lucky.accelerometer().y());
+  Serial.print("  z: ");
+  Serial.println(lucky.accelerometer().z());
+
+  //read magnetometer sensor
+  Serial.print("Mx: ");
+  Serial.print(lucky.magnetometer().x());
+  Serial.print("  My: ");
+  Serial.print(lucky.magnetometer().y());
+  Serial.print("  Mz: ");
+  Serial.println(lucky.magnetometer().z());
+
+
+  //read environment sensor
+  Serial.print("Temperature = ");
+  Serial.print(lucky.environment().temperature());
+  Serial.println(" *C");
+  Serial.print("Pressure = ");
+  Serial.print(lucky.environment().pressure() / 100.0F);
+  Serial.println(" hPa");
+  Serial.print("Approx. Altitude = ");
+  Serial.print(lucky.environment().altitude(SEALEVELPRESSURE_HPA));
+  Serial.println(" m");
+  Serial.print("Humidity = ");
+  Serial.print(lucky.environment().humidity());
+  Serial.println(" %");
+
+  //clear oled
+  lucky.oled().clearDisplay();
+  lucky.oled().display();
+
+  delay(1000);
+
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/PresenceAlarm/PresenceAlarm.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/PresenceAlarm/PresenceAlarm.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/PresenceAlarm/PresenceAlarm.ino	(revision 175)
@@ -0,0 +1,59 @@
+/*
+Presence Alarm
+
+A simple Arduino sketch that play a sound with the on board buzzer when a presence is
+detected by the PIR
+
+The buzzer is directly connected on the digital pin 5
+
+The following pins are defined in the Lucky Shield library, they directly map the digitals
+of the Lucky Shield
+
+LED1: on board first LED
+LED2: on board second LED
+
+REL1: on board first Relay
+REL2: on board second Relay
+
+JOYR: on board Joystick - moved right
+JOYL: on board Joystick - moved left
+JOYU: on board Joystick - moved up
+JOYD: on board Joystick - moved down
+JOYC: on board Joystick - central pressed
+
+PIR: on board (Passive Infrared Sensor) Presence Sensor
+
+PB1: on board first Push Button
+PB2: on board second Push Button
+
+created Mar 2016
+by  andrea@arduino.org,
+    sergio@arduino.org
+*/
+
+#include <Lucky.h>
+#include <Wire.h>
+
+#define BUZ 5
+#define NOTE_1 220
+#define NOTE_2 300
+
+void setup() {
+
+  lucky.begin();
+
+}
+
+void loop() {
+
+  if(lucky.gpio().digitalRead(PIR) == LOW ){
+    for(int i = 0; i < 5; i++){
+      tone(BUZ, NOTE_2);
+      delay(500);
+      tone(BUZ, NOTE_1);
+      delay(500);
+    }
+    noTone(BUZ);
+  }
+
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/SimpleGPIO/SimpleGPIO.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/SimpleGPIO/SimpleGPIO.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/SimpleGPIO/SimpleGPIO.ino	(revision 175)
@@ -0,0 +1,62 @@
+/*
+Simple GPIO
+
+A simple Arduino sketch that turn off and on the onboard relais and leds of the Lucky Shield.
+When the joystick is moved on the left, led n1 and relay n1 are turned on,
+when the joystick is moved on the right, led n2 and relay n2 are turned off.
+
+The following pins are defined in the Lucky Shield library, they directly map the digitals
+of the Lucky Shield
+
+LED1: on board first LED
+LED2: on board second LED
+
+REL1: on board first Relay
+REL2: on board second Relay
+
+JOYR: on board Joystick - moved right
+JOYL: on board Joystick - moved left
+JOYU: on board Joystick - moved up
+JOYD: on board Joystick - moved down
+JOYC: on board Joystick - central pressed
+
+PIR: on board (Passive Infrared Sensor) Presence Sensor
+
+PB1: on board first Push Button
+PB2: on board second Push Button
+
+created Mar 2016
+by  andrea@arduino.org,
+    sergio@arduino.org
+*/
+
+#include <Lucky.h>
+#include <Wire.h>
+
+void setup() {
+  lucky.begin();
+
+}
+
+void loop() {
+
+  //Check if the the joystick is moved to the left
+  if(lucky.gpio().digitalRead(JOYL) == HIGH){
+    lucky.gpio().digitalWrite(LED1, HIGH);
+    lucky.gpio().digitalWrite(REL1, HIGH);
+  }
+  else {
+    lucky.gpio().digitalWrite(LED1, LOW);
+    lucky.gpio().digitalWrite(REL1, LOW);
+  }
+
+  //Check if the the joystick is moved to the right
+  if(lucky.gpio().digitalRead(JOYR) == HIGH){
+    lucky.gpio().digitalWrite(LED2, HIGH);
+    lucky.gpio().digitalWrite(REL2, HIGH);
+  }
+  else {
+    lucky.gpio().digitalWrite(LED2, LOW);
+    lucky.gpio().digitalWrite(REL2, LOW);
+  }
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/WeatherStation/WeatherStation.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/WeatherStation/WeatherStation.ino	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/examples/WeatherStation/WeatherStation.ino	(revision 175)
@@ -0,0 +1,57 @@
+/*
+Weather Station
+
+A simple Arduino sketch that reads values from temperature, humidity and pressure sensors
+of the Lucky Shield and display it in the OLED add-on (and also via Serial).
+
+created Mar 2016
+by  andrea@arduino.org,
+    sergio@arduino.org
+*/
+
+#include <Lucky.h>
+#include <Wire.h>
+
+String tmp_lbl, tmp_um, tmp_val, hum_lbl, hum_um, hum_val, pre_lbl, pre_um, pre_val;
+void setup() {
+  Serial.begin(9600);
+
+  lucky.begin();
+
+  //setup the Lucky OLED
+  lucky.oled().setTextSize(0.5);
+  lucky.oled().setTextColor(WHITE);
+  lucky.oled().clearDisplay();
+
+  tmp_lbl = "Temper.: ";
+  hum_lbl = "Humidity:";
+  pre_lbl = "Pressure:";
+
+  tmp_um = " C.";
+  hum_um = " %";
+  pre_um = " hPa";
+}
+
+void loop() {
+
+  lucky.oled().clearDisplay();
+
+  tmp_val = String(lucky.environment().temperature());
+  lucky.oled().setCursor(5, 10);
+  lucky.oled().print(tmp_lbl + tmp_val + tmp_um);
+  Serial.println(tmp_lbl + tmp_val + tmp_um);
+
+  hum_val = String(lucky.environment().humidity());
+  lucky.oled().setCursor(5, 30);
+  lucky.oled().print(hum_lbl + hum_val + hum_um);
+  Serial.println(hum_lbl + hum_val + hum_um);
+
+  pre_val = String(lucky.environment().pressure() / 100.0F);
+  lucky.oled().setCursor(5, 50);
+  lucky.oled().print(pre_lbl + pre_val + pre_um);
+  Serial.println(pre_lbl + pre_val + pre_um);
+
+  lucky.oled().display();
+
+  delay(1000);
+}
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/keywords.txt
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/keywords.txt	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/keywords.txt	(revision 175)
@@ -0,0 +1,36 @@
+#######################################
+# Syntax Coloring Map For Lucky Library
+#######################################
+
+#######################################
+# Class (KEYWORD3)
+#######################################
+Lucky	KEYWORD3
+lucky	KEYWORD3
+
+#######################################
+# Methods and Functions (KEYWORD2)
+#######################################
+
+accelerometer	KEYWORD2
+environment	KEYWORD2
+oled	KEYWORD2
+magnetometer	KEYWORD2
+gpio	KEYWORD2
+
+#######################################
+# Constants (LITERAL1)
+#######################################
+
+LED1	LITERAL1
+LED2	LITERAL1
+REL1	LITERAL1
+REL2	LITERAL1
+JOYD	LITERAL1
+JOYR	LITERAL1
+JOYL	LITERAL1
+JOYU	LITERAL1
+JOYC	LITERAL1
+PIR	LITERAL1
+PB1	LITERAL1
+PB2	LITERAL1
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/library.properties
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/library.properties	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/library.properties	(revision 175)
@@ -0,0 +1,9 @@
+name=Lucky Shield
+version=1.0.2
+author=Arduino srl
+maintainer=Arduino srl <swdev@arduino.org>
+sentence=Arduino library for Lucky Shield
+paragraph=Arduino library for Lucky Shield
+category=Sensors
+url=https://github.com/arduino-org/arduino-library-lucky-shield
+architectures=*
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/Lucky.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/Lucky.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/Lucky.h	(revision 175)
@@ -0,0 +1,72 @@
+/*
+****************************************************************************
+* This file is part of Arduino Lucky Shield Library
+*
+* Copyright (c) 2016 Arduino srl. All right reserved.
+*
+* File : Lucky.h
+* Date : 2016/03/21
+* Revision : 0.0.1 $
+* Author: andrea[at]arduino[dot]org
+*
+****************************************************************************
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+******************************************************************************/
+
+#ifndef Lucky_h
+#define Lucky_h
+
+#include "lib/CAT9555.h"
+#include "lib/MMA8491Q.h"
+#include "lib/MAG3110.h"
+#include "lib/BME280.h"
+#include "lib/Adafruit_GFX.h"
+#include "lib/Adafruit_SSD1306.h"
+#include <Arduino.h>
+#include "Wire.h"
+
+class Lucky
+{
+	public:
+		
+		void begin(){ 
+			Wire.begin();
+			cat9555.begin();
+			ssd1306.begin();
+			mag3110.begin();
+  			bme280.begin();
+		}	
+		MMA8491Q& accelerometer(){
+		 	return mma8491q;
+		}
+		MAG3110& magnetometer(){
+		 	return mag3110;
+		}
+		BME280& environment(){
+		 	return bme280;
+		}
+		CAT9555& gpio(){
+		 	return cat9555;
+		}
+		Adafruit_SSD1306& oled(){
+		 	return ssd1306;
+		}
+};
+
+extern Lucky lucky;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_GFX.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_GFX.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_GFX.cpp	(revision 175)
@@ -0,0 +1,615 @@
+/*
+This is the core graphics library for all our displays, providing a common
+set of graphics primitives (points, lines, circles, etc.).  It needs to be
+paired with a hardware-specific library for each display device we carry
+(to handle the lower-level functions).
+
+Adafruit invests time and resources providing this open source code, please
+support Adafruit & open-source hardware by purchasing products from Adafruit!
+ 
+Copyright (c) 2013 Adafruit Industries.  All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+- Redistributions of source code must retain the above copyright notice,
+  this list of conditions and the following disclaimer.
+- Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "Adafruit_GFX.h"
+#include "glcdfont.c"
+#ifdef __AVR__
+ #include <avr/pgmspace.h>
+#elif defined(ESP8266)
+ #include <pgmspace.h>
+#else
+ #define pgm_read_byte(addr) (*(const unsigned char *)(addr))
+#endif
+
+#ifndef min
+ #define min(a,b) ((a < b) ? a : b)
+#endif
+
+Adafruit_GFX::Adafruit_GFX(int16_t w, int16_t h):
+  WIDTH(w), HEIGHT(h)
+{
+  _width    = WIDTH;
+  _height   = HEIGHT;
+  rotation  = 0;
+  cursor_y  = cursor_x    = 0;
+  textsize  = 1;
+  textcolor = textbgcolor = 0xFFFF;
+  wrap      = true;
+  _cp437    = false;
+}
+
+// Draw a circle outline
+void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r,
+    uint16_t color) {
+  int16_t f = 1 - r;
+  int16_t ddF_x = 1;
+  int16_t ddF_y = -2 * r;
+  int16_t x = 0;
+  int16_t y = r;
+
+  drawPixel(x0  , y0+r, color);
+  drawPixel(x0  , y0-r, color);
+  drawPixel(x0+r, y0  , color);
+  drawPixel(x0-r, y0  , color);
+
+  while (x<y) {
+    if (f >= 0) {
+      y--;
+      ddF_y += 2;
+      f += ddF_y;
+    }
+    x++;
+    ddF_x += 2;
+    f += ddF_x;
+  
+    drawPixel(x0 + x, y0 + y, color);
+    drawPixel(x0 - x, y0 + y, color);
+    drawPixel(x0 + x, y0 - y, color);
+    drawPixel(x0 - x, y0 - y, color);
+    drawPixel(x0 + y, y0 + x, color);
+    drawPixel(x0 - y, y0 + x, color);
+    drawPixel(x0 + y, y0 - x, color);
+    drawPixel(x0 - y, y0 - x, color);
+  }
+}
+
+void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0,
+               int16_t r, uint8_t cornername, uint16_t color) {
+  int16_t f     = 1 - r;
+  int16_t ddF_x = 1;
+  int16_t ddF_y = -2 * r;
+  int16_t x     = 0;
+  int16_t y     = r;
+
+  while (x<y) {
+    if (f >= 0) {
+      y--;
+      ddF_y += 2;
+      f     += ddF_y;
+    }
+    x++;
+    ddF_x += 2;
+    f     += ddF_x;
+    if (cornername & 0x4) {
+      drawPixel(x0 + x, y0 + y, color);
+      drawPixel(x0 + y, y0 + x, color);
+    } 
+    if (cornername & 0x2) {
+      drawPixel(x0 + x, y0 - y, color);
+      drawPixel(x0 + y, y0 - x, color);
+    }
+    if (cornername & 0x8) {
+      drawPixel(x0 - y, y0 + x, color);
+      drawPixel(x0 - x, y0 + y, color);
+    }
+    if (cornername & 0x1) {
+      drawPixel(x0 - y, y0 - x, color);
+      drawPixel(x0 - x, y0 - y, color);
+    }
+  }
+}
+
+void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r,
+			      uint16_t color) {
+  drawFastVLine(x0, y0-r, 2*r+1, color);
+  fillCircleHelper(x0, y0, r, 3, 0, color);
+}
+
+// Used to do circles and roundrects
+void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r,
+    uint8_t cornername, int16_t delta, uint16_t color) {
+
+  int16_t f     = 1 - r;
+  int16_t ddF_x = 1;
+  int16_t ddF_y = -2 * r;
+  int16_t x     = 0;
+  int16_t y     = r;
+
+  while (x<y) {
+    if (f >= 0) {
+      y--;
+      ddF_y += 2;
+      f     += ddF_y;
+    }
+    x++;
+    ddF_x += 2;
+    f     += ddF_x;
+
+    if (cornername & 0x1) {
+      drawFastVLine(x0+x, y0-y, 2*y+1+delta, color);
+      drawFastVLine(x0+y, y0-x, 2*x+1+delta, color);
+    }
+    if (cornername & 0x2) {
+      drawFastVLine(x0-x, y0-y, 2*y+1+delta, color);
+      drawFastVLine(x0-y, y0-x, 2*x+1+delta, color);
+    }
+  }
+}
+
+// Bresenham's algorithm - thx wikpedia
+void Adafruit_GFX::drawLine(int16_t x0, int16_t y0,
+			    int16_t x1, int16_t y1,
+			    uint16_t color) {
+  int16_t steep = abs(y1 - y0) > abs(x1 - x0);
+  if (steep) {
+    swap(x0, y0);
+    swap(x1, y1);
+  }
+
+  if (x0 > x1) {
+    swap(x0, x1);
+    swap(y0, y1);
+  }
+
+  int16_t dx, dy;
+  dx = x1 - x0;
+  dy = abs(y1 - y0);
+
+  int16_t err = dx / 2;
+  int16_t ystep;
+
+  if (y0 < y1) {
+    ystep = 1;
+  } else {
+    ystep = -1;
+  }
+
+  for (; x0<=x1; x0++) {
+    if (steep) {
+      drawPixel(y0, x0, color);
+    } else {
+      drawPixel(x0, y0, color);
+    }
+    err -= dy;
+    if (err < 0) {
+      y0 += ystep;
+      err += dx;
+    }
+  }
+}
+
+// Draw a rectangle
+void Adafruit_GFX::drawRect(int16_t x, int16_t y,
+			    int16_t w, int16_t h,
+			    uint16_t color) {
+  drawFastHLine(x, y, w, color);
+  drawFastHLine(x, y+h-1, w, color);
+  drawFastVLine(x, y, h, color);
+  drawFastVLine(x+w-1, y, h, color);
+}
+
+void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y,
+				 int16_t h, uint16_t color) {
+  // Update in subclasses if desired!
+  drawLine(x, y, x, y+h-1, color);
+}
+
+void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y,
+				 int16_t w, uint16_t color) {
+  // Update in subclasses if desired!
+  drawLine(x, y, x+w-1, y, color);
+}
+
+void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h,
+			    uint16_t color) {
+  // Update in subclasses if desired!
+  for (int16_t i=x; i<x+w; i++) {
+    drawFastVLine(i, y, h, color);
+  }
+}
+
+void Adafruit_GFX::fillScreen(uint16_t color) {
+  fillRect(0, 0, _width, _height, color);
+}
+
+// Draw a rounded rectangle
+void Adafruit_GFX::drawRoundRect(int16_t x, int16_t y, int16_t w,
+  int16_t h, int16_t r, uint16_t color) {
+  // smarter version
+  drawFastHLine(x+r  , y    , w-2*r, color); // Top
+  drawFastHLine(x+r  , y+h-1, w-2*r, color); // Bottom
+  drawFastVLine(x    , y+r  , h-2*r, color); // Left
+  drawFastVLine(x+w-1, y+r  , h-2*r, color); // Right
+  // draw four corners
+  drawCircleHelper(x+r    , y+r    , r, 1, color);
+  drawCircleHelper(x+w-r-1, y+r    , r, 2, color);
+  drawCircleHelper(x+w-r-1, y+h-r-1, r, 4, color);
+  drawCircleHelper(x+r    , y+h-r-1, r, 8, color);
+}
+
+// Fill a rounded rectangle
+void Adafruit_GFX::fillRoundRect(int16_t x, int16_t y, int16_t w,
+				 int16_t h, int16_t r, uint16_t color) {
+  // smarter version
+  fillRect(x+r, y, w-2*r, h, color);
+
+  // draw four corners
+  fillCircleHelper(x+w-r-1, y+r, r, 1, h-2*r-1, color);
+  fillCircleHelper(x+r    , y+r, r, 2, h-2*r-1, color);
+}
+
+// Draw a triangle
+void Adafruit_GFX::drawTriangle(int16_t x0, int16_t y0,
+				int16_t x1, int16_t y1,
+				int16_t x2, int16_t y2, uint16_t color) {
+  drawLine(x0, y0, x1, y1, color);
+  drawLine(x1, y1, x2, y2, color);
+  drawLine(x2, y2, x0, y0, color);
+}
+
+// Fill a triangle
+void Adafruit_GFX::fillTriangle ( int16_t x0, int16_t y0,
+				  int16_t x1, int16_t y1,
+				  int16_t x2, int16_t y2, uint16_t color) {
+
+  int16_t a, b, y, last;
+
+  // Sort coordinates by Y order (y2 >= y1 >= y0)
+  if (y0 > y1) {
+    swap(y0, y1); swap(x0, x1);
+  }
+  if (y1 > y2) {
+    swap(y2, y1); swap(x2, x1);
+  }
+  if (y0 > y1) {
+    swap(y0, y1); swap(x0, x1);
+  }
+
+  if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing
+    a = b = x0;
+    if(x1 < a)      a = x1;
+    else if(x1 > b) b = x1;
+    if(x2 < a)      a = x2;
+    else if(x2 > b) b = x2;
+    drawFastHLine(a, y0, b-a+1, color);
+    return;
+  }
+
+  int16_t
+    dx01 = x1 - x0,
+    dy01 = y1 - y0,
+    dx02 = x2 - x0,
+    dy02 = y2 - y0,
+    dx12 = x2 - x1,
+    dy12 = y2 - y1;
+  int32_t
+    sa   = 0,
+    sb   = 0;
+
+  // For upper part of triangle, find scanline crossings for segments
+  // 0-1 and 0-2.  If y1=y2 (flat-bottomed triangle), the scanline y1
+  // is included here (and second loop will be skipped, avoiding a /0
+  // error there), otherwise scanline y1 is skipped here and handled
+  // in the second loop...which also avoids a /0 error here if y0=y1
+  // (flat-topped triangle).
+  if(y1 == y2) last = y1;   // Include y1 scanline
+  else         last = y1-1; // Skip it
+
+  for(y=y0; y<=last; y++) {
+    a   = x0 + sa / dy01;
+    b   = x0 + sb / dy02;
+    sa += dx01;
+    sb += dx02;
+    /* longhand:
+    a = x0 + (x1 - x0) * (y - y0) / (y1 - y0);
+    b = x0 + (x2 - x0) * (y - y0) / (y2 - y0);
+    */
+    if(a > b) swap(a,b);
+    drawFastHLine(a, y, b-a+1, color);
+  }
+
+  // For lower part of triangle, find scanline crossings for segments
+  // 0-2 and 1-2.  This loop is skipped if y1=y2.
+  sa = dx12 * (y - y1);
+  sb = dx02 * (y - y0);
+  for(; y<=y2; y++) {
+    a   = x1 + sa / dy12;
+    b   = x0 + sb / dy02;
+    sa += dx12;
+    sb += dx02;
+    /* longhand:
+    a = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
+    b = x0 + (x2 - x0) * (y - y0) / (y2 - y0);
+    */
+    if(a > b) swap(a,b);
+    drawFastHLine(a, y, b-a+1, color);
+  }
+}
+
+void Adafruit_GFX::drawBitmap(int16_t x, int16_t y,
+			      const uint8_t *bitmap, int16_t w, int16_t h,
+			      uint16_t color) {
+
+  int16_t i, j, byteWidth = (w + 7) / 8;
+
+  for(j=0; j<h; j++) {
+    for(i=0; i<w; i++ ) {
+      if(pgm_read_byte(bitmap + j * byteWidth + i / 8) & (128 >> (i & 7))) {
+        drawPixel(x+i, y+j, color);
+      }
+    }
+  }
+}
+
+// Draw a 1-bit color bitmap at the specified x, y position from the
+// provided bitmap buffer (must be PROGMEM memory) using color as the
+// foreground color and bg as the background color.
+void Adafruit_GFX::drawBitmap(int16_t x, int16_t y,
+            const uint8_t *bitmap, int16_t w, int16_t h,
+            uint16_t color, uint16_t bg) {
+
+  int16_t i, j, byteWidth = (w + 7) / 8;
+  
+  for(j=0; j<h; j++) {
+    for(i=0; i<w; i++ ) {
+      if(pgm_read_byte(bitmap + j * byteWidth + i / 8) & (128 >> (i & 7))) {
+        drawPixel(x+i, y+j, color);
+      }
+      else {
+      	drawPixel(x+i, y+j, bg);
+      }
+    }
+  }
+}
+
+//Draw XBitMap Files (*.xbm), exported from GIMP,
+//Usage: Export from GIMP to *.xbm, rename *.xbm to *.c and open in editor.
+//C Array can be directly used with this function
+void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
+                              const uint8_t *bitmap, int16_t w, int16_t h,
+                              uint16_t color) {
+  
+  int16_t i, j, byteWidth = (w + 7) / 8;
+  
+  for(j=0; j<h; j++) {
+    for(i=0; i<w; i++ ) {
+      if(pgm_read_byte(bitmap + j * byteWidth + i / 8) & (1 << (i % 8))) {
+        drawPixel(x+i, y+j, color);
+      }
+    }
+  }
+}
+
+#if ARDUINO >= 100
+size_t Adafruit_GFX::write(uint8_t c) {
+#else
+void Adafruit_GFX::write(uint8_t c) {
+#endif
+  if (c == '\n') {
+    cursor_y += textsize*8;
+    cursor_x  = 0;
+  } else if (c == '\r') {
+    // skip em
+  } else {
+    drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize);
+    cursor_x += textsize*6;
+    if (wrap && (cursor_x > (_width - textsize*6))) {
+      cursor_y += textsize*8;
+      cursor_x = 0;
+    }
+  }
+#if ARDUINO >= 100
+  return 1;
+#endif
+}
+
+// Draw a character
+void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c,
+			    uint16_t color, uint16_t bg, uint8_t size) {
+
+  if((x >= _width)            || // Clip right
+     (y >= _height)           || // Clip bottom
+     ((x + 6 * size - 1) < 0) || // Clip left
+     ((y + 8 * size - 1) < 0))   // Clip top
+    return;
+
+  if(!_cp437 && (c >= 176)) c++; // Handle 'classic' charset behavior
+
+  for (int8_t i=0; i<6; i++ ) {
+    uint8_t line;
+    if (i == 5) 
+      line = 0x0;
+    else 
+      line = pgm_read_byte(font+(c*5)+i);
+    for (int8_t j = 0; j<8; j++) {
+      if (line & 0x1) {
+        if (size == 1) // default size
+          drawPixel(x+i, y+j, color);
+        else {  // big size
+          fillRect(x+(i*size), y+(j*size), size, size, color);
+        } 
+      } else if (bg != color) {
+        if (size == 1) // default size
+          drawPixel(x+i, y+j, bg);
+        else {  // big size
+          fillRect(x+i*size, y+j*size, size, size, bg);
+        }
+      }
+      line >>= 1;
+    }
+  }
+}
+
+void Adafruit_GFX::setCursor(int16_t x, int16_t y) {
+  cursor_x = x;
+  cursor_y = y;
+}
+
+int16_t Adafruit_GFX::getCursorX(void) const {
+  return cursor_x;
+}
+
+int16_t Adafruit_GFX::getCursorY(void) const {
+  return cursor_y;
+}
+
+void Adafruit_GFX::setTextSize(uint8_t s) {
+  textsize = (s > 0) ? s : 1;
+}
+
+void Adafruit_GFX::setTextColor(uint16_t c) {
+  // For 'transparent' background, we'll set the bg 
+  // to the same as fg instead of using a flag
+  textcolor = textbgcolor = c;
+}
+
+void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) {
+  textcolor   = c;
+  textbgcolor = b; 
+}
+
+void Adafruit_GFX::setTextWrap(boolean w) {
+  wrap = w;
+}
+
+uint8_t Adafruit_GFX::getRotation(void) const {
+  return rotation;
+}
+
+void Adafruit_GFX::setRotation(uint8_t x) {
+  rotation = (x & 3);
+  switch(rotation) {
+   case 0:
+   case 2:
+    _width  = WIDTH;
+    _height = HEIGHT;
+    break;
+   case 1:
+   case 3:
+    _width  = HEIGHT;
+    _height = WIDTH;
+    break;
+  }
+}
+
+// Enable (or disable) Code Page 437-compatible charset.
+// There was an error in glcdfont.c for the longest time -- one character
+// (#176, the 'light shade' block) was missing -- this threw off the index
+// of every character that followed it.  But a TON of code has been written
+// with the erroneous character indices.  By default, the library uses the
+// original 'wrong' behavior and old sketches will still work.  Pass 'true'
+// to this function to use correct CP437 character values in your code.
+void Adafruit_GFX::cp437(boolean x) {
+  _cp437 = x;
+}
+
+// Return the size of the display (per current rotation)
+int16_t Adafruit_GFX::width(void) const {
+  return _width;
+}
+ 
+int16_t Adafruit_GFX::height(void) const {
+  return _height;
+}
+
+void Adafruit_GFX::invertDisplay(boolean i) {
+  // Do nothing, must be subclassed if supported
+}
+
+/***************************************************************************/
+// code for the GFX button UI element
+
+Adafruit_GFX_Button::Adafruit_GFX_Button(void) {
+   _gfx = 0;
+}
+
+void Adafruit_GFX_Button::initButton(Adafruit_GFX *gfx,
+					  int16_t x, int16_t y, 
+					  uint8_t w, uint8_t h, 
+					  uint16_t outline, uint16_t fill, 
+					  uint16_t textcolor,
+					  char *label, uint8_t textsize)
+{
+  _x = x;
+  _y = y;
+  _w = w;
+  _h = h;
+  _outlinecolor = outline;
+  _fillcolor = fill;
+  _textcolor = textcolor;
+  _textsize = textsize;
+  _gfx = gfx;
+  strncpy(_label, label, 9);
+  _label[9] = 0;
+}
+
+ 
+
+ void Adafruit_GFX_Button::drawButton(boolean inverted) {
+   uint16_t fill, outline, text;
+
+   if (! inverted) {
+     fill = _fillcolor;
+     outline = _outlinecolor;
+     text = _textcolor;
+   } else {
+     fill =  _textcolor;
+     outline = _outlinecolor;
+     text = _fillcolor;
+   }
+
+   _gfx->fillRoundRect(_x - (_w/2), _y - (_h/2), _w, _h, min(_w,_h)/4, fill);
+   _gfx->drawRoundRect(_x - (_w/2), _y - (_h/2), _w, _h, min(_w,_h)/4, outline);
+   
+   
+   _gfx->setCursor(_x - strlen(_label)*3*_textsize, _y-4*_textsize);
+   _gfx->setTextColor(text);
+   _gfx->setTextSize(_textsize);
+   _gfx->print(_label);
+ }
+
+boolean Adafruit_GFX_Button::contains(int16_t x, int16_t y) {
+   if ((x < (_x - _w/2)) || (x > (_x + _w/2))) return false;
+   if ((y < (_y - _h/2)) || (y > (_y + _h/2))) return false;
+   return true;
+ }
+
+
+ void Adafruit_GFX_Button::press(boolean p) {
+   laststate = currstate;
+   currstate = p;
+ }
+ 
+ boolean Adafruit_GFX_Button::isPressed() { return currstate; }
+ boolean Adafruit_GFX_Button::justPressed() { return (currstate && !laststate); }
+ boolean Adafruit_GFX_Button::justReleased() { return (!currstate && laststate); }
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_GFX.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_GFX.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_GFX.h	(revision 175)
@@ -0,0 +1,124 @@
+#ifndef _ADAFRUIT_GFX_H
+#define _ADAFRUIT_GFX_H
+
+#if ARDUINO >= 100
+ #include "Arduino.h"
+ #include "Print.h"
+#else
+ #include "WProgram.h"
+#endif
+
+#define swap(a, b) { int16_t t = a; a = b; b = t; }
+
+class Adafruit_GFX : public Print {
+
+ public:
+
+  Adafruit_GFX(int16_t w, int16_t h); // Constructor
+
+  // This MUST be defined by the subclass:
+  virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0;
+
+  // These MAY be overridden by the subclass to provide device-specific
+  // optimized code.  Otherwise 'generic' versions are used.
+  virtual void
+    drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color),
+    drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color),
+    drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color),
+    drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color),
+    fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color),
+    fillScreen(uint16_t color),
+    invertDisplay(boolean i);
+
+  // These exist only with Adafruit_GFX (no subclass overrides)
+  void
+    drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color),
+    drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername,
+      uint16_t color),
+    fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color),
+    fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername,
+      int16_t delta, uint16_t color),
+    drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1,
+      int16_t x2, int16_t y2, uint16_t color),
+    fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1,
+      int16_t x2, int16_t y2, uint16_t color),
+    drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h,
+      int16_t radius, uint16_t color),
+    fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h,
+      int16_t radius, uint16_t color),
+    drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
+      int16_t w, int16_t h, uint16_t color),
+    drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
+      int16_t w, int16_t h, uint16_t color, uint16_t bg),
+    drawXBitmap(int16_t x, int16_t y, const uint8_t *bitmap, 
+      int16_t w, int16_t h, uint16_t color),
+    drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color,
+      uint16_t bg, uint8_t size),
+    setCursor(int16_t x, int16_t y),
+    setTextColor(uint16_t c),
+    setTextColor(uint16_t c, uint16_t bg),
+    setTextSize(uint8_t s),
+    setTextWrap(boolean w),
+    setRotation(uint8_t r),
+    cp437(boolean x=true);
+
+#if ARDUINO >= 100
+  virtual size_t write(uint8_t);
+#else
+  virtual void   write(uint8_t);
+#endif
+
+  int16_t height(void) const;
+  int16_t width(void) const;
+
+  uint8_t getRotation(void) const;
+
+  // get current cursor position (get rotation safe maximum values, using: width() for x, height() for y)
+  int16_t getCursorX(void) const;
+  int16_t getCursorY(void) const;
+
+ protected:
+  const int16_t
+    WIDTH, HEIGHT;   // This is the 'raw' display w/h - never changes
+  int16_t
+    _width, _height, // Display w/h as modified by current rotation
+    cursor_x, cursor_y;
+  uint16_t
+    textcolor, textbgcolor;
+  uint8_t
+    textsize,
+    rotation;
+  boolean
+    wrap,   // If set, 'wrap' text at right edge of display
+    _cp437; // If set, use correct CP437 charset (default is off)
+};
+
+class Adafruit_GFX_Button {
+
+ public:
+  Adafruit_GFX_Button(void);
+  void initButton(Adafruit_GFX *gfx, int16_t x, int16_t y, 
+		      uint8_t w, uint8_t h, 
+		      uint16_t outline, uint16_t fill, uint16_t textcolor,
+		      char *label, uint8_t textsize);
+  void drawButton(boolean inverted = false);
+  boolean contains(int16_t x, int16_t y);
+
+  void press(boolean p);
+  boolean isPressed();
+  boolean justPressed();
+  boolean justReleased();
+  Adafruit_GFX *_gfx;
+
+ private:
+  //Adafruit_GFX *_gfx;
+  int16_t _x, _y;
+  uint16_t _w, _h;
+  uint8_t _textsize;
+  uint16_t _outlinecolor, _fillcolor, _textcolor;
+  char _label[10];
+
+  boolean currstate, laststate;
+};
+
+#endif // _ADAFRUIT_GFX_H
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.cpp	(revision 175)
@@ -0,0 +1,688 @@
+/*********************************************************************
+This is a library for our Monochrome OLEDs based on SSD1306 drivers
+
+  Pick one up today in the adafruit shop!
+  ------> http://www.adafruit.com/category/63_98
+
+These displays use SPI to communicate, 4 or 5 pins are required to  
+interface
+
+Adafruit invests time and resources providing this open source code, 
+please support Adafruit and open-source hardware by purchasing 
+products from Adafruit!
+
+Written by Limor Fried/Ladyada  for Adafruit Industries.  
+BSD license, check license.txt for more information
+All text above, and the splash screen below must be included in any redistribution
+
+ - 21 Mar. 2016
+ Library modified to work with Arduino Lucky Shield
+ by andrea[at]arduino[dot]org
+*********************************************************************/
+
+#include <avr/pgmspace.h>
+#if !defined __SAM3X8E__ && !defined ARDUINO_ARCH_SAMD
+#include <util/delay.h>
+#endif
+#include <stdlib.h>
+
+#include <Wire.h>
+
+#include "Adafruit_GFX.h"
+#include "Adafruit_SSD1306.h"
+
+// the memory buffer for the LCD
+
+static uint8_t buffer[SSD1306_LCDHEIGHT * SSD1306_LCDWIDTH / 8] = { 
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
+0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x80, 0x80, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xF8, 0xE0, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80,
+0x80, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0xFF,
+#if (SSD1306_LCDHEIGHT * SSD1306_LCDWIDTH > 96*16)
+0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x00, 0x00,
+0x80, 0xFF, 0xFF, 0x80, 0x80, 0x00, 0x80, 0x80, 0x00, 0x80, 0x80, 0x80, 0x80, 0x00, 0x80, 0x80,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x00, 0x8C, 0x8E, 0x84, 0x00, 0x00, 0x80, 0xF8,
+0xF8, 0xF8, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xE0, 0xE0, 0xC0, 0x80,
+0x00, 0xE0, 0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xC7, 0x01, 0x01,
+0x01, 0x01, 0x83, 0xFF, 0xFF, 0x00, 0x00, 0x7C, 0xFE, 0xC7, 0x01, 0x01, 0x01, 0x01, 0x83, 0xFF,
+0xFF, 0xFF, 0x00, 0x38, 0xFE, 0xC7, 0x83, 0x01, 0x01, 0x01, 0x83, 0xC7, 0xFF, 0xFF, 0x00, 0x00,
+0x01, 0xFF, 0xFF, 0x01, 0x01, 0x00, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x00, 0x00, 0x7F, 0xFF,
+0x80, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF,
+0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x03, 0x0F, 0x3F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC7, 0xC7, 0x8F,
+0x8F, 0x9F, 0xBF, 0xFF, 0xFF, 0xC3, 0xC0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xFC, 0xFC,
+0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xF8, 0xF8, 0xF0, 0xF0, 0xE0, 0xC0, 0x00, 0x01, 0x03, 0x03, 0x03,
+0x03, 0x03, 0x01, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x03, 0x03, 0x01, 0x01,
+0x03, 0x01, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x03, 0x03, 0x01, 0x01, 0x03, 0x03, 0x00, 0x00,
+0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+0x03, 0x03, 0x03, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00, 0x01, 0x03, 0x01, 0x00, 0x00, 0x00, 0x03,
+0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+#if (SSD1306_LCDHEIGHT == 64)
+0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x1F, 0x0F,
+0x87, 0xC7, 0xF7, 0xFF, 0xFF, 0x1F, 0x1F, 0x3D, 0xFC, 0xF8, 0xF8, 0xF8, 0xF8, 0x7C, 0x7D, 0xFF,
+0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3F, 0x0F, 0x07, 0x00, 0x30, 0x30, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xC0, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0xC0, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x7F, 0x3F, 0x1F,
+0x0F, 0x07, 0x1F, 0x7F, 0xFF, 0xFF, 0xF8, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xF8, 0xE0,
+0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00,
+0x00, 0xFC, 0xFE, 0xFC, 0x0C, 0x06, 0x06, 0x0E, 0xFC, 0xF8, 0x00, 0x00, 0xF0, 0xF8, 0x1C, 0x0E,
+0x06, 0x06, 0x06, 0x0C, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0xFC,
+0xFE, 0xFC, 0x00, 0x18, 0x3C, 0x7E, 0x66, 0xE6, 0xCE, 0x84, 0x00, 0x00, 0x06, 0xFF, 0xFF, 0x06,
+0x06, 0xFC, 0xFE, 0xFC, 0x0C, 0x06, 0x06, 0x06, 0x00, 0x00, 0xFE, 0xFE, 0x00, 0x00, 0xC0, 0xF8,
+0xFC, 0x4E, 0x46, 0x46, 0x46, 0x4E, 0x7C, 0x78, 0x40, 0x18, 0x3C, 0x76, 0xE6, 0xCE, 0xCC, 0x80,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x0F, 0x1F, 0x1F, 0x3F, 0x3F, 0x3F, 0x3F, 0x1F, 0x0F, 0x03,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x00, 0x00,
+0x00, 0x0F, 0x0F, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x00, 0x00, 0x03, 0x07, 0x0E, 0x0C,
+0x18, 0x18, 0x0C, 0x06, 0x0F, 0x0F, 0x0F, 0x00, 0x00, 0x01, 0x0F, 0x0E, 0x0C, 0x18, 0x0C, 0x0F,
+0x07, 0x01, 0x00, 0x04, 0x0E, 0x0C, 0x18, 0x0C, 0x0F, 0x07, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x00,
+0x00, 0x0F, 0x0F, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x00, 0x00, 0x00, 0x07,
+0x07, 0x0C, 0x0C, 0x18, 0x1C, 0x0C, 0x06, 0x06, 0x00, 0x04, 0x0E, 0x0C, 0x18, 0x0C, 0x0F, 0x07,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+#endif
+#endif
+};
+
+#define ssd1306_swap(a, b) { int16_t t = a; a = b; b = t; }
+
+// the most basic function, set a single pixel
+void Adafruit_SSD1306::drawPixel(int16_t x, int16_t y, uint16_t color) {
+  if ((x < 0) || (x >= width()) || (y < 0) || (y >= height()))
+    return;
+
+  // check rotation, move pixel around if necessary
+  switch (getRotation()) {
+  case 1:
+    ssd1306_swap(x, y);
+    x = WIDTH - x - 1;
+    break;
+  case 2:
+    x = WIDTH - x - 1;
+    y = HEIGHT - y - 1;
+    break;
+  case 3:
+    ssd1306_swap(x, y);
+    y = HEIGHT - y - 1;
+    break;
+  }  
+
+  // x is which column
+    switch (color) 
+    {
+      case WHITE:   buffer[x+ (y/8)*SSD1306_LCDWIDTH] |=  (1 << (y&7)); break;
+      case BLACK:   buffer[x+ (y/8)*SSD1306_LCDWIDTH] &= ~(1 << (y&7)); break; 
+      case INVERSE: buffer[x+ (y/8)*SSD1306_LCDWIDTH] ^=  (1 << (y&7)); break; 
+    }
+    
+}
+
+// Adafruit_SSD1306::Adafruit_SSD1306(int8_t SID, int8_t SCLK, int8_t DC, int8_t RST, int8_t CS) : Adafruit_GFX(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT) {
+//   cs = CS;
+//   rst = RST;
+//   dc = DC;
+//   sclk = SCLK;
+//   sid = SID;
+//   hwSPI = false;
+// }
+
+// constructor for hardware SPI - we indicate DataCommand, ChipSelect, Reset 
+// Adafruit_SSD1306::Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS) : Adafruit_GFX(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT) {
+//   dc = DC;
+//   rst = RST;
+//   cs = CS;
+//   hwSPI = true;
+// }
+
+// initializer for I2C - we only indicate the reset pin!
+Adafruit_SSD1306::Adafruit_SSD1306() :
+Adafruit_GFX(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT) {
+  //sclk = dc = cs = sid = -1;
+  //rst = 4;
+}
+  
+
+void Adafruit_SSD1306::begin() {
+  _vccstate = SSD1306_SWITCHCAPVCC;
+  _i2caddr = 0X3C;
+
+#ifdef __SAM3X8E__
+    // Force 400 KHz I2C, rawr! (Uses pins 20, 21 for SDA, SCL)
+    TWI1->TWI_CWGR = 0;
+    TWI1->TWI_CWGR = ((VARIANT_MCK / (2 * 400000)) - 4) * 0x101;
+#endif
+  //}
+
+  //if (reset) {
+    // Setup reset pin direction (used by both SPI and I2C)  
+    // pinMode(rst, OUTPUT);
+    // digitalWrite(rst, HIGH);
+    // // VDD (3.3V) goes high at start, lets just chill for a ms
+    // delay(1);
+    // // bring reset low
+    // digitalWrite(rst, LOW);
+    // // wait 10ms
+    // delay(10);
+    // // bring out of reset
+    // digitalWrite(rst, HIGH);
+    // turn on VCC (9V?)
+    Wire.beginTransmission(0x20);  // setup out direction registers
+    Wire.write(0x03);  // pointer
+    Wire.write(128);  // DDR Port0 bits 0-3 input 4-7 output
+    Wire.endTransmission();
+ // }
+
+   #if defined SSD1306_128_32
+    // Init sequence for 128x32 OLED module
+    ssd1306_command(SSD1306_DISPLAYOFF);                    // 0xAE
+    ssd1306_command(SSD1306_SETDISPLAYCLOCKDIV);            // 0xD5
+    ssd1306_command(0x80);                                  // the suggested ratio 0x80
+    ssd1306_command(SSD1306_SETMULTIPLEX);                  // 0xA8
+    ssd1306_command(0x1F);
+    ssd1306_command(SSD1306_SETDISPLAYOFFSET);              // 0xD3
+    ssd1306_command(0x0);                                   // no offset
+    ssd1306_command(SSD1306_SETSTARTLINE | 0x0);            // line #0
+    ssd1306_command(SSD1306_CHARGEPUMP);                    // 0x8D
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x10); }
+    else 
+      { ssd1306_command(0x14); }
+    ssd1306_command(SSD1306_MEMORYMODE);                    // 0x20
+    ssd1306_command(0x00);                                  // 0x0 act like ks0108
+    ssd1306_command(SSD1306_SEGREMAP | 0x1);
+    ssd1306_command(SSD1306_COMSCANDEC);
+    ssd1306_command(SSD1306_SETCOMPINS);                    // 0xDA
+    ssd1306_command(0x02);
+    ssd1306_command(SSD1306_SETCONTRAST);                   // 0x81
+    ssd1306_command(0x8F);
+    ssd1306_command(SSD1306_SETPRECHARGE);                  // 0xd9
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x22); }
+    else 
+      { ssd1306_command(0xF1); }
+    ssd1306_command(SSD1306_SETVCOMDETECT);                 // 0xDB
+    ssd1306_command(0x40);
+    ssd1306_command(SSD1306_DISPLAYALLON_RESUME);           // 0xA4
+    ssd1306_command(SSD1306_NORMALDISPLAY);                 // 0xA6
+  #endif
+
+  #if defined SSD1306_128_64
+    // Init sequence for 128x64 OLED module
+    ssd1306_command(SSD1306_DISPLAYOFF);                    // 0xAE
+    ssd1306_command(SSD1306_SETDISPLAYCLOCKDIV);            // 0xD5
+    ssd1306_command(0x80);                                  // the suggested ratio 0x80
+    ssd1306_command(SSD1306_SETMULTIPLEX);                  // 0xA8
+    ssd1306_command(0x3F);
+    ssd1306_command(SSD1306_SETDISPLAYOFFSET);              // 0xD3
+    ssd1306_command(0x0);                                   // no offset
+    ssd1306_command(SSD1306_SETSTARTLINE | 0x0);            // line #0
+    ssd1306_command(SSD1306_CHARGEPUMP);                    // 0x8D
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x10); }
+    else 
+      { ssd1306_command(0x14); }
+    ssd1306_command(SSD1306_MEMORYMODE);                    // 0x20
+    ssd1306_command(0x00);                                  // 0x0 act like ks0108
+    ssd1306_command(SSD1306_SEGREMAP | 0x1);
+    ssd1306_command(SSD1306_COMSCANDEC);
+    ssd1306_command(SSD1306_SETCOMPINS);                    // 0xDA
+    ssd1306_command(0x12);
+    ssd1306_command(SSD1306_SETCONTRAST);                   // 0x81
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x9F); }
+    else 
+      { ssd1306_command(0xCF); }
+    ssd1306_command(SSD1306_SETPRECHARGE);                  // 0xd9
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x22); }
+    else 
+      { ssd1306_command(0xF1); }
+    ssd1306_command(SSD1306_SETVCOMDETECT);                 // 0xDB
+    ssd1306_command(0x40);
+    ssd1306_command(SSD1306_DISPLAYALLON_RESUME);           // 0xA4
+    ssd1306_command(SSD1306_NORMALDISPLAY);                 // 0xA6
+  #endif
+
+  #if defined SSD1306_96_16
+    // Init sequence for 96x16 OLED module
+    ssd1306_command(SSD1306_DISPLAYOFF);                    // 0xAE
+    ssd1306_command(SSD1306_SETDISPLAYCLOCKDIV);            // 0xD5
+    ssd1306_command(0x80);                                  // the suggested ratio 0x80
+    ssd1306_command(SSD1306_SETMULTIPLEX);                  // 0xA8
+    ssd1306_command(0x0F);
+    ssd1306_command(SSD1306_SETDISPLAYOFFSET);              // 0xD3
+    ssd1306_command(0x00);                                   // no offset
+    ssd1306_command(SSD1306_SETSTARTLINE | 0x0);            // line #0
+    ssd1306_command(SSD1306_CHARGEPUMP);                    // 0x8D
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x10); }
+    else 
+      { ssd1306_command(0x14); }
+    ssd1306_command(SSD1306_MEMORYMODE);                    // 0x20
+    ssd1306_command(0x00);                                  // 0x0 act like ks0108
+    ssd1306_command(SSD1306_SEGREMAP | 0x1);
+    ssd1306_command(SSD1306_COMSCANDEC);
+    ssd1306_command(SSD1306_SETCOMPINS);                    // 0xDA
+    ssd1306_command(0x2);	//ada x12
+    ssd1306_command(SSD1306_SETCONTRAST);                   // 0x81
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x10); }
+    else 
+      { ssd1306_command(0xAF); }
+    ssd1306_command(SSD1306_SETPRECHARGE);                  // 0xd9
+    if (_vccstate == SSD1306_EXTERNALVCC) 
+      { ssd1306_command(0x22); }
+    else 
+      { ssd1306_command(0xF1); }
+    ssd1306_command(SSD1306_SETVCOMDETECT);                 // 0xDB
+    ssd1306_command(0x40);
+    ssd1306_command(SSD1306_DISPLAYALLON_RESUME);           // 0xA4
+    ssd1306_command(SSD1306_NORMALDISPLAY);                 // 0xA6
+  #endif
+
+  ssd1306_command(SSD1306_DISPLAYON);//--turn on oled panel
+}
+
+
+void Adafruit_SSD1306::invertDisplay(uint8_t i) {
+  if (i) {
+    ssd1306_command(SSD1306_INVERTDISPLAY);
+  } else {
+    ssd1306_command(SSD1306_NORMALDISPLAY);
+  }
+}
+
+void Adafruit_SSD1306::ssd1306_command(uint8_t c) { 
+
+    uint8_t control = 0x00;   // Co = 0, D/C = 0
+    Wire.beginTransmission(_i2caddr);
+    WIRE_WRITE(control);
+    WIRE_WRITE(c);
+    Wire.endTransmission();
+
+}
+
+// startscrollright
+// Activate a right handed scroll for rows start through stop
+// Hint, the display is 16 rows tall. To scroll the whole display, run:
+// display.scrollright(0x00, 0x0F) 
+void Adafruit_SSD1306::startscrollright(uint8_t start, uint8_t stop){
+  ssd1306_command(SSD1306_RIGHT_HORIZONTAL_SCROLL);
+  ssd1306_command(0X00);
+  ssd1306_command(start);
+  ssd1306_command(0X00);
+  ssd1306_command(stop);
+  ssd1306_command(0X00);
+  ssd1306_command(0XFF);
+  ssd1306_command(SSD1306_ACTIVATE_SCROLL);
+}
+
+// startscrollleft
+// Activate a right handed scroll for rows start through stop
+// Hint, the display is 16 rows tall. To scroll the whole display, run:
+// display.scrollright(0x00, 0x0F) 
+void Adafruit_SSD1306::startscrollleft(uint8_t start, uint8_t stop){
+  ssd1306_command(SSD1306_LEFT_HORIZONTAL_SCROLL);
+  ssd1306_command(0X00);
+  ssd1306_command(start);
+  ssd1306_command(0X00);
+  ssd1306_command(stop);
+  ssd1306_command(0X00);
+  ssd1306_command(0XFF);
+  ssd1306_command(SSD1306_ACTIVATE_SCROLL);
+}
+
+// startscrolldiagright
+// Activate a diagonal scroll for rows start through stop
+// Hint, the display is 16 rows tall. To scroll the whole display, run:
+// display.scrollright(0x00, 0x0F) 
+void Adafruit_SSD1306::startscrolldiagright(uint8_t start, uint8_t stop){
+  ssd1306_command(SSD1306_SET_VERTICAL_SCROLL_AREA);  
+  ssd1306_command(0X00);
+  ssd1306_command(SSD1306_LCDHEIGHT);
+  ssd1306_command(SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL);
+  ssd1306_command(0X00);
+  ssd1306_command(start);
+  ssd1306_command(0X00);
+  ssd1306_command(stop);
+  ssd1306_command(0X01);
+  ssd1306_command(SSD1306_ACTIVATE_SCROLL);
+}
+
+// startscrolldiagleft
+// Activate a diagonal scroll for rows start through stop
+// Hint, the display is 16 rows tall. To scroll the whole display, run:
+// display.scrollright(0x00, 0x0F) 
+void Adafruit_SSD1306::startscrolldiagleft(uint8_t start, uint8_t stop){
+  ssd1306_command(SSD1306_SET_VERTICAL_SCROLL_AREA);  
+  ssd1306_command(0X00);
+  ssd1306_command(SSD1306_LCDHEIGHT);
+  ssd1306_command(SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL);
+  ssd1306_command(0X00);
+  ssd1306_command(start);
+  ssd1306_command(0X00);
+  ssd1306_command(stop);
+  ssd1306_command(0X01);
+  ssd1306_command(SSD1306_ACTIVATE_SCROLL);
+}
+
+void Adafruit_SSD1306::stopscroll(void){
+  ssd1306_command(SSD1306_DEACTIVATE_SCROLL);
+}
+
+// Dim the display
+// dim = true: display is dimmed
+// dim = false: display is normal
+void Adafruit_SSD1306::dim(boolean dim) {
+  uint8_t contrast;
+
+  if (dim) {
+    contrast = 0; // Dimmed display
+  } else {
+    if (_vccstate == SSD1306_EXTERNALVCC) {
+      contrast = 0x9F;
+    } else {
+      contrast = 0xCF;
+    }
+  }
+  // the range of contrast to too small to be really useful
+  // it is useful to dim the display
+  ssd1306_command(SSD1306_SETCONTRAST);
+  ssd1306_command(contrast);
+}
+
+void Adafruit_SSD1306::ssd1306_data(uint8_t c) {
+    uint8_t control = 0x40;   // Co = 0, D/C = 1
+    Wire.beginTransmission(_i2caddr);
+    WIRE_WRITE(control);
+    WIRE_WRITE(c);
+    Wire.endTransmission();
+  //}
+}
+
+void Adafruit_SSD1306::display(void) {
+  ssd1306_command(SSD1306_COLUMNADDR);
+  ssd1306_command(0);   // Column start address (0 = reset)
+  ssd1306_command(SSD1306_LCDWIDTH-1); // Column end address (127 = reset)
+
+  ssd1306_command(SSD1306_PAGEADDR);
+  ssd1306_command(0); // Page start address (0 = reset)
+  #if SSD1306_LCDHEIGHT == 64
+    ssd1306_command(7); // Page end address
+  #endif
+  #if SSD1306_LCDHEIGHT == 32
+    ssd1306_command(3); // Page end address
+  #endif
+  #if SSD1306_LCDHEIGHT == 16
+    ssd1306_command(1); // Page end address
+  #endif
+
+#if !defined __SAM3X8E__ && !defined ARDUINO_ARCH_SAMD
+    uint8_t twbrbackup = TWBR;
+    TWBR = 12; // upgrade to 400KHz!
+#endif
+
+    //Serial.println(TWBR, DEC);
+    //Serial.println(TWSR & 0x3, DEC);
+
+    // I2C
+    for (uint16_t i=0; i<(SSD1306_LCDWIDTH*SSD1306_LCDHEIGHT/8); i++) {
+      // send a bunch of data in one xmission
+      Wire.beginTransmission(_i2caddr);
+      WIRE_WRITE(0x40);
+      for (uint8_t x=0; x<16; x++) {
+	       WIRE_WRITE(buffer[i]);
+	       i++;
+      }
+      i--;
+      Wire.endTransmission();
+    }
+#if !defined __SAM3X8E__ && !defined ARDUINO_ARCH_SAMD
+    TWBR = twbrbackup;
+#endif
+  //}
+}
+
+// clear everything
+void Adafruit_SSD1306::clearDisplay(void) {
+  memset(buffer, 0, (SSD1306_LCDWIDTH*SSD1306_LCDHEIGHT/8));
+}
+
+void Adafruit_SSD1306::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) {
+  boolean bSwap = false;
+  switch(rotation) { 
+    case 0:
+      // 0 degree rotation, do nothing
+      break;
+    case 1:
+      // 90 degree rotation, swap x & y for rotation, then invert x
+      bSwap = true;
+      ssd1306_swap(x, y);
+      x = WIDTH - x - 1;
+      break;
+    case 2:
+      // 180 degree rotation, invert x and y - then shift y around for height.
+      x = WIDTH - x - 1;
+      y = HEIGHT - y - 1;
+      x -= (w-1);
+      break;
+    case 3:
+      // 270 degree rotation, swap x & y for rotation, then invert y  and adjust y for w (not to become h)
+      bSwap = true;
+      ssd1306_swap(x, y);
+      y = HEIGHT - y - 1;
+      y -= (w-1);
+      break;
+  }
+
+  if(bSwap) { 
+    drawFastVLineInternal(x, y, w, color);
+  } else { 
+    drawFastHLineInternal(x, y, w, color);
+  }
+}
+
+void Adafruit_SSD1306::drawFastHLineInternal(int16_t x, int16_t y, int16_t w, uint16_t color) {
+  // Do bounds/limit checks
+  if(y < 0 || y >= HEIGHT) { return; }
+
+  // make sure we don't try to draw below 0
+  if(x < 0) { 
+    w += x;
+    x = 0;
+  }
+
+  // make sure we don't go off the edge of the display
+  if( (x + w) > WIDTH) { 
+    w = (WIDTH - x);
+  }
+
+  // if our width is now negative, punt
+  if(w <= 0) { return; }
+
+  // set up the pointer for  movement through the buffer
+  register uint8_t *pBuf = buffer;
+  // adjust the buffer pointer for the current row
+  pBuf += ((y/8) * SSD1306_LCDWIDTH);
+  // and offset x columns in
+  pBuf += x;
+
+  register uint8_t mask = 1 << (y&7);
+
+  switch (color) 
+  {
+  case WHITE:         while(w--) { *pBuf++ |= mask; }; break;
+    case BLACK: mask = ~mask;   while(w--) { *pBuf++ &= mask; }; break;
+  case INVERSE:         while(w--) { *pBuf++ ^= mask; }; break;
+  }
+}
+
+void Adafruit_SSD1306::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) {
+  bool bSwap = false;
+  switch(rotation) { 
+    case 0:
+      break;
+    case 1:
+      // 90 degree rotation, swap x & y for rotation, then invert x and adjust x for h (now to become w)
+      bSwap = true;
+      ssd1306_swap(x, y);
+      x = WIDTH - x - 1;
+      x -= (h-1);
+      break;
+    case 2:
+      // 180 degree rotation, invert x and y - then shift y around for height.
+      x = WIDTH - x - 1;
+      y = HEIGHT - y - 1;
+      y -= (h-1);
+      break;
+    case 3:
+      // 270 degree rotation, swap x & y for rotation, then invert y 
+      bSwap = true;
+      ssd1306_swap(x, y);
+      y = HEIGHT - y - 1;
+      break;
+  }
+
+  if(bSwap) { 
+    drawFastHLineInternal(x, y, h, color);
+  } else {
+    drawFastVLineInternal(x, y, h, color);
+  }
+}
+
+
+void Adafruit_SSD1306::drawFastVLineInternal(int16_t x, int16_t __y, int16_t __h, uint16_t color) {
+
+  // do nothing if we're off the left or right side of the screen
+  if(x < 0 || x >= WIDTH) { return; }
+
+  // make sure we don't try to draw below 0
+  if(__y < 0) { 
+    // __y is negative, this will subtract enough from __h to account for __y being 0
+    __h += __y;
+    __y = 0;
+
+  } 
+
+  // make sure we don't go past the height of the display
+  if( (__y + __h) > HEIGHT) { 
+    __h = (HEIGHT - __y);
+  }
+
+  // if our height is now negative, punt 
+  if(__h <= 0) { 
+    return;
+  }
+
+  // this display doesn't need ints for coordinates, use local byte registers for faster juggling
+  register uint8_t y = __y;
+  register uint8_t h = __h;
+
+
+  // set up the pointer for fast movement through the buffer
+  register uint8_t *pBuf = buffer;
+  // adjust the buffer pointer for the current row
+  pBuf += ((y/8) * SSD1306_LCDWIDTH);
+  // and offset x columns in
+  pBuf += x;
+
+  // do the first partial byte, if necessary - this requires some masking
+  register uint8_t mod = (y&7);
+  if(mod) {
+    // mask off the high n bits we want to set 
+    mod = 8-mod;
+
+    // note - lookup table results in a nearly 10% performance improvement in fill* functions
+    // register uint8_t mask = ~(0xFF >> (mod));
+    static uint8_t premask[8] = {0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE };
+    register uint8_t mask = premask[mod];
+
+    // adjust the mask if we're not going to reach the end of this byte
+    if( h < mod) { 
+      mask &= (0XFF >> (mod-h));
+    }
+
+  switch (color) 
+    {
+    case WHITE:   *pBuf |=  mask;  break;
+    case BLACK:   *pBuf &= ~mask;  break;
+    case INVERSE: *pBuf ^=  mask;  break;
+    }
+  
+    // fast exit if we're done here!
+    if(h<mod) { return; }
+
+    h -= mod;
+
+    pBuf += SSD1306_LCDWIDTH;
+  }
+
+
+  // write solid bytes while we can - effectively doing 8 rows at a time
+  if(h >= 8) { 
+    if (color == INVERSE)  {          // separate copy of the code so we don't impact performance of the black/white write version with an extra comparison per loop
+      do  {
+      *pBuf=~(*pBuf);
+
+        // adjust the buffer forward 8 rows worth of data
+        pBuf += SSD1306_LCDWIDTH;
+
+        // adjust h & y (there's got to be a faster way for me to do this, but this should still help a fair bit for now)
+        h -= 8;
+      } while(h >= 8);
+      }
+    else {
+      // store a local value to work with 
+      register uint8_t val = (color == WHITE) ? 255 : 0;
+
+      do  {
+        // write our value in
+      *pBuf = val;
+
+        // adjust the buffer forward 8 rows worth of data
+        pBuf += SSD1306_LCDWIDTH;
+
+        // adjust h & y (there's got to be a faster way for me to do this, but this should still help a fair bit for now)
+        h -= 8;
+      } while(h >= 8);
+      }
+    }
+
+  // now do the final partial byte, if necessary
+  if(h) {
+    mod = h & 7;
+    // this time we want to mask the low bits of the byte, vs the high bits we did above
+    // register uint8_t mask = (1 << mod) - 1;
+    // note - lookup table results in a nearly 10% performance improvement in fill* functions
+    static uint8_t postmask[8] = {0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F };
+    register uint8_t mask = postmask[mod];
+    switch (color) 
+    {
+      case WHITE:   *pBuf |=  mask;  break;
+      case BLACK:   *pBuf &= ~mask;  break;
+      case INVERSE: *pBuf ^=  mask;  break;
+    }
+  }
+}
+
+Adafruit_SSD1306 ssd1306;
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/Adafruit_SSD1306.h	(revision 175)
@@ -0,0 +1,175 @@
+/*********************************************************************
+This is a library for our Monochrome OLEDs based on SSD1306 drivers
+
+  Pick one up today in the adafruit shop!
+  ------> http://www.adafruit.com/category/63_98
+
+These displays use SPI to communicate, 4 or 5 pins are required to  
+interface
+
+Adafruit invests time and resources providing this open source code, 
+please support Adafruit and open-source hardware by purchasing 
+products from Adafruit!
+
+Written by Limor Fried/Ladyada  for Adafruit Industries.  
+BSD license, check license.txt for more information
+All text above, and the splash screen must be included in any redistribution
+
+ - 21 Mar. 2016
+ Library modified to work with Arduino Lucky Shield
+ by andrea[at]arduino[dot]org
+*********************************************************************/
+
+#if ARDUINO >= 100
+ #include "Arduino.h"
+ #define WIRE_WRITE Wire.write
+#else
+ #include "WProgram.h"
+  #define WIRE_WRITE Wire.send
+#endif
+
+#ifdef __SAM3X8E__
+ typedef volatile RwReg PortReg;
+ typedef uint32_t PortMask;
+#else
+  typedef volatile uint8_t PortReg;
+  typedef uint8_t PortMask;
+#endif
+
+//#include <SPI.h>
+#include "Adafruit_GFX.h"
+
+#define BLACK 0
+#define WHITE 1
+#define INVERSE 2
+
+#define SSD1306_I2C_ADDRESS   0x3C	// 011110+SA0+RW - 0x3C or 0x3D
+// Address for 128x32 is 0x3C
+// Address for 128x64 is 0x3D (default) or 0x3C (if SA0 is grounded)
+
+/*=========================================================================
+    SSD1306 Displays
+    -----------------------------------------------------------------------
+    The driver is used in multiple displays (128x64, 128x32, etc.).
+    Select the appropriate display below to create an appropriately
+    sized framebuffer, etc.
+
+    SSD1306_128_64  128x64 pixel display
+
+    SSD1306_128_32  128x32 pixel display
+
+    SSD1306_96_16
+
+    -----------------------------------------------------------------------*/
+   #define SSD1306_128_64
+//   #define SSD1306_128_32
+//   #define SSD1306_96_16
+/*=========================================================================*/
+
+#if defined SSD1306_128_64 && defined SSD1306_128_32
+  #error "Only one SSD1306 display can be specified at once in SSD1306.h"
+#endif
+#if !defined SSD1306_128_64 && !defined SSD1306_128_32 && !defined SSD1306_96_16
+  #error "At least one SSD1306 display must be specified in SSD1306.h"
+#endif
+
+#if defined SSD1306_128_64
+  #define SSD1306_LCDWIDTH                  128
+  #define SSD1306_LCDHEIGHT                 64
+#endif
+#if defined SSD1306_128_32
+  #define SSD1306_LCDWIDTH                  128
+  #define SSD1306_LCDHEIGHT                 32
+#endif
+#if defined SSD1306_96_16
+  #define SSD1306_LCDWIDTH                  96
+  #define SSD1306_LCDHEIGHT                 16
+#endif
+
+#define SSD1306_SETCONTRAST 0x81
+#define SSD1306_DISPLAYALLON_RESUME 0xA4
+#define SSD1306_DISPLAYALLON 0xA5
+#define SSD1306_NORMALDISPLAY 0xA6
+#define SSD1306_INVERTDISPLAY 0xA7
+#define SSD1306_DISPLAYOFF 0xAE
+#define SSD1306_DISPLAYON 0xAF
+
+#define SSD1306_SETDISPLAYOFFSET 0xD3
+#define SSD1306_SETCOMPINS 0xDA
+
+#define SSD1306_SETVCOMDETECT 0xDB
+
+#define SSD1306_SETDISPLAYCLOCKDIV 0xD5
+#define SSD1306_SETPRECHARGE 0xD9
+
+#define SSD1306_SETMULTIPLEX 0xA8
+
+#define SSD1306_SETLOWCOLUMN 0x00
+#define SSD1306_SETHIGHCOLUMN 0x10
+
+#define SSD1306_SETSTARTLINE 0x40
+
+#define SSD1306_MEMORYMODE 0x20
+#define SSD1306_COLUMNADDR 0x21
+#define SSD1306_PAGEADDR   0x22
+
+#define SSD1306_COMSCANINC 0xC0
+#define SSD1306_COMSCANDEC 0xC8
+
+#define SSD1306_SEGREMAP 0xA0
+
+#define SSD1306_CHARGEPUMP 0x8D
+
+#define SSD1306_EXTERNALVCC 0x1
+#define SSD1306_SWITCHCAPVCC 0x2
+
+// Scrolling #defines
+#define SSD1306_ACTIVATE_SCROLL 0x2F
+#define SSD1306_DEACTIVATE_SCROLL 0x2E
+#define SSD1306_SET_VERTICAL_SCROLL_AREA 0xA3
+#define SSD1306_RIGHT_HORIZONTAL_SCROLL 0x26
+#define SSD1306_LEFT_HORIZONTAL_SCROLL 0x27
+#define SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL 0x29
+#define SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL 0x2A
+
+class Adafruit_SSD1306 : public Adafruit_GFX {
+ public:
+  //Adafruit_SSD1306(int8_t SID, int8_t SCLK, int8_t DC, int8_t RST, int8_t CS);
+  //Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS);
+  Adafruit_SSD1306();
+
+  void begin();
+  void ssd1306_command(uint8_t c);
+  void ssd1306_data(uint8_t c);
+
+  void clearDisplay(void);
+  void invertDisplay(uint8_t i);
+  void display();
+
+  void startscrollright(uint8_t start, uint8_t stop);
+  void startscrollleft(uint8_t start, uint8_t stop);
+
+  void startscrolldiagright(uint8_t start, uint8_t stop);
+  void startscrolldiagleft(uint8_t start, uint8_t stop);
+  void stopscroll(void);
+
+  void dim(boolean dim);
+
+  void drawPixel(int16_t x, int16_t y, uint16_t color);
+
+  virtual void drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color);
+  virtual void drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color);
+
+ private:
+  int8_t _i2caddr, _vccstate, sid, sclk, dc, rst, cs;
+
+  boolean hwSPI;
+  PortReg *mosiport, *clkport, *csport, *dcport;
+  PortMask mosipinmask, clkpinmask, cspinmask, dcpinmask;
+
+  inline void drawFastVLineInternal(int16_t x, int16_t y, int16_t h, uint16_t color) __attribute__((always_inline));
+  inline void drawFastHLineInternal(int16_t x, int16_t y, int16_t w, uint16_t color) __attribute__((always_inline));
+
+};
+
+extern Adafruit_SSD1306 ssd1306;
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/BME280.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/BME280.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/BME280.cpp	(revision 175)
@@ -0,0 +1,280 @@
+/***************************************************************************
+  This is a library for the BME280 humidity, temperature & pressure sensor
+
+  Designed specifically to work with the Adafruit BME280 Breakout
+  ----> http://www.adafruit.com/products/2650
+
+  These sensors use I2C or SPI to communicate, 2 or 4 pins are required
+  to interface.
+
+  Adafruit invests time and resources providing this open source code,
+  please support Adafruit andopen-source hardware by purchasing products
+  from Adafruit!
+
+  Written by Limor Fried & Kevin Townsend for Adafruit Industries.
+  BSD license, all text above must be included in any redistribution
+ ***************************************************************************/
+#include "Arduino.h"
+#include <Wire.h>
+#include "BME280.h"
+
+
+/***************************************************************************
+ PRIVATE FUNCTIONS
+ ***************************************************************************/
+
+
+bool BME280::begin(uint8_t a) {
+  _i2caddr = a;
+
+  if (read8(BME280_REGISTER_CHIPID) != 0x60)
+    return false;
+
+  readCoefficients();
+
+  //Set before CONTROL_meas (DS 5.4.3)
+  write8(BME280_REGISTER_CONTROLHUMID, 0x05); //16x oversampling 
+
+  write8(BME280_REGISTER_CONTROL, 0xB7); // 16x ovesampling, normal mode
+  return true;
+}
+
+
+/**************************************************************************/
+/*!
+    @brief  Writes an 8 bit value over I2C/SPI
+*/
+/**************************************************************************/
+void BME280::write8(byte reg, byte value)
+{
+    Wire.beginTransmission((uint8_t)_i2caddr);
+    Wire.write((uint8_t)reg);
+    Wire.write((uint8_t)value);
+    Wire.endTransmission();
+}
+
+/**************************************************************************/
+/*!
+    @brief  Reads an 8 bit value over I2C
+*/
+/**************************************************************************/
+uint8_t BME280::read8(byte reg)
+{
+  uint8_t value;
+
+  Wire.beginTransmission((uint8_t)_i2caddr);
+  Wire.write((uint8_t)reg);
+  Wire.endTransmission();
+  Wire.requestFrom((uint8_t)_i2caddr, (byte)1);
+  value = Wire.read();
+  return value;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Reads a 16 bit value over I2C
+*/
+/**************************************************************************/
+uint16_t BME280::read16(byte reg)
+{
+  uint16_t value;
+
+    Wire.beginTransmission((uint8_t)_i2caddr);
+    Wire.write((uint8_t)reg);
+    Wire.endTransmission();
+    Wire.requestFrom((uint8_t)_i2caddr, (byte)2);
+    value = (Wire.read() << 8) | Wire.read();
+
+  return value;
+}
+
+uint16_t BME280::read16_LE(byte reg) {
+  uint16_t temp = read16(reg);
+  return (temp >> 8) | (temp << 8);
+
+}
+
+/**************************************************************************/
+/*!
+    @brief  Reads a signed 16 bit value over I2C
+*/
+/**************************************************************************/
+int16_t BME280::readS16(byte reg)
+{
+  return (int16_t)read16(reg);
+
+}
+
+int16_t BME280::readS16_LE(byte reg)
+{
+  return (int16_t)read16_LE(reg);
+
+}
+
+
+/**************************************************************************/
+/*!
+    @brief  Reads a 24 bit value over I2C
+*/
+/**************************************************************************/
+
+uint32_t BME280::read24(byte reg)
+{
+  uint32_t value;
+
+    Wire.beginTransmission((uint8_t)_i2caddr);
+    Wire.write((uint8_t)reg);
+    Wire.endTransmission();
+    Wire.requestFrom((uint8_t)_i2caddr, (byte)3);
+    
+    value = Wire.read();
+    value <<= 8;
+    value |= Wire.read();
+    value <<= 8;
+    value |= Wire.read();
+
+  return value;
+}
+
+
+/**************************************************************************/
+/*!
+    @brief  Reads the factory-set coefficients
+*/
+/**************************************************************************/
+void BME280::readCoefficients(void)
+{
+    _bme280_calib.dig_T1 = read16_LE(BME280_REGISTER_DIG_T1);
+    _bme280_calib.dig_T2 = readS16_LE(BME280_REGISTER_DIG_T2);
+    _bme280_calib.dig_T3 = readS16_LE(BME280_REGISTER_DIG_T3);
+
+    _bme280_calib.dig_P1 = read16_LE(BME280_REGISTER_DIG_P1);
+    _bme280_calib.dig_P2 = readS16_LE(BME280_REGISTER_DIG_P2);
+    _bme280_calib.dig_P3 = readS16_LE(BME280_REGISTER_DIG_P3);
+    _bme280_calib.dig_P4 = readS16_LE(BME280_REGISTER_DIG_P4);
+    _bme280_calib.dig_P5 = readS16_LE(BME280_REGISTER_DIG_P5);
+    _bme280_calib.dig_P6 = readS16_LE(BME280_REGISTER_DIG_P6);
+    _bme280_calib.dig_P7 = readS16_LE(BME280_REGISTER_DIG_P7);
+    _bme280_calib.dig_P8 = readS16_LE(BME280_REGISTER_DIG_P8);
+    _bme280_calib.dig_P9 = readS16_LE(BME280_REGISTER_DIG_P9);
+
+    _bme280_calib.dig_H1 = read8(BME280_REGISTER_DIG_H1);
+    _bme280_calib.dig_H2 = readS16_LE(BME280_REGISTER_DIG_H2);
+    _bme280_calib.dig_H3 = read8(BME280_REGISTER_DIG_H3);
+    _bme280_calib.dig_H4 = (read8(BME280_REGISTER_DIG_H4) << 4) | (read8(BME280_REGISTER_DIG_H4+1) & 0xF);
+    _bme280_calib.dig_H5 = (read8(BME280_REGISTER_DIG_H5+1) << 4) | (read8(BME280_REGISTER_DIG_H5) >> 4);
+    _bme280_calib.dig_H6 = (int8_t)read8(BME280_REGISTER_DIG_H6);
+}
+
+/**************************************************************************/
+/*!
+
+*/
+/**************************************************************************/
+float BME280::temperature(void)
+{
+  int32_t var1, var2;
+
+  int32_t adc_T = read24(BME280_REGISTER_TEMPDATA);
+  adc_T >>= 4;
+
+  var1  = ((((adc_T>>3) - ((int32_t)_bme280_calib.dig_T1 <<1))) *
+	   ((int32_t)_bme280_calib.dig_T2)) >> 11;
+
+  var2  = (((((adc_T>>4) - ((int32_t)_bme280_calib.dig_T1)) *
+	     ((adc_T>>4) - ((int32_t)_bme280_calib.dig_T1))) >> 12) *
+	   ((int32_t)_bme280_calib.dig_T3)) >> 14;
+
+  t_fine = var1 + var2;
+
+  float T  = (t_fine * 5 + 128) >> 8;
+  return T/100;
+}
+
+/**************************************************************************/
+/*!
+
+*/
+/**************************************************************************/
+float BME280::pressure(void) {
+  int64_t var1, var2, p;
+
+  temperature(); // must be done first to get t_fine
+
+  int32_t adc_P = read24(BME280_REGISTER_PRESSUREDATA);
+  adc_P >>= 4;
+
+  var1 = ((int64_t)t_fine) - 128000;
+  var2 = var1 * var1 * (int64_t)_bme280_calib.dig_P6;
+  var2 = var2 + ((var1*(int64_t)_bme280_calib.dig_P5)<<17);
+  var2 = var2 + (((int64_t)_bme280_calib.dig_P4)<<35);
+  var1 = ((var1 * var1 * (int64_t)_bme280_calib.dig_P3)>>8) +
+    ((var1 * (int64_t)_bme280_calib.dig_P2)<<12);
+  var1 = (((((int64_t)1)<<47)+var1))*((int64_t)_bme280_calib.dig_P1)>>33;
+
+  if (var1 == 0) {
+    return 0;  // avoid exception caused by division by zero
+  }
+  p = 1048576 - adc_P;
+  p = (((p<<31) - var2)*3125) / var1;
+  var1 = (((int64_t)_bme280_calib.dig_P9) * (p>>13) * (p>>13)) >> 25;
+  var2 = (((int64_t)_bme280_calib.dig_P8) * p) >> 19;
+
+  p = ((p + var1 + var2) >> 8) + (((int64_t)_bme280_calib.dig_P7)<<4);
+  return (float)p/256;
+}
+
+
+/**************************************************************************/
+/*!
+
+*/
+/**************************************************************************/
+float BME280::humidity(void) {
+
+  temperature(); // must be done first to get t_fine
+
+  int32_t adc_H = read16(BME280_REGISTER_HUMIDDATA);
+
+  int32_t v_x1_u32r;
+
+  v_x1_u32r = (t_fine - ((int32_t)76800));
+
+  v_x1_u32r = (((((adc_H << 14) - (((int32_t)_bme280_calib.dig_H4) << 20) -
+		  (((int32_t)_bme280_calib.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) *
+	       (((((((v_x1_u32r * ((int32_t)_bme280_calib.dig_H6)) >> 10) *
+		    (((v_x1_u32r * ((int32_t)_bme280_calib.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) +
+		  ((int32_t)2097152)) * ((int32_t)_bme280_calib.dig_H2) + 8192) >> 14));
+
+  v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
+			     ((int32_t)_bme280_calib.dig_H1)) >> 4));
+
+  v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r;
+  v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r;
+  float h = (v_x1_u32r>>12);
+  return  h / 1024.0;
+}
+
+/**************************************************************************/
+/*!
+    Calculates the altitude (in meters) from the specified atmospheric
+    pressure (in hPa), and sea-level pressure (in hPa).
+
+    @param  seaLevel      Sea-level pressure in hPa
+    @param  atmospheric   Atmospheric pressure in hPa
+*/
+/**************************************************************************/
+float BME280::altitude(float seaLevel)
+{
+  // Equation taken from BMP180 datasheet (page 16):
+  //  http://www.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf
+
+  // Note that using the equation from wikipedia can give bad results
+  // at high altitude.  See this thread for more information:
+  //  http://forums.adafruit.com/viewtopic.php?f=22&t=58064
+
+  float atmospheric = pressure() / 100.0F;
+  return 44330.0 * (1.0 - pow(atmospheric / seaLevel, 0.1903));
+}
+
+BME280 bme280;
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/BME280.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/BME280.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/BME280.h	(revision 175)
@@ -0,0 +1,140 @@
+/***************************************************************************
+  This is a library for the BME280 humidity, temperature & pressure sensor
+
+  Designed specifically to work with the Adafruit BME280 Breakout
+  ----> http://www.adafruit.com/products/2650
+
+  These sensors use I2C or SPI to communicate, 2 or 4 pins are required
+  to interface.
+
+  Adafruit invests time and resources providing this open source code,
+  please support Adafruit andopen-source hardware by purchasing products
+  from Adafruit!
+
+  Written by Limor Fried & Kevin Townsend for Adafruit Industries.
+  BSD license, all text above must be included in any redistribution
+
+
+ ***************************************************************************/
+#ifndef __BME280_H__
+#define __BME280_H__
+
+#if (ARDUINO >= 100)
+ #include "Arduino.h"
+#else
+ #include "WProgram.h"
+#endif
+
+#include <Wire.h>
+
+/*=========================================================================
+    I2C ADDRESS/BITS
+    -----------------------------------------------------------------------*/
+    #define BME280_ADDRESS                (0x77)
+/*=========================================================================*/
+
+/*=========================================================================
+    REGISTERS
+    -----------------------------------------------------------------------*/
+    enum
+    {
+      BME280_REGISTER_DIG_T1              = 0x88,
+      BME280_REGISTER_DIG_T2              = 0x8A,
+      BME280_REGISTER_DIG_T3              = 0x8C,
+
+      BME280_REGISTER_DIG_P1              = 0x8E,
+      BME280_REGISTER_DIG_P2              = 0x90,
+      BME280_REGISTER_DIG_P3              = 0x92,
+      BME280_REGISTER_DIG_P4              = 0x94,
+      BME280_REGISTER_DIG_P5              = 0x96,
+      BME280_REGISTER_DIG_P6              = 0x98,
+      BME280_REGISTER_DIG_P7              = 0x9A,
+      BME280_REGISTER_DIG_P8              = 0x9C,
+      BME280_REGISTER_DIG_P9              = 0x9E,
+
+      BME280_REGISTER_DIG_H1              = 0xA1,
+      BME280_REGISTER_DIG_H2              = 0xE1,
+      BME280_REGISTER_DIG_H3              = 0xE3,
+      BME280_REGISTER_DIG_H4              = 0xE4,
+      BME280_REGISTER_DIG_H5              = 0xE5,
+      BME280_REGISTER_DIG_H6              = 0xE7,
+
+      BME280_REGISTER_CHIPID             = 0xD0,
+      BME280_REGISTER_VERSION            = 0xD1,
+      BME280_REGISTER_SOFTRESET          = 0xE0,
+
+      BME280_REGISTER_CAL26              = 0xE1,  // R calibration stored in 0xE1-0xF0
+
+      BME280_REGISTER_CONTROLHUMID       = 0xF2,
+      BME280_REGISTER_CONTROL            = 0xF4,
+      BME280_REGISTER_CONFIG             = 0xF5,
+      BME280_REGISTER_PRESSUREDATA       = 0xF7,
+      BME280_REGISTER_TEMPDATA           = 0xFA,
+      BME280_REGISTER_HUMIDDATA          = 0xFD,
+    };
+
+/*=========================================================================*/
+
+/*=========================================================================
+    CALIBRATION DATA
+    -----------------------------------------------------------------------*/
+    typedef struct
+    {
+      uint16_t dig_T1;
+      int16_t  dig_T2;
+      int16_t  dig_T3;
+
+      uint16_t dig_P1;
+      int16_t  dig_P2;
+      int16_t  dig_P3;
+      int16_t  dig_P4;
+      int16_t  dig_P5;
+      int16_t  dig_P6;
+      int16_t  dig_P7;
+      int16_t  dig_P8;
+      int16_t  dig_P9;
+
+      uint8_t  dig_H1;
+      int16_t  dig_H2;
+      uint8_t  dig_H3;
+      int16_t  dig_H4;
+      int16_t  dig_H5;
+      int8_t   dig_H6;
+    } bme280_calib_data;
+/*=========================================================================*/
+
+
+
+class BME280
+{
+  public:
+
+    bool  begin(uint8_t addr = BME280_ADDRESS);
+    float temperature(void);
+    float pressure(void);
+    float humidity(void);
+    float altitude(float seaLevel);
+
+  private:
+
+    void readCoefficients(void);
+
+    void      write8(byte reg, byte value);
+    uint8_t   read8(byte reg);
+    uint16_t  read16(byte reg);
+    uint32_t  read24(byte reg);
+    int16_t   readS16(byte reg);
+    uint16_t  read16_LE(byte reg); // little endian
+    int16_t   readS16_LE(byte reg); // little endian
+
+    uint8_t   _i2caddr;
+    int32_t   _sensorID;
+    int32_t t_fine;
+
+    bme280_calib_data _bme280_calib;
+
+};
+
+extern BME280 bme280;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/CAT9555.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/CAT9555.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/CAT9555.cpp	(revision 175)
@@ -0,0 +1,115 @@
+/*
+****************************************************************************
+* Copyright (c) 2015 Arduino srl. All right reserved.
+*
+* File : CAT9555.cpp
+* Date : 2016/03/21
+* Revision : 0.0.1 $
+* Author: andrea[at]arduino[dot]org
+*
+****************************************************************************
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+******************************************************************************/
+
+#include "CAT9555.h"
+#include <Wire.h>
+
+// CONSTRUCTUR
+CAT9555::CAT9555(uint8_t addr)
+{
+	address = addr; // Store address into private variable
+}
+
+void CAT9555::begin(){
+
+	writeRegister(CONFIG_PORT0, 0x0E);	// setup direction register port0
+	writeRegister(CONFIG_PORT1, 0x7F);	// setup direction register port1
+	writeRegister(OUTPUT_PORT0, 0x3c);	// set all output pin to LOW level
+
+}
+
+void CAT9555::digitalWrite(int PIN, int data){
+
+	uint8_t data_reg = read_8_Register(INPUT_PORT0);
+	if (data == HIGH )
+		if (PIN == LED1 || PIN == LED2)
+      		data_reg = ~PIN >> 8 & data_reg;
+    	else
+    		data_reg = PIN >> 8 | data_reg;
+    else if (data == LOW)
+    	if (PIN == LED1 || PIN == LED2)
+    		data_reg = PIN >> 8 | data_reg;
+    	else
+    		data_reg = (0xFF ^ PIN >> 8) &  data_reg;
+    writeRegister(OUTPUT_PORT0, data_reg);
+    data_reg = read_8_Register(INPUT_PORT0);
+
+}
+
+int CAT9555::digitalRead(int PIN){
+
+	uint16_t data = read_16_Register(INPUT_PORT0);
+	//Serial.println(data,BIN);
+	int result = (data ^ 0x30FF) & PIN;  //0xFFFF
+	if (result)
+		return HIGH;
+	else
+		return result;
+	
+}
+// WRITE REGISTER
+void CAT9555::writeRegister(int reg, int data)
+{
+
+    Wire.beginTransmission(address);  
+    Wire.write(reg); 
+    Wire.write(data); 
+    Wire.endTransmission(); 
+}
+
+
+uint8_t CAT9555::read_8_Register(int reg)
+{
+	uint8_t _data0;
+	Wire.beginTransmission(address);
+	Wire.write(reg);
+	Wire.endTransmission();  
+	Wire.requestFrom(address, (byte)1); 
+	if(Wire.available()) {
+		_data0 = Wire.read();
+	}
+	return _data0;
+}
+// READ REGISTER
+uint16_t CAT9555::read_16_Register(int reg)
+{
+	uint16_t _data0;
+	Wire.beginTransmission(address);
+	Wire.write(reg);
+	Wire.endTransmission();  
+	Wire.requestFrom(address, (byte)2); 
+	if(Wire.available()) {
+		_data0 = Wire.read() << 8 ;
+	}
+	if(Wire.available()) {
+		_data0 |= Wire.read();
+	}
+
+	return _data0;
+}
+
+CAT9555 cat9555;
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/CAT9555.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/CAT9555.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/CAT9555.h	(revision 175)
@@ -0,0 +1,88 @@
+/*
+****************************************************************************
+* This file is part of Arduino Lucky Shield Library
+*
+* Copyright (c) 2016 Arduino srl. All right reserved.
+*
+* File : CAT9555.h
+* Date : 2016/03/21
+* Revision : 0.0.1 $
+* Author: andrea[at]arduino[dot]org
+*
+****************************************************************************
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+******************************************************************************/
+
+#ifndef CAT9555_h
+#define CAT9555_h
+
+#include <Arduino.h>
+
+///////////////////////////////////
+// CAT9555 Register Definitions  //
+///////////////////////////////////
+
+#define	INPUT_PORT0				(uint8_t)0x00
+#define	INPUT_PORT1				(uint8_t)0x01
+#define	OUTPUT_PORT0			(uint8_t)0x02
+#define	OUTPUT_PORT1			(uint8_t)0x03
+#define	POLARITY_PORT0		(uint8_t)0x04
+#define	POLARITY_PORT1		(uint8_t)0x05
+#define	CONFIG_PORT0			(uint8_t)0x06
+#define	CONFIG_PORT1			(uint8_t)0x07
+#define	ADDRESS					  (uint8_t)0x20
+
+///////////////////////////////////
+// CAT9555 PIN Definitions  //
+///////////////////////////////////
+
+#define	PIR 		(uint16_t)0x800	  //reg0
+#define	LED1		(uint16_t)0x1000	//reg0
+#define	LED2 		(uint16_t)0x2000	//reg0
+#define	REL1		(uint16_t)0x4000	//reg0
+#define	REL2		(uint16_t)0x8000	//reg0
+#define	ACC			(uint16_t)0x0100	//reg0
+#define	JOYL		(uint8_t)0X04	    //reg1
+#define	JOYR		(uint8_t)0X08	    //reg1
+#define	JOYU		(uint8_t)0X01	    //reg1
+#define	JOYD		(uint8_t)0X02	    //reg1
+#define	JOYC		(uint8_t)0X10	    //reg1
+#define PB1			(uint8_t)0x20     //reg1 
+#define PB2 		(uint8_t)0x40     //reg1
+#define	OLEDR		(uint8_t)0x80	    //reg1
+
+////////////////////////////////
+// CAT9555 Class Declaration  //
+////////////////////////////////
+class CAT9555
+{
+public:	
+	CAT9555(uint8_t addr = ADDRESS);
+	void begin();
+	int digitalRead(int pin);
+	void digitalWrite(int pin, int value);
+
+private:
+	byte address;
+	void writeRegister(int reg, int data);
+	uint8_t read_8_Register(int reg);
+	uint16_t read_16_Register(int reg);
+};
+
+extern CAT9555 cat9555;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.cpp	(revision 175)
@@ -0,0 +1,153 @@
+/*
+mag3110.cpp
+libary for using the I2C mag3110 magnetometer
+
+(c) Written by Jeroen Cappaert for NanoSatisfi, August 2012
+
+ - 21 Mar. 2016
+ Library modified to work with Arduino Lucky Shield
+ by andrea[at]arduino[dot]org
+ 
+*/
+
+#include <Arduino.h>
+#include "MAG3110.h"
+#include <Wire.h>
+
+//Constructor
+MAG3110::MAG3110()
+{
+  
+}
+
+
+
+// Configure magnetometer
+void MAG3110::begin(void) {
+  //CTRL_REG1
+  //DR2|DR1|DR0|OS1|OS0|FastRead|Trigger|ActiveMode|
+  // 0 | 1 | 1 | 1 | 1 |    0   |   0   |    1     |=dec121
+  Wire.beginTransmission(MAG_ADDR);// transmit to device 0x0E
+  Wire.write(0x10);                // cntrl register1
+  Wire.write(0x79); // Active Mode, 1.25 Hz datarate, 8x oversampling
+  Wire.endTransmission();          // stop transmitting
+  
+  delay(15);
+  
+  //CTRL_REG2: 
+  //AutoMagRst|---|Raw|Mag_Rst|---|---|---|---|
+  //    1     | 0 | 0 |   0   | 0 | 0 | 0 | 0 |
+  Wire.beginTransmission(MAG_ADDR);// transmit to device 0x0E
+  Wire.write(0x11);                // cntrl register2
+  Wire.write(0x80);        // Auto resets before each measurement
+  Wire.endTransmission();          // stop transmitting
+}
+
+
+// read X value
+int MAG3110::readx(void)
+{
+  int xl, xh;  //define the MSB and LSB
+  
+  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
+  Wire.write(0x01);              // x MSB reg
+  Wire.endTransmission();       // stop transmitting
+ 
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
+  while(Wire.available())    // slave may send less than requested
+  { 
+    xh = Wire.read(); // receive the byte
+  }
+  
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
+  Wire.write(0x02);              // x LSB reg
+  Wire.endTransmission();       // stop transmitting
+ 
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
+  while(Wire.available())    // slave may send less than requested
+  { 
+    xl = Wire.read(); // receive the byte
+  }
+  
+  int xout = (xl|(xh << 8)); //concatenate the MSB and LSB
+  return xout;
+}
+
+//read Y value
+int MAG3110::ready(void)
+{
+  int yl, yh;  //define the MSB and LSB
+  
+  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
+  Wire.write(0x03);              // y MSB reg
+  Wire.endTransmission();       // stop transmitting
+ 
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
+  while(Wire.available())    // slave may send less than requested
+  { 
+    yh = Wire.read(); // receive the byte
+  }
+  
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
+  Wire.write(0x04);              // y LSB reg
+  Wire.endTransmission();       // stop transmitting
+ 
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
+  while(Wire.available())    // slave may send less than requested
+  { 
+    yl = Wire.read(); // receive the byte
+  }
+  
+  int yout = (yl|(yh << 8)); //concatenate the MSB and LSB
+  return yout;
+}
+
+// read Z value
+int MAG3110::readz(void)
+{
+  int zl, zh;  //define the MSB and LSB
+  
+  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
+  Wire.write(0x05);              // z MSB reg
+  Wire.endTransmission();       // stop transmitting
+ 
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
+  while(Wire.available())    // slave may send less than requested
+  { 
+    zh = Wire.read(); // receive the byte
+  }
+  
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
+  Wire.write(0x06);              // z LSB reg
+  Wire.endTransmission();       // stop transmitting
+ 
+  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
+  
+  Wire.requestFrom(MAG_ADDR, 1); // request 1 byte
+  while(Wire.available())    // slave may send less than requested
+  { 
+    zl = Wire.read(); // receive the byte
+  }
+  
+  int zout = (zl|(zh << 8)); //concatenate the MSB and LSB
+  return zout;
+}
+
+MAG3110 mag3110;
+
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MAG3110.h	(revision 175)
@@ -0,0 +1,41 @@
+/*
+mag3110.h
+libary for using the I2C mag3110 magnetometer
+
+(c) Written by Jeroen Cappaert for NanoSatisfi, August 2012
+
+ - 21 Mar. 2016
+ Library modified to work with Arduino Lucky Shield
+ by andrea[at]arduino[dot]org
+
+*/
+
+#ifndef MAG3110_h
+#define MAG3110_h
+
+#include <Arduino.h>
+
+
+// define magnetometer I2C address (fixed)
+
+#define MAG_ADDR  0x0E // Magnetometer MAG3110
+
+
+class MAG3110
+{
+  public:
+    MAG3110();
+    void begin();
+    int readx();
+    int ready();
+    int readz();
+	
+	int x(){return readx();};
+	int y(){return ready();};
+	int z(){return readz();};
+  private:
+};
+
+extern MAG3110 mag3110;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MMA8491Q.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MMA8491Q.cpp	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MMA8491Q.cpp	(revision 175)
@@ -0,0 +1,96 @@
+/*
+****************************************************************************
+* This file is part of Arduino Lucky Shield Library
+*
+* Copyright (c) 2016 Arduino srl. All right reserved.
+*
+* File : MMA8491Q.cpp
+* Date : 2016/03/21
+* Revision : 0.0.1 $
+* Author: andrea[at]arduino[dot]org
+*
+****************************************************************************
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+******************************************************************************/
+
+#include "MMA8491Q.h"
+#include <Wire.h>
+
+// CONSTRUCTUR
+MMA8491Q::MMA8491Q(uint8_t addr)
+{
+	address = addr; // Store address into private variable
+}
+
+void MMA8491Q::read(){
+	readRegister(STATE);
+}
+
+void MMA8491Q::enable(){
+
+	Wire.beginTransmission(GPIO_ADDRESS); //read the gpio expander value
+	Wire.write(GPIO_READ);
+	Wire.endTransmission();  
+	Wire.requestFrom(GPIO_ADDRESS,(byte)1); 
+	if(Wire.available()) {
+		data_read = Wire.read();
+	}
+	data_read = data_read | 0x01; //enable
+	Wire.beginTransmission(GPIO_ADDRESS);	
+	Wire.write(GPIO_WRITE_PORT0);
+	Wire.write(data_read);
+	Wire.endTransmission();
+}
+
+void MMA8491Q::disable(){
+
+	Wire.beginTransmission(GPIO_ADDRESS);
+	Wire.write(GPIO_WRITE_PORT0);
+	Wire.write(data_read & 0xFE); //disable
+	Wire.endTransmission();
+
+}
+
+float MMA8491Q::value(int val){
+
+	if (val < 0x2000)
+		return float(val)/1024;   // read value is between 0 and 8191 (0g 8g)
+	else
+		return float((0x1FFF & val) - 0x2000)/1024;
+
+}
+
+void MMA8491Q::readRegister(int reg)
+{
+	enable();
+	delay(5);
+	Wire.beginTransmission(address);
+	Wire.write(reg);
+	Wire.endTransmission();  
+	Wire.requestFrom(address, (byte)7); 
+	state = Wire.read();
+	cx = Wire.read(); cx <<= 8; cx |= Wire.read(); cx >>= 2;
+	cy = Wire.read(); cy <<= 8; cy |= Wire.read(); cy >>= 2;
+	cz = Wire.read(); cz <<= 8; cz |= Wire.read(); cz >>= 2;
+	x_ = value(cx);
+	y_ = value(cy);
+	z_ = value(cz);
+	disable();
+
+}
+
+MMA8491Q mma8491q;
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MMA8491Q.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MMA8491Q.h	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/MMA8491Q.h	(revision 175)
@@ -0,0 +1,76 @@
+/*
+****************************************************************************
+* This file is part of Arduino Lucky Shield Library
+*
+* Copyright (c) 2016 Arduino srl. All right reserved.
+*
+* File : MMA8491Q.h
+* Date : 2016/03/21
+* Revision : 0.0.1 $
+* Author: andrea[at]arduino[dot]org
+*
+****************************************************************************
+
+  This library is free software; you can redistribute it and/or
+  modify it under the terms of the GNU Lesser General Public
+  License as published by the Free Software Foundation; either
+  version 2.1 of the License, or (at your option) any later version.
+
+  This library is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public
+  License along with this library; if not, write to the Free Software
+  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+******************************************************************************/
+
+#ifndef MMA8491Q_h
+#define MMA8491Q_h
+
+#include <Arduino.h>
+
+///////////////////////////////////
+// MMA8491Q Register Definitions  //
+///////////////////////////////////
+
+#define	STATE					(uint8_t)0x00
+#define	GPIO_ADDRESS			(uint8_t)0x20
+#define	GPIO_READ				(uint8_t)0x00
+#define	GPIO_WRITE_PORT0		(uint8_t)0x02
+#define	ADDRESS					(uint8_t)0x55	
+
+////////////////////////////////
+// MMA8491Q Class Declaration  //
+////////////////////////////////
+class MMA8491Q
+{
+public:	
+	MMA8491Q(uint8_t addr = ADDRESS);
+	void read();
+	float x(){return x_;};
+	float y(){return y_;};
+	float z(){return z_;};
+
+private:
+	byte address;
+	uint8_t data_read;
+	void readRegister(int reg);
+	float value(int val);
+	void enable();
+	void disable();
+	float x_;
+	float y_;
+	float z_;
+	uint16_t cx;
+	uint16_t cy;
+	uint16_t cz;
+	uint16_t state;
+
+};
+
+extern MMA8491Q mma8491q;
+
+#endif
Index: /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/glcdfont.c
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/glcdfont.c	(revision 175)
+++ /rtos_arduino/trunk/arduino_lib/libraries/LuckyShield/src/lib/glcdfont.c	(revision 175)
@@ -0,0 +1,273 @@
+#ifndef FONT5X7_H
+#define FONT5X7_H
+
+#ifdef __AVR__
+ #include <avr/io.h>
+ #include <avr/pgmspace.h>
+#elif defined(ESP8266)
+ #include <pgmspace.h>
+#else
+ #define PROGMEM
+#endif
+
+// Standard ASCII 5x7 font
+
+static const unsigned char font[] PROGMEM = {
+	0x00, 0x00, 0x00, 0x00, 0x00,
+	0x3E, 0x5B, 0x4F, 0x5B, 0x3E,
+	0x3E, 0x6B, 0x4F, 0x6B, 0x3E,
+	0x1C, 0x3E, 0x7C, 0x3E, 0x1C,
+	0x18, 0x3C, 0x7E, 0x3C, 0x18,
+	0x1C, 0x57, 0x7D, 0x57, 0x1C,
+	0x1C, 0x5E, 0x7F, 0x5E, 0x1C,
+	0x00, 0x18, 0x3C, 0x18, 0x00,
+	0xFF, 0xE7, 0xC3, 0xE7, 0xFF,
+	0x00, 0x18, 0x24, 0x18, 0x00,
+	0xFF, 0xE7, 0xDB, 0xE7, 0xFF,
+	0x30, 0x48, 0x3A, 0x06, 0x0E,
+	0x26, 0x29, 0x79, 0x29, 0x26,
+	0x40, 0x7F, 0x05, 0x05, 0x07,
+	0x40, 0x7F, 0x05, 0x25, 0x3F,
+	0x5A, 0x3C, 0xE7, 0x3C, 0x5A,
+	0x7F, 0x3E, 0x1C, 0x1C, 0x08,
+	0x08, 0x1C, 0x1C, 0x3E, 0x7F,
+	0x14, 0x22, 0x7F, 0x22, 0x14,
+	0x5F, 0x5F, 0x00, 0x5F, 0x5F,
+	0x06, 0x09, 0x7F, 0x01, 0x7F,
+	0x00, 0x66, 0x89, 0x95, 0x6A,
+	0x60, 0x60, 0x60, 0x60, 0x60,
+	0x94, 0xA2, 0xFF, 0xA2, 0x94,
+	0x08, 0x04, 0x7E, 0x04, 0x08,
+	0x10, 0x20, 0x7E, 0x20, 0x10,
+	0x08, 0x08, 0x2A, 0x1C, 0x08,
+	0x08, 0x1C, 0x2A, 0x08, 0x08,
+	0x1E, 0x10, 0x10, 0x10, 0x10,
+	0x0C, 0x1E, 0x0C, 0x1E, 0x0C,
+	0x30, 0x38, 0x3E, 0x38, 0x30,
+	0x06, 0x0E, 0x3E, 0x0E, 0x06,
+	0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x5F, 0x00, 0x00,
+	0x00, 0x07, 0x00, 0x07, 0x00,
+	0x14, 0x7F, 0x14, 0x7F, 0x14,
+	0x24, 0x2A, 0x7F, 0x2A, 0x12,
+	0x23, 0x13, 0x08, 0x64, 0x62,
+	0x36, 0x49, 0x56, 0x20, 0x50,
+	0x00, 0x08, 0x07, 0x03, 0x00,
+	0x00, 0x1C, 0x22, 0x41, 0x00,
+	0x00, 0x41, 0x22, 0x1C, 0x00,
+	0x2A, 0x1C, 0x7F, 0x1C, 0x2A,
+	0x08, 0x08, 0x3E, 0x08, 0x08,
+	0x00, 0x80, 0x70, 0x30, 0x00,
+	0x08, 0x08, 0x08, 0x08, 0x08,
+	0x00, 0x00, 0x60, 0x60, 0x00,
+	0x20, 0x10, 0x08, 0x04, 0x02,
+	0x3E, 0x51, 0x49, 0x45, 0x3E,
+	0x00, 0x42, 0x7F, 0x40, 0x00,
+	0x72, 0x49, 0x49, 0x49, 0x46,
+	0x21, 0x41, 0x49, 0x4D, 0x33,
+	0x18, 0x14, 0x12, 0x7F, 0x10,
+	0x27, 0x45, 0x45, 0x45, 0x39,
+	0x3C, 0x4A, 0x49, 0x49, 0x31,
+	0x41, 0x21, 0x11, 0x09, 0x07,
+	0x36, 0x49, 0x49, 0x49, 0x36,
+	0x46, 0x49, 0x49, 0x29, 0x1E,
+	0x00, 0x00, 0x14, 0x00, 0x00,
+	0x00, 0x40, 0x34, 0x00, 0x00,
+	0x00, 0x08, 0x14, 0x22, 0x41,
+	0x14, 0x14, 0x14, 0x14, 0x14,
+	0x00, 0x41, 0x22, 0x14, 0x08,
+	0x02, 0x01, 0x59, 0x09, 0x06,
+	0x3E, 0x41, 0x5D, 0x59, 0x4E,
+	0x7C, 0x12, 0x11, 0x12, 0x7C,
+	0x7F, 0x49, 0x49, 0x49, 0x36,
+	0x3E, 0x41, 0x41, 0x41, 0x22,
+	0x7F, 0x41, 0x41, 0x41, 0x3E,
+	0x7F, 0x49, 0x49, 0x49, 0x41,
+	0x7F, 0x09, 0x09, 0x09, 0x01,
+	0x3E, 0x41, 0x41, 0x51, 0x73,
+	0x7F, 0x08, 0x08, 0x08, 0x7F,
+	0x00, 0x41, 0x7F, 0x41, 0x00,
+	0x20, 0x40, 0x41, 0x3F, 0x01,
+	0x7F, 0x08, 0x14, 0x22, 0x41,
+	0x7F, 0x40, 0x40, 0x40, 0x40,
+	0x7F, 0x02, 0x1C, 0x02, 0x7F,
+	0x7F, 0x04, 0x08, 0x10, 0x7F,
+	0x3E, 0x41, 0x41, 0x41, 0x3E,
+	0x7F, 0x09, 0x09, 0x09, 0x06,
+	0x3E, 0x41, 0x51, 0x21, 0x5E,
+	0x7F, 0x09, 0x19, 0x29, 0x46,
+	0x26, 0x49, 0x49, 0x49, 0x32,
+	0x03, 0x01, 0x7F, 0x01, 0x03,
+	0x3F, 0x40, 0x40, 0x40, 0x3F,
+	0x1F, 0x20, 0x40, 0x20, 0x1F,
+	0x3F, 0x40, 0x38, 0x40, 0x3F,
+	0x63, 0x14, 0x08, 0x14, 0x63,
+	0x03, 0x04, 0x78, 0x04, 0x03,
+	0x61, 0x59, 0x49, 0x4D, 0x43,
+	0x00, 0x7F, 0x41, 0x41, 0x41,
+	0x02, 0x04, 0x08, 0x10, 0x20,
+	0x00, 0x41, 0x41, 0x41, 0x7F,
+	0x04, 0x02, 0x01, 0x02, 0x04,
+	0x40, 0x40, 0x40, 0x40, 0x40,
+	0x00, 0x03, 0x07, 0x08, 0x00,
+	0x20, 0x54, 0x54, 0x78, 0x40,
+	0x7F, 0x28, 0x44, 0x44, 0x38,
+	0x38, 0x44, 0x44, 0x44, 0x28,
+	0x38, 0x44, 0x44, 0x28, 0x7F,
+	0x38, 0x54, 0x54, 0x54, 0x18,
+	0x00, 0x08, 0x7E, 0x09, 0x02,
+	0x18, 0xA4, 0xA4, 0x9C, 0x78,
+	0x7F, 0x08, 0x04, 0x04, 0x78,
+	0x00, 0x44, 0x7D, 0x40, 0x00,
+	0x20, 0x40, 0x40, 0x3D, 0x00,
+	0x7F, 0x10, 0x28, 0x44, 0x00,
+	0x00, 0x41, 0x7F, 0x40, 0x00,
+	0x7C, 0x04, 0x78, 0x04, 0x78,
+	0x7C, 0x08, 0x04, 0x04, 0x78,
+	0x38, 0x44, 0x44, 0x44, 0x38,
+	0xFC, 0x18, 0x24, 0x24, 0x18,
+	0x18, 0x24, 0x24, 0x18, 0xFC,
+	0x7C, 0x08, 0x04, 0x04, 0x08,
+	0x48, 0x54, 0x54, 0x54, 0x24,
+	0x04, 0x04, 0x3F, 0x44, 0x24,
+	0x3C, 0x40, 0x40, 0x20, 0x7C,
+	0x1C, 0x20, 0x40, 0x20, 0x1C,
+	0x3C, 0x40, 0x30, 0x40, 0x3C,
+	0x44, 0x28, 0x10, 0x28, 0x44,
+	0x4C, 0x90, 0x90, 0x90, 0x7C,
+	0x44, 0x64, 0x54, 0x4C, 0x44,
+	0x00, 0x08, 0x36, 0x41, 0x00,
+	0x00, 0x00, 0x77, 0x00, 0x00,
+	0x00, 0x41, 0x36, 0x08, 0x00,
+	0x02, 0x01, 0x02, 0x04, 0x02,
+	0x3C, 0x26, 0x23, 0x26, 0x3C,
+	0x1E, 0xA1, 0xA1, 0x61, 0x12,
+	0x3A, 0x40, 0x40, 0x20, 0x7A,
+	0x38, 0x54, 0x54, 0x55, 0x59,
+	0x21, 0x55, 0x55, 0x79, 0x41,
+	0x22, 0x54, 0x54, 0x78, 0x42, // a-umlaut
+	0x21, 0x55, 0x54, 0x78, 0x40,
+	0x20, 0x54, 0x55, 0x79, 0x40,
+	0x0C, 0x1E, 0x52, 0x72, 0x12,
+	0x39, 0x55, 0x55, 0x55, 0x59,
+	0x39, 0x54, 0x54, 0x54, 0x59,
+	0x39, 0x55, 0x54, 0x54, 0x58,
+	0x00, 0x00, 0x45, 0x7C, 0x41,
+	0x00, 0x02, 0x45, 0x7D, 0x42,
+	0x00, 0x01, 0x45, 0x7C, 0x40,
+	0x7D, 0x12, 0x11, 0x12, 0x7D, // A-umlaut
+	0xF0, 0x28, 0x25, 0x28, 0xF0,
+	0x7C, 0x54, 0x55, 0x45, 0x00,
+	0x20, 0x54, 0x54, 0x7C, 0x54,
+	0x7C, 0x0A, 0x09, 0x7F, 0x49,
+	0x32, 0x49, 0x49, 0x49, 0x32,
+	0x3A, 0x44, 0x44, 0x44, 0x3A, // o-umlaut
+	0x32, 0x4A, 0x48, 0x48, 0x30,
+	0x3A, 0x41, 0x41, 0x21, 0x7A,
+	0x3A, 0x42, 0x40, 0x20, 0x78,
+	0x00, 0x9D, 0xA0, 0xA0, 0x7D,
+	0x3D, 0x42, 0x42, 0x42, 0x3D, // O-umlaut
+	0x3D, 0x40, 0x40, 0x40, 0x3D,
+	0x3C, 0x24, 0xFF, 0x24, 0x24,
+	0x48, 0x7E, 0x49, 0x43, 0x66,
+	0x2B, 0x2F, 0xFC, 0x2F, 0x2B,
+	0xFF, 0x09, 0x29, 0xF6, 0x20,
+	0xC0, 0x88, 0x7E, 0x09, 0x03,
+	0x20, 0x54, 0x54, 0x79, 0x41,
+	0x00, 0x00, 0x44, 0x7D, 0x41,
+	0x30, 0x48, 0x48, 0x4A, 0x32,
+	0x38, 0x40, 0x40, 0x22, 0x7A,
+	0x00, 0x7A, 0x0A, 0x0A, 0x72,
+	0x7D, 0x0D, 0x19, 0x31, 0x7D,
+	0x26, 0x29, 0x29, 0x2F, 0x28,
+	0x26, 0x29, 0x29, 0x29, 0x26,
+	0x30, 0x48, 0x4D, 0x40, 0x20,
+	0x38, 0x08, 0x08, 0x08, 0x08,
+	0x08, 0x08, 0x08, 0x08, 0x38,
+	0x2F, 0x10, 0xC8, 0xAC, 0xBA,
+	0x2F, 0x10, 0x28, 0x34, 0xFA,
+	0x00, 0x00, 0x7B, 0x00, 0x00,
+	0x08, 0x14, 0x2A, 0x14, 0x22,
+	0x22, 0x14, 0x2A, 0x14, 0x08,
+	0x55, 0x00, 0x55, 0x00, 0x55, // #176 (25% block) missing in old code
+	0xAA, 0x55, 0xAA, 0x55, 0xAA, // 50% block
+	0xFF, 0x55, 0xFF, 0x55, 0xFF, // 75% block
+	0x00, 0x00, 0x00, 0xFF, 0x00,
+	0x10, 0x10, 0x10, 0xFF, 0x00,
+	0x14, 0x14, 0x14, 0xFF, 0x00,
+	0x10, 0x10, 0xFF, 0x00, 0xFF,
+	0x10, 0x10, 0xF0, 0x10, 0xF0,
+	0x14, 0x14, 0x14, 0xFC, 0x00,
+	0x14, 0x14, 0xF7, 0x00, 0xFF,
+	0x00, 0x00, 0xFF, 0x00, 0xFF,
+	0x14, 0x14, 0xF4, 0x04, 0xFC,
+	0x14, 0x14, 0x17, 0x10, 0x1F,
+	0x10, 0x10, 0x1F, 0x10, 0x1F,
+	0x14, 0x14, 0x14, 0x1F, 0x00,
+	0x10, 0x10, 0x10, 0xF0, 0x00,
+	0x00, 0x00, 0x00, 0x1F, 0x10,
+	0x10, 0x10, 0x10, 0x1F, 0x10,
+	0x10, 0x10, 0x10, 0xF0, 0x10,
+	0x00, 0x00, 0x00, 0xFF, 0x10,
+	0x10, 0x10, 0x10, 0x10, 0x10,
+	0x10, 0x10, 0x10, 0xFF, 0x10,
+	0x00, 0x00, 0x00, 0xFF, 0x14,
+	0x00, 0x00, 0xFF, 0x00, 0xFF,
+	0x00, 0x00, 0x1F, 0x10, 0x17,
+	0x00, 0x00, 0xFC, 0x04, 0xF4,
+	0x14, 0x14, 0x17, 0x10, 0x17,
+	0x14, 0x14, 0xF4, 0x04, 0xF4,
+	0x00, 0x00, 0xFF, 0x00, 0xF7,
+	0x14, 0x14, 0x14, 0x14, 0x14,
+	0x14, 0x14, 0xF7, 0x00, 0xF7,
+	0x14, 0x14, 0x14, 0x17, 0x14,
+	0x10, 0x10, 0x1F, 0x10, 0x1F,
+	0x14, 0x14, 0x14, 0xF4, 0x14,
+	0x10, 0x10, 0xF0, 0x10, 0xF0,
+	0x00, 0x00, 0x1F, 0x10, 0x1F,
+	0x00, 0x00, 0x00, 0x1F, 0x14,
+	0x00, 0x00, 0x00, 0xFC, 0x14,
+	0x00, 0x00, 0xF0, 0x10, 0xF0,
+	0x10, 0x10, 0xFF, 0x10, 0xFF,
+	0x14, 0x14, 0x14, 0xFF, 0x14,
+	0x10, 0x10, 0x10, 0x1F, 0x00,
+	0x00, 0x00, 0x00, 0xF0, 0x10,
+	0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+	0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
+	0xFF, 0xFF, 0xFF, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0xFF, 0xFF,
+	0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
+	0x38, 0x44, 0x44, 0x38, 0x44,
+	0xFC, 0x4A, 0x4A, 0x4A, 0x34, // sharp-s or beta
+	0x7E, 0x02, 0x02, 0x06, 0x06,
+	0x02, 0x7E, 0x02, 0x7E, 0x02,
+	0x63, 0x55, 0x49, 0x41, 0x63,
+	0x38, 0x44, 0x44, 0x3C, 0x04,
+	0x40, 0x7E, 0x20, 0x1E, 0x20,
+	0x06, 0x02, 0x7E, 0x02, 0x02,
+	0x99, 0xA5, 0xE7, 0xA5, 0x99,
+	0x1C, 0x2A, 0x49, 0x2A, 0x1C,
+	0x4C, 0x72, 0x01, 0x72, 0x4C,
+	0x30, 0x4A, 0x4D, 0x4D, 0x30,
+	0x30, 0x48, 0x78, 0x48, 0x30,
+	0xBC, 0x62, 0x5A, 0x46, 0x3D,
+	0x3E, 0x49, 0x49, 0x49, 0x00,
+	0x7E, 0x01, 0x01, 0x01, 0x7E,
+	0x2A, 0x2A, 0x2A, 0x2A, 0x2A,
+	0x44, 0x44, 0x5F, 0x44, 0x44,
+	0x40, 0x51, 0x4A, 0x44, 0x40,
+	0x40, 0x44, 0x4A, 0x51, 0x40,
+	0x00, 0x00, 0xFF, 0x01, 0x03,
+	0xE0, 0x80, 0xFF, 0x00, 0x00,
+	0x08, 0x08, 0x6B, 0x6B, 0x08,
+	0x36, 0x12, 0x36, 0x24, 0x36,
+	0x06, 0x0F, 0x09, 0x0F, 0x06,
+	0x00, 0x00, 0x18, 0x18, 0x00,
+	0x00, 0x00, 0x10, 0x10, 0x00,
+	0x30, 0x40, 0xFF, 0x01, 0x01,
+	0x00, 0x1F, 0x01, 0x01, 0x1E,
+	0x00, 0x19, 0x1D, 0x17, 0x12,
+	0x00, 0x3C, 0x3C, 0x3C, 0x3C,
+	0x00, 0x00, 0x00, 0x00, 0x00  // #255 NBSP
+};
+#endif // FONT5X7_H
Index: /rtos_arduino/trunk/arduino_lib/libraries/NAxesMotion/NAxisMotion.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/NAxesMotion/NAxisMotion.h	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/NAxesMotion/NAxisMotion.h	(revision 175)
@@ -137,9 +137,5 @@
 	*Return Parameter: None
 	*******************************************************************************************/
-#if defined(ARDUINO_ARCH_SAMD)
-	void initSensor(unsigned int address = 0x29);
-#else /* !defined(ARDUINO_ARCH_SAMD) */    
 	void initSensor(unsigned int address = 0x28);
-#endif /* defined(ARDUINO_ARCH_SAMD) */  
 
 	/*******************************************************************************************
Index: /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/ALARM_interrupt/ALARM_interrupt.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/ALARM_interrupt/ALARM_interrupt.ino	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/ALARM_interrupt/ALARM_interrupt.ino	(revision 175)
@@ -3,4 +3,8 @@
 This mode is more conveniently because you use processor for other tasks and when alarm match occurs interrupt routine is executed.
 In this way, alarm flag checking is indipendent from main program flow.
+
+NOTE: for M0/M0 pro only you can select the oscillator source for count.
+If you want to use a low power oscillator use rtc.begin(TIME_H24, LOW_POWER); function.
+If you want to use a more accurate oscillator use rtc.begin(TIME_H24, HIGH_PRECISION); function.
 ******************************************************************************************************************************************************************************/
 
@@ -18,7 +22,7 @@
   rtc.setDate(13,8,15);     //setting date
   rtc.enableAlarm(SEC,ALARM_INTERRUPT,alarm_int); //enabling alarm in polled mode and match on second
-  rtc.local_time.hour=17;
-  rtc.local_time.minute=5;
-  rtc.local_time.second=10;  //setting second to match
+  rtc.time.hour=17;
+  rtc.time.minute=5;
+  rtc.time.second=10;  //setting second to match
   rtc.setAlarm();  //write second in alarm register
 }
Index: /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/ALARM_polled/ALARM_polled.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/ALARM_polled/ALARM_polled.ino	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/ALARM_polled/ALARM_polled.ino	(revision 175)
@@ -2,4 +2,8 @@
 * This sketch demonstrates how configure alarm in polled mode.
   In this mode you hav to check continuously ALARM0 flag in the main program code.
+  
+  NOTE: for M0/M0 pro only you can select the oscillator source for count.
+If you want to use a low power oscillator use rtc.begin(TIME_H24, LOW_POWER); function.
+If you want to use a more accurate oscillator use rtc.begin(TIME_H24, HIGH_PRECISION); function.
 *********************************************************************************************************************************************************************************/  
 
@@ -17,7 +21,7 @@
   rtc.setDate(13,8,15);     //setting date
   rtc.enableAlarm(SEC,ALARM_POLLED,NULL); //enabling alarm in polled mode and match on second
-  rtc.local_time.hour=17;
-  rtc.local_time.minute=5;
-  rtc.local_time.second=10;  //setting second to match
+  rtc.time.hour=17;
+  rtc.time.minute=5;
+  rtc.time.second=10;  //setting second to match
   rtc.setAlarm();  //write second in alarm register
 }
Index: /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/RTC_simple/RTC_simple.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/RTC_simple/RTC_simple.ino	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/RTC_simple/RTC_simple.ino	(revision 175)
@@ -2,4 +2,8 @@
 This sketch gives a simple demonstration of how to use RTC library.
 The code sets date and time using internal structure and then print on serial date and time. Time representation is 12 hour mode
+
+NOTE: for M0/M0 pro only you can select the oscillator source for count.
+If you want to use a low power oscillator use rtc.begin(TIME_H12, LOW_POWER); function.
+If you want to use a more accurate oscillator use rtc.begin(TIME_H12, HIGH_PRECISION); function.
 **********************************************************************************************************************************************************/
 
@@ -17,13 +21,13 @@
   
   //filling internal structure for time
-  rtc.local_time.hour = 10;          //hour
-  rtc.local_time.minute = 44;       //minute
-  rtc.local_time.second = 0;        //second
-  rtc.local_time.Tmode = ANTI_MERIDIAN;  
+  rtc.time.hour = 10;          //hour
+  rtc.time.minute = 44;       //minute
+  rtc.time.second = 0;        //second
+  rtc.time.Tmode = ANTI_MERIDIAN;  
   
   //filling internal structure for date
-  rtc.local_date.day = 13;        //day
-  rtc.local_date.month = 8;       //month
-  rtc.local_date.year = 15;       //year
+  rtc.date.day = 13;        //day
+  rtc.date.month = 8;       //month
+  rtc.date.year = 15;       //year
   
   rtc.setTime();  //setting time
@@ -42,19 +46,19 @@
  
  //printing date in format YYYY/MM/DD
- Serial.print(rtc.local_date.year+2000); // year
+ Serial.print(rtc.date.year+2000); // year
  Serial.print('/');
- Serial.print(rtc.local_date.month);    // month
+ Serial.print(rtc.date.month);    // month
  Serial.print('/');
- Serial.print(rtc.local_date.day);      // day
+ Serial.print(rtc.date.day);      // day
  Serial.print(' ');
  
  //printing time
- Serial.print(rtc.local_time.hour);    //hour
+ Serial.print(rtc.time.hour);    //hour
  Serial.print(':');
- Serial.print(rtc.local_time.minute);  //minute
+ Serial.print(rtc.time.minute);  //minute
  Serial.print(':');
- Serial.print(rtc.local_time.second);  //second
+ Serial.print(rtc.time.second);  //second
  Serial.print (' ');
- if(rtc.local_time.Tmode == ANTI_MERIDIAN) Serial.println("AM"); // print AM or PM
+ if(rtc.time.Tmode == ANTI_MERIDIAN) Serial.println("AM"); // print AM or PM
  else Serial.println("PM");
  
Index: /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/RTC_simple_24H_mode/RTC_simple_24H_mode.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/RTC_simple_24H_mode/RTC_simple_24H_mode.ino	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/RTC/examples/RTC_simple_24H_mode/RTC_simple_24H_mode.ino	(revision 175)
@@ -2,4 +2,8 @@
 This sketch gives a simple demonstration of how to use RTC library.
 The code sets date and time using internal structure and then print on serial date and time. Time representation is 24 hour mode
+
+NOTE: for M0/M0 pro only you can select the oscillator source for count.
+If you want to use a low power oscillator use rtc.begin(TIME_H24, LOW_POWER); function.
+If you want to use a more accurate oscillator use rtc.begin(TIME_H24, HIGH_PRECISION); function.
 **********************************************************************************************************************************************************/
 
@@ -34,17 +38,17 @@
  
  //printing date in format YYYY/MM/DD
- Serial.print(rtc.local_date.year+2000); // year
+ Serial.print(rtc.date.year+2000); // year
  Serial.print('/');
- Serial.print(rtc.local_date.month);    // month
+ Serial.print(rtc.date.month);    // month
  Serial.print('/');
- Serial.print(rtc.local_date.day);      // day
+ Serial.print(rtc.date.day);      // day
  Serial.print(' ');
  
  //printing time
- Serial.print(rtc.local_time.hour);    //hour
+ Serial.print(rtc.time.hour);    //hour
  Serial.print(':');
- Serial.print(rtc.local_time.minute);  //minute
+ Serial.print(rtc.time.minute);  //minute
  Serial.print(':');
- Serial.println(rtc.local_time.second);  //second
+ Serial.println(rtc.time.second);  //second
  
  delay(1000);
Index: /rtos_arduino/trunk/arduino_lib/libraries/RTC/src/RTCInt.cpp
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/RTC/src/RTCInt.cpp	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/RTC/src/RTCInt.cpp	(revision 175)
@@ -2,15 +2,12 @@
   RTC library for Arduino M0/M0PRO.
   Copyright (c) 2015 Arduino SRL. All right reserved.
-
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
-
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   Lesser General Public License for more details.
-
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
@@ -28,5 +25,5 @@
 *Return Parameter: None
 *******************************************************************************************/
-void RTCInt::begin(bool timeRep) 
+void RTCInt::begin(bool timeRep, int oscillatorType) 
 {
   
@@ -37,5 +34,13 @@
   while (GCLK->STATUS.bit.SYNCBUSY);
   
-  GCLK->GENCTRL.reg = (GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_ID(4) | GCLK_GENCTRL_DIVSEL );
+  //Set the oscillator to use - M0 only
+  if(oscillatorType==HIGH_PRECISION)
+  //External oscillator
+  GCLK->GENCTRL.reg = (GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_XOSC32K | GCLK_GENCTRL_ID(4) | GCLK_GENCTRL_DIVSEL );
+  
+  else
+  //Internal low power oscillator (default configuration)
+  GCLK->GENCTRL.reg = (GCLK_GENCTRL_GENEN |  GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_ID(4) | GCLK_GENCTRL_DIVSEL );
+  
   while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);
   
@@ -73,4 +78,8 @@
   RTCenable();
   
+}
+
+void RTCInt::begin(bool timeRep){
+    begin(timeRep, LOW_POWER);
 }
 
@@ -132,5 +141,5 @@
 
 /**********************************************************************************************************************
-*Description: Function for getting time (hours, minutes and seconds). This function fills a structure called local_time
+*Description: Function for getting time (hours, minutes and seconds). This function fills a structure called time
 			  accessible in the class RTCInt.	
 *Input Parameters: None
@@ -141,13 +150,13 @@
 	unsigned int hour=0, h=0;
 	
-	local_time.hour = getHour();
+	time.hour = getHour();
 	if(time_Mode == TIME_H12)
 	{
 		h=RTC->MODE2.CLOCK.bit.HOUR;
 		while (RTCSync());
-		local_time.Tmode = h & 0x10;
+		time.Tmode = h & 0x10;
 	}	
-	local_time.minute = getMinute();
-	local_time.second = getSecond();
+	time.minute = getMinute();
+	time.second = getSecond();
 }
 
@@ -219,5 +228,5 @@
 
 /**********************************************************************************************************************
-*Description: Function for getting date (day, month and year). This function fills a structure called local_date
+*Description: Function for getting date (day, month and year). This function fills a structure called date
 			  accessible in the class RTCInt.	
 *Input Parameters: None
@@ -226,7 +235,7 @@
 void RTCInt::getDate(void)
 {
-	local_date.day = getDay();
-	local_date.month = getMonth();
-	local_date.year = getYear();
+	date.day = getDay();
+	date.month = getMonth();
+	date.year = getYear();
 }
 
@@ -315,5 +324,5 @@
 /**********************************************************************************************************************
 *Description: Function for setting time (hour, minute and second). This function sets time retrieving values from a 
-			  local structure called local_time accessible in the class RTCInt.	
+			  local structure called time accessible in the class RTCInt.	
 *Input Parameters: None
 *Return Parameter: None
@@ -321,7 +330,7 @@
 void RTCInt::setTime(void)
 {
-	setHour(local_time.hour,local_time.Tmode);
-    setMinute(local_time.minute);
-    setSecond(local_time.second);  
+	setHour(time.hour,time.Tmode);
+    setMinute(time.minute);
+    setSecond(time.second);  
 }
 
@@ -397,5 +406,5 @@
 /**********************************************************************************************************************
 *Description: Function for setting date (day, month and year). This function retrieves values from a local structure 
-			  called local_date accessible in the class RTCInt.	
+			  called date accessible in the class RTCInt.	
 *Input Parameters: None
 *Return Parameter: None
@@ -403,7 +412,7 @@
 void RTCInt::setDate(void)
 {
-	setDay(local_date.day);
-	setMonth(local_date.month);  
-    setYear(local_date.year);
+	setDay(date.day);
+	setMonth(date.month);  
+    setYear(date.year);
 }
 
@@ -461,6 +470,6 @@
  /**********************************************************************************************************************
 *Description: Function for setting alarm. This function retrieves values from two local structures 
-			  called local_date and local_time accessible in the class RTCInt. According to match alarm type, values 
-			  can be obtained from local_time, local_date or both structures.	
+			  called date and time accessible in the class RTCInt. According to match alarm type, values 
+			  can be obtained from time, date or both structures.	
 *Input Parameters: None
 *Return Parameter: None
@@ -474,55 +483,55 @@
       break;
    case SEC :
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= local_time.second;
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= time.second;
 	  while (RTCSync());
 	  break;	
    case MMSS :
-      RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= local_time.minute;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= local_time.second;
+      RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= time.minute;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= time.second;
 	  while (RTCSync());
 	  break;
    case HHMMSS :
-      RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= local_time.hour;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= local_time.minute;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= local_time.second;
+      RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= time.hour;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= time.minute;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= time.second;
 	  while (RTCSync());
       break;
    case DDHHMMSS :
-      RTC->MODE2.Mode2Alarm->ALARM.bit.DAY= local_date.day;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= local_time.hour;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= local_time.minute;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= local_time.second;
+      RTC->MODE2.Mode2Alarm->ALARM.bit.DAY= date.day;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= time.hour;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= time.minute;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= time.second;
 	  while (RTCSync());
       break;
    case MMDDHHMMSS :
-      RTC->MODE2.Mode2Alarm->ALARM.bit.MONTH= local_date.month;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.DAY= local_date.day;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= local_time.hour;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= local_time.minute;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= local_time.second;
+      RTC->MODE2.Mode2Alarm->ALARM.bit.MONTH= date.month;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.DAY= date.day;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= time.hour;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= time.minute;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= time.second;
 	  while (RTCSync());
       break;
    case YYMMDDHHMMSS :
-      RTC->MODE2.Mode2Alarm->ALARM.bit.YEAR= local_date.year;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.MONTH= local_date.month;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.DAY= local_date.day;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= local_time.hour;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= local_time.minute;
-	  while (RTCSync());
-	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= local_time.second;
+      RTC->MODE2.Mode2Alarm->ALARM.bit.YEAR= date.year;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.MONTH= date.month;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.DAY= date.day;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.HOUR= time.hour;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.MINUTE= time.minute;
+	  while (RTCSync());
+	  RTC->MODE2.Mode2Alarm->ALARM.bit.SECOND= time.second;
 	  while (RTCSync());
       break;	  
Index: /rtos_arduino/trunk/arduino_lib/libraries/RTC/src/RTCInt.h
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/RTC/src/RTCInt.h	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/RTC/src/RTCInt.h	(revision 175)
@@ -2,15 +2,12 @@
   RTC library for Arduino Zero.
   Copyright (c) 2015 Arduino LLC. All right reserved.
-
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
-
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   Lesser General Public License for more details.
-
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
@@ -38,4 +35,8 @@
 #define POST_MERIDIAN 1
 
+//Parameter for oscillatorType - M0 only
+#define HIGH_PRECISION 0
+#define LOW_POWER 1
+
 #include "Arduino.h"
 
@@ -60,7 +61,8 @@
   RTCInt() {};
   
-  TIME local_time;
-  DATE local_date;
+  TIME time;
+  DATE date;
   
+  void begin(bool timeMode, int oscillatorType);
   void begin(bool timeMode);
   
Index: /rtos_arduino/trunk/arduino_lib/libraries/Rest/library.properties
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/Rest/library.properties	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/Rest/library.properties	(revision 175)
@@ -5,5 +5,5 @@
 sentence=Allows to use the sleep functionalities. For Arduino M0 or M0PRO only.
 paragraph=With this library you can manage power on an Arduino M0/M0PRO.
-category=power
+category=Device Control
 url=http://www.arduino.org
 architectures=samd
Index: /rtos_arduino/trunk/arduino_lib/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino
===================================================================
--- /rtos_arduino/trunk/arduino_lib/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino	(revision 174)
+++ /rtos_arduino/trunk/arduino_lib/libraries/TFT/examples/Arduino/TFTDisplayText/TFTDisplayText.ino	(revision 175)
@@ -21,6 +21,6 @@
 // pin definition for the Uno
 #define cs   10
-#define dc   8
-#define rst  9
+#define dc   9
+#define rst  8
 
 // pin definition for the Leonardo
