void *joystickStart() {
	int value;
 	while(1) {
 		pollDelay();
 		value = checkInput();
 		if(value) {
 			nxtMove(value);
 			actionDelay();
 		}
 		else if(mapButtonPressed) {
 			nxtMove(5);
 			mapButtonPressed = false;
 		}
 	}
 }
I2C::I2C(int scl, int sda, int freq)
{  
	// only allow speeds up to 400khz for now
	if (freq > 400000)
		freq = 400000;

    //I2C_INIT init;
    m_par.cog            		= -1;
    m_par.init.scl       		= scl;
    m_par.init.sda       		= sda;
    m_par.init.ticks_per_cycle 	= (CLKFREQ / freq)-25;
    m_par.init.mailbox   		= &m_par.mailbox;
    m_par.mailbox.cmd    		= I2C_CMD_INIT;
    
    // Start the COG according to the method needed for LMM/XMM memory models
    #if defined(__PROPELLER_XMMC__) || defined(__PROPELLER_XMM__)
        int size = _load_stop_I2CDriver_cog - _load_start_I2CDriver_cog;
        unsigned int cogbuffer[size];
        // memcpy does bytes, so we copy numbytes * 4 = num ints.      
        memcpy(cogbuffer, _load_start_I2CDriver_cog, size<<2);
    #else
        int *cogbuffer = (int*)_load_start_I2CDriver_cog;
    #endif
    
    m_par.cog = cognew(cogbuffer, &m_par.init);

    volatile int n;
    while (m_par.mailbox.cmd != I2C_CMD_IDLE)
    {
        if (n > 127)
        {
            m_ready = 0;
            return;          // Timeout waiting after ~3.8ms
        }
        pollDelay();        // Wait 30 uSecs.
        n++;
    }

    m_ready = 1;
}
int main(void)
{

/*  Initialise hardware timers and ports. All start off as inputs */
/*  PD0 is RxD
    PD1 is TxD */
/** PORTB is set as outputs on bits 0,3,4 to set controls.
    The SPI output ports SCK and MOSI stay as inputs until ready to program.
    Set the Ports PB0-2 as outputs and set high to turn off all LEDs
    PB0 = programming mode LED
    PB3 = programming completed LED (and serial comms switch over)
    PB4 = programming active LED (and reset out)
    PB5 = MOSI
    PB6 = MISO
    PB7 = SCK */

    sbi(ACSR,7);                                        // Turn off Analogue Comparator
    initbootuart();           	                        // Initialize UART.
    uint8_t sigByte1=0;                                 // Target Definition defaults
    uint8_t sigByte2=0;
    uint8_t sigByte3=0;
    uint8_t fuseBits=0;
    uint8_t highFuseBits=0;
    uint8_t extendedFuseBits=0;
    uint8_t lockBits=0;

/*---------------------------------------------------------------------------*/
/* Main loop. We exit this only with an "E" command. */
    {
        for(;;)
        {
            command=recchar();                          // Loop and wait for command character.

/** 'a' Check autoincrement status.
This allows a block of data to be uploaded to consecutive addresses without
specifying the address each time */
            if (command=='a')
            {
                sendchar('Y');                          // Yes, we will autoincrement.
            }

/** 'A' Set address.
This is stored and incremented for each upload/download.
NOTE: Flash addresses are given as word addresses, not byte addresses. */
            else if (command=='A')                       // Set address
            {
                address = (recchar()<<8);               // Set address high byte first.
                address |= recchar();                   // Then low byte.
                sendchar('\r');                         // Send OK back.
            }

/** 'b' Check block load support. This returns the allowed block size.
We will not buffer anything so we will use the FLASH page size to limit
the programmer's blocks to those that will fit the target's page. This then avoids
the long delay when the page is committed, that may cause incoming data to be lost.
This should not be called before the P command is executed, and the target device
characteristics obtained. The fPageSize characteristic should be non zero.*/
           else if (command=='b')
            {
                uint16_t blockLength = ((uint16_t)fPageSize<<1);
                if (fPageSize > 0) sendchar('Y');       // Report block load supported.
                else sendchar('N');
                sendchar(high(blockLength));            // MSB first.
                sendchar(low(blockLength));             // Report FLASH pagesize (bytes).
            }

/** 'p' Get programmer type. This returns just 'S' for serial. */
            else if (command=='p')
            {
                sendchar('S');                          // Answer 'SERIAL'.
            }

/** 'S' Return programmer identifier. Always 7 digits. We call it AVRSPRG */
            else if (command=='S')
            {
                sendchar('A');
                sendchar('V');                          // ID always 7 characters.
                sendchar('R');
                sendchar('S');
                sendchar('P');
                sendchar('R');
                sendchar('G');
            }

/** 'V' Return software version. */
            else if (command=='V')
            {
                sendchar('0');
                sendchar('0');
            }

/** 't' Return supported device codes. This returns a list of devices that can be programmed.
This is only used by AVRPROG so we will not use it - we work with signature bytes instead. */
            else if(command=='t')
            {
                sendchar( 0 );                          // Send list terminator.
            }

/** 'x' Set LED. */
            else if ((command=='x') || (command=='y') || (command=='T'))
            {
//                if (command=='x') sbi(PORTB,LED);
//                else if (command=='y') cbi(PORTB,LED);
                recchar();                              // Discard sent value
                sendchar('\r');                         // Send OK back.
            }

/** 'P' Enter programming mode.
This starts the programming of the device. Pulse the reset line high while SCK is low.
Send the command and ensure that the echoed second byte is correct, otherwise redo.
With this we get the device signature and search the table for its characteristics.
A timeout is provided in case the device doesn't respond. This will allow fall through
to an ultimate error response.
The reset line is held low until programming mode is exited. */
            else if (command=='P')
            {
                outb(DDRB,(inb(DDRB) | 0xB9));          // Setup SPI output ports
                outb(PORTB,(inb(PORTB) | 0xB9));        // SCK and MOSI high, and LEDs off
                uint8_t retry = 10;
                uint8_t result = 0;
                while ((result != 0x53) && (retry-- > 0))
                {
                    cbi(PORTB,SCK);                     // Set serial clock low
                    sbi(PORTB,RESET);                   // Pulse reset line off
                    _delay_us(100);                     // Delay to let CPU know that programming will occur
                    cbi(PORTB,RESET);                   // Pulse reset line on
                    _delay_us(25000);                   // 25ms delay
                    writeCommand(0xAC,0x53,0x00,0x00);  // "Start programming" command
                    result=buffer[2];
                }
/** Once we are in programming mode, grab the signature bytes and extract all information
about the target device such as its memory sizes, page sizes and capabilities. */
                writeCommand(0x30,0x00,0x00,0x00);
                sigByte1 = buffer[3];
                writeCommand(0x30,0x00,0x01,0x00);
                sigByte2 = buffer[3];
                writeCommand(0x30,0x00,0x02,0x00);      // Signature Bytes
                sigByte3 = buffer[3];
/* Check for device support. If the first signature byte is not 1E, then the device is
either not an Atmel device, is locked, or is not responding.*/
                uint8_t found=FALSE;                    // Indicates if the target device is supported
                uint8_t partNo = 0;
                if (sigByte1 == 0x1E)
                {
                    while ((partNo < NUMPARTS) && (! found))
                    {
                        found = ((part[partNo][0] == sigByte2) && (part[partNo][1] == sigByte3));
                        partNo++;
                    }
                }
                if (found)
                {
                    partNo--;
                    sendchar('\r');
                    fPageSize = part[partNo][2];
                    ePageSize = part[partNo][3];
                    canCheckBusy = part[partNo][4];
                    lfCapability = part[partNo][5];
                    buffer[3] = 0;                      // In case we cannot read these
                    if (lfCapability & 0x08) writeCommand(0x50,0x08,0x00,0x00);  // Read Extended Fuse Bits
                    extendedFuseBits = buffer[3];
                    if (lfCapability & 0x04) writeCommand(0x58,0x08,0x00,0x00);  // Read High Fuse Bits
                    highFuseBits = buffer[3];
                    if (lfCapability & 0x02) writeCommand(0x50,0x00,0x00,0x00);  // Read Fuse Bits
                    fuseBits = buffer[3];
                    if (lfCapability & 0x01) writeCommand(0x58,0x00,0x00,0x00);  // Read Lock Bits
                    lockBits = buffer[3];
                }
                else                                    // Not found?
                {
                    sbi(PORTB,RESET);                   // Lift reset line
                    sendchar('?');                      // Device cannot be programmed
                    outb(DDRB,(inb(DDRB) & ~0xA0));     // Set SPI ports to inputs
                }
            }

/** 'L' Leave programming mode. */
            else if(command=='L')
            {
                sbi(PORTB,RESET);                       // Turn reset line off
                sendchar('\r');                         // Answer OK.
                outb(DDRB,(inb(DDRB) & ~0xA0));         // Set SPI ports to inputs
            }

/** 'e' Chip erase.
This requires several ms. Ensure that the command has finished before acknowledging. */
            else if (command=='e')
            {
                writeCommand(0xAC,0x80,0x00,0x00);      // Erase command
                pollDelay(FALSE);
                sendchar('\r');                         // Send OK back.
            }

/** 'R' Read program memory */
            else if (command=='R')
            {
/** Send high byte, then low byte of flash word.
Send each byte from the address specified (note address variable is modified).*/
                lsbAddress = low(address);
                msbAddress = high(address);
                writeCommand(0x28,msbAddress,lsbAddress,0x00);  // Read high byte
                sendchar(buffer[3]);
                writeCommand(0x20,msbAddress,lsbAddress,0x00);  // Read low byte
                sendchar(buffer[3]);
                address++;                              // Auto-advance to next Flash word.
            }

/** 'c' Write to program memory page buffer, low byte.
NOTE: Always use this command before sending the high byte. It is written to the
page but the address is not incremented.*/
            else if (command=='c')
            {
                received = recchar();
                writeCommand(0x40,0x00,address & 0x7F,received);    // Low byte
                sendchar('\r');                         // Send OK back.
            }

/** 'C' Write to program memory page buffer, high byte.
This will cause the word to be written to the page and the address incremented. It is
the responsibility of the user to issue a page write command.*/
            else if (command=='C')
            {
                received = recchar();
                writeCommand(0x48,0x00,address & 0x7F,received);    // High Byte
                address++;                              // Auto-advance to next Flash word.
                sendchar('\r');                         // Send OK back.
            }

/** 'm' Issue Page Write. This writes the target device page buffer to the Flash.
The address is that of the page, with the lower bits masked out.
This requires several ms. Ensure that the command has finished before acknowledging.
We could check for end of memory here but that would require storing the Flash capacity
for each device. The calling program will know in any case if it has overstepped.*/
            else if (command== 'm')
            {
                writeCommand(0x4C,(address>>8) & 0x7F,address & 0xE0,0x00);  // Write Page
                pollDelay(TRUE);                        // Short delay
                sendchar('\r');                         // Send OK back.
            }
/** 'D' Write EEPROM memory
This writes the byte directly to the EEPROM at the specified address.
This requires several ms. Ensure that the command has finished before acknowledging.*/
            else if (command == 'D')
            {
                lsbAddress = low(address);
                msbAddress = high(address);
                writeCommand(0xC0,msbAddress,lsbAddress,recchar());     // EEPROM byte
                address++;                              // Auto-advance to next EEPROM byte.
                pollDelay(FALSE);                       // Long delay
                sendchar('\r');                         // Send OK back.
            }

/** 'd' Read EEPROM memory */
            else if (command == 'd')
            {
                lsbAddress = low(address);
                msbAddress = high(address);
                writeCommand(0xA0,msbAddress,lsbAddress, 0x00);
                sendchar(buffer[3]);
                address++;                              // Auto-advance to next EEPROM byte.
            }

/** 'B' Start block load.
 The address must have already been set otherwise it will be undefined. */
            else if (command=='B')
            {
                tempInt = (recchar()<<8);               // Get block size high byte first.
                tempInt |= recchar();                   // Low Byte.
                sendchar(BlockLoad(tempInt,recchar(),&address));  // Block load.
            }

/** 'g' Start block read.
 The address must have already been set otherwise it will be undefined.*/
            else if (command=='g')
            {
                tempInt = (recchar()<<8);               // Get block size high byte first.
                tempInt |= recchar();                   // Low Byte.
                command = recchar();                    // Get memory type
                BlockRead(tempInt,command,&address);    // Block read
            }
/** 'r' Read lock bits. */
            else if (command=='r')
            {
                sendchar(lockBits);
            }

/** 'l' Write lockbits. */
            else if (command=='l')
            {
                if (lfCapability & 0x10) writeCommand(0xAC,0xE0,0x00,recchar());
                sendchar('\r');                         // Send OK back.
            }

/** 'F' Read fuse bits. */
            else if (command=='F')
            {
                sendchar(fuseBits);
            }

/** 'f' Write fuse bits. */
            else if (command=='f')
            {
                if (lfCapability & 0x20) writeCommand(0xAC,0xA0,0x00,recchar()); // Fuse byte
                sendchar('\r');                         // Send OK back.
            }

/** 'N' Read high fuse bits. */
            else if (command=='N')
            {
                sendchar(highFuseBits);
            }

/** 'n' Write high fuse bits. */
            else if (command=='n')
            {
                if (lfCapability & 0x40) writeCommand(0xAC,0xA8,0x00,recchar()); // High Fuse byte
                sendchar('\r');                         // Send OK back.
            }

/** 'Q' Read extended fuse bits. */
            else if (command=='Q')
            {
                sendchar(extendedFuseBits);
            }

/** 'q' Write extended fuse bits. */
            else if (command=='q')
            {
                if (lfCapability & 0x80) writeCommand(0xAC,0xA4,0x00,recchar()); // Extended Fuse byte
                sendchar('\r');                         // Send OK back.
            }

/** 's' Return signature bytes. Sent Most Significant Byte first. */
            else if (command=='s')
            {
                sendchar(sigByte3);
                sendchar(sigByte2);
                sendchar(sigByte1);
            }

/** 'E' Exit bootloader.
At this command we enter serial passthrough and don't return from it until a
hardware reset occurs.
At the same time we should lift the reset from the target. Spin endlessly so we
don't interpret serial data, and wait for our own hard reset.*/
            else if (command=='E')
            {
                sendchar('\r');
                sbi(PORTB,RESET);                       // Pulse reset line off
                cbi(PORTB,PASSTHROUGH);                 // Change to serial passthrough
                outb(DDRB,(inb(DDRB) & ~0xA0));         // Set SPI ports to inputs
                for (;;);                    // Spin endlessly
            }

/** The last command to accept is ESC (synchronization).
This is used to abort any command by filling in remaining parameters, after which
it is simply ignored.
Otherwise, the command is not recognized and a "?" is returned.*/
            else if (command!=0x1b) sendchar('?');       // If not ESC, then it is unrecognized
        }