Example #1
0
void write_code_EE_2( unsigned long address, unsigned char* data, char blocksize, char lastblock )
{
	unsigned char i, tries;
	char blockcounter;

	tries = 0;
restart:
	I2C_start();
	I2C_write( 0xA0 | (address >= 0x10000? 8: 0) ); 	//Device Address + 0=write

	I2C_write( (unsigned char) ((address & 0xFF00) >> 8) ); //MSB
	I2C_write( (unsigned char) ((address & 0x00FF)) );	//LSB

	for( blockcounter = 0; blockcounter < blocksize; blockcounter++ )
	{
		i = (unsigned int) I2C_write( data[blockcounter] );
		if( i == 1 )   // received a NACK
		{
			for( i = 0; i < 4; i++ ) {
				setLeds( 7);
				DelayMs(125);
				setLeds(0);
				DelayMs( 125 );
			}
			I2C_stop();
			DelayMs(30);
			if( tries < 2 )
				goto restart;
			return; // what else to do??
		}
	}
	I2C_stop();
	DelayMs( 30 );
}
task usercontrol()
{
	word button5U2Last,
		button5D2Last;

	// User control code here, inside the loop

	while (true)
	{
		arcade4(vexRT[Ch1], vexRT[Ch3], flWheel, blWheel, frWheel, brWheel);
		joyDigiMtr2(roller, vexRT[Btn6U], 127, vexRT[btn6D], -127);
		setMotor(elevator, vexRT[Ch2Xmtr2]);
		if(vexRT[Btn5UXmtr2] && !button5U2Last) {
			flyTarget += 5;
		}
		else if(vexRT[Btn5DXmtr2] && !button5D2Last) {
			flyTarget -= 5;
		}
		if(vexRT[Btn5U]) {
			if(abs(flyTarget - velAvg) > flyThresh + 50 || abs(lVelAvg - rVelAvg) > lRFlyThresh) {
				setLeds(0);
			}
			else if(abs(flyTarget - velAvg) < flyThresh + 50 && abs(flyTarget - velAvg) > flyThresh) {
				setLeds(1);
			}
			else {
				setLeds(2);
			}
			if(abs(lVelAvg - rVelAvg) > lRFlyThresh) {
				if(lVelAvg > rVelAvg) {
					motor[blFly] = motor[tlFly] = 95;
					motor[brFly] = motor[trFly] = 127;
				}
				else {
					motor[brFly] = motor[trFly] = 95;
					motor[blFly] = motor[tlFly] = 127;
				}
			}
			else if(flyTarget - velAvg > flyThresh) {
				setFlywheel(127);
			}
			else if(velAvg - flyTarget > flyThresh) {
				setFlywheel(63);
			}
			else {
				setFlywheel(79);
			}
		}
		else if(vexRT[Btn5D] && velAvg <= 50) {
			setFlywheel(-31);
		}
		else {
			setFlywheel(0);
			setLeds(3);
		}
		button5U2Last = vexRT[Btn5UXmtr2];
		button5D2Last = vexRT[Btn5DXmtr2];
		wait1Msec(20);
	}
}
Example #3
0
void N800Hardware::chargingChanged(bool charging)
{
    if (charging)
        setLeds(101);
    else
        setLeds(batterySource->charge());
}
Example #4
0
void write_code_EE_1( unsigned long address, unsigned char* data, char blocksize, char lastblock )
{
//FIXME: This currently dowsn't work as the app sends too many bytes for the write cache (2-16bytes depending on model)

	unsigned char i, tries;
	char blockcounter;

	tries = 0;
restart:
	I2C_start();
	I2C_write( 0xA0 | ((int)address>>7)&0x0E );			//Device Address + 0=write

	I2C_write( (unsigned char) ((address & 0x00FF)) ); 	//LSB

	for( blockcounter = 0; blockcounter < blocksize; blockcounter++ )
	{
		i = (unsigned int) I2C_write( data[blockcounter] );
		if( i == 1 )   // received a NACK
		{
			for( i = 0; i < 4; i++ ) {
				setLeds( 7);
				DelayMs(125);
				setLeds(0);
				DelayMs( 125 );
			}
			I2C_stop();
			DelayMs(30);
			if( tries < 2 )
				goto restart;
			return; // what else to do??
		}
	}
	I2C_stop();
	DelayMs( 10 );
}
Example #5
0
int main(int argc, char * argv[])
{
	struct pwcmech * pwcmech;
	pwcmech->dev = ifinit_pwcblock();
	pwcmech->com = ifinit_usbcom();

	ifbind_pwcblock(pwcmech->dev, pwcmech->com);

	//use driver
	usb_init(pwcmech->com);
	if ( usb_open(pwcmech->com) )
	{
		finish(pwcmech);
		return 0;
	}

	//should work seamlessly
	usb_if_claim(pwcmech->com, pwcmech->com->standard_descriptors.highspeed.cameraStream.cameraStreamConf);

	setVideoMode(pwcmech, 9);

	setLeds(pwcmech, 10,5);

	usb_release_interface(pwcmech->com, pwcmech->com->standard_descriptors.highspeed.cameraStream.cameraStreamConf);

	usb_close(pwcmech->com);

	finish(pwcmech);

	return 0;
}
Example #6
0
File: main.c Project: z80/IPM
int main(void)
{
    halInit();
    chSysInit();

    initLed();
    setLeds( 7 );
    initRead();
    initWrite();
    initI2c();
    initUsb();


    /*IWDGConfig cfg;
    cfg.div = IWDG_DIV_256;
    cfg.counter = (40000 / 256 / 2 );
    iwdgInit();
    iwdgStart( &IWDGD, &cfg );
    iwdgReset( &IWDGD );*/

    while (TRUE)
    {
        //iwdgReset( &IWDGD );
        processShell();
        chThdSleepMilliseconds( 250 );
    }
    return 0;
}
Example #7
0
/******************************************************************************
 * Function:        void BlinkUSBStatus(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        BlinkUSBStatus turns on and off LEDs corresponding to
 *                  the USB device state.
 *
 * Note:            mLED macros can be found in io_cfg.h
 *                  usb_device_state is declared in usbmmap.c and is modified
 *                  in usbdrv.c, usbctrltrf.c, and usb9.c
 *****************************************************************************/
void BlinkUSBStatus(void)
{
	static word led_count=0;
	static char startup_state=0xFF;
	
	if(led_count == 0)led_count = 10000U;
		led_count--;
	
	if(UCONbits.SUSPND == 1)
	{
		//USBWakeFromSuspend();
		if(led_count==0)
		{
			mLED_1_Off();
			mLED_2_Off();
			mLED_3_Toggle();
		}//end if
	}
	else
	{
		if(usb_device_state == DETACHED_STATE)
		{
			setLeds(1);
		}
		else if(usb_device_state == ATTACHED_STATE)
		{
			setLeds(2);
		}
		else if(usb_device_state == POWERED_STATE)
		{
			setLeds(4);
		}
		else if(usb_device_state == DEFAULT_STATE)
		{
			setLeds(2);
		}
		else if(usb_device_state == ADDRESS_STATE)
		{
			setLeds(LEDS_ON);
		}
		else if(usb_device_state == CONFIGURED_STATE)
		{
			startup_state=0;
		}
	}
}
int main(){
	initLedButtons();
	char buttonState;
	while(1){
		char t = readButtons();
		if (t != buttonState){
			buttonState =t;
			setLeds(buttonState);
		}
	}
	closeLedButtons();
}
Example #9
0
/******************************************************************************
 *
 * Description:
 *    Set LED states (on or off).
 *
 * Params:
 *    [in]  ledOnMask  - The LEDs that should be turned on. This mask has
 *                       priority over ledOffMask
 *    [in]  ledOffMask - The LEDs that should be turned off.
 *
 *****************************************************************************/
void pca9532_setLeds (uint16_t ledOnMask, uint16_t ledOffMask)
{
    /* turn off leds */
    ledStateShadow &= (~(ledOffMask) & 0xffff);

    /* ledOnMask has priority over ledOffMask */
    ledStateShadow |= ledOnMask;

    /* turn off blinking */
    blink0Shadow &= (~(ledOffMask) & 0xffff);
    blink1Shadow &= (~(ledOffMask) & 0xffff);

    setLeds();
}
Example #10
0
void isr() { //uint8_t* toggle) {
	// todo do PWM signal
  setLeds(G_LED0);
/*	if(toggle) {
    setLeds(G_LED0);
		*toggle = 0;
	}	else {
    setLeds(~G_LED0);
		*toggle = 1;
	}
*/
	timer_irq_ack(&timer_handle);

}
task autonomous()
{
	startTask(rpmCalc);
	while(true) {
		if(abs(flyTarget - velAvg) > flyThresh + 50 || abs(lVelAvg - rVelAvg) > lRFlyThresh) {
			setLeds(0);
		}
		else if(abs(flyTarget - velAvg) < flyThresh + 50 && abs(flyTarget - velAvg) > flyThresh) {
			setLeds(1);
		}
		else {
				setLeds(2);
		}
		if(abs(lVelAvg - rVelAvg) > lRFlyThresh) {
			if(lVelAvg > rVelAvg) {
				motor[blFly] = motor[tlFly] = 95;
				motor[brFly] = motor[trFly] = 127;
			}
			else {
				motor[brFly] = motor[trFly] = 95;
				motor[blFly] = motor[tlFly] = 127;
			}
		}
		else if(flyTarget - velAvg > flyThresh) {
			setFlywheel(127);
		}
		else if(velAvg - flyTarget > flyThresh) {
			setFlywheel(63);
		}
		else {
			setFlywheel(79);
			motor[elevator] = 127;

		}
		wait1Msec(20);
	}
}
Example #12
0
int main(void)
{
	cli();
	// Disable the watchdog
	wdt_disable();
	
	// Setup LEDS
	setupLeds();
	
	// Two second blink
	setLeds(0xFF);
	_delay_ms(2000);
	setLeds(0);
	
	setupTimer();
	
	setupInterrupt();

	// Enable interrupts
	sei();
	
	// Halt
	while(1);
}
Example #13
0
// Initialise the software
TICK_COUNT appInitSoftware(TICK_COUNT loopStart){
	for (int i=0; i < 14; i+=1){
			led[i].r = 0;
			led[i].g = 0;
			led[i].b = 0;
		}
		
	setLeds();
	
	halfperiods[0] = 500000; // us
	halfperiods[1] = 625000;
	switchtime = clockGetus();
	newbrightness = minbright;
	
	return 0;
}
Example #14
0
File: main.c Project: z80/digitizer
int main(void)
{
    halInit();
    chSysInit();

    initCpuIo();
    initLed();
    initDfu( 5000 );

    setLeds( 3 );

    // Use virtual timer to execute regular firmware within
    // some time if nothing happens.
    while ( 1 )
    {
    	processCpuIo();
    }
    return 0;
}
/*
 * This method is called when a packet is received
 *
 * @param recv_func Function pointer to either serial or radio receive function
 * @p Parameters of environment
 */
void bs_receive(error_t (*recv_func)(message_t*, uint32_t, am_id_t), bs_params_t* p) {
  message_t m;
  BlinkToRadioMsg_t* btrpkt;

  for(;;) {
    if( (*(recv_func))(&m, 0, AM_RECEIVE_FROM_ANY) == SUCCESS ) {
      btrpkt = (BlinkToRadioMsg_t*)radioGetPayload(&m, sizeof(BlinkToRadioMsg_t));
      if( isValidMsgID(btrpkt->msgID) ) { //only accept if new msgID
        messageID = btrpkt->msgID;  //save newest msgID
        if(isValidDestination(btrpkt->destMask)){ //check if current mote is addressed
          setLeds(btrpkt->ledID);
        }
	      mutex_lock( &(p->mutex) );
	        while( enqueueMsg(p, &m) == FAIL )
	          condvar_wait( &(p->condvar), &(p->mutex) );
	      mutex_unlock( &(p->mutex) );
	      condvar_signalAll( &(p->condvar) );
      }
	  }
  }
}
Example #16
0
/**
 * Set port A as output and B as input.
 */
void Controls::init() {
  Serial.println("Expander: setting port A as out");
  //  setting port A as output
  Wire.beginTransmission(EXPANDER_CONTROLS_ADDRESS);
  Wire.write(0x00); // IODIRA register
  Wire.write(0x00); // set all of port A to outputs
  byte results = Wire.endTransmission();
  checkError(results);

  Serial.println("Expander: setting port B as out");
  //  setting port B as input
  Wire.beginTransmission(EXPANDER_CONTROLS_ADDRESS);
  Wire.write(0x01); // IODIRB register
  Wire.write(0x00); // set all of port B to outputs
  results = Wire.endTransmission();
  checkError(results);

  Serial.println("Expander: setting leds");
  setLeds(0xAA);

  Serial.println("Controls initialized.");
}
Example #17
0
DWORD LED_Write(DWORD dwOpen, LPVOID pBuffer, DWORD dwCount)
{
	PDRVCONTEXT pDrv = (PDRVCONTEXT)dwOpen;

	RETAILMSG(RETAIL_ON, (DTAG TEXT("LED_Write++ dwContext: %x\r\n"), dwOpen));

	// Verify that the context handle is valid
	if(pDrv && (pDrv->dwSize != sizeof(DRVCONTEXT))){
		return 0;
	}

	char* input = (char*) pBuffer;

	setLeds(pDrv->pGpioRegs, *input);

	// Count the number of opens
	InterlockedDecrement((long *)&pDrv->nNumOpens);

	RETAILMSG(RETAIL_ON, (TEXT("LED_Write-- \r\n")));

	return 1;
}
Example #18
0
int main(){
	initScreen();
	initSound();
	initLedButtons();
	lcdTest();
	while(1){
		fillBoard();
		printBoard();
		
		for (int i = 0; i < 100; i++){
			setLeds((char)i);
			setFrequency(120*(i%20));
			playerStep();
			printBoard();
			playSounds();
			if (readButtons() & 0x01 > 0) break;
		}
	}
	closeLedButtons();
	closeScreen();
	closeSound();

}
Example #19
0
void ProcessIO(void)
{
	char oldPGDtris;
	char PIN;
	static byte counter=0;
	int nBytes;
	unsigned long address;
	unsigned char i;
	
	input_buffer[0]=UART1RX(); //USBGenRead((byte*)input_buffer,64);
//	if(nBytes>0)
//	{
		switch(input_buffer[0])
		{
			case CMD_ERASE:
				setLeds(LEDS_ON | LEDS_WR);
				getBytes(1,1);//get more data, #bytes, where to insert in input buffer array
				output_buffer[0]=bulk_erase(picfamily,pictype,input_buffer[1]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_ID:
				setLeds(LEDS_ON | LEDS_RD);
				switch(picfamily)
				{
					case DSPIC30:
						read_code(picfamily,pictype,0xFF0000,(unsigned char*)output_buffer,2,3);
						break;
					case PIC18:
						read_code(picfamily,pictype,0x3FFFFE,(unsigned char*)output_buffer,2,3);  //devid is at location 0x3ffffe   for PIC18 devices
						break;
					case PIC16:
						set_vdd_vpp(picfamily, pictype, 0);
						read_code(picfamily,pictype,0x2006,(unsigned char*)output_buffer,2,3);  //devid is at location 0x2006  for PIC16 devices
						break;
				}
				counter=2;
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CODE:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_code(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_CODE:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				read_code(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]);
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_DATA:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_data(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]); 
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_DATA:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				read_data(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]); 
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CONFIG:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_config_bits(picfamily, pictype, address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_SET_PICTYPE:
				output_buffer[0]=set_pictype(input_buffer+1);
				//output_buffer[0]=1; //Ok
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_FIRMWARE_VERSION:
				for(counter=0; counter<18; counter++)output_buffer[counter]=upp_version[counter];
				counter=18;
				setLeds(LEDS_ON);
				break;
			case CMD_DEBUG:
				setLeds(LEDS_ON | LEDS_WR | LEDS_RD);
				switch(input_buffer[1])
				{
					case 0:
						set_vdd_vpp(dsP30F, DSPIC30, 1);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 1:
						set_vdd_vpp(dsP30F, DSPIC30, 0);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 2:
						dspic_send_24_bits(((unsigned long)input_buffer[2])|
								((unsigned long)input_buffer[3])<<8|
								((unsigned long)input_buffer[4])<<16);
						output_buffer[0]=1;
						counter=1;
						break;
					case 3:
						nBytes =  dspic_read_16_bits();
						output_buffer[0]=(unsigned char)nBytes;
						output_buffer[1]=(unsigned char)(nBytes>>8);
						counter=2;
						break;
						
				}
				break;
			case CMD_GET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						if((!TRISPGC_LOW)&&(!PGC_LOW)) //3.3V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_3_3V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else	//5V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						counter=1;
						break;
					case SUBCMD_PIN_PGD:
						if(TRISPGD)//PGD is input
						{
							if(PGD_READ) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else
						{							
							if((!TRISPGD_LOW)&&(!PGD_LOW)) //3.3V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_3_3V;
								else output_buffer[0] = PIN_STATE_0V;
							}
							else	//5V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_5V;
								else output_buffer[0] = PIN_STATE_0V;
							}
						}
						counter=1;
						break;
					case SUBCMD_PIN_VDD:
						//if(VDD) output_buffer[0] = PIN_STATE_FLOAT;
						//else output_buffer[0] = PIN_STATE_5V;
						output_buffer[0] = PIN_STATE_5V;
						counter = 1;
						break;
					case SUBCMD_PIN_VPP:
						counter=1;
						if(!VPP){output_buffer[0] = PIN_STATE_12V;break;}
						if(VPP_RST){output_buffer[0] = PIN_STATE_0V;break;}
						if(VPP_RUN){output_buffer[0] = PIN_STATE_5V;break;}
						output_buffer[0] = PIN_STATE_FLOAT;
						break;
					case SUBCMD_PIN_VPP_VOLTAGE:
						ReadAdc(output_buffer);
						counter=2;
						break;
					default:
						output_buffer[0]=3;
						counter=1;
						break;
				}
				break;
			case CMD_SET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGC = 0;
								PGC = 0;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 0;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_PGD:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGD = 0;
								PGD = 0;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 0;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_INPUT:
								TRISPGD_LOW = 1;
								TRISPGD = 1;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VDD:
						switch(input_buffer[2])
						{
							case PIN_STATE_5V:
								//VDD = 0;
								output_buffer[0]=1;
								break;
							case PIN_STATE_FLOAT:
								//VDD = 1;
								output_buffer[0]=1;
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VPP:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								VPP = 1;
								VPP_RST = 1;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 1;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_12V:
								VPP = 0;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_FLOAT:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					default:
						output_buffer[0]=3;
				}
				counter=1;
				break;
		}
	//} //if nBytes>0
	if(counter != 0)
	{
		//if(!mUSBGenTxIsBusy())
		//USBGenWrite((byte*)&output_buffer,counter);
		for(i=0; i<counter; i++) UART1TX(output_buffer[i]);
		counter=0;
	}
}//end ProcessIO
Example #20
0
File: i2c_ctrl.c Project: z80/IPM
static msg_t i2cThread( void *arg )
{
    (void)arg;
    chRegSetThreadName( "i" );
    // To all LOW/HIGH levels on address pins to reach their levels.
    chThdSleepMilliseconds( I2C_IO_TIMEOUT_MS );
    while ( 1 )
    {
        // Read ADDRESS pins.
        uint16_t ind = palReadPad( ADDR_PORT, ADDR_0_PIN ) |
                     ( palReadPad( ADDR_PORT, ADDR_1_PIN ) << 1 ) |
                     ( palReadPad( ADDR_PORT, ADDR_2_PIN ) << 2 );
        ind = (~ind) & 0x0007;

        static uint8_t master;
        static msg_t status;
        static systime_t tmo;
        tmo = MS2ST( I2C_IO_TIMEOUT_MS );
        master = ( ind == 0 ) ? 1 : 0;
        // I/O with other boards.
        static uint32_t dataOut = 0;
        static uint32_t pendDataOut = 0;
        static uint32_t dataIn = 0;
        setLeds( master ? 1 : 0 );
        if ( master )
        {
            // First the board itself.
            chMtxLock( &mutex );
                ins[0] = valueRead();
                write( pendOuts[0] );
            chMtxUnlock();
            // After all slave boards.
            static int8_t i;
            for ( i=0; i<I2C_SLAVES_CNT; i++ )
            {
                // To make IO thread safe IO itself takes place in separate variables.
                // But storage arrays are filled within locked mutex.
                // Get output.
                chMtxLock( &mutex );
                    pendDataOut = pendOuts[i+1];
                    dataOut     = outs[i+1];
                chMtxUnlock();
                // Write only if data to write differs from already written.
                if ( pendDataOut != dataOut )
                {
                    // IO itself.
                    status = i2cMasterTransmitTimeout( &I2CD1, I2C_BASE_ADDR+i,
                                                       (uint8_t *)(&pendDataOut), sizeof(pendDataOut),
                                                       0,  0,
                                                       tmo );
                    if ( status == RDY_OK )
                    {
                        chMtxLock( &mutex );
                            outs[i+1] = pendDataOut;
                        chMtxUnlock();
                        toggleLedsImmediate( 2 );
                    }
                    else
                    {
                        setLeds( 7 );
                        i2cStop( &I2CD1 );
                        chThdSleepMilliseconds( 10 );
                        i2cStart( &I2CD1, &i2cfg1 );
                        continue;
                    }
                }
                status = i2cMasterReceiveTimeout( &I2CD1, I2C_BASE_ADDR+i,
                                                  (uint8_t *)(&dataIn),  sizeof(dataIn),
                                                  tmo );
                if ( status == RDY_OK )
                {
                    toggleLedsImmediate( 4 );
                }
                else
                {
                    setLeds( 7 );
                    i2cStop( &I2CD1 );
                    chThdSleepMilliseconds( 10 );
                    i2cStart( &I2CD1, &i2cfg1 );
                    continue;
                }
                // Get back input.
                chMtxLock( &mutex );
                //ins[i+1] = (dataIn & 0x0000FFFF);
                ins[i+1] = dataIn;
                chMtxUnlock();
            }

            // Here is generic I2C io.
            i2cIo();

            chThdSleepMilliseconds( I2C_QUERY_PERIOD_MS );

        }
        else
        {
            static uint8_t addr;
            addr = I2C_BASE_ADDR + ind - 1;
            //setLeds( addr );

            dataIn = valueRead();
            do {
                //dataIn = 0x12345678;
                status = i2cSlaveIoTimeout( &I2CD1, addr,
                                            (uint8_t *)&dataOut,  sizeof( dataOut ),
                                            (uint8_t *)&dataIn, sizeof( dataIn ),
                                            i2cRxCb, i2cTxCb, tmo );
                if ( status != RDY_OK )
                {
                    i2cStart( &I2CD1, &i2cfg1 );
                    setLeds( 7 );
                }
            } while ( status != RDY_OK );

            // Managed to initialize I2C slave IO.
            setLeds( 0 );
            while ( 1 )
            {
                /*
                status = i2cSlaveIoTimeout( &I2CD1, addr,
                                            (uint8_t *)&dataOut,  sizeof( dataOut ),
                                            (uint8_t *)&dataIn, sizeof( dataIn ),
                                            i2cRxCb, i2cTxCb, tmo );
                */
                chThdSleepMilliseconds( I2C_QUERY_PERIOD_MS );
                pendDataOut = valueRead();
                chSysLock();
                    dataIn = pendDataOut;
                chSysUnlock();
                write( dataOut );
            }
        }
        /*if ( a == 0b00000111 )
        {
            setLeds( 1 );
            static uint32_t out = 0x12345678;
            status = RDY_OK;
            status = i2cMasterTransmitTimeout( &I2CD1, testAddr,
                                               (uint8_t *)(&out), sizeof(out),
                                               0,  0,
                                               tmo );
        }
        else
            setLeds( 2 );
        */
    }

    return 0;
}
int main(void) {
    unsigned int b;
    unsigned char c;

    init_all();
    lcd_puts("Ready.", FIRST);
    for(;;)
    {
        /*
         * Get received character from ringbuffer
         * uart_getc() returns in the lower byte the received character and
         * in the higher byte (bitmask) the last receive error
         * UART_NO_DATA is returned when no data is available.
         *
         */
        b = uart_getc();
        if ( b & UART_NO_DATA )
        {
            /*
             * no data available from UART
             */
        }
        else
        {
            /*
             * new data available from UART
             * check for Frame or Overrun error
             */
            if ( b & UART_FRAME_ERROR )
            {
                /* Framing Error detected, i.e no stop bit detected */
                lcd_puts("UART Frame Error", FIRST);
            }
            if ( b & UART_OVERRUN_ERROR )
            {
                /*
                 * Overrun, a character already present in the UART UDR register was
                 * not read by the interrupt handler before the next character arrived,
                 * one or more received characters have been dropped
                 */
                lcd_puts("UART Overrun Error", FIRST);
            }
            if ( b & UART_BUFFER_OVERFLOW )
            {
                /*
                 * We are not reading the receive buffer fast enough,
                 * one or more received character have been dropped
                 */
                lcd_puts("Buffer overflow error", FIRST);
            }
            /*
             * send received character back
             */
            c = (unsigned char) b;
            switch(c) {
            case 0x16:
                uart_putc(button);
                button = 0;
                break;
            case 0x00:
                break;
            case 0x07: //BELL
                beep(); //BEEP!!!
                break;

            case 0x11: //DEVICE CONTROL 1
                setLeds(getLeds() ^ RED); //rote LED togglen
                break;

            case 0x12: //DEVICE CONTROL 2
                setLeds(getLeds() ^ GREEN); //gruene LED togglen
                break;

            case 0x13: //DEVICE CONTROL 3
                lcd_clearLine(FIRST); //Erste Zeile leeren und ab da schreiben
                break;

            case 0x14: //DEVICE CONTROL 4
                lcd_clearLine(SECOND); //Zweite Zeile leeren und ab da schreiben
                break;

            default:	// Normales Zeichen
                lcd_putc(c); //Zeichen schreiben
                break;
            }
        }
    }

    return 0;
}
Example #22
0
static void set_leds( uint8_t * args )
{
	setLeds( args[0] );
}
Example #23
0
File: i2c_ctrl.c Project: z80/IPM
void i2cIo( void )
{
    static msg_t status;
    static uint8_t st;
         // Debug code.
            /*

          static uint16_t nnn = 0;
            if ( nnn++ > 50 )
                nnn = 0;
            else
                return;
            g_i2cAddr = 64;
            g_i2cStatus = 1;
            g_i2cTxSz = 4;
            g_i2cRxSz = 0;
            g_i2cOutBuffer[0] = 6;
            g_i2cOutBuffer[1] = 1;
            g_i2cOutBuffer[2] = 0x0F;
            g_i2cOutBuffer[3] = 0x70;

          */
        // / Debug code.
    chMtxLock( &mutex );
        st = g_i2cStatus;
    chMtxUnlock();
    if ( st == 1 )
    {
        static systime_t tmo;
        tmo = MS2ST( 300 );
        if ( g_i2cTxSz > 0 )
        {
            status = i2cMasterTransmitTimeout( &I2CD1, g_i2cAddr,
                                               g_i2cOutBuffer, g_i2cTxSz,
                                               0,  0,
                                               tmo );
            if ( status == RDY_OK )
                toggleLedsImmediate( 2 );
            else
                setLeds( 7 );
            if ( status != RDY_OK )
            {
                chMtxLock( &mutex );
                    g_i2cStatus = 2;
                chMtxUnlock();
                i2cStart( &I2CD1, &i2cfg1 );
                return;
            }
        }
        if ( g_i2cRxSz > 0 )
        {
            status = i2cMasterReceiveTimeout( &I2CD1, g_i2cAddr,
                                              g_i2cInBuffer, g_i2cRxSz,
                                              tmo );
            if ( status == RDY_OK )
                toggleLedsImmediate( 4 );
            else
                setLeds( 7 );
            if ( status != RDY_OK )
            {
                chMtxLock( &mutex );
                    g_i2cStatus = 3;
                chMtxUnlock();
                i2cStart( &I2CD1, &i2cfg1 );
                return;
            }
        }
        chMtxLock( &mutex );
            g_i2cStatus = 0;
        chMtxUnlock();
Example #24
0
int main(int argc, char *argv[])
{
	int i, iRet = 0;
	struct pwcmech * pwcmech;

	//
	// Signal Handling
	//
	sigset_t block_no_signals;
	sigemptyset(&block_no_signals);


	struct sigaction pwc_sig_handler;
	struct sigaction standard_sig_handler;
	struct sigaction video_io_sig_handler;

	pwc_sig_handler.sa_flags = 0;
	pwc_sig_handler.sa_handler = &sig_handler;

	sigaction(SIGINT, &pwc_sig_handler, &standard_sig_handler);
	sigaction(SIGTERM, &pwc_sig_handler, &standard_sig_handler);

	video_io_sig_handler.sa_flags = 0;
	video_io_sig_handler.sa_handler = &ioctl_callback;
	sigaction(SIGIO, &video_io_sig_handler, &standard_sig_handler);


	//
	// Userspace Driver Interfaces
	//
	struct devClass * video_dev;
	struct images * p_img;


	//
	// Buffering Initialization
	//
	printf("Allocating buffers...");
	frames = alloc_buffers();
	if ( frames == NULL )
	{
		printf("failed?!\n");
		goto finish;
	}
	init_data_buffer(frames);
	printf("done!\n");


	//
	// Device Initialization
	//
	printf("Create camera device...");
	pwcmech = pwc_devmech_start();
	if ( pwcmech_register_driver(pwcmech) )
	{
		printf("failed?!\n");
		goto release_buffers;
	}
	printf("done!\n");

	printf("Initialize camera device...");
	if ( pwcmech_register_handler(pwcmech) )
	{
		perror("Failed opening camera device");
		printf("failed?!\n");
		goto stop_usb;
	}
	printf("done!\n");

	printf("Set camera's video mode...");
	//if_claim should work seamslessly somehow
	iRet = usb_if_claim(pwcmech->com, pwcmech->com->standard_descriptors.highspeed.cameraStream.cameraStreamConf);
	if ( iRet )
	{
		perror("Failed setting camera's video mode");
		printf("failed?!\n");
		goto close_camera;
	}
	iRet = setVideoMode(pwcmech, 9);	//still old way, pre-setting instead of from V4L
	if ( iRet )
	{
		perror("Failed setting camera's video mode");
		printf("failed?!\n");
		goto close_camera;
	}
	set_ctrl0_timeout(pwcmech->com, 1000);
	setLeds(pwcmech, 0,0);	//don't bother with the light
	iRet = sendVideoCommand(pwcmech, video_mode_string, VIDEO_MODE_STRING_LEN);
	if ( iRet )
	{
		perror("Failed setting camera's video mode");
		printf("failed?!\n");
		goto close_camera;
	}
	printf("done!\n");


	//
	// Decompression
	//
	printf("Initializing decompression system...");
	p_img = alloc_images();
	if ( p_img == NULL )
	{
		printf("failed?!\n");
		goto close_camera;
	}
	if ( ( iRet = init_images(p_img) ) )
	{
		printf("failed?!\n");
		goto free_p_img;
	}
	printf("done!\n");

#ifndef NO_IMG
	//
	// Open video pipe
	//
	printf("Opening the video pipe (vl4 device emulation)...");
	video_dev = alloc_devClass();
	if ( video_dev == NULL )
	{
		printf("failed?!\n");
		goto free_p_img;
	}
	p_img->img_buf = init_devClass(video_dev, argv[1], p_img);
	if ( p_img->img_buf == NULL )
	{
		perror("Initializing device class failed");
		printf("failed?!\n");
		printf("Did you input the device path, \"/dev/video0\"?\"\n\n\n");
		goto free_video_dev;
	}
	printf("done!\n");
#endif

	//
	//	ISO transfers
	//
	printf("Create USB isochronous transfers...");
	for (i = 0; i < ISO_BUFFERS_NR; i++)
	{
		iRet = assignVideoBuffer(pwcmech, frames->iso_buffer[i], ISO_BUFFER_SIZE);
		if (iRet)
		{
			perror("Failed creating image transfer");
			printf("failed?!\n");
			goto unregister_buffers;
		}
	}
	printf("done!\n");


	//
	// Threads
	//
	printf("Set-up threads...");
	int active_threads = 0;
	pthread_t threads[NUM_THREADS];

	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	struct acqArg * acq_arg;
	acq_arg = malloc(sizeof(struct acqArg));
	if ( acq_arg == NULL )
	{
		printf("failed?!\n");
		goto close_threads;
	}
	acq_arg->abort = &thread_abort;
	acq_arg->pwcmech = pwcmech;

	struct imgArg * img_arg;
	img_arg = malloc(sizeof(struct imgArg));
	if ( img_arg == NULL )
	{
		printf("failed?!\n");
		goto close_threads;
	}
	img_arg->frames = frames;
	img_arg->p_img = p_img;
	img_arg->video_pipe = video_dev;
	img_arg->capture = 0;
	img_arg->abort = &thread_abort;
	printf("done!\n");


	//
	//	MAIN
	//
	printf("Registering callback function for Isochronous transfer...");
	setPower(pwcmech, 0);		//enable camera (our state machine discovered that this was missing)
	registerVideoCallback(pwcmech, acquire_frame, pwcmech);
	if ( acknowledgeVideoCallback(pwcmech) )
		goto close_threads;
	printf("done!\n");

#ifndef NO_COM
	printf("Creating the data acquisition thread...");
	if ( ( iRet = pthread_create(&threads[active_threads], &attr, process_usb, (void *)acq_arg) ) )
	{
		printf("failed?!\n");
		goto stop_camera;
	}
	active_threads++;
	printf("done!\n");
#endif

#ifndef NO_IMG
	printf("Creating the image fill thread...");
	if ( ( iRet = pthread_create(&threads[active_threads], &attr, fillImageData, (void *)img_arg) ) )
	{
		printf("failed?!\n");
		goto stop_camera;
	}
	active_threads++;
	printf("done!\n");
#endif

	while (!op_abort)
	{
//		sigsuspend(&block_no_signals);
		if ( ioctl_call )
		{
			devClass_ioctl(video_dev, &img_arg->capture);
			ioctl_call = 0;
		}
	}


	//
	//	~MAIN
	//

stop_camera:
	printf("Releasing video callback...");
	releaseVideoCallback(pwcmech);
	printf("done!\n");
	printf("Unregistering buffers...");
	unassignVideoBuffers(pwcmech);
	printf("done!\n");

close_threads:
	printf("Closing all threads...");
	thread_abort = 1;
	for ( i = 0; i < active_threads; i++)
		pthread_join(threads[i], NULL);

	free(acq_arg);
	free(img_arg);

	pthread_attr_destroy(&attr);
	printf("done!\n");

unregister_buffers:
	printf("Unregistering buffers if not done before...");
	unassignVideoBuffers(pwcmech);
	printf("done!\n");

free_video_dev:
#ifndef NO_IMG
	printf("Closing video pipe...");
	close_devClass(video_dev);
	free_devClass(video_dev);
	printf("done!\n");
#endif

free_p_img:
	printf("Releasing decompression system...");
	free_images(p_img);
	printf("done!\n");
	usb_release_interface(pwcmech->com, pwcmech->com->standard_descriptors.highspeed.cameraStream.cameraStreamConf);

close_camera:
	printf("Close camera device...");
	pwcmech_deregister_handler(pwcmech);
	printf("done!\n");

stop_usb:
	printf("Stopping USB interface...");
	pwcmech_deregister_driver(pwcmech);
	printf("done!\n");

release_buffers:
	pwc_devmech_stop(pwcmech);
	//release buffers, they are linked to the camera device
	//so only release them after releasing the camera
	printf("Releasing buffers...");
	free_buffers(frames);
	printf("done!\n");

finish:
	return 0;
}
Example #25
0
// This is the main loop
TICK_COUNT appControl(LOOP_COUNT loopCount, TICK_COUNT loopStart) {
	
	//Toggle mode via button
	if (!buttonWait){
		if(SWITCH_pressed(&button)){
			// pressed
			mode = (mode + 1) % NUMMODES;
			buttonWait = 1;
			buttonWaitStartTime = loopStart;
		
			// Clear vals for new mode
			for (int i=set; i < 14; i++){
				led[i].r = 0;
				led[i].g = 0;
				led[i].b = 0;
			}
			setLeds();
		}
	}
	// Wait 1 second after noticing a button press before allowing another button press
	else {
		if (clockHasElapsedGetOverflow(buttonWaitStartTime, buttonWaitTime, &unusedButtonRemainingTime)){
			buttonWait = 0;
		}
	}

	/// alternating half bright half fading
	if (mode == 1) {
		if (clockHasElapsedGetOverflow(switchtime, halfperiods[set], &remainingtime)) {
			// rprintf("boom!\n");
			delay_ms(400);
			// Switch modes if we've reached the end of increasing brightness
			if (dir == 1){
				set = (set + 1) % 2;
			}
			switchtime = clockGetus();
			dir *= -1;
			remainingtime = halfperiods[set] - remainingtime;
			
			// Set half the LEDs to maximum brightness
			for (int i=(1-set); i < 14; i+=2){
				// led[i].b = maxbright * 2;
				led[i].r = maxbright * 2;
				led[i].g = maxbright;
			}
		}
		
		// Calculate brightness of dimmer LEDs
		if(dir == 1){ // increasing brightness
			newbrightness = maxbright - (maxbright - minbright) * remainingtime / halfperiods[set];
		}
		else{ // decreasing brightness
			newbrightness = minbright + (maxbright - minbright) * remainingtime / halfperiods[set];
		}
		// Monocolor
		// newbrightness *= 2;
		// newbrightness += 1;
		
		for (int i=set; i < 14; i+=2){
			// blue
			// led[i].b = newbrightness;
			// orange
			led[i].r = newbrightness * 2 + 1;
			led[i].g = newbrightness + 1;
		}
		
		setLeds();
	}
	
	///
	else if (mode == 2) {
		if (clockHasElapsedGetOverflow(switchtime, halfperiods[set], &remainingtime)) {
			// rprintf("boom!\n");
			set = (set + 1) % 2;
			switchtime = clockGetus();
			remainingtime = halfperiods[set] - remainingtime;
		}
		
		for (int i=0; i < 14; i+=2){
			led[i].b = 0;
		}
		
		j = (14 * (remainingtime /1000))  / (halfperiods[set] / 1000);
		
		led[j].b = maxbright;
		
		setLeds();
	}
	
	/// moving orange
	else if (mode == 3) {
		if (clockHasElapsedGetOverflow(switchtime, halfperiods[set], &remainingtime)) {
			//delay_ms(250);
			// Switch modes if we've reached the end of increasing brightness
			//if (dir == 1){
			set = (set + 1) % 2;
			//}
			switchtime = clockGetus();
			//dir *= -1;
			remainingtime = halfperiods[set] - remainingtime;
		}
		
		for (int i=0; i < 14; i++){
			led[i].r = 0;
			led[i].g = 0;
			led[i].b = 0;
		}
		
		j = (14 * (remainingtime /1000))  / (halfperiods[set] / 1000);
		
		led[j].r = maxbright;
		led[j].g = maxbright/2;
		//led[j].b = maxbright;
		
		setLeds();
	}
	
	/// FLASHING WHITE
	else if (mode == 4) {
		if (clockHasElapsedGetOverflow(switchtime, halfperiods[set], &remainingtime)) {
			delay_ms(400);
			// Switch modes if we've reached the end of increasing brightness
			if (dir == 1){
				set = (set + 1) % 2;
			}
			switchtime = clockGetus();
			dir *= -1;
			remainingtime = halfperiods[set] - remainingtime;
			
		}
		
		// Calculate brightness
		if(dir == 1){ // increasing brightness
			newbrightness = maxbright - (maxbright - minbright) * remainingtime / halfperiods[set];
		}
		else{ // decreasing brightness
			newbrightness = minbright + (maxbright - minbright) * remainingtime / halfperiods[set];
		}
		
		for (int i=0; i < 14; i++){
			led[i].r = newbrightness * 2;
			led[i].g = newbrightness * 2;
			led[i].b = newbrightness * 2;
		}
		
		setLeds();
	}
	
	else if (mode == 5)
	{	
		k = (k+1)%w;
		y = 4;
		z = 7;
		w = 7;
		int val = (k*y)%z;
		// >>>  for k in xrange(w): print (k*y)%z;
		// for (int k=0; k < w; k+=x)
		// {
			// val = (k*y)%z;
		// }
		for (int i=0; i < 14; i++){
			led[i].r = maxbright * 2;
			led[i].g = maxbright;
			// led[i].b = newbrightness * 2;
		}
		led[val].r = maxbright * 2;
		led[val].g = maxbright * 2;
		
		led[val+7].r = maxbright * 3;
		led[val+7].g = maxbright * 2;
		
		setLeds();
		return 500000;
	}

	
	// ///////
	// // BlinkM control (doesn't work; probably need pull up resistors)
	// uint8_t blinkm_packet_setcolor[4];
	
	// blinkm_packet_setcolor[0] = (uint8_t)'n';
	// blinkm_packet_setcolor[1] = 50;
	// blinkm_packet_setcolor[2] = 50;
	// blinkm_packet_setcolor[3] = 50;
		
	// i2cMasterSend(&blinkm.i2cInfo, sizeof(blinkm_packet_setcolor), blinkm_packet_setcolor);
	// // i2cMasterSend(&blinkm.i2cInfo, sizeof(blinkm_packet_setcolor), *blinkm_packet_setcolor);
	// delay_ms(50);

	else if (mode == 0){
		
		for (int i=0; i < 14; i++){
			led[i].r = 0;
			led[i].g = 0;
			led[i].b = 0;
		}
		
		setLeds();	
	}
	
	return 20000;
}
Example #26
0
/******************************************************************************
 *
 * Description:
 *    Set the LEDs that should blink with rate and duty cycle from PWM1.
 *    Blinking is turned off with pca9532_setLeds.
 *
 * Params:
 *    [in]  ledMask  - LEDs that should blink.
 *
 *****************************************************************************/
void pca9532_setBlink1Leds(uint16_t ledMask)
{
    blink1Shadow |= ledMask;
    setLeds();
}
Example #27
0
static void set_led( uint8_t * args )
{
	turnCountdownOff();

	setLeds( args[0] );
}
Example #28
0
void av::vrpn::Wiimote::setLED3CB(const av::SFBool::SetValueEvent& event)
{
    const bool ledOn = (event.getValue());
    //  std::cout << "LedOn: " << ledOn << std::endl;
    setLeds(3, ledOn);
}
Example #29
0
void N800Hardware::chargeChanged(int charge)
{
    if (!batterySource->charging())
        setLeds(charge);
}
Example #30
0
void ProcessIO(void)
{
	char oldPGDtris;
	char PIN;
	static byte counter=0;
	int nBytes;
	unsigned long address;
	
	// When the device is plugged in, the leds give the numbers 1, 2, 3, 4, 5. 
	//After configured state, the leds are controlled by the next lines in this function
	if((usb_device_state < CONFIGURED_STATE)||(UCONbits.SUSPND==1))
	{
		BlinkUSBStatus();
		return;
	}
	

	nBytes=USBGenRead((byte*)input_buffer,64);
	if(nBytes>0)
	{
		switch(input_buffer[0])
		{
			case CMD_ERASE:
				setLeds(LEDS_ON | LEDS_WR);
				output_buffer[0]=bulk_erase(picfamily,pictype,input_buffer[1]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_ID:
				setLeds(LEDS_ON | LEDS_RD);
				switch(picfamily)
				{
					case PIC24:
					case dsPIC30:
						read_code(picfamily,pictype,0xFF0000,(unsigned char*)output_buffer,2,3);
						break;
					case PIC18:
					case PIC18J:
					case PIC18K:
						read_code(picfamily,pictype,0x3FFFFE,(unsigned char*)output_buffer,2,3);  //devid is at location 0x3ffffe   for PIC18 devices
						break;
					case PIC16:
						set_vdd_vpp(picfamily, pictype, 0);
						read_code(picfamily,pictype,0x2006,(unsigned char*)output_buffer,2,3);  //devid is at location 0x2006  for PIC16 devices
						break;
				}
				counter=2;
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CODE:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_code(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_CODE:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				PIN=read_code(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]);
				if(PIN==3)output_buffer[0]=0x3;
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_DATA:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_data(picfamily,pictype,address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]); 
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_READ_DATA:
				setLeds(LEDS_ON | LEDS_RD);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				read_data(picfamily,pictype,address,(unsigned char*)output_buffer,input_buffer[1],input_buffer[5]); 
				counter=input_buffer[1];
				setLeds(LEDS_ON);
				break;
			case CMD_WRITE_CONFIG:
				setLeds(LEDS_ON | LEDS_WR);
				address=((unsigned long)input_buffer[2])<<16|
						((unsigned long)input_buffer[3])<<8|
						((unsigned long)input_buffer[4]);
				output_buffer[0]=write_config_bits(picfamily, pictype, address, (unsigned char*)(input_buffer+6),input_buffer[1],input_buffer[5]);
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_SET_PICTYPE:
				output_buffer[0]=set_pictype(input_buffer+1);
				//output_buffer[0]=1; //Ok
				counter=1;
				setLeds(LEDS_ON);
				break;
			case CMD_FIRMWARE_VERSION:
				strcpypgm2ram((char*)output_buffer,(const far rom char*)upp_version);
				counter=18;
				setLeds(LEDS_ON);

				break;
			case CMD_DEBUG:
				setLeds(LEDS_ON | LEDS_WR | LEDS_RD);
				switch(input_buffer[1])
				{
					case 0:
						set_vdd_vpp(dsP30F, dsPIC30, 1);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 1:
						set_vdd_vpp(dsP30F, dsPIC30, 0);
						output_buffer[0]=1;
						counter=1;	
						break;
					case 2:
						dspic_send_24_bits(((unsigned long)input_buffer[2])|
								((unsigned long)input_buffer[3])<<8|
								((unsigned long)input_buffer[4])<<16);
						output_buffer[0]=1;
						counter=1;
						break;
					case 3:
						nBytes =  dspic_read_16_bits(1);
						output_buffer[0]=(unsigned char)nBytes;
						output_buffer[1]=(unsigned char)(nBytes>>8);
						counter=2;
						break;
						
				}
				break;
			case CMD_GET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						if((!TRISPGC_LOW)&&(!PGC_LOW)) //3.3V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_3_3V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else	//5V levels
						{
							if(PGC) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						counter=1;
						break;
					case SUBCMD_PIN_PGD:
						if(TRISPGD)//PGD is input
						{
							if(PGD_READ) output_buffer[0] = PIN_STATE_5V;
							else output_buffer[0] = PIN_STATE_0V;
						}
						else
						{							
							if((!TRISPGD_LOW)&&(!PGD_LOW)) //3.3V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_3_3V;
								else output_buffer[0] = PIN_STATE_0V;
							}
							else	//5V levels
							{
								if(PGD) output_buffer[0] = PIN_STATE_5V;
								else output_buffer[0] = PIN_STATE_0V;
							}
						}
						counter=1;
						break;
					case SUBCMD_PIN_VDD:
						if(VDD) output_buffer[0] = PIN_STATE_FLOAT;
						else output_buffer[0] = PIN_STATE_5V;
						counter = 1;
						break;
					case SUBCMD_PIN_VPP:
						counter=1;
						if(!VPP){output_buffer[0] = PIN_STATE_12V;break;}
						if(VPP_RST){output_buffer[0] = PIN_STATE_0V;break;}
						if(VPP_RUN){output_buffer[0] = PIN_STATE_5V;break;}
						output_buffer[0] = PIN_STATE_FLOAT;
						break;
					case SUBCMD_PIN_VPP_VOLTAGE:
						ReadAdc(output_buffer);
						counter=2;
						break;
					default:
						output_buffer[0]=3;
						counter=1;
						break;
				}
				break;
			case CMD_SET_PIN_STATUS:
				switch(input_buffer[1])
				{
					case SUBCMD_PIN_PGC:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGC = 0;
								PGC = 0;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 0;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGC = 0;
								PGC = 1;
								TRISPGC_LOW = 1;
								PGC_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_PGD:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								TRISPGD = 0;
								PGD = 0;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_3_3V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 0;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								TRISPGD = 0;
								PGD = 1;
								TRISPGD_LOW = 1;
								PGD_LOW = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_INPUT:
								TRISPGD_LOW = 1;
								TRISPGD = 1;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VDD:
						switch(input_buffer[2])
						{
							case PIN_STATE_5V:
								VDD = 0;
								output_buffer[0]=1;
								break;
							case PIN_STATE_FLOAT:
								VDD = 1;
								output_buffer[0]=1;
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					case SUBCMD_PIN_VPP:
						switch(input_buffer[2])
						{
							case PIN_STATE_0V:
								VPP = 1;
								VPP_RST = 1;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_5V:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 1;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_12V:
								VPP = 0;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							case PIN_STATE_FLOAT:
								VPP = 1;
								VPP_RST = 0;
								VPP_RUN = 0;
								output_buffer[0]=1;//ok
								break;
							default:
								output_buffer[0]=3;
								break;
						}
						break;
					default:
						output_buffer[0]=3;
				}
				counter=1;
				break;
		}
	}
	if(counter != 0)
	{
		if(!mUSBGenTxIsBusy())
		USBGenWrite((byte*)&output_buffer,counter);
		counter=0;
	}
}//end ProcessIO