コード例 #1
0
ファイル: KP_ANALOG.C プロジェクト: jgambox/DCRabbit_9
main ()
{
	static int enable,stopUpdate,updatecomplete;
	auto int loop,keyPress;
	static byte init,input;
	static CoData BarGraph;
	
		//Set all the Channels Structures to a default state
		// Enabled, 0 to 10Vdc range.
	for (loop = 0 ; loop < 8 ; loop++)
	{
		AnaSetting[loop].In = loop;
		AnaSetting[loop].GainMode = 1;
		AnaSetting[loop].Enable = 1;
	}
	
	updatecomplete = 0;
	stopUpdate = 1;
	brdInit();			// Initialize the Controller
	glInit();			// Initialize the LCD
	keyInit();			// Initialize the Keypad
	keypadDef();		// Setup the Keypad Default Values
	LastContrast = 24;  // Setup the Inital Contrast Setting
	// Turn on the Backlight
	glBackLight(1);
	// Set the Contrast
	glSetContrast(LastContrast);
	// Setup the Fonts used in this sample
	glXFontInit(&fi6x8,   6,  8,  32, 255, Font6x8);
	glXFontInit(&fi8x10,  8,  10, 32, 127, Font8x10);
	glXFontInit(&fi10x16, 10, 16, 32, 127, Font10x16);
	glXFontInit(&fi17x35, 17,35,0x20,0xFF, Font17x35);
	// Setup the Menus 
	glMenuInit( &MenuStart, &fi10x16, DOUBLE_LINE, SHADOW,startMenu,
	 				" START MENU ", -1 );
	glMenuInit( &MenuSysSetup, &fi10x16, DOUBLE_LINE, SHADOW,systemSetup,
					" SYSTEM SETUP ", -1 );
	glMenuInit( &MenuAnaSetup, &fi10x16, DOUBLE_LINE, SHADOW,analogSetup,
					" ANALOG SETUP ", 5 );
	glMenuInit( &MenuAdjContrast, &fi10x16, DOUBLE_LINE, SHADOW,adjContrast,
					" CONSTRAST ADJUST ", -1 );
	glMenuInit( &MenuRangeSel, &fi10x16, DOUBLE_LINE, SHADOW,rangeSelect,
					" RANGE SELECT ", 5 );
	glMenuInit( &MenuAnaSet2, &fi10x16, DOUBLE_LINE, SHADOW,analogSet2,
					" ANALOG SETUP2 ", -1 );
	input = 0;
	init = 1;
	for (;;)
	{
			// Check for any keypresses
		keyProcess();

		// This costate displays the Initial screen, and Starts the
		// Bargraphing demo
		costate
		{
			waitfor (init);
			waitfor ( bgMainScreen () );
			init = 0;
			input = 0;
			waitfor ( bgBarSet(&fi8x10) );
			stopUpdate = 0;
			CoBegin( &BarGraph );
		}

		// This costate checks for the 'S' key to be pressed
		//	(key just below the label 'CONFIG DEMO')
																				
		costate
		{
			waitfor ( ( keyPress = keyGet() )== 'S' );
			stopUpdate = 1;
			waitfor (updatecomplete);
			CoReset( &BarGraph );
			waitfor ( bgMenuStart() );
			init = 1;
		}
		
		// This costate displays the Bargraphs
		costate BarGraph  
		{
			waitfor(!stopUpdate);
			waitfor(IntervalMs(350));
			updatecomplete = 0;
			glBuffLock();
			input = 0;
			while (input <= 7)
			{
				if ( AnaSetting[input].Enable )
				{
					waitfor ( bgBarGraph ( &AnaSetting[ input ],
								 &fi8x10 ) );
				}
				input++;
				waitfor (DelayMs(1));
			}
			glBuffUnlock();
			updatecomplete = 1;	
			CoBegin( &BarGraph );
		}
	}
}
コード例 #2
0
ファイル: SWITCHCHAR.C プロジェクト: jgambox/DCRabbit_9
main()
{
	auto int i, ch;
	auto char buffer[64];	//buffer used for serial data
	auto int sw1, sw2, led1, led2;

	static const char string1[] = {"This message has been Rcv'd from serial port E !!!\n\n\r"};
	static const char string2[] = {"This message has been Rcv'd from serial port C !!!\n\n\r"};

	//---------------------------------------------------------------------
	//	Initialize the controller
	//---------------------------------------------------------------------
	brdInit();							//initialize board for this demo

   BitWrPortI(PEDR, &PEDRShadow, 0, 5);	//set low to enable rs232 device

	led1=led2=1;						//initialize led to off value
	sw1=sw2=0;							//initialize switch to false value

	// Initialize serial port E, set baud rate to 19200
 	serEopen(19200);
	serEwrFlush();
 	serErdFlush();

  	// Initialize serial port C, set baud rate to 19200
   serCopen(19200);
   serCwrFlush();
   serCrdFlush();

	// Clear data buffer
   memset(buffer, 0x00, sizeof(buffer));

   printf("\nStart of Sample Program!!!\n\n\n\r");
   //---------------------------------------------------------------------
   // Do continuous loop transmitting data between serial ports E and C
   //---------------------------------------------------------------------
   for(;;)
   {
		costate
		{
			if (pbRdSwitch(S1))				//wait for switch S1 press
				abort;
			waitfor(DelayMs(50));
			if (pbRdSwitch(S1))				//wait for switch release
			{
				sw1=!sw1;
				abort;
			}
		}

		costate
		{
			if (pbRdSwitch(S2))				//wait for switch S2 press
				abort;
			waitfor(DelayMs(50));
			if (pbRdSwitch(S2))				//wait for switch release
			{
				sw2=!sw2;
				abort;
			}
		}

		costate
		{	// toggle DS1 upon valid S1 press/release
			if (sw1)
			{
				pbWrLed(DS1, ON);   		//turn on DS1 led
				sw1=!sw1;

   			// Transmit an ascii string from serial port C to serial port E
				memcpy(buffer, string2, strlen(string2));
   			serCputs(buffer);
				memset(buffer, 0x00, sizeof(buffer));

   			// Get the data string that was transmitted by port C
		    	i = 0;
		     	while((ch = serEgetc()) != '\r')
     			{
		     		// Copy only valid RCV'd characters to the buffer
					if(ch != -1)
					{
						buffer[i++] = ch;
					}
				}
				buffer[i++] = ch;			 //copy '\r' to the data buffer
     			buffer[i]   = '\0';      //terminate the ascii string

		     	// Display ascii string received from serial port C
     			printf("%s", buffer);

		  		// Clear buffer
				memset(buffer, 0x00, sizeof(buffer));
				pbWrLed(DS1, OFF);		//turn off DS1
			}
		}

		costate
		{	// toggle DS2 upon valid S2 press/release
			if (sw2)
			{
				pbWrLed(DS2, ON);		//turn on DS2 led
				sw2=!sw2;

		   	// Transmit an ascii string from serial port E to serial port C
				memcpy(buffer, string1, strlen(string1));
     			serEputs(buffer);
		     	memset(buffer, 0x00, sizeof(buffer));

				// Get the data string that was transmitted by serial port E
     			i = 0;
		     	while((ch = serCgetc()) != '\r')
     			{
					// Copy only valid RCV'd characters to the buffer
					if(ch != -1)
					{
						buffer[i++] = ch;
					}
				}
		     	buffer[i++] = ch; 		//copy '\r' to the data buffer
		     	buffer[i]   = '\0';     //terminate the ascii string

	     		// Display ascii string received from serial port E
		   	printf("%s", buffer);
				pbWrLed(DS2, OFF);		//turn off DS2
			} //endif
		} //endcostate
	} //endfor
}
コード例 #3
0
ファイル: CONTROLLED.C プロジェクト: daveoman/DCRabbit_10
main()
{

	auto char s[128];
	auto char display[128];
	auto char channels[8];
	auto int output_status, channel;
	auto int output_level;
	auto unsigned int outputChannel;

	// Initialize I/O pins
	brdInit();

	// Display user instructions and channel headings
	DispStr(8, 2, "<<< Proto-board LED's   >>>");
	DispStr(8, 4, "DS2\tDS3");
	DispStr(8, 5, "-----\t-----");

	DispStr(8, 10, "From PC keyboard:");
	DispStr(8, 21, "< Press 'Q' To Quit >");

	for(channel = DS2; channel <=DS3 ; channel++)
	{
		channels[channel] = 1;		// Indicate output is OFF
		pbLedOut(channel, 1);
	}

	// Loop until user presses the upper/lower case "Q" key
	for(;;)
	{
		// Update high current outputs
		display[0] = '\0';								//initialize for strcat function
		for(channel = DS2; channel <= DS3; channel++)	//output to DS2 and DS3 only
		{
			output_level = channels[channel];		//output logic level to channel
			pbLedOut(channel, output_level);
			sprintf(s, "%s\t", output_level?"OFF":"ON ");		//format logic level for display
			strcat(display,s);							//add to display string
		}
		DispStr(8, 6, display);							//update output status

		// Wait for user to make output channel selection or exit program
		sprintf(display, "Select 2=DS2 or 3=DS3 to toggle LED's");
		DispStr(8, 12, display);
     	do
		{
			channel = getchar();
			if (channel == 'Q' || channel == 'q')		// check if it's the q or Q key
			{
      		exit(0);
     		}
     		channel = channel - 0x30;		// convert ascii to integer
		} while (!((channel >= DS2) && (channel <= DS3)));

		// Display the channel that the user has selected
		sprintf(display, "Selected DS%d to toggle               ", channel);
		DispStr(8, 12, display);

		// Wait for user to select logic level or exit program
		sprintf(display, "Select 1=OFF or 0=ON");
		DispStr(8, 13, display);
		do
		{
			output_level = getchar();
			if (output_level == 'Q' || output_level == 'q')		// check if it's the q or Q key
			{
      		exit(0);
     		}
     		output_level = output_level - 0x30;
		} while (!((output_level >= 0) && (output_level <= 1)));
		sprintf(display, "Selected %s         ", output_level?"OFF":"ON ");
     	DispStr(8, 13, display);
     	channels[channel] = output_level;

  		// Clear channel and logic level selection prompts
  		DispStr(8, 12, "                                                  ");
  		DispStr(8, 13, "                                                  ");
   }
}
コード例 #4
0
ファイル: ADCAL_SE_ALL.C プロジェクト: jgambox/DCRabbit_9
void main ()
{
	auto long average;
	auto unsigned int rawdata;
	auto int channel, gaincode;
	auto int key, i;
	auto float voltage, cal_voltage;
	auto char buffer[64];

	
	brdInit();	
	while(1)
	{
		DispStr(1, 1,"!!!Caution this will overwrite the calibration constants set at the factory.");
		DispStr(1, 2,"Do you want to continue(Y/N)?");  

		while(!kbhit());
		key = getchar();
		if(key == 'Y' || key == 'y')
		{		
			break;
		}
		else if(key == 'N' || key == 'n')
		{
			exit(0);
		}		
	}
	
	while (1)
	{
		printrange();
		printf("\nChoose gain code .... ");
		do
		{
			gaincode = getchar();
		} while (!( (gaincode >= '0') && (gaincode <= '7')) );
		gaincode = gaincode - 0x30;
		printf("%d", gaincode);
		while(kbhit()) getchar();
		
		cal_voltage = .1*vmax[gaincode];
		printf("\nAdjust to approx. %.4f and then enter actual voltage = ", cal_voltage);
		gets(buffer);
		for (channel=STARTCHAN; channel<=ENDCHAN; channel++)
		{
			ln[channel].volts1 = atof(buffer);
			average = 0;
			for(i=0; i<10; i++)
				average += anaIn(channel, SE_MODE, gaincode);
			ln[channel].value1 = (int)average/10;
			printf("lo:  channel=%d raw=%d\n", channel, ln[channel].value1);
		}
		while(kbhit()) getchar();
	
		cal_voltage = .9*vmax[gaincode];
		printf("\nAdjust to approx. %.4f and then enter actual voltage = ", cal_voltage);
		gets(buffer);
		for (channel=STARTCHAN; channel<=ENDCHAN; channel++)
		{
			ln[channel].volts2 = atof(buffer);
			average = 0;
			for(i=0; i<10; i++)
				average += anaIn(channel, SE_MODE, gaincode);
			ln[channel].value2 = (int)average/10;
			printf("hi:  channel=%d raw=%d\n", channel, ln[channel].value2);
		}
		while(kbhit()) getchar();
			
		for (channel=STARTCHAN; channel<=ENDCHAN; channel++)
		{
 			anaInCalib(channel, SE_MODE, gaincode, ln[channel].value1, ln[channel].volts1,
 			                                       ln[channel].value2, ln[channel].volts2);
		}
		
		printf("\nstore constants to flash\n");
		for (channel=STARTCHAN; channel<=ENDCHAN; channel++)
		{
			anaInEEWr(channel, SE_MODE, gaincode);				//store all channels
		}
		
		printf("\nread back constants\n");
		anaInEERd(ALL_CHANNELS, SE_MODE, gaincode);				//read all channels
		
		printf("\nVary voltage within the range selected\n");
		
		do 
		{
			for (channel=STARTCHAN; channel<=ENDCHAN; channel++)
			{
				voltage = anaInVolts(channel, gaincode);
				printf("Ch %2d Volt=%.5f \n", channel, voltage);
			}
			printf("Press ENTER key to read values again or 'Q' to calibrate another gain\n\n");
			while(!kbhit());
			key = getchar();
			while(kbhit()) getchar();
			
		}while(key != 'q' && key != 'Q');
	}            
}
コード例 #5
0
ファイル: SPEAKER.C プロジェクト: jgambox/DCRabbit_9
void main (void)
{
	unsigned	int aFreq, aAmp, wKey, akey, validkey;

	brdInit();				// initialize board, keypad, display
	keypadDef();			// set keypad to default layout
	dispContrast(BCONTRAST);		// adjust contrast
	dispBacklight(1);		// turn on backlight

	dispGoto(0,0);
	dispPrintf ("1-4 for volume" );
	dispGoto(0,1);
	dispPrintf ("'5' inc, '0' dec" );

	aFreq = LOFREQ;
	aAmp = 0;
	wKey=akey='0';
	validkey = 1;

	dispGoto(0,2);
	dispPrintf("Vol level %c", wKey);
	dispGoto(0,3);
	dispPrintf("Frequency %d", aFreq);

	for (;;) {
		costate {								//	Process Keypad Press/Hold/Release
			keyProcess ();
			waitfor ( DelayMs(10) );
			}

		costate {									//	Process Keypad Press/Hold/Release
			waitfor ( wKey = keyGet() );		//	Wait for Keypress
			switch ( wKey) {
				case	'1':
					aAmp = 0;		// no volume
					akey=wKey;
					break;
				case	'2':
					aAmp = 2;		// level 1
					akey=wKey;
					break;
				case	'3':
					aAmp = 1;		// level 2
					akey=wKey;
					break;
				case	'4':
					aAmp = 3;		// level 3
					akey=wKey;
					break;
				case	'5':
					if (aFreq < HIFREQ)
						aFreq+=STEP;    // increase frequency
					break;
				case	'0':
					if (aFreq > LOFREQ)
						aFreq-=STEP;		// decrease frequency
					break;
				default:
					validkey = 0;
					break;
				}

			if (validkey) {
				dispGoto(10,2);
				dispPrintf("%c  ", akey);
				dispGoto(10,3);
				dispPrintf("%d  ", aFreq);
				spkrOut (aFreq, aAmp );		// output to speaker
				}
			else
				validkey=1;
			}
		}
}
コード例 #6
0
ファイル: ALPHANUM.C プロジェクト: jgambox/DCRabbit_9
//***************************************************************************
//	Mainline
//***************************************************************************
void main (	void	)
{
	auto char entry[256];

	auto int wKey, i, loop;
	auto int helpMenuDone;

	//------------------------------------------------------------------------
	// Board and drivers initialization
	//------------------------------------------------------------------------
	brdInit();		// Required for all controllers
	dispInit();		// Graphic driver initialization, Start-up the keypad driver
	keypadDef();	// Set keys to the default driver configuration

	//------------------------------------------------------------------------
	// Font initialization
	//------------------------------------------------------------------------
	// Initialize structures with FONT bitmap information
	glXFontInit(&fi6x8, 6, 8, 32, 127, Font6x8);				//	initialize basic font

	//------------------------------------------------------------------------
	// Text window initialization
	//------------------------------------------------------------------------
	// Setup the widow frame to be the entire LCD to display information
	TextWindowFrame(&textWindow1, &fi6x8, 0, 0, 122, 32);
	TextWindowFrame(&textWindow2, &fi6x8, 0, 24, 122, 8);

	//------------------------------------------------------------------------
	// Main loop for the user to create messages from the keypad
	//------------------------------------------------------------------------
	while(1)
	{
		// Display user prompt for the message menu
		glBlankScreen();
		TextGotoXY(&textWindow1, 0, 0);
		TextPrintf(&textWindow1, "Press + to create a message...\n");

		// Wait for ENTER key to be pressed
		do
		{
			keyProcess();
			wKey = keyGet();
		} while(wKey != '+');

		// Go to the message menu
		glBlankScreen();
		memset(entry,0,sizeof(entry));
		enter_chars(entry);

		// Display the message the user typed
		glBlankScreen();
		TextGotoXY(&textWindow1, 0, 0);
		TextPrintf(&textWindow1, "Typed...%s", entry);

		// Wait for user to press any key to startover
		TextGotoXY(&textWindow1, 0, 3);
		TextPrintf(&textWindow1, "ENTER to Continue");
		do
		{
			keyProcess();
			wKey = keyGet();
		} while(wKey == 0);
	}
}
コード例 #7
0
ファイル: DNLOADCALIB.C プロジェクト: jgambox/DCRabbit_9
/////////////////////////////////////////////////////////////////////
//	Retrieve analog calibration data and rewrite to the flash
/////////////////////////////////////////////////////////////////////
void main()
{
	auto unsigned long fileptr, tempPtr, xmemPtr, index;
	auto unsigned long len;
	auto int i;
	auto char serialNumber[64];

	//------------------------------------------------------------------------
	//		Initialize the Controller
	//------------------------------------------------------------------------
	brdInit();

   BitWrPortI(PEDR, &PEDRShadow, 0, 5);	//set low to enable rs232 device

	seropen(BAUDRATE);	//set baud rates for the serial ports to be used
	serwrFlush();		//clear Rx and Tx data buffers
	serrdFlush();

	//------------------------------------------------------------------------
	//		Allocate and Clear XMEM
	//------------------------------------------------------------------------

	// Allocate XMEM memory for the file that will be read in from the PC
	xmemPtr = xalloc(FILEBUFSIZE);

	// Clear the buffer in XMEM
	for(index =0; index < FILEBUFSIZE; index++)
	{
		root2xmem(xmemPtr + index, "\x00", 1);
	}

	//------------------------------------------------------------------------
	//		Download the Data File from the PC
	//------------------------------------------------------------------------
	sprintf(string, "\r\nWaiting...Please Send Data file\n\r");
	serwrite(string, strlen(string));

	// Get the calibration data file from the PC and put it into XMEM
	if(!(len = getfile(xmemPtr)))
	{
		caldata_error(string, "\r\n\nEncounter an error while reading calibration file");
		exit(1);
	}
	fileptr = xmemPtr;
	sprintf(string, "\r\n\nDownload Complete\n\n\r");
	serwrite(string, strlen(string));

	//------------------------------------------------------------------------
	//	 Parse data file and write to calibrations to flash
	//------------------------------------------------------------------------
	sprintf(string, "\r\nParsing data file\n\r");
	serwrite(string, strlen(string));

	tempPtr = find_tag(fileptr, len);

	sprintf(string, "\r\n\nExiting....Calibration data successfully written\n\n\r");
	serwrite(string, strlen(string));
	while (serwrFree() != OUTBUFSIZE);
   while((RdPortI(SXSR)&0x08) || (RdPortI(SXSR)&0x04));
	serclose();
}
コード例 #8
0
ファイル: PUTS.C プロジェクト: jgambox/DCRabbit_9
void main()
{
	auto int i, ch;
	auto char buffer[64];	//buffer used for serial data
	
	static const char string1[] = "Rcv'd data on serial port C from serial port B\n\r";
	static const char string2[] = "Rcv'd data on serial port B from serial Port C\n\r";

	brdInit();		//required for BL2000 series boards
	
	// initialize serial portB, set baud rate to 19200
   serBopen(19200);
   serBwrFlush();
   serBrdFlush();

   // initialize serial portC, set baud rate to 19200
   serCopen(19200);
   serCwrFlush();
   serCrdFlush();

   serMode(0);			//required for BL2000 series bds...must be done after serXopen function(s)
   
	//clear data buffer
   memset(buffer, 0x00, sizeof(buffer));


   printf("\nStart of Sample Program!!!\n\n\n\r");
   for(;;)
   {
   	//transmit an ascii string from serial port B to serial port C
		memcpy(buffer, string1, strlen(string1));
     	serBputs(buffer);
		memset(buffer, 0x00, sizeof(buffer));
     	
		//get the data string that was transmitted by serial port B
     	i = 0;
     	while((ch = serCgetc()) != '\r')
     	{
			if(ch != -1)
			{
				buffer[i++] = ch;
			}
		}
     	buffer[i++] = ch; 		//copy '\r' to the data buffer
     	buffer[i]   = '\0';     //terminate the ascii string
     	
     	// display ascii string received from serial port B
   	printf("%s", buffer);
    	
   	//transmit an ascii string from serial port C to serial port B
		memcpy(buffer, string2, strlen(string2));
   	serCputs(buffer);
		memset(buffer, 0x00, sizeof(buffer));

   	//get the data string that was transmitted by port C
    	i = 0;
     	while((ch = serBgetc()) != '\r')
     	{	
			if(ch != -1)
			{
				buffer[i++] = ch;
			}
		}
		buffer[i++] = ch;			 //copy '\r' to the data buffer
     	buffer[i]   = '\0';      //terminate the ascii string

     	// display ascii string received from serial port C
     	printf("%s", buffer);
   }
}
コード例 #9
0
main()
{
	longword seq,ping_who,tmp_seq,time_out;
	char	buffer[100];
   auto wifi_region region_info;
   auto char index[10];
   auto int option;
   auto char tmpbuf[64];
   auto int updateRegion;
   auto int country;
   auto int configured;


	brdInit();				//initialize board for this demo

	seq=0;

	sock_init();			// Initial wifi interface

   // Make sure wifi IF is down to do ifconfig's functions
	printf("\nBringing interface down (disassociate)...\n");
   ifdown(IF_WIFI0);
   while (ifpending(IF_WIFI0) != IF_DOWN) {
     	printf(".");
     	tcp_tick(NULL);
   }
	printf("...Done.\n");

   configured = FALSE;
   updateRegion = FALSE;
   do
   {
   	country = get_stored_region(&region_info);
   	// Check if the region has been previously set.
 		if(country < 0 || updateRegion)
   	{
      	// Populate structure with region info, then display
   		ifconfig (IF_WIFI0, IFG_WIFI_REGION_INFO, &region_info, IFS_END);
   		printf("\nCurrent region setting:\n");
   		display_info(&region_info);

         // Select Region and write value to userblock
    		country = wifi_config_region(&region_info);
         updateRegion = FALSE;

   	}
   	else
   	{
      	// Set Region from previously saved value read from the userblock, this
      	// will set the runtime limits to be used by the wifi driver.

   		ifconfig (IF_WIFI0, IFS_WIFI_REGION, country,
         	IFG_WIFI_REGION_INFO, &region_info, IFS_END);

   		printf("\nRuntime region setting now being used by wifi driver:\n");
         display_info(&region_info);

      	// Region has already been set at runtime, check if it needs to
         // be changed due to country to country roaming.
    		printf("\nRegion already set, select option to continue");
         printf("\n1. Continue.");
         printf("\n2. Select new region.");
         printf("\nSelect > ");
			do
			{
				option = atoi(gets(tmpbuf));
	  		} while (!((option >= 1) && (option <= 2)));
         if(option == 2)
         	updateRegion = TRUE;
         else
         	configured = TRUE;
      }
	}while(!configured);

   // If you are not going to use the defaulted channel and/or power level,
   // then you can use the following functions to set channel and/or the
   // power level. This needs to be done after setting the region/country
   // to meet wifi driver requirements.

   //ifconfig (IF_WIFI0, IFS_WIFI_CHANNEL, 0, IFS_END); // Scan all channels
   //ifconfig (IF_WIFI0, IFS_WIFI_TX_POWER, 8, IFS_END); // Set to Pwr level 8


   // Startup the  wireless interface here...
	printf("Bringing interface back up (associate)...\n");
   ifup(IF_WIFI0);
   while (ifpending(IF_WIFI0) == IF_COMING_UP) {
      tcp_tick(NULL);
   }
	printf("...Done.\n");
	if (ifpending(IF_WIFI0) != IF_UP) {
		printf("Unfortunately, it failed to associate :-(\n");
		exit(1);
	}
   // End of regional setting section, from this point on do standard tcp/ip
   // protocol.


   /*
   // Here is where we gather the statistics...
	// Note that if you get a compile error here, it is because you are not running
	// this sample on a Wifi-equipped board.

	/* Print who we are... */
	printf( "My IP address is %s\n\n", inet_ntoa(buffer, gethostid()) );

	/*
	 *		Get the binary ip address for the target of our
	 *		pinging.
	 */

#ifdef PING_WHO
	/* Ping a specific IP addr: */
	ping_who=resolve(PING_WHO);
	if(ping_who==0) {
		printf("ERROR: unable to resolve %s\n",PING_WHO);
		exit(2);
	}
#else
	/* Examine our configuration, and ping the default router: */
	tmp_seq = ifconfig( IF_ANY, IFG_ROUTER_DEFAULT, & ping_who, IFS_END );
	if( tmp_seq != 0 ) {
		printf( "ERROR: ifconfig() failed --> %d\n", (int) tmp_seq );
		exit(2);
	}
	if(ping_who==0) {
		printf("ERROR: unable to resolve IFG_ROUTER_DEFAULT\n");
		exit(2);
	}
#endif

	for(;;) {
		/*
		 *		It is important to call tcp_tick here because
		 *		ping packets will not get processed otherwise.
		 *
		 */

		tcp_tick(NULL);

		/*
		 *		Send one ping every PING_DELAY ms.
		 */

		costate {
			waitfor(DelayMs(PING_DELAY));
			_ping(ping_who,seq++);
			pingoutled(LEDON);					// flash transmit LED
			waitfor(DelayMs(50));
			pingoutled(LEDOFF);
		}

		/*
		 *		Has a ping come in?  time_out!=0xfffffff->yes.
		 */

		costate {
			time_out=_chk_ping(ping_who,&tmp_seq);
			if(time_out!=0xffffffff) {

#ifdef VERBOSE
				printf("received ping:  %ld\n", tmp_seq);
#endif

				pinginled(LEDON);					// flash receive LED
				waitfor(DelayMs(50));
				pinginled(LEDOFF);
			}
		}
	}
}
コード例 #10
0
ファイル: AIN_CALSE_ALL.C プロジェクト: daveoman/DCRabbit_10
void main ()
{
	auto int device0, status;
	auto char buffer[64];
   auto rn_search newdev;
   auto rn_AinData aindata;
   auto float voltage, cal_voltage;
	auto int rawdata;
   auto int gaincode;
   auto int data1, data2;
   auto int channel;
   auto int key;


	brdInit();
   rn_init(RN_PORTS, 1);      //initialize controller RN ports

   //search for device match
	newdev.flags = MATCHFLAG;
	newdev.productid = MATCHPID;
   if ((device0 = rn_find(&newdev)) == -1)
   {
   	printf("\n no device found\n");
      exit(0);
   }

   while(1)
	{
		DispStr(1, 1,"!!!Caution this will overwrite the calibration constants set at the factory.");
		DispStr(1, 2,"Do you want to continue(Y/N)?");

		while(!kbhit());
		key = getchar();
		if(key == 'Y' || key == 'y')
		{
			break;
		}
		else if(key == 'N' || key == 'n')
		{
			exit(0);
		}

	}
	printf("\n");
	while(kbhit()) getchar();

   while (1)
	{
		// display the voltage that was read on the A/D channels
   	printrange();
		printf("\nChoose Voltage Configuration for the ADC Board 0 - 7.... ");
		do
		{
			gaincode = getchar();
		} while (!( (gaincode >= '0') && (gaincode <= '7')) );
		gaincode = gaincode - 0x30;
		printf("%d", gaincode);
		while(kbhit()) getchar();

	   // enable on all channels for conversions
		for(channel = 0; channel < 8; channel++)
		{
			status = rn_anaInConfig(device0, channel, RNSINGLE, gaincode, 0);
	   }

     	cal_voltage = .1*vmax[gaincode];
		printf("\nAdjust to approx. %.4f and then enter actual voltage = ", cal_voltage);
		gets(buffer);
		for (channel=0; channel < 8; channel++)
		{
			ln[channel].volts1 = atof(buffer);
			status = rn_anaIn(device0, channel, &data1, NUMSAMPLES, 0);
			ln[channel].value1 = data1;
			if (ln[channel].value1 == ADOVERFLOW)
				printf("lo:  channel=%d overflow\n", channel);
			else
				printf("lo:  channel=%d raw=%d\n", channel, ln[channel].value1);
		}

   	cal_voltage = .9*vmax[gaincode];
		printf("\nAdjust to approx. %.4f and then enter actual voltage = ", cal_voltage);
		gets(buffer);
		for (channel=0; channel < 8; channel++)
		{
			ln[channel].volts2 = atof(buffer);
			status = rn_anaIn(device0, channel, &data2, NUMSAMPLES, 0);
			ln[channel].value2 = data2;
			if (ln[channel].value2 == ADOVERFLOW)
				printf("hi:  channel=%d overflow\n", channel);
			else
				printf("hi:  channel=%d raw=%d\n", channel, ln[channel].value2);
		}

		printf("\nstore all constants to flash\n");
		for (channel=0; channel < 8; channel++)
		{
 			rn_anaInCalib(channel, RNSINGLE, gaincode, ln[channel].value1,
         	ln[channel].volts1,ln[channel].value2, ln[channel].volts2, &aindata);
	   	printf("gain=%8.5f offset=%d\n", aindata.gain, aindata.offset);
			status = rn_anaInWrCalib(device0, channel, RNSINGLE, gaincode, aindata, 0);
		}

		printf("\nread back constants\n");
		for (channel=0; channel < 8; channel++)
		{
			status = rn_anaInRdCalib(device0, channel, RNSINGLE, gaincode, &aindata, 0);
   		printf("read back gain=%8.5f offset=%d\n", aindata.gain, aindata.offset);
		}

      //After writing constants to flash, you must hard reset to close
      // off flash writes.  Wait 1 second to make sure device reinitializes
      // and clear the reset register.
      rn_reset(device0, 0);
      rn_msDelay(1000);

      //Check and clear reset status
      if(!((status = rn_rst_status(device0, buffer)) & 0x01))
     	{
      	printf("Error! ADC board didn't reset");
         exit(1);
      }
     	status =  rn_enable_wdt(device0, 1);  //enable device hardware watchdog

	   // Must enable on all channels for conversions again after reset
		for(channel = 0; channel < 8; channel++)
		{
			status = rn_anaInConfig(device0, channel, RNSINGLE, gaincode, 0);
	   }
  		printf("\nVary power supply for the voltage range selected.... \n\n");
		do
		{
      	for(channel = 0; channel < 8; channel++)
         {
         	status = rn_anaInVolts(device0, channel, &voltage, NUMSAMPLES, 0);
				printf("Ch %2d Volt=%.5f \n", channel, voltage);
         }
			printf("Press ENTER key to read value again or 'Q' to select another gain option\n\n");
			while(!kbhit());
			key = getchar();
			while(kbhit()) getchar();

		}while(key != 'q' && key != 'Q');
	}
}
コード例 #11
0
ファイル: ThermOffset.c プロジェクト: jgambox/DCRabbit_9
void main()
{
	auto int i;
   auto float temperature;
   auto char s[256];
   auto int key;
   auto int calib;
   auto int temp_units;

	// Initialize the I/O on the RabbitFLEX SBC40 board
	brdInit();

   while(1)
	{
		DispStr(1, 1,"!!!Caution this will overwrite the offset constant set at the factory.");
		DispStr(1, 2,"Do you want to continue(Y/N)?");
      while(!kbhit());
		key = getchar();
		if(key == 'Y' || key == 'y')
		{
      	calib = TRUE;
			break;
		}
		else if(key == 'N' || key == 'n')
		{
         calib = FALSE;
			break;
		}
	}
	while(kbhit()) getchar();
   if(calib)
   {
   	printf("\n\n");
      printf(" Select unit type you will be entering\n");
      printf(" -------------------------------------\n");
      printf(" 0 = Celsius\n");
      printf(" 1 = Fahrenheit\n");
      printf(" 2 = Kelvin\n");
		printf(" Select (0-2) =  ");
		do
		{
			temp_units = getchar();
		} while (!( (temp_units >= '0') && (temp_units <= '2')) );
		temp_units = temp_units - 0x30;
		printf("%d\n\n", temp_units);

		while(kbhit()) getchar();
		printf(" Enter the value from your temperature reference = ");
		gets(s);
		while(kbhit()) getchar();
		temperature = atof(s);

      // Create temperature offset constant and then write to flash.
      thermOffset(temp_units, temperature);
   }
   printf(" Thermistor adjustment completed...\n");
   printf(" Now display temperature continually...\n\n\n");
   while(1)
   {
     	sprintf(s, " Celsius=%.1f Fahrenheit=%.1f Kelvin=%.1f  \r",
      		  thermReading(0), thermReading(1), thermReading(2));
      printf("%s", s);
	}
}
コード例 #12
0
ファイル: DIGOUT.C プロジェクト: jgambox/DCRabbit_9
void main()
{

	auto char s[128];
	auto char display[128];
	auto char channels[16];
	auto int output_status, channel;
	auto int output_level;
	auto unsigned int outputChannel;

   brdInit();

	// Display user instructions and channel headings
	DispStr(8, 1, " <<< Sinking output channels  = OUT1-OUT7   >>>");
	DispStr(8, 2, " <<< Sourcing output channel  = OUT8-OUT9   >>>");
	DispStr(8, 4, "OUT0\tOUT1\tOUT2\tOUT3\tOUT4\tOUT5\tOUT6\tOUT7");
	DispStr(8, 5, "-----\t-----\t-----\t-----\t-----\t-----\t-----\t-----");

	DispStr(8, 9, "OUT8\tOUT9");
	DispStr(8, 10, "-----\t-----");

	DispStr(8, 14, "Connect the Demo Bd. LED's to the outputs that you want to demo.");
	DispStr(8, 15, "(See instructions in sample program for complete details)");
	DispStr(8, 21, "<-PRESS 'Q' TO QUIT->");

	// Set the channel array to reflect the output channel default value
	outputChannel = OUTCONFIG;
	for(channel = 0; channel <=9 ; channel++)
	{
		// Set outputs to be OFF, for both sinking
		// and sourcing type outputs.
		channels[channel] = outputChannel & 0x0001;
		outputChannel = outputChannel >> 1;
	}

	// Loop until user presses the upper/lower case "Q" key
	for(;;)
	{
		// Update high current outputs
		display[0] = '\0';								//initialize for strcat function
		for(channel = 0; channel <= 7; channel++)	//output to channels 0 - 7
		{
			output_level = channels[channel];		//output logic level to channel
			digOut(channel, output_level);
			sprintf(s, "%d\t", output_level);		//format logic level for display
			strcat(display,s);							//add to display string
		}
		DispStr(8, 6, display);							//update output status


		display[0] = '\0';
		for(channel = 8; channel <= 9; channel++)	//output to channels 8 - 9
		{
			output_level = channels[channel];			//output logic level to channel
			digOut(channel, output_level);
			sprintf(s, "%d\t", output_level);
			strcat(display,s);
		}
		DispStr(8, 11, display);

		// Wait for user to make output channel selection or exit program
		sprintf(display, "Select output channel 0 - 9 (Input Hex 0-F) = ");
		DispStr(8, 17, display);
     	do
		{
			channel = getchar();
			if (channel == 'Q' || channel == 'q')		// check if it's the q or Q key
			{
      		exit(0);
     		}
		}while(!isxdigit(channel));

		// Convert the ascii hex value to a interger
		if( channel >= '0' && channel <='9')
		{
			channel = channel - 0x30;
		}

		// Display the channel that ths user has selected
		sprintf(display, "Select output channel 0 - 9  = %d", channel);
		DispStr(8, 17, display);


		// Wait for user to select logic level or exit program
		sprintf(display, "Select logic level = ");
		DispStr(8, 18, display);
		do
		{
			output_level = getchar();
			if (output_level == 'Q' || output_level == 'q')		// check if it's the q or Q key
			{
      		exit(0);
     		}
     		output_level = output_level - 0x30;

		} while(!((output_level >= 0) && (output_level <= 1)));

		sprintf(display, "Select logic level = %d", output_level);
     	DispStr(8, 18, display);
     	channels[channel] = output_level;

  		// Clear channel and logic level selection prompts
  		DispStr(8, 17, "                                                  ");
  		DispStr(8, 18, "                                                  ");
   }
}
コード例 #13
0
ファイル: pong.c プロジェクト: daveoman/DCRabbit_10
void main (	void	)
{
	auto int wKey, ballspeed, stop;
 	auto int device0;
   auto rn_search newdev;
   auto unsigned int i;

	auto int	px,py;                        // Current Position
	auto int dx,dy;                        // Current Direction
	auto int nx,ny;                        // New Position
	auto int	xl, xh,	yl, yh;

	//------------------------------------------------------------------------
	// Initialize the controller
	//------------------------------------------------------------------------
	brdInit();			// Initialize the controller

   rn_init(RN_PORTS, 1);      // Initialize controller RN ports

   // Verify that the Rabbitnet display board is connected
	newdev.flags = MATCHFLAG;
	newdev.productid = MATCHPID;
   if ((device0 = rn_find(&newdev)) == -1)
   {
   	printf("\n no device found\n");
      exit(0);
   }

   // Initialize Display and Keypad low-level drivers
   // Note: Functions brdInit() and rn_init() must executed before initializing
   //       display and keypad drivers.
   rn_keyInit(device0, KEYSTROBLINES, 10);   //set key press buzzer for 10ms
	configKeypad3x4(device0);	// Set keys to the default driver configuration
	rn_dispInit(device0, DISPROWS, DISPCOLS);

   rn_dispPrintf(device0, 0, "Start   Pong");
   rn_keyBuzzerAct(device0, 100, 0);
	for (i=0; i<40000; i++);	//small delay
   rn_keyBuzzerAct(device0, 100, 0);
   rn_dispClear(device0, 0);
	rn_dispCursor(device0, RNDISP_CURBLINKON, 0);

	xl =  0;							// box coordinates, start column
	xh =  DISPCOLS;				// box coordinates, end column
	yl =  0;                   // box coordinates, start row
	yh =  DISPROWS; 				// lines 0 .. yh-1
   px = xl; py = yl;        	// Position Ball
   dx = 1; dy = 1;            // Give Direction

   ballspeed = 200;           // start ball speed at 200 ms delay
   stop = 0;

	while(1)
	{
   	costate
      {
      	if (!stop)
         {
		      rn_dispGoto (device0, px, py, 0);
				waitfor(DelayMs(ballspeed));

	   	   nx = px + dx;               	// Try New Position
   	   	ny = py + dy;

	      	if (nx <= xl || nx >= xh)     // Avoid Collision
   	      	dx = -dx;
	   	   if (ny <= yl || ny >= yh)
   	   	   dy = -dy;

	      	nx = px + dx;               	// Next Position
		      ny = py + dy;

	   	   rn_dispGoto (device0, px, py, 0);
				waitfor(DelayMs(ballspeed));

	   	   px = nx; py = ny;           	// Move Ball
         }
      }

		costate
		{
			rn_keyProcess (device0, 0);
			waitfor ( DelayMs(10) );
		}

		costate
		{
			waitfor ( wKey = rn_keyGet(device0, 0) );	//	Wait for Keypress
         if (wKey != 0)
         {
				printf("KEY PRESSED = %c\n", wKey);
         }
		}

		costate
		{
      	if ((wKey == '-') && (ballspeed<500))
         {
         	ballspeed+=10;		//increase delay
            stop = 0;
         }
		}

		costate
		{
      	if ((wKey == '+') && (ballspeed>10))
         {
         	ballspeed-=10;		//decrease delay
            stop = 0;
         }
		}

		costate
		{
      	if (wKey == '0')
         {
         	stop = 1;			//stop ball movement
         }
		}
   }
}
コード例 #14
0
ファイル: POWERDOWN.C プロジェクト: daveoman/DCRabbit_10
main()
{
	int state;
	word tmo;


	brdInit();				//initialize board for this demo

	// Bring up interface first time (also prints our address)
	sock_init_or_exit(1);

	// First initialization OK, turn on both LEDs
	if_led(LEDON);
	xcvr_led(LEDON);

	state = 0;
	tmo = _SET_SHORT_TIMEOUT(UPTIME);

	for(;;) {
		switch (state) {
		case 0:	// Up, timing out
			tcp_tick(NULL);
			if (_CHK_SHORT_TIMEOUT(tmo)) {
				printf("Bringing interface down...\n");
				state = 1;
				ifdown(IF_WIFI0);
			}
			break;
		case 1:	// bringing down
			tcp_tick(NULL);
			if (ifpending(IF_WIFI0) == IF_DOWN) {
				printf("Powering down...\n");
	         if_led(LEDOFF);
	         xcvr_led(LEDOFF);

            // Set flag for MAC to power down when tcp_tick function is called!
            pd_powerdown(IF_WIFI0);
	         tmo =_SET_SHORT_TIMEOUT(DOWNTIME);
	         state = 2;
	      }
	      break;
	   case 2:	// down, waiting
      	tcp_tick(NULL);
	   	if (_CHK_SHORT_TIMEOUT(tmo)) {
				printf("Powering up...\n");

            // Set flag for MAC to power-up when tcp_tick function is called!
	         pd_powerup(IF_WIFI0);
            xcvr_led(LEDON);
	         tmo =_SET_SHORT_TIMEOUT(500);	// settle for 1/2 sec
	         state = 3;
			}
			break;
		case 3: // let power stabilize
      	tcp_tick(NULL);
			if (_CHK_SHORT_TIMEOUT(tmo)) {
				printf("Bringing interface up...\n");
				ifup(IF_WIFI0);
	         state = 4;
			}
			break;
		case 4:	// waiting for up
			tcp_tick(NULL);
			if (ifpending(IF_WIFI0) != IF_COMING_UP) {
				if (ifpending(IF_WIFI0) == IF_DOWN) {
					printf("!!!!! Failed to come back up!!!!!\n");
					return -1;
				}
				printf("Up again!\n");
				if_led(LEDON);
	         tmo =_SET_SHORT_TIMEOUT(UPTIME);
				state = 0;
			}
			break;
		}
	}
}
コード例 #15
0
ファイル: Triac_ratio.c プロジェクト: jgambox/DCRabbit_9
main()
{
	auto int key, i;
   auto int triac_cntrl0, triac_cntrl1;
	auto int increment, decrement;
   auto int triac;
   auto char s[256];

   // The brdInit function is only used to configure the I/O
   // on the prototyping board and is not required for the triac
   // library which will configure everything required for triac
   // control.
   brdInit();

   triac_TimePropInit(1, 3);
   triac_TimePropCntrlPin(0, PFDR, 2, 0);
   triac_TimePropCntrlPin(1, PFDR, 3, 0);
   triac_cntrl0 = 0;
   triac_cntrl1 = 0;
   triac = 0;

   DispStr(1, 1,  "Triac Status");
   DispStr(1, 2,  "------------");
   sprintf(s,"Triac 0 ON/OFF ratio = %d/10", triac_cntrl0);
   DispStr(1, 3, s);

   sprintf(s,"Triac 1 ON/OFF ratio = %d/5", triac_cntrl1);
   DispStr(1, 4, s);
   sprintf(s,"Triac selected = %d", triac);
   DispStr(1, 5, s);

   DispStr(1, 7,  "Triac control Menu");
	DispStr(1, 8,  "------------------");
   DispStr(1, 9,  "1. Select triac 0 for control");
   DispStr(1, 10, "2. Select triac 1 for control");
	DispStr(1, 11, "3. Increment number of ON cycles");
	DispStr(1, 12, "4. Decrement number of ON cycles");
   DispStr(1, 13, "Select Option 1 - 4 > ");

	while (1)
	{
      costate
      {
      	switch(triac)
         {
         	case 0:
      			triac_TimePropCntrl(0, triac_cntrl0, 10);
               break;

            case 1:
               triac_TimePropCntrl(1, triac_cntrl1, 5);
               break;
         }
      }
		costate
		{
         if(kbhit())
			{
				key = getchar();
            while(kbhit()) getchar();
            msDelay(500);
            if( key >= '0' && key <='4')
				{
            	sprintf(s, "Select Option 1 - 4 > %c  ", key);
            	DispStr(1, 13, s);
				}
            switch(key)
            {
            	case '1':
               	triac = 0;
                  break;

               case '2':
               	triac = 1;
               	break;

               case '3':
               	switch(triac)
               	{
                		case 0:
                        if(triac_cntrl0 < 10)
                        	triac_cntrl0++;
                     	break;

                  	case 1:
                     	if(triac_cntrl1 < 5)
                  			triac_cntrl1++;
                     	break;
               	}
                  break;

               case '4':
             		switch(triac)
               	{
                		case 0:
                   		if (triac_cntrl0 > 0 )
                        	triac_cntrl0--;
                     	break;
                  	case 1:
                  		if (triac_cntrl1 > 0 )
                        	triac_cntrl1--;
                    	 	break;
               	}
                  break;


     			}
            sprintf(s,"Triac 0 ON/OFF ratio = %d/10   ", triac_cntrl0);
   			DispStr(1, 3, s);
         	sprintf(s,"Triac 1 ON/OFF ratio = %d/5    ", triac_cntrl1);
   			DispStr(1, 4, s);
         	sprintf(s,"Triac selected = %d", triac);
   			DispStr(1, 5, s);
			}
   	}
	}
}
コード例 #16
0
ファイル: heading_loop.c プロジェクト: ChrisHoder/Projects
void main()
   {
	auto int chan, ang, rvalue;
   auto float dist;
   auto int pwm, r_head, r_head2, head;
   auto long freq;
   auto char tmpbuf[128], c;
	char gpsString[MAX_SENTENCE];
   GPSPosition testPoint, testPoint_old;



	brdInit();
   serPORT(BAUDGPS);
   //serCopen(BAUDGPS);
   serMode(0);
   serCrdFlush();// main loop

   initGPS();
   freq = pwm_init(450ul);
   printf("pick heading: ");
   r_head = atoi(gets(tmpbuf));

   //while(1)
  // {
   /*goal.lat_degrees = 43;
   goal.lat_minutes = 7036;
   goal.lon_degrees = 72;
   goal.lon_minutes = 2811;
   goal.lat_direction = 'N';
   goal.lon_direction = 'W';
   goal.sog = 0;
   //goal.tog =
   */

   if ((r_head > 90) || (r_head < -90))
   	{
      printf("\nbad heading ");
     	}
   else {
   	while (1)
   		{
      	costate GPSRead always_on
				{
				// wait until gps mode is engaged and a gps string has been recieved
				waitfor(serCrdUsed() > 0);
				//printf("gps read:   ");

				// read until finding the beginning of a gps string then wait
				while(1)
					{
            //int test2;
            	c = serCgetc();
					if (c == -1)
						{
						serCrdFlush();
					  	abort;
						}
					else if (c == '$')
						{
						waitfor(DelayMs(20));  //should only take 5ms or so at 115200 baud
						break;
						}
				  	}//end while(1)

				// now that 20 ms have passed, read in the gps string (it must all
				// be there by now, since so much time has passed

				getgps(gpsString);
         	rvalue = gps_get_position(&testPoint,gpsString);
         	if( rvalue != -1)
         		{
         	  	printGPSPosition(&testPoint);
         		}
         	//printf("gps: %u \n",strlen(test2));
				printf("gps: %s ",gpsString);
            //printGPSPosition(&testPoint);
				//puts(gpsString);
				//puts(":   end gps \n");

         //dist = gps_ground_distance(&testPoint, &testPoint_old);
         //head = (int)gps_bearing(&testPoint, &testPoint_old, dist);
         //testPoint_old = testPoint;
         head = testPoint.tog;	// grab current heading
      	r_head2 = r_head-head;
         pwm = set_angle(0, r_head2);
         printf("angle: %d, head %d \n",pwm, head);
				}//end costate



  			}	// end while
   	}  // end else
	//} // end first while
	} // end main
コード例 #17
0
ファイル: main.c プロジェクト: AMDG2/DroneWifi
/** \fn void main(void)
	\ingroup Rabbit
	\brief Fonction principal : gestion du pilotage du drone en fonctions des entrées/sorties
	\author Baudouin Feildel
	\author Thibaut Marty
**/
void main(void)
{
	etat_commandes ec;
	ardrone droneV;
	ardrone* drone = &droneV;
	char cptPassErr = 0;
	wifi_status status;
	int initOk;
	
	/// Initialise les ports de la carte et les entrées/sorties
	brdInit(); // fonction de base de Rabbit
	BRDInit(); // fonction pour les bits utilisés
	init_etat_commandes(&ec);
	lireCommandes(&ec);

	/// Crée la structure du drone
	newARDrone(drone);
	
	/// Initialise la connexion (tant que toutes les étapes ne sont pas réussies) :
	do
	{
		printf("tentative d'initialisation\n");
		initOk = 0;
		
		/// .... Initialise le driver TCP
		if(sock_init())
			printf("erreur de sock_init()\n");
		else
			initOk++;
	
		/// .... Initialise la socket de connexion avec le drone
		if(!connectToDrone(drone))
			printf("erreur connectToDrone()\n");
		else
			initOk++;
		
		/// .... Se connecte au réseau WiFi
		connexion(&ec);
		
		/// .... Initialise le drone
		if(!initDrone(drone, &ec))
			printf("erreur initDrone()\n");
		else
			initOk++;
	} while(initOk < 3);
	printf("tentative d'initialisation reussie\n");
	
	/// Vérifie que l'on n'est pas déjà en position 'vol', sinon indique à l'utilisateur de changer le switch en faisant clignoter la LED erreur
	do
	{
		costate
		{
			lireCommandes(&ec);
			yield;
		}
		costate // Fait clignoter la LED d'erreur
		{
			ec.led_erreur = ec.led_erreur ? 0 : 1;
			ecrireCommandes(&ec);
			waitfor(DelayMs(300));
		}
	} while(ec.switch_land == 0);
	
	ec.led_erreur = 0;
	ecrireCommandes(&ec);

	
	/// Boucle principale (déroulement) :
	for(;;)
	{
		/// .... Tâche de gestion des entrées/sorties et de l'envoi de commandes au drone
		costate
		{
			tcp_tick(NULL);
			
			
			// Lit les entrées
			lireCommandes(&ec);

			/// ........ Si le bouton d'arrêt d'urgence est actif :
			if(!ec.bp_arret_urgence)
			{
				/// ............ Envoie la commande d'arrêt d'urgence
				aru(drone);
				drone->fly = false;
				/// ............ Attend le relâchement du bouton en faisant clignoter la LED debug
				do
				{
					costate
					{
						lireCommandes(&ec);
						yield;
					}
					costate // Fait clignoter la LED de debug
					{
						ec.led_debug = ec.led_debug ? 0 : 1;
						ecrireCommandes(&ec);
						waitfor(DelayMs(100));
					}
					yield; // Pour la tâche de vérification de la connexion WiFi
				} while(!ec.bp_arret_urgence);
				ec.led_debug = 0;
				ecrireCommandes(&ec);
				
				/// ............ Renvoie la commande (pour sortir du mode d'arrêt d'urgence)
				aru(drone);
			}
			/// ........ Sinon (traitement de tous les cas position du switch / vol en cours) :
			else
			{
				// pour plus tard :
				// if(ec.bp_video)	{ }
				
				/// ............ Si le bouton trim est actif et que l'on n'est pas en cours de vol, réinitialise le drone
				if(!ec.bp_trim && !drone->fly)
					initDrone(drone, &ec);
				
				/// ............ Si le switch est en position haute et que l'on ne vole pas
				if(ec.switch_land == 0 && !drone->fly)
				{
					/// ................ Fait décoler le drone. S'il y a une erreur : attend que l'utilisateur repasse le switch en position basse en faisant clignoter la LED erreur
					if(!(initDrone(drone, &ec) && takeoff(drone)))
					{
						do
						{
							costate
							{
								lireCommandes(&ec);
								yield;
							}
							costate // Fait clignoter la LED d'erreur
							{
								ec.led_erreur = ec.led_erreur ? 0 : 1;
								ecrireCommandes(&ec);
								waitfor(DelayMs(100));
							}
						} while(ec.switch_land == 0);
					}
				}
				/// ............ Si le switch est en position basse et que l'on vole
				else if(ec.switch_land == 1 && drone->fly)
				{
					/// ................ Fait atterrir le drone. S'il y a une erreur : attend que l'utilisateur passe le switch en position haute
					if(!land(drone))
					{
						do
						{
							costate
							{
								lireCommandes(&ec);
								yield;
							}
							costate // Fait clignoter la LED d'erreur
							{
								ec.led_erreur = ec.led_erreur ? 0 : 1;
								ecrireCommandes(&ec);
								waitfor(DelayMs(300));
							}
						} while(ec.switch_land == 1);
					}
				}
				/// ............ Les autres cas sont normaux et ne nécessitent pas de traitement particulier


				/// ............ Si on est en vol :
				if(drone->fly)
				{
					/// ................ Traite la valeur des joysticks et la stock dans la structure ardrone
					
					     setGoUpDown(drone, (float)(ec.joystick_2x - 2048) / 2048);
					setTurnLeftRight(drone, (float)(ec.joystick_2y - 2048) / 2048);
					setTiltFrontBack(drone, (float)(ec.joystick_1x - 2048) / 2048);
					setTiltLeftRight(drone, (float)(ec.joystick_1y - 2048) / 2048);

					/// ................ Envoie la commande avec les valeurs : s'il y a une erreur on incrémente un compteur d'erreurs. Au delà de dix erreurs de suite on tente de faire atterir le drone. S'il n'y a pas d'erreurs, on attend 30ms avant le prochain envoi
					if(!(volCommand(drone, drone->tiltLeftRight, drone->tiltFrontBack, drone->goUpDown, drone->turnLeftRight)))
					{
						if(cptPassErr > 10)
							land(drone);
						else
							cptPassErr++;
					}
					else
					{
						cptPassErr = 0; // Remise à zéro du compteur d'erreur en cas de réussite
						waitfor(DelayMs(30)); // prochain envoi de commande dans 30 ms
					}
				}
				else
					yield;
			}
コード例 #18
0
int main()
{
	int status, led2, led3, sw2;

	// Initialize I/O pins
	brdInit();

   led2 = 0;
   led3 = 1;
	DS2led(OFF);
	DS3led(OFF);
   sw2 = 0;
   status = !SECURE;

   while(1) {
      costate {
         waitfor(DelayMs(200));
         if(status == SECURE) {
            // LED's on
				DS2led(ON);
				DS3led(ON);
         }
         else {
            // Flash LED's
	         led2 = !led2;
	         led3 = !led2;
				DS2led(led2);
				DS3led(led3);
         }
      }
      costate {
         // Wait for switch S2 press
			if(BitRdPortI(PBDR, S2_BIT))
				abort;
			waitfor(DelayMs(50));				// switch press detected
			if(BitRdPortI(PBDR, S2_BIT))	// wait for switch release
			{
				sw2 = !sw2;							// set valid switch
				abort;
			}
      }
      costate {
         // Periodically check the VBAT RAM
         memset(buffer, 0, 32);
         vram2root(buffer, 0, 32);

         if(memcmp(buffer, key, 32) == 0)
            status = SECURE;
         else
            status = !SECURE;

         waitfor(DelayMs(1000));
      }
      costate {
         // If the switch is pressed, reset the VBAT RAM
         if(sw2) {
            root2vram(key, 0, 32);
            sw2 = !sw2;
         }
      }
   }
}
コード例 #19
0
ファイル: PARITY.C プロジェクト: jgambox/DCRabbit_9
main()
{
	auto char received;
	auto int i;
	auto int txconfig;

	brdInit();				//initialize board for this demo
						
	serBopen(baud_rate);
	serCopen(baud_rate);
	
	serBparity(PARAM_OPARITY);
	serCparity(PARAM_OPARITY);
	txconfig = PARAM_OPARITY;
	
	printf("Starting...\n");
				
	while (1)
	{
		costate
		{
			//send as fast as we can
			for (i = 0; i < 128; i++)
			{
				waitfor(DelayMs(10)); 	//necessary if we are not using
											 	//flow control
				waitfordone{ cof_serBputc(i); }
			}
			// wait for data buffer, internal data and shift registers to become empty
  			waitfor(serBwrFree() == BOUTBUFSIZE);
  			waitfor(!((RdPortI(SBSR)&0x08) || (RdPortI(SBSR)&0x04)));
			yield;
  			
			//toggle between sending parity bits, and not
			if (txconfig)
			{
				txconfig = PARAM_NOPARITY;
				printf("\nParity option set to no parity\n");
			}
			else
			{
				txconfig = PARAM_OPARITY;
				printf("\nParity option set to odd parity\n");
			}
			serBparity(txconfig);
		}
		
		costate
		{
			//receive characters in a leisurely fashion
			waitfordone
			{
				received = cof_serCgetc();
			}
			printf("received 0x%x\n", received);
			if (serCgetError() & SER_PARITY_ERROR)
			{
				printf("PARITY ERROR\n");
			}
	   }
	}
}
コード例 #20
0
ファイル: KEYPADTOLED.C プロジェクト: jgambox/DCRabbit_9
main()
{
	static int led, channel, wKey, keypad_active, prompt_displayed;
	static int new_keypress_message, release_value, i;
	//------------------------------------------------------------------------
	// Initialize the controller
	//------------------------------------------------------------------------
	brdInit();				// Initialize the controller for this demo

	// Start-up the keypad driver and
	// Initialize the graphic driver
	dispInit();

	// Use default key values along with a key release code
	keyConfig (  3,'R', '1', 0, 0,  0, 0 );
	keyConfig (  6,'E', '2', 0, 0,  0, 0 );
	keyConfig (  2,'D', '3', 0, 0,  0, 0 );
	keyConfig (  5,'+', '4', 0, 0,  0, 0 );
	keyConfig (  1,'U', '5', 0, 0,  0, 0 );
	keyConfig (  4,'-', '6', 0, 0,  0, 0 );
	keyConfig (  0,'L', '7', 0, 0,  0, 0 );

	// Initialize 6x8 font
	glXFontInit(&fi6x8, 6, 8, 32, 127, Font6x8);          // Initialize 6x8 font
	glXFontInit(&fi8x10, 8, 10, 32, 127, Font8x10);			//	initialize 8x10 font
	glBlankScreen();

	// Initialize control flags
	keypad_active = FALSE;
	prompt_displayed = FALSE;
	new_keypress_message = FALSE;
	for(;;)
	{
		costate
		{
			keyProcess ();
			waitfor ( DelayMs(10) );

		}

		costate
		{
			// Wait for any key to be pressed
			waitfor((wKey = keyGet()) != 0);
			release_value = -1;
			switch(wKey)
			{
				case 'L': 	release_value = '7'; break;
				case '-': 	release_value = '6'; break;
				case 'U':   release_value = '5'; break;
				case '+': 	release_value = '4'; break;
				case 'D':	release_value = '3'; break;
				case 'E':	release_value = '2'; break;
				case 'R':	release_value = '1'; break;
			}
			if(release_value != -1)
			{
				keypad_active = TRUE;
				// Wait for the key to be released
				waitfor(keyGet() == release_value);
				keypad_active = FALSE;
			}
		}

		costate
		{
			if(!keypad_active)
			{
				if(!prompt_displayed)
				{
					glBlankScreen();
					glPrintf (0,  0, &fi6x8,  "Waiting for a Key to");
					glPrintf (0,  8, &fi6x8,  "be pressed on the ");
					glPrintf (0,  16, &fi6x8, "LCD Keypad....");
					glFillPolygon(4, 115, 26,  121,26,   121,31,   115, 31);
					prompt_displayed = TRUE;
					new_keypress_message = FALSE;

					// Turn-Off leds on the Demo board
					pbLedOut(DS1, OFF); 		//DS1 off
					pbLedOut(DS2, OFF);		//DS2 off
				}

				for(channel = 0; channel <= 6; channel++)
				{
					for(led = 0; led <=6; led++)
					{
						if(led != channel)
						dispLedOut(led, 0);
					}
					dispLedOut(channel, 1);
					waitfor(DelayMs(100));
					if(keypad_active)
					{

						break;
					}
				}
			}
		}

		costate
		{
			if(keypad_active && !new_keypress_message)
			{
				glBlankScreen();
				glFillPolygon(4, 113, 26,  121,26,   121,31,   113, 31);
				switch(wKey)
				{
					case 'L':
						glPrintf (0,  0, &fi8x10, "Scroll-Left key");
						glPrintf (0,  16, &fi8x10, "is Active.");
						dispLedOut(0, 1);
						channel = 0;
						break;

					case '-':
						glPrintf (0,  0, &fi8x10, "Page-Down key");
						glPrintf (0,  16, &fi8x10, "is Active.");
						dispLedOut(1, 1);
						channel = 1;
						pbLedOut(DS1, ON); 		//DS1 on
						break;

					case 'U':
						glPrintf (0,  0, &fi8x10, "Scroll-Up key");
						glPrintf (0,  16, &fi8x10, "is Active.");
						dispLedOut(2, 1);
						channel = 2;
						break;

					case '+':
						glPrintf (0,  0, &fi8x10, "Page-Up key");
						glPrintf (0,  16, &fi8x10, "is Active.");
						dispLedOut(3, 1);
						channel = 3;
						pbLedOut(DS2, ON); 		//DS2 on
						break;

					case 'D':
						glPrintf (0,  0, &fi8x10, "Scroll-Down key");
						glPrintf (0,  16, &fi8x10, "is Active.");
						dispLedOut(4, 1);
						channel = 4;
						break;

					case 'E':
						glPrintf (0,  0, &fi8x10, "Enter key");
						glPrintf (0,  16, &fi8x10, "is Active.");
						dispLedOut(5, 1);
						channel = 5;
						break;

					case 'R':
						glPrintf (0,  0, &fi8x10, "Scroll-Right");
						glPrintf (0,  16, &fi8x10, "key is Active.");
						dispLedOut(6, 1);
						channel = 6;
						break;
				}
				for(led=0; led <=6; led++)
				{
					if(led != channel)
					{
						dispLedOut(led, 0);
					}
				}
				prompt_displayed = FALSE;
				new_keypress_message = TRUE;
			}
		}
		costate
		{
			if(keypad_active)
			{
				for(i=0; i<(LCD_XS-8); i+=4)
				{
					glHScroll(0, 26, LCD_XS, 6, -4);
					waitfor(DelayMs(5));
					if(!keypad_active)
						abort;
				}
				for(i=0; i<(LCD_XS-8); i+=4)
				{
					glHScroll(0, 26, LCD_XS, 6, 4);
					waitfor(DelayMs(5));
					if(!keypad_active)
						abort;
				}
			}
		}
	}
}
コード例 #21
0
ファイル: RELAYCHR.C プロジェクト: jgambox/DCRabbit_9
void main()
{
   auto int c, num_bytes, done;
   auto char *ptr;
	auto int parallel_counter, loop_counter;
	auto char buffer[256];
	auto char s[256];
   

	brdInit();		//required for BL2100 series boards
		
	c = 0;			//initialize variables
	parallel_counter = 0;
	loop_counter	  = 0;
	done				  = FALSE;

	sprintf(s, "Character counter = %d", 0);	//initialize for proper STDIO effects
   DispStr(2, 2, s);

   // display exit message
   DispStr(2, 5, "Press the ESC key in Hyperterminal to exit the program");
   
	serCopen(BAUD_RATE);	//set baud rates for the serial ports to be used
   serBopen(BAUD_RATE);
   
	serCwrFlush();		//clear Rx and Tx data buffers 
	serCrdFlush();

	serBwrFlush();		
	serBrdFlush();
   
   serMode(0);			//required for BL2100 series bds...must be done after serXopen function(s)
 
   while (!done) {
               
   	loophead();			//required for single-user cofunctions
   	
   	costate				//single-user serial cofunctions 
   	{
   		// Wait for char from hyperterminal
	      wfd c = cof_serBgetc(); // yields until successfully getting a character

			//do clean exit from costatement
	      if(c == ESC)
   	   {
   	   	//flag used to exit out of this WHILE loop and other costatements
				done = TRUE;
				
				//abort this costatement
				abort;		
   	   }

	      // send character to serial port C
   	   wfd cof_serBputc(c);    // yields until c successfully put

   	   // wait for char from serial port C
   	   wfd c = cof_serCgetc(); // yields until successfully getting a character

   	   //send character back to hyperterminal
   	   wfd cof_serCputc(c);    // yields until c successfully put

   	   waitfor(serCwrUsed() == 0);
   	   
   	   //demonstrates that the above cofunctions only yields to other costates
   	   //and not to the code within the same costatement section.
   	   sprintf(s, "Character counter = %d", ++loop_counter);
   	   DispStr(2, 2, s);
      }
      costate
      {
      	// Abort this costatement if the done flag has been set
      	if(done)
   	   {
				abort;	//do clean exit of costatement
   	   }
			//execute code while waiting for characters from hyperterminal
			sprintf(s, "Parallel code execution counter = %d\r", parallel_counter++);
			DispStr(2, 3, s);
      }
   }
   
   // send program exit message
   serBputs("\n\n\rProgram Done...exiting");
   
   // wait for memory data buffer, serial holding register, and shift
   // register all to become empty
   while (serBwrFree() != BOUTBUFSIZE);
   while((RdPortI(SBSR)&0x08) || (RdPortI(SBSR)&0x04));

	// read data and send to hyperterminal
   num_bytes = serCread(buffer, sizeof(buffer), 5);
   buffer[num_bytes] = '\0';
	serCwrite(buffer, strlen(buffer));
	
   // wait for memory data buffer, serial holding register, and shift
   // register all to become empty
   while (serCwrFree() != COUTBUFSIZE);
   while((RdPortI(SCSR)&0x08) || (RdPortI(SCSR)&0x04));
 
   //close the serial ports
   serCclose();
   serBclose();
}
コード例 #22
0
ファイル: YETI_SPOLE_V1_5.c プロジェクト: ChrisHoder/Projects
main()
{
   char radioOutput[511];
   // buffer to read the radio input from user laptop
   char radioInput[CINBUFSIZE];
   char radioOutput2[511];
   // buffer to read the radio input from instrument laptop
   char radioInput2[EINBUFSIZE];
   // buffer to output encoder info
   char enc_data[70];
   // buffer to relay data from the datalogger through to the radio
   char loggerInput[EINBUFSIZE+2];
   char yetiState[10];
   char axis_1[20];
   char axis_2[20];
   char axis_3[20];
   char axis_4[20];
   char temp[3];
   // whether the robot has gotten a ping recently or not
   char ping;
   // the number of waypoints the robot has
   int numWayPoints;
   // the current waypoint the robot is on
   char curWayPoint;
   // interval(sec) b/w telemtry broacastings from the robot to user and to instrument
   char telemetryInterval;
   // whether gps string is valid or not
   int valid_gps;

   // whether gps navigation is engaged or not
   char engageGPSnav;
   // how many bytes in the serial buffer are used
   int used;
   int usedE;
   // int for indexing loops
   int i;
   // requested linear and angular velocites of robot from java
   int v;
   int w;
   // updated linear and angular velocites
   int newV;
   int newW;
   // difference between current and desired linear and angular velocites
   int vDiff;
   int wDiff;
   // how many characters of a gps string have been read in so far
   int charCounter;
   // character read in off the serial port (look at serFgetc() to see why it is
   // an int
   int c;
   // holds a gps string after reading it in
   char gpsString[85];
   // stopping interval for data collection in seconds
   int resting_interval;

   // int to keep track of if this is the first run of the program or not
   int helpLast,helpLast2;

   //Encoder Sending code
   int j;
   int delayvar;
   int asb, bsb, csb;
   long position, asb_l, bsb_l, csb_l;

   float currentToGoal; //distance between current position and goal
   float originToCurrent; //distance between origin to current position
   float bearingToGoal; //bearing from current position to goal in degree
   float bearingToCurrent; //bearing from origin to current position in degree

   float INTEGRALMAX; //maximum that integral can get

   float deltaloop;

   int flag; //flag for restoring yeti to GPS navigation automatically
   int flag2; //flag for changing last gps coordinate

   // initialize hardware
   brdInit();

   LastGPS.lat_degrees = 72;
   LastGPS.lat_minutes = 32.123;
   LastGPS.lon_degrees = 17;
   LastGPS.lon_minutes = 42.232;

   CurrentGPS.lat_degrees = 72;
   CurrentGPS.lat_minutes = 32.200;
   CurrentGPS.lon_degrees = 17;
   CurrentGPS.lon_minutes = 42.232;

   Goal.lat_degrees = 72;
   Goal.lat_minutes = 33.200;
   Goal.lon_degrees = 17;
   Goal.lon_minutes = 43.500;

   GoalPos = getPol(getCart(&CurrentGPS,&Goal));
	bearingToGoal = gps_bearing2(&CurrentGPS, &Goal);
   CurCart = getCart(&LastGPS,&CurrentGPS);
   CurPol = getPol(CurCart);
	bearingToCurrent = gps_bearing2(&LastGPS,&CurrentGPS);
	error = bearRange(CurPol.t-GoalPos.t);
	error2 = bearRange((bearingToCurrent-bearingToGoal)*PI/180.0);

   printf("%f, %f\n",bearingToCurrent,bearingToGoal);
   printf("error:%f,   error2:%f\n",error,error2);

   //digOutConfig(DIGOUTCONFIG);
   digOutConfig(0xff00);
   //digHoutConfig(0x07);        // Set Hout0 Sinking
   digHTriStateConfig(0x06);  // Set Hout1 & Hout2 for Tristate
   //initialize Encoder Board
   initEncoder();

   //initialize state machine flags
   controlMode = USER_CONTROL_MODE;
   robotMobility = MOBILE;
   classificationMode = CLASSIFICATION_OFF;
   obstacleType = OBSTACLE_1;

   // open 2 radio serial ports and gps serial ports
   serCopen(BAUDR1);
   serFopen(BAUDGPS);
   serEopen(BAUDR2);
   //serEopen(BAUDLOG);

   //disable motor controllers
   //digHout(0,0);
   digHoutTriState(1,0);

   // set wheel velocities to 0
   anaOutConfig(1,1);
   anaOutPwr(1);
   anaOutVolts(0,0);
   anaOutVolts(1,0);
   anaOutVolts(2,0);
   anaOutVolts(3,0);
   anaOutStrobe();

   // set serial port mode
   serMode(0);
   // initialize variables
   ping = 1;
   numWayPoints = 0;
   coords_received = 0;
   //engageGPSnav = 0;     //remove
   curWayPoint = 0;
   currentV = 0;
   currentW = 0;
   desiredV = 0;
   desiredW = 0;
   helpLast = 0;
   helpLast2 = 0;

   // intialize WMAX so that Vmin > Vmax / 4 (preventing robot from turning in circle)
   MAXW = min(2000 - AUTONOMOUS_SPEED, AUTONOMOUS_SPEED);
   if((AUTONOMOUS_SPEED+MAXW)/4 > AUTONOMOUS_SPEED-MAXW)
   	MAXW = 3*AUTONOMOUS_SPEED/5;
   printf("MAXW : %d\n",MAXW);

   telemetryInterval = 1; //default telemetry broadcasting interval = 1 sec

   //controller coefficients
   P_coeff = .30;                   //starting point .30
   I_coeff = .002;          //starting point .002
   loop_gain = 714;                 //starting point 714
   INTEGRALMAX = (float)MAXW / loop_gain / I_coeff / 2.0; //integral effort max = 1/2 speed differential

   // clear any junk out of serial ports
   serFrdFlush();
   serCrdFlush();
   serErdFlush();

   sprintf(radioOutput, "Waypoints not received, %s", gpsString);

   // error integration initialization
   last_error = 0;
   error_integral = 0;
   error = 0;
   error2 = 0;
   last_time = TICK_TIMER;
   deltat = 0;

   // stopping at each waypoint as a default setting
   stoppingMode = 1;
   resting_interval = 0;

   // initialize distance and bearing
   originToCurrent = 0;
   currentToGoal = 0;
   bearingToGoal = 0;
   bearingToCurrent =0;

   loop_time = TICK_TIMER;

   flag=0;
   flag2=0;
   valid_gps=-1;

   // main while loop
   while(1)
   {
      deltaloop = (float)(TICK_TIMER-loop_time)/1024;
      loop_time = TICK_TIMER;

      //Test if Serial ports have input
      costate
      {
         used = serCrdUsed();       //bytes being used in serial buffer for radio communication port1
         usedE = serErdUsed();      //bytes being used in serial buffer for radio communication port2 or data logger
      }

      // sending data from robot to user computer
#ifdef _send_telemetry_
      costate sendTelemetry always_on
      {
         waitfor(DelaySec(telemetryInterval));

         sprintf(radioOutput,"valid GPS: %d, ",valid_gps);
         serCputs(radioOutput);
         DelayMs(35);

         /*sprintf(radioOutput,"current GPS: %d,%f,%d,%f,*", CurrentGPS.lat_degrees, CurrentGPS.lat_minutes, CurrentGPS.lon_degrees, CurrentGPS.lon_minutes);
         serCputs(radioOutput);
         DelayMs(35);

         sprintf(radioOutput,"coord GPS: %d,%f,%d,%f,*", WayPoints[0].lat_degrees, WayPoints[0].lat_minutes, WayPoints[0].lon_degrees, WayPoints[0].lon_minutes);
         serCputs(radioOutput);
         DelayMs(35);*/

         sprintf(radioOutput,"errors: %f,%f, deltat: %f, ",error,error2,deltat);
         serCputs(radioOutput);
         DelayMs(35);

         sprintf(radioOutput,"integral term: %f, w:%d, ",I_coeff*error_integral*loop_gain,currentW);
         serCputs(radioOutput);
         DelayMs(35);

         sprintf(radioOutput,"dis: %f,%f,*",currentToGoal,GoalPos.r);
         serCputs(radioOutput);
         DelayMs(35);

         /*DelayMs(35);
         sprintf(radioOutput2,"loop:%f,*",deltaloop);
         serCputs(radioOutput2);*/

         sprintf(radioOutput,"%d,%f,%d,%f,", CurrentGPS.lat_degrees, CurrentGPS.lat_minutes, CurrentGPS.lon_degrees, CurrentGPS.lon_minutes);
         serCputs(radioOutput);
         DelayMs(35);
         sprintf(radioOutput,"%d,%d,%d,",currentV,currentW,controlMode);
         serCputs(radioOutput);
         DelayMs(35);
         sprintf(radioOutput,"%d,%f,%d,%f,*", Goal.lat_degrees, Goal.lat_minutes, Goal.lon_degrees, Goal.lon_minutes);
         serCputs(radioOutput);
      }
      costate sendTelemetry2 always_on
      {
         waitfor(DelaySec(telemetryInterval));

         //send current moving status of robot to instrument package laptop
         sprintf(radioOutput2,"%d,%f,%d,%f,", CurrentGPS.lat_degrees, CurrentGPS.lat_minutes, CurrentGPS.lon_degrees, CurrentGPS.lon_minutes);
         serEputs(radioOutput2);

         DelayMs(35);
         sprintf(radioOutput2,"%d,%d,%d,*",currentV,currentW,controlMode);
         serEputs(radioOutput2);

         DelayMs(35);
         sprintf(radioOutput2,"stopmode: %d, controlmode: %d,*",stoppingMode, controlMode);
         serEputs(radioOutput2);
      }
#endif

      //***********************************************************************************
      // serial message interpretation costate
      costate serialIn always_on
      {
         // wait until a message comes
         waitfor(used > 0);

         // give the message a chance to finish sending
         waitfor(DelayMs(100));
         if(used > 100) waitfor(DelaySec(2)); //increase in case receiving long waypoint list
         used = serCrdUsed();
         serCread(radioInput,used, 2);
         radioInput[used] = '\0';      //terminate string

         // since a message came, we know we are in radio contact
         ping = 1;
         serCrdFlush();

         //remote control mode
         // [zeros] [v byte 1] [v byte 2] [w byte 1] [w byte 2]
         if(radioInput[0] == 0)
         {
            // recieve a remote control driving command
            //engageGPSnav = 0;       //remove
            if (controlMode != ESCAPE_CONTROL_MODE)
            {
               controlMode = USER_CONTROL_MODE;
               error_integral = 0;
               last_time = TICK_TIMER;

               v = (int)radioInput[2]<<8; 
               desiredV = v+radioInput[1];
               w = (int)radioInput[4]<<8;
               desiredW = w+radioInput[3];
#ifdef _debug_
               printf("command\n");
#endif
            }
         }

         else if (radioInput[0] == 1) //receiving gps waypoint list
         {
            // load in gps coordinates
            // convention N = +lat_deg +lat_min, W = +long_deg +long_min
            //				  S = -lat_deg -lat_min, E = -long_deg -long_min
            if(radioInput[1] > 180){
               numWayPoints = 180;
            }
            else if(radioInput[1] >0){
               numWayPoints = (int)(radioInput[1]);
            }
            else{
               numWayPoints = 0;
            }

            for(i = 0;i<numWayPoints;i++)
            {
               WayPoints[i].lat_degrees = CtoI(radioInput[2+i*12],radioInput[2+i*12+1]);
               WayPoints[i].lat_minutes = CtoF(radioInput[2+i*12+2],radioInput[2+i*12+3],radioInput[2+i*12+4],radioInput[2+i*12+5]);
               WayPoints[i].lon_degrees = CtoI(radioInput[2+i*12+6],radioInput[2+i*12+7]);
               WayPoints[i].lon_minutes = CtoF(radioInput[2+i*12+8],radioInput[2+i*12+9],radioInput[2+i*12+10],radioInput[2+i*12+11]);

               DelayMs(35);   //print waypoint list to logfile
               sprintf(radioOutput,"waypoint,%d,%d,%f,%d,%f,*",i,WayPoints[i].lat_degrees,WayPoints[i].lat_minutes,WayPoints[i].lon_degrees,WayPoints[i].lon_minutes);
               serCputs(radioOutput);
            }
            curWayPoint = 0;
            Goal = WayPoints[0];

            if (numWayPoints > 0){
               coords_received  = 1;
            }

            DelayMs(35);
            sprintf(radioOutput,"coords loaded,%d,*",numWayPoints);
            serCputs(radioOutput);
            //DelayMs(35);
            //sprintf(radioOutput,"1st pos: %d,%f,%d,%f,*", Goal.lat_degrees, Goal.lat_minutes, Goal.lon_degrees, Goal.lon_minutes);
            //serCputs(radioOutput);

#ifdef _debug_
            printf("load coord\n");
#endif
         }

         else if (radioInput[0] == 3)
         {
            // engage GPS navigation system
            if (numWayPoints>0){
               controlMode = GPS_CONTROL_MODE;
               error_integral = 0;
               last_time = TICK_TIMER;
               helpLast =0;
               helpLast2 = 0;
               originToCurrent = 0;
               currentToGoal = 999999;

               sprintf(radioOutput,"GPS mode started,*",numWayPoints);
               serCputs(radioOutput);
            }
#ifdef _debug_
            printf("GPS\n");
#endif
         }

         else if (radioInput[0] == 4)
         {
            //set the interval for telemetry broadcasting
            telemetryInterval = radioInput[1];
         }
         // {
            // // set the current waypoint the robot is heading for
            // if ((radioInput[1] <= numWayPoints) && (radioInput[1] > 0))
            // curWayPoint = radioInput[1]-1;
         // }
         // Signal to test escape sequences and re-routing

         // Emergency Stop the robot if Escape Mode is enabled
         else if (radioInput[0] == 6)
         {
            controlMode = USER_CONTROL_MODE;
#ifdef _debug_
            printf("E-stop\n");
#endif
            desiredV = 0;
            desiredW = 0;

            sprintf(radioOutput,"User Control Mode,*");
            serCputs(radioOutput);
         }

         // Toggle Classification mode
         else if (radioInput[0] == 7)
         {
            if (classificationMode == CLASSIFICATION_OFF)
            {
#ifdef _debug_
               printf("Classification on\n");
#endif
               classificationMode = CLASSIFICATION_ON;
            }
            else
            {
#ifdef _debug_
               printf("Classification off\n");
#endif
               classificationMode = CLASSIFICATION_OFF;
            }
         }

         //change controller coefficients
         else if (radioInput[0] == 8)
         {
            P_coeff = CtoF(radioInput[1],radioInput[2],radioInput[3],radioInput[4]);
            I_coeff = CtoF(radioInput[5],radioInput[6],radioInput[7],radioInput[8]);
            loop_gain = CtoF(radioInput[9],radioInput[10],radioInput[11],radioInput[12]);

            INTEGRALMAX = (float)MAXW / loop_gain / I_coeff / 2.0;

            DelayMs(35);
            sprintf(radioOutput,"Coefficients loaded,*");
            serCputs(radioOutput);
         }
      }

      //this costate controls state update for the control mode.  State transitions
      //can also take place within functions, but where it doesn't make sense make
      //those transitions within a function it is taken care of here.

      /*costate controlModeUpdate always_on
      {
         if ((controlMode == GPS_CONTROL_MODE)&&(robotMobility == IMMOBILIZED))
         {
            controlMode = ESCAPE_CONTROL_MODE;
            printf("escape control set\n");
         }
      }
      */

      //***********************************************************************************
      // serial message interpretation costate for instrument package communication
      costate serial2In always_on
      {
         // wait until a message comes
         waitfor(usedE > 0);

         // give the message a chance to finish sending
         waitfor(DelayMs(100));
         usedE = serErdUsed();
         serEread(radioInput2,usedE, 2);
         radioInput2[usedE] = '\0';    //terminate string

         serErdFlush();

         if(radioInput2[0] == 0)
         {
            // recieve a remote control driving command
            //engageGPSnav = 0;       //remove
            if (controlMode != ESCAPE_CONTROL_MODE)
            {
               controlMode = USER_CONTROL_MODE;
               error_integral = 0;
               last_time = TICK_TIMER;

               v = (int)radioInput2[2]<<8;
               desiredV = v+radioInput2[1];
               w = (int)radioInput2[4]<<8;
               desiredW = w+radioInput2[3];
#ifdef _debug_
               printf("command\n");
#endif
            }
         }

         else if (radioInput2[0] == 1) //Set autonomous mode
         {
            // load in gps coordinates
            // [1] [lattitude degrees int byte 1] [longitutde degrees int byte 2]...
            if(radioInput2[1] > 180){
               numWayPoints = 180;
            }
            else if(radioInput2[1] >0){
               numWayPoints = (int)(radioInput2[1]);
            }
            else{
               numWayPoints =0;
            }

            for(i = 0;i<numWayPoints;i++)
            {
               WayPoints[i].lat_degrees = CtoI(radioInput2[2+i*12],radioInput2[2+i*12+1]);
               WayPoints[i].lat_minutes = CtoF(radioInput2[2+i*12+2],radioInput2[2+i*12+3],radioInput2[2+i*12+4],radioInput2[2+i*12+5]);
               WayPoints[i].lon_degrees = CtoI(radioInput2[2+i*12+6],radioInput2[2+i*12+7]);
               WayPoints[i].lon_minutes = CtoF(radioInput2[2+i*12+8],radioInput2[2+i*12+9],radioInput2[2+i*12+10],radioInput2[2+i*12+11]);
            }

            curWayPoint = 0;
            Goal = WayPoints[0];
            if (numWayPoints > 0)
               coords_received=1;

            sprintf(radioOutput2,"numway: %d,*",radioInput2[1]);
            serEputs(radioOutput2);
            sprintf(radioOutput2,"coords loaded,*");
            serEputs(radioOutput2);

#ifdef _debug_
            printf("load coord\n");
#endif
         }

         else if (radioInput2[0] == 3)
         {
            // engage GPS navigation system
            if (numWayPoints>0){
               controlMode = GPS_CONTROL_MODE;
               error_integral = 0;
               last_time = TICK_TIMER;
               helpLast =0;
               helpLast2 = 0;
               originToCurrent = 0;
               currentToGoal = 999999;

               sprintf(radioOutput2,"GPS Mode,*");
               serEputs(radioOutput2);
            }

            //engageGPSnav = 1;    //remove
#ifdef _debug_
            printf("GPS\n");
#endif
         }

         else if (radioInput2[0] == 4)
         {
            //set the interval for telemetry broadcasting
            telemetryInterval = radioInput2[1];
         }

         // Signal to test escape sequences and re-routing
         // Emergency Stop the robot if Escape Mode is enabled

         else if (radioInput2[0] == 6)
         {
            controlMode = USER_CONTROL_MODE;
#ifdef _debug_
            printf("E-stop\n");
#endif
            desiredV = 0;
            desiredW = 0;

            sprintf(radioOutput2,"User Control Mode,*");
            serEputs(radioOutput2);
         }

         else if (radioInput2[0] == 8)
         {
            P_coeff = CtoF(radioInput2[1],radioInput2[2],radioInput2[3],radioInput2[4]);
            I_coeff = CtoF(radioInput2[5],radioInput2[6],radioInput2[7],radioInput2[8]);
            loop_gain = CtoF(radioInput2[9],radioInput2[10],radioInput2[11],radioInput2[12]);

            INTEGRALMAX = (float)MAXW / loop_gain / I_coeff / 2.0;

            sprintf(radioOutput2,"coefficients loaded,*");
            serEputs(radioOutput2);
         }

         // restore control mode to GPS control mode from Instrument mode
         else if(radioInput2[0] == 9 && controlMode == INSTRUMENT_MODE)
         {
            controlMode = GPS_CONTROL_MODE;
            last_time = TICK_TIMER;

            desiredW = 0;
            desiredV = AUTONOMOUS_SPEED;
            //DelaySec(2);
         }

         // stop for each waypoint for X seconds
         else if(radioInput2[0] == 10)
         {
            sprintf(radioOutput2,"command 10,*");
            serEputs(radioOutput2);

            stoppingMode = 1;
            resting_interval = CtoI(radioInput2[1],radioInput2[2]);
         }

         // stop the robot for X seconds right now
         else if(radioInput2[0] == 11)
         {
            stoppingMode = 2;
            resting_interval = CtoI(radioInput2[1],radioInput2[2]);
            controlMode = INSTRUMENT_MODE;
            desiredV = 0;
            desiredW = 0;
         }

         // restore stopping mode to 0 (non-stoppig mode)
         else if(radioInput2[0] == 12)
         {
            stoppingMode = 0;
         }
      }

      //***********************************************************************************
      //if no moving signal from instrument laptop is received for designated resting interval + 2sec
      //assume connection with instrument laptop is broken and go back to autonomous mode
      costate monitorStop always_on
      {
         if(stoppingMode != 0 && controlMode == INSTRUMENT_MODE && currentV==0 && curWayPoint < numWayPoints){
            waitfor(DelaySec(resting_interval+2)); //2 sec delay in addition to resting_interval

            if(controlMode == INSTRUMENT_MODE){
               //stoppingMode = 0;  //9-13-11 retain stop at each waypoint
               controlMode = GPS_CONTROL_MODE;
            	last_time = TICK_TIMER;
            	desiredW = 0;
            	desiredV = AUTONOMOUS_SPEED;
            }
         }
      }

      //***********************************************************************************
#ifdef _debug_
      costate debugHelp always_on
      {
         waitfor(DelayMs(1000));
         {
            switch(controlMode){
               case(USER_CONTROL_MODE):
               printf("user control,   ");
               break;
               case(GPS_CONTROL_MODE):
               printf("gps control,    ");
               break;
               case(ESCAPE_CONTROL_MODE):
               printf("escape ctrl.,   ");
               break;
               case(ESCAPE_CONFIRM_MODE):
               printf("escape confirm, ");
               break;
            }

            switch(classificationMode){
               case(CLASSIFICATION_ON):
               printf("class. on,   ");
               break;
               case(CLASSIFICATION_OFF):
               printf("class. off,  ");
               break;
            }

            switch(obstacleType){
               case(OBSTACLE_0):
               printf("obstacle 0,  ");
               break;
               case(OBSTACLE_1):
               printf("obstacle 1,  ");
               break;
            }

            switch(robotMobility){
               case(MOBILE):
               printf("mobile   ,   ");
               break;
               case(ALMOST_IMMOBILIZED):
               printf("almost immob.,  ");
               break;
               case(IMMOBILIZED):
               printf("immobilized,    ");
               break;
            }
            printf("\n");
         }
      }
#endif
      /* **********************************************************************************
      //this costate interprets the results from the mobility and obstacle detection
      //classifiers
      //this function is disabled in this version of yeti code because we need a serial port
      //for a second radio for the communication with instrument package latop
      costate loggerInterpret always_on
      {
         // wait for a message from datalogger port
         waitfor(usedE > 0);

         // give the message a chance to finish sending
         waitfor(DelayMs(8));

         if  (classificationMode == CLASSIFICATION_ON)
         {

            usedE = serErdUsed();
            serEread(loggerInput,usedE, 2);
            loggerInput[usedE] = '\0';
            serErdFlush();

            switch(loggerInput[1]) {
            case '0':
               robotMobility = MOBILE;
               break;
            case '1':
               robotMobility = ALMOST_IMMOBILIZED;
               break;
            case '2':
               robotMobility = IMMOBILIZED;
               break;
            }

            switch(loggerInput[2]) {
            case '0':
               obstacleType = OBSTACLE_0;
               break;
            case '1':
               obstacleType = OBSTACLE_1;
               break;
            default:
               obstacleType = OBSTACLE_1;
            }
         }
         else
         {
            serErdFlush();
         }
      }
   */

      //***********************************************************************************
      // this costate updates the velocity of the wheels
      // acc rate is such that it takes 1 sec to go from 0 to max V
      // therefore can change v by at most 100 at each 50 ms time step
      costate
      {
         waitfor(DelayMs(50));

         newV = currentV;
         newW = currentW;
         vDiff = desiredV - currentV;
         wDiff = desiredW - currentW;

         if (vDiff > 0)
         {
            newV = currentV + min(50,vDiff); //emt - changed to 50 from 100
         }
         else if (vDiff < 0)
         {
            newV = currentV + max(-50,vDiff);
         }

         if (wDiff > 0)
         {
            newW = currentW + min(50,wDiff);
         }
         else if (wDiff < 0)
         {
            newW = currentW + max(-50,wDiff);
         }
         if ((newV != currentV) || (newW != currentW))
         {
            //disable motor controllers if velocity should be 0
            if (newV == 0 && newW == 0)
            digHoutTriState(1,0);
            else
            digHoutTriState(1,2);

            setVel(newV,newW);
            currentV = newV;
            currentW = newW;
         }
      }

      /* **********************************************************************************
      // Send encoder data through serial to Datalogger needed for mobility detection
      // This function is disabled in this version of C code
      */

      /*costate sendEncoder always_on
      {
         waitfor(DelayMs(45));     //send faster than 20Hz
         for (j = 0; j < 4; j++)
         {
            EncWrite(j, TRSFRCNTR_OL, CNT);
            // EncWrite(j,BP_RESET,CNT);
            EncWrite(j,BP_RESETB,CNT);
            asb = EncRead(j,DAT);
            asb_l = asb;
            bsb = EncRead(j,DAT);
            bsb_l = bsb;
            csb = EncRead(j,DAT);
            csb_l = csb;
            position  = asb_l;       // least significant byte
            position += (bsb_l << 8);
            position += (csb_l <<16);

            switch(j) {
            case 0:
               sprintf(axis_1,"%ld",position);
               break;
            case 1:
               sprintf(axis_2,"%ld",position);
               break;
            case 2:
               sprintf(axis_3,"%ld",position);
               break;
            case 3:
               sprintf(axis_4,"%ld",position);
               break;
            }
         }
         sprintf(enc_data,",%s,%s,%s,%s*",axis_1,axis_2,axis_3,axis_4);
         serEputs(enc_data);
      }*/


      //***********************************************************************************
      // stop robot if get no pings from java for 5 seconds DURING user control mode
      // continue GPS mode even if communication to user has been lost
      /*costate pingCheck always_on
      {
         if(controlMode == USER_CONTROL_MODE){
	      	if (ping == 1)
  	      	{
   	         waitfor(DelayMs(500));
      	      ping = 0;
        	    	abort;
        	 	}
        	 	else
        	 	{
           		waitfor(DelaySec(5));
            	if (ping == 1)
         	   	abort;
            	else
            	{
               	desiredV = 0;
               	desiredW = 0;
            	}
            }
         }
      }*/

      //***********************************************************************************
      // this costate will check if the GPS has sent some data or not and
      // call the appropriate functions to process the data
      costate GPSRead always_on
      {
         //printf("gps read started\n");
         waitfor((serFrdUsed() > 0)); //always read GPS even during user control mode
         //printf("gps string came in\n");

         charCounter = 0;
         // read until finding the beginning of a gps string then wait 2 seconds
         while(1)
         {
            c = serFgetc();
            if (c == -1)
            {
               serFrdFlush();
               abort;
            }
            else if (c == '$')
            {
               waitfor(DelayMs(20));     //wait for full message to send
               break;
            }
         }

         // now that 20 ms have passed, read in the gps string (it must all
         // be there by now, since so much time has passed

         getgps2(gpsString);

#ifdef _debug_GPS_
         //printf("gps: %u \n",strlen(test2));
         printf("gps: %s ",gpsString);
         //puts(gpsString);
         //puts(":   end gps \n");
#endif

         //===================================================================================
#ifdef _debug_GPS_fine_
         printf("gps 2\n");
#endif
         // use Luke's library function to get gps position data from the
         // gps string
         valid_gps = gps_get_position(&CurrentGPS,gpsString);
         //num_sat = gps_get_satellites(&Satellite,gpsString); //<-can be used only during GPGSA mode

         printf("valid gps: %d, CurrentGPS: %d %f, %d %f\n", valid_gps, CurrentGPS.lat_degrees, CurrentGPS.lat_minutes, CurrentGPS.lon_degrees, CurrentGPS.lon_minutes);
         //printf("# of sat: %d\n",num_sat);

#ifdef _debug_GPS_fine_
         printf("valid gps: %d, CurrentGPS: %d %f, %d %f\n", valid_gps, CurrentGPS.lat_degrees, CurrentGPS.lat_minutes, CurrentGPS.lon_degrees, CurrentGPS.lon_minutes);
#endif

#ifdef _debug_GPS_fine_
         printf("gps 3\n");
#endif

#ifdef _debug_GPS_fine_
         printf("gps 4\n");
#endif

			flag2=0;
         //valid gps=0 - success, -1 - parsing error, 1 - sentence marked invalid
         if(valid_gps==0 && controlMode == GPS_CONTROL_MODE){
            // initialize last gps coordinate if program is just starting
            if(helpLast == 0)
            {
               LastGPS = CurrentGPS;
               helpLast = 1;
            }

            // find the x and y distances between the last and current GPS
            // positions of the robot
            CurCart = getCart(&LastGPS,&CurrentGPS);

            originToCurrent = gps_ground_distance(&LastGPS, &CurrentGPS);
        		currentToGoal = gps_ground_distance(&CurrentGPS, &Goal);

            printf("CurrentGPS: %d %f, %d %f\n",CurrentGPS.lat_degrees, CurrentGPS.lat_minutes, CurrentGPS.lon_degrees, CurrentGPS.lon_minutes);
            printf("LastGPS: %d,%f,%d,%f\n", LastGPS.lat_degrees, LastGPS.lat_minutes, LastGPS.lon_degrees, LastGPS.lon_minutes);
            printf("originTocurrent: %f, currentToGoal: %f\n",originToCurrent, currentToGoal);

            if(currentToGoal>=WAYPOINT_RADIUS){
            	// compute bearing if there the robot traveled enough distance 2m
			  		if(originToCurrent >= 0.002 || helpLast2 == 0){

                  if(helpLast2 == 0)
               		helpLast2 = 1;

                  // set the flag so that v,w are updated in the second if statement
						flag2=1;

           			// compute the bearing and distance from current pos to the next waypoint
           			GoalPos = getPol(getCart(&CurrentGPS,&Goal));

	           		bearingToGoal = gps_bearing2(&CurrentGPS, &Goal);

   	      		// compute bearing from origin to current
      	     		// if the robot is not stationary, calculate robot bearing
         	  		// this is necessary because atan2 breaks if it is given 0/0
        	     		if(!(CurCart.x == 0 && CurCart.y == 0))
        	     		{
            			CurPol = getPol(CurCart);
         	  	 	}
         			else
           	 		{
           				CurPol.t = GoalPos.t;
           	 		}

              	 	if(originToCurrent!=0)
               	{
              			bearingToCurrent = gps_bearing2(&LastGPS,&CurrentGPS);
             		}
           			else
               	{
               		bearingToCurrent = bearingToGoal;
            		}

                  LastGPS = CurrentGPS;

               	/*sprintf(radioOutput,"bearing calculation: %f, %f\n", bearRange(CurPol.t-GoalPos.t),bearRange((bearingToCurrent-bearingToGoal)*PI/180.0));
                  serCputs(radioOutput);
                  printf("bearing calculation: %f, %f\n", bearRange(CurPol.t-GoalPos.t),bearRange((bearingToCurrent-bearingToGoal)*PI/180.0));*/
            	}
            }
         }

         // if within 10m of the next way point, switch to the next waypoint
         // in the array, or stop of there are no more waypoints
         if (controlMode == GPS_CONTROL_MODE && currentToGoal >= WAYPOINT_RADIUS)
         {
            if (valid_gps == 0 && flag2==1)   //0 = good GPS, -1 = bad GPS
            {
               // compute bearing error
               error = bearRange(CurPol.t-GoalPos.t);

               // bearing error using double precision calculation
               error2 = bearRange((bearingToCurrent-bearingToGoal)*PI/180.0);

               //only add up integral term when the robot is currently moving at full speed
               //& the robot has actually moved 1m from the last positoin
               if(currentV == AUTONOMOUS_SPEED)
               {
                  deltat = (float)(TICK_TIMER-last_time) / (1024);
                  //TICK_TIMER is shared unsigned long that counts every 1/1024 sec
                  if(deltat<0)
                  {
                     deltat=(float)(TICK_TIMER-last_time+1024)/1024;
                  }
                  if(deltat<0) //invalid deltat -> set deltat=0
                  {
                     deltat=0;
                  }
                  error_integral = error_integral + (error2 + last_error)/2*deltat;
                  error_integral = bound(error_integral,INTEGRALMAX);
               }

               desiredW = (int)(bound(((-P_coeff*error2) - I_coeff*error_integral)*loop_gain, MAXW));
               desiredV = AUTONOMOUS_SPEED;

               last_error = error2;
               last_time = TICK_TIMER; //(1024 times per second)
            }
            /*else if(valid_gps!=0)
            {
               // without valid GPS, go straight but slower (half of autonomous speed)
               // still under autonomous mode
               desiredW = 0;
               desiredV = AUTONOMOUS_SPEED_SLOW;
               abort;
            }*/
         }
      }

      //***********************************************************************************
      // change the current waypoint to the nextway point when the robot reaches
      // near the current waypoint
      costate WaypointCheck always_on
      {
			//default distance = .005 (5 meters)
         if (currentToGoal < WAYPOINT_RADIUS && controlMode == GPS_CONTROL_MODE && valid_gps==0)
         {
         	// go straight for 2sec (travel about 4m straight)
            desiredW = 0;
            desiredV = AUTONOMOUS_SPEED;
            waitfor(DelaySec(2));

            // stop at each waypoint when stoppingMode = 1
            if(stoppingMode == 1){
            	controlMode = INSTRUMENT_MODE;
               desiredV = 0;
               desiredW = 0;
            }

            curWayPoint++;

            // if at the last way point, stop
            if(curWayPoint >= numWayPoints)
            {
	            controlMode = USER_CONTROL_MODE;
               desiredV = 0;
               desiredW = 0;
               curWayPoint = 0;
               Goal = WayPoints[0];
               abort;
            }
            else{
  	         	Goal = WayPoints[curWayPoint];
            	currentToGoal = gps_ground_distance(&CurrentGPS, &Goal);
            	error_integral = 0; //reset error integral for PI control
            	last_time = TICK_TIMER; //(1024 times per second)
         	}
         }
      }
      //***********************************************************************************
      // Change to user control mode when there is no good GPS connection
      /*costate GPSPingCheck always_on
      {
         waitfor(valid_gps != 0);
         waitfor(DelaySec(10) || (valid_gps == 0));
         if (valid_gps != 0)
         {
            controlMode = USER_CONTROL_MODE;
            desiredV = 0;
            desiredW = 0;

            flag=1;
         }

         if(valid_gps == 0 && flag==1){
            controlMode = GPS_CONTROL_MODE;
            flag=0;
         }
      }*/
      //***********************************************************************************
      //Escape mode disabled in this version because datalogger is not being used
      /*costate escapeSequence always_on
      {
         waitfor(controlMode == ESCAPE_CONTROL_MODE);
         desiredV = 0;
         desiredW = 0;
         setVel(0,0);
         //printf("waiting for escape confirm... \n");
         //waitfor(controlMode  == ESCAPE_CONFIRM_MODE);

         printf("escape sequence initiated \n");
         switch(obstacleType){
         case OBSTACLE_0:
            desiredV = 0;
            desiredW = 0;
            waitfor(DelayMs(500));

            desiredV = -300;
            desiredW = 0;
            waitfor(DelayMs(4000));

            desiredV = 0;
            desiredW = -600;
            waitfor(DelayMs(2000));

            desiredV = 800;
            desiredW = 0;
            waitfor(DelayMs(4000));
            break;
         case OBSTACLE_1:
            desiredV = 0;
            desiredW = 0;
            waitfor(DelayMs(500));

            desiredV = -400;
            desiredW = 0;
            waitfor(DelayMs(4000));

            desiredV = 1500;
            desiredW = 0;
            waitfor(DelayMs(3500));

            desiredV = -400;
            desiredW = 0;
            waitfor(DelayMs(4000));

            desiredV = 1500;
            desiredW = 0;
            waitfor(DelayMs(3500));
            break;
         }

         //relinquish control to User
         desiredV = 0;
         desiredW = 0;
         controlMode = USER_CONTROL_MODE;
         robotMobility = MOBILE;
         classificationMode = CLASSIFICATION_OFF;
      }*/
   }
}
コード例 #23
0
ファイル: Relay_sequence.c プロジェクト: daveoman/DCRabbit_10
main()
{
   auto int device0;
   auto rn_search newdev;
   auto char s[128];
   auto int counter, i, option;

   // Array locations 0 - 5 used to indicate what state relays
   // 0 - 5 are in, here's the possible states.
   // -----------------------------------------
   //  0 = Relay OFF...no action to be taken
   //  1 = Request for relay to be activated
   //  2 = Relay actvated...no action to be taken.
   //  3 = Request for relay to be deactivated.
	//
   // The user will select a menu option which set the memory
   // locations 0 - 5 with the desired relay state. The main
   // program will detect when a change occurs in the memory
   // array, which will then update the relay(s) with the new
   // Relay state.

   auto char CurrentRelayState[6];
   auto char NewRelayState[6];
   auto int relay_control_update;
   auto int relay;

	brdInit();                 //initialize controller
   rn_init(RN_PORTS, 1);      //initialize controller RN ports

   //search for device match
	newdev.flags = MATCHFLAG;
	newdev.productid = MATCHPID;
   if ((device0 = rn_find(&newdev)) == -1)
   {
   	printf("\n no device found\n");
      exit(0);
   }

  	//Display user instructions and channel headings
  	DispStr(2, 1, "<<< Relay Control Menu >>>");
   DispStr(2, 2, "--------------------------");
   DispStr(2, 3, "1.Sequence Relays 0, 2, and 4 ON, set all others OFF.");
   DispStr(2, 4, "2.Sequence Relays 0, 1, 3, and 5 ON, set all others OFF.");
   DispStr(2, 5, "3.Sequence All Relays ON.");
   DispStr(2, 6, "4.Sequence All Relays OFF.");

   counter = 0;
   relay_control_update = FALSE;
   memset(CurrentRelayState, 0x00, 6);
   memset(NewRelayState, 0x00, 6);

   for(;;)
   {

   	costate
      {
      	sprintf(s,"Application program is running, counter = %d", counter++);
      	DispStr(2, 10, s);

      }
   	costate
   	{
         if(kbhit())
         {
            option = getchar();
           	set_relay_state(option, &CurrentRelayState[0], &relay_control_update);
         }
         waitfor(DelayMs(10));
      }
      costate
      {
      	if(relay_control_update)
         {
         	for(relay=0; relay < 6; relay++)
            {
            	if(NewRelayState[relay] == 1)
               {
               	// Activate given relay, then wait for 50ms
                  rn_Relay(device0, relay, 1, 0);
                  NewRelayState[relay] = RELAY_IS_ON;
                  CurrentRelayState[relay] = RELAY_IS_ON;
                  // Wait for relay to stabilize
                  waitfor(DelayMs(50));
               }
               else if(NewRelayState[relay] == 3)
               {
               	// Deactivate relay, then wait for 5ms
                  rn_Relay(device0, relay, 0, 0);
                  NewRelayState[relay] = RELAY_IS_OFF;
                  CurrentRelayState[relay] = RELAY_IS_OFF;
                  // Wait for relay power OFF completely
                  waitfor(DelayMs(50));
               }
        		}
            relay_control_update = FALSE;
         }
         else
         {
         	if(memcmp(CurrentRelayState,NewRelayState, 6) != 0)
   			{
          		memcpy(NewRelayState, CurrentRelayState, 6);
          		relay_control_update = TRUE;
         	}
         }
      }
   }
}
コード例 #24
0
ファイル: PINGLED.C プロジェクト: daveoman/DCRabbit_10
main()
{
	longword seq,ping_who,tmp_seq,time_out;
	char	buffer[100];

	brdInit();				//initialize board for this demo

	seq=0;

	// Start network and wait for interface to come up (or error exit).
	sock_init_or_exit(1);

	/*
	 *		Get the binary ip address for the target of our
	 *		pinging.
	 */

#ifdef PING_WHO
	/* Ping a specific IP addr: */
	ping_who=resolve(PING_WHO);
	if(ping_who==0) {
		printf("ERROR: unable to resolve %s\n",PING_WHO);
		exit(2);
	}
#else
	/* Examine our configuration, and ping the default router: */
	tmp_seq = ifconfig( IF_ANY, IFG_ROUTER_DEFAULT, & ping_who, IFS_END );
	if( tmp_seq != 0 ) {
		printf( "ERROR: ifconfig() failed --> %d\n", (int) tmp_seq );
		exit(2);
	}
	if(ping_who==0) {
		printf("ERROR: unable to resolve IFG_ROUTER_DEFAULT\n");
		exit(2);
	}
#endif

	for(;;) {
		/*
		 *		It is important to call tcp_tick here because
		 *		ping packets will not get processed otherwise.
		 *
		 */

		tcp_tick(NULL);

		/*
		 *		Send one ping every PING_DELAY ms.
		 */

		costate {
			waitfor(DelayMs(PING_DELAY));
			_ping(ping_who,seq++);
			pingoutled(LEDON);					// flash transmit LED
			waitfor(DelayMs(50));
			pingoutled(LEDOFF);
		}

		/*
		 *		Has a ping come in?  time_out!=0xfffffff->yes.
		 */

		costate {
			time_out=_chk_ping(ping_who,&tmp_seq);
			if(time_out!=0xffffffff) {

#ifdef VERBOSE
				printf("received ping:  %ld\n", tmp_seq);
#endif

				pinginled(LEDON);					// flash receive LED
				waitfor(DelayMs(50));
				pinginled(LEDOFF);
			}
		}
	}
}
コード例 #25
0
ファイル: sflash_inspect.c プロジェクト: daveoman/DCRabbit_10
void main(void)
{
	char ascii_buffer[17];
	char fbyte, inchar;
	int i, j, k, pagenum, value, start, end;
	char linebuf[80], *p, *buf, ch;

	brdInit();
	sfspi_init();
	if (sf_init()) {
		printf("Flash init failed\n");
		exit(-1);
	}
	else {
		printf("Flash init OK\n");
		printf("# of blocks: %d\n", sf_blocks);
		printf("size of block: %d\n\n", sf_blocksize);
	}
	print_command();

	while (1) {
		inchar = tolower(getchar());
		if (inchar == 'c') {
			printf("page number to clear?");
			pagenum = input_number();
			if (pagenum >= 0 && pagenum < sf_blocks) {
				printf("\nClearing page %d\n", pagenum);
				memset(flash_buf, 0, sf_blocksize);
				sf_writeRAM(flash_buf, 0, sf_blocksize);
				sf_RAMToPage(pagenum);
			}
			else {
				printf("ERROR: invalid page number\n");
			}
		}	// end if(inchar =='c')
		else if ((inchar == 'p') || (inchar == 'r')) {
			if (inchar == 'p') {
				// Use start for page to print
				printf("Page number to print out?");
				start = input_number();
				// Check that it is a valid page
				if (start < 0 || start >= sf_blocks) {
					printf("Invalid page number.\n\n");
					continue;
				}
				// Set single page range for 'p' command
				end = start;
			}
			else {
				printf("Starting page number to print out?");
				start = input_number();
				// Check that it is a valid page
				if (start < 0 || start >= sf_blocks) {
					printf("Invalid page number.\n\n");
					continue;
				}
				printf("\nEnding page number to print out?");
				end = input_number();
				if (end < start || end >= sf_blocks) {
					printf("Invalid page number.\n\n");
					continue;
				}
			}
			// Loop through range of pages (range of 1 page for 'p' command)
			for (pagenum = start; pagenum <= end; ++pagenum) {
				printf("\nPage %d", pagenum);
				sf_pageToRAM(pagenum);
				sf_readRAM(flash_buf, 0, sf_blocksize);
				// Test if entire buffer filled with a single value
				buf = flash_buf;
				for (j = k = 0, ch = *buf; j < 512; ++j) {
					if (ch != *buf++) {
						k = 1;
						break;
					}
				}
				// See if page is all the same value
				if (k) {
					printf("\n");  // No, drop through to print data
				}
				else {
					// Yes, print out message instead
					printf("   ALL = 0x%02x\n", ch);
					continue;
				}
				k = (sf_blocksize & 0xFFF0) + ((sf_blocksize & 0x000F) ? 16 : 0);
				ascii_buffer[16] = 0;
				for (j = 0, buf = flash_buf; j < k; ++j) {
					if (j % 16 == 0) {
						p = linebuf;
						p += sprintf (p, "%04x: ", j);
					}
					fbyte = *buf++;
					if (j >= sf_blocksize) {
						p += sprintf (p, "   ");
						ascii_buffer[j % 16] = ' ';
					}
					else {
						p += sprintf (p, "%02x ", fbyte);
						ascii_buffer[j % 16] = isprint (fbyte) ? fbyte : '.';
					}
					if (j % 16 == 15) {
						printf ("%s   %s\n", linebuf, ascii_buffer);
					}
				}
			}
		}	// end if((inchar =='p') || (inchar == 'r'))
		else if (inchar == 'f') {
			printf("page number to fill with specified value?  ");
			pagenum = input_number();
			if (pagenum >= 0 && pagenum < sf_blocks) {
				printf("\nPage %d\n", pagenum);
				printf("enter fill value  ");
				value = input_number();
				printf("\nValue is %d dec is %02x hex", value, value);
				printf("\nFilling page %d with value %02x hex\n", pagenum, value);
				memset(flash_buf, value, sf_blocksize);
				sf_writeRAM(flash_buf, 0, sf_blocksize);
				sf_RAMToPage(pagenum);
			}
			else {
				printf("ERROR: invalid page number\n");
			}
		}	// end of if(inchar == 'f')
		else if (inchar == 't') {
			printf("page number in which to write text? ");
			pagenum = input_number();
			if (pagenum >= 0 && pagenum < sf_blocks) {
				printf("\nPage %d\n", pagenum);
				printf("enter character string followed by RETURN  \n");
				gets(flash_buf);
				printf("Storing the following text ==> %s \n", flash_buf);
				sf_writeRAM(flash_buf, 0, sf_blocksize);
				sf_RAMToPage(pagenum);
			}
			else {
				printf("ERROR: invalid page number\n");
			}
		}	// end of if(inchar == 't')
		print_command();
	}	// end of while
}
コード例 #26
0
ファイル: KEYMENU.C プロジェクト: daveoman/DCRabbit_10
//------------------------------------------------------------------------
// Sample program to demonstrate the LCD and keypad
//------------------------------------------------------------------------
void main (	void	)
{
	auto int option;
	static int state;

	//------------------------------------------------------------------------
	// Initialize the controller
	//------------------------------------------------------------------------
	brdInit();			// Initialize the controller
	dispInit();			// Start-up the keypad driver, Initialize the graphic driver
	keypadDef();		// Use the default keypad ASCII return values


	glBackLight(1);	// Turn-on the backlight
	glXFontInit(&fi6x8, 6, 8, 32, 127, Font6x8);			//	Initialize 6x8 font
	glXFontInit(&fi8x10, 8, 10, 32, 127, Font8x10);		//	Initialize 10x16 font
	glXFontInit(&fi12x16, 12, 16, 32, 127, Font12x16);	//	Initialize 12x16 font

	// Setup and center text window to be the entire display
	TextWindowFrame(&textWindow, &fi6x8, 1, 0, 121, 32);

	// Set variables to known states
	ledCntrl = LEDOFF;	// Initially disable the LED's
	state = MENU_INIT;
	//------------------------------------------------------------------------
	// Display Sign-on message and wait for keypress
	//------------------------------------------------------------------------
	SignOnMessage();

	//------------------------------------------------------------------------
	// Main program loop for the MENU system
	//------------------------------------------------------------------------
	for (;;)
	{
		costate
		{
			keyProcess ();
			waitfor(DelayMs(10));
		}

		costate
		{
			leds(OPERATE);
			waitfor(DelayMs(50));
		}
		costate
		{
			// Display the MAIN MENU
			waitfor((option = display_menu(main_menu, &state, LVL_MAINMENU, NUM_MAINMENU_OPTS)) > 0);


			// Get menu option from the user
			switch(option)
			{
				// Change Date/Time
				case 1:	glBlankScreen();
							SetDateTime();
							state = MENU_INIT;
							break;

				// Display current Date/Time
				case 2:	glBlankScreen();
							waitfor(dispDate());
							state = MENU_INIT;
							break;

				// Display backlight memu options
				case 3:	waitfor(backlight_menu());
							state = MENU_REFRESH;
							break;

				// Enable Toggle leds option
				case 4:	leds(TOGGLE);
							state = MENU_NO_CHANGE;
							break;

				// Enable Increment leds option
				case 5:	leds(INCREMENT);
							state = MENU_NO_CHANGE;
							break;

				// Disable LED's
				case 6:	leds(LEDOFF);
							state = MENU_NO_CHANGE;
							break;

				// User made invalid selection
				default:
					break;
			}
		}
	}
}
コード例 #27
0
main()
{
	longword seq,ping_who,tmp_seq,time_out;
	char	buffer[100];


	brdInit();				//initialize board for this demo
	seq=0;

	sock_init();			// Initialize wifi interface

   // Make sure wifi IF is down to do ifconfig's functions
	printf("\nBringing interface down (disassociate)...\n");
   ifdown(IF_WIFI0);
   while (ifpending(IF_WIFI0) != IF_DOWN) {
     	printf(".");
     	tcp_tick(NULL);
   }
	printf("...Done.\n");

   // Enable 802.11d country information capability
   // Note: Access Point must have 802.11d enabled with proper country selected
   ifconfig(IF_WIFI0, IFS_WIFI_MULTI_DOMAIN, 1, IFS_END);

   // Startup the  wireless interface here...
	printf("Bringing interface back up (associate)...\n");
   ifup(IF_WIFI0);
   while (ifpending(IF_WIFI0) == IF_COMING_UP) {
      tcp_tick(NULL);
   }
	printf("...Done.\n");
	if (ifpending(IF_WIFI0) != IF_UP) {
		printf("Unfortunately, it failed to associate :-(\n");
		exit(1);
	}
   // End of regional setting section, from this point on do standard tcp/ip
   // protocol.


   /*
   // Here is where we gather the statistics...
	// Note that if you get a compile error here, it is because you are not running
	// this sample on a Wifi-equipped board.

	/* Print who we are... */
	printf( "My IP address is %s\n\n", inet_ntoa(buffer, gethostid()) );

	/*
	 *		Get the binary ip address for the target of our
	 *		pinging.
	 */

#ifdef PING_WHO
	/* Ping a specific IP addr: */
	ping_who=resolve(PING_WHO);
	if(ping_who==0) {
		printf("ERROR: unable to resolve %s\n",PING_WHO);
		exit(2);
	}
#else
	/* Examine our configuration, and ping the default router: */
	tmp_seq = ifconfig( IF_ANY, IFG_ROUTER_DEFAULT, & ping_who, IFS_END );
	if( tmp_seq != 0 ) {
		printf( "ERROR: ifconfig() failed --> %d\n", (int) tmp_seq );
		exit(2);
	}
	if(ping_who==0) {
		printf("ERROR: unable to resolve IFG_ROUTER_DEFAULT\n");
		exit(2);
	}
#endif

	for(;;) {
		/*
		 *		It is important to call tcp_tick here because
		 *		ping packets will not get processed otherwise.
		 *
		 */

		tcp_tick(NULL);

		/*
		 *		Send one ping every PING_DELAY ms.
		 */

		costate {
			waitfor(DelayMs(PING_DELAY));
			pingoutled(LEDON);					// flash transmit LED
			waitfor(DelayMs(50));
			pingoutled(LEDOFF);
			_ping(ping_who,seq++);
		}

		/*
		 *		Has a ping come in?  time_out!=0xfffffff->yes.
		 */

		costate {
			time_out=_chk_ping(ping_who,&tmp_seq);
			if(time_out!=0xffffffff) {

#ifdef VERBOSE
				printf("received ping:  %ld\n", tmp_seq);
#endif

				pinginled(LEDON);					// flash receive LED
				waitfor(DelayMs(50));
				pinginled(LEDOFF);
#if RCM5600W_SERIES
				waitfor(DelayMs(250));
				pinginled(LEDON);					// flash receive LED again
				waitfor(DelayMs(50));
				pinginled(LEDOFF);
#endif
			}
		}
	}
}