Ejemplo n.º 1
0
/*
 * display the I2C status and error message and release the I2C bus
 */
void i2c_error(const char * message, uint8_t cr, uint8_t status)
{
  i2c_stop();
  printf_P(message);
  printf_P(s_fmt_i2c_error, cr, status);
}
void help(uint16_t data)
{
	printf_P(HELP);
}
void parse_command()
{
	int i = 0;
	int j = 0;
	int k = 0;

	uint8_t buf[USART0_RECEIVE_BUFFER_LEN];	

	uint8_t temp_buf[20];
	uint8_t command[20];
	uint8_t data[20];

	// Transfer to input to local buffer
	// TODO: This could cause problems if the ISR is loading new
	// data while the buffer is being transferred. FIX THIS	
	strcpy((char *)buf,(char *)usart0_receive_buffer);	

//#define TERMINATOR '!'
//#define DELIMITER ','
//#define SEPARATOR ' '

	// Show each command and data
	for(i = 0; i < strlen((const char *)buf); i++)
	{
		if(buf[i] != DELIMITER)// printf("i = %d\n",i);
		{
			temp_buf[j++] = buf[i];
		}
		else // Process command unit
		{
			temp_buf[j] = '\0'; // Turn it into a string
			j = 0;

			// Extract the command name
			for(j = 0; j < 20; j++)
			{
				// Validate that command is all alphabetic or numeric
				if(temp_buf[j] != SEPARATOR)
				{
					if(isalnum(temp_buf[j]))
					{
						command[k++] = temp_buf[j];
					}
					else
					{
						printf("ERROR in parse_command(): not a command - not alpha: %c\n",temp_buf[j]);
						return;
					}
				}
				else
				{
					command[k] = '\0';
					k = 0;
					j++;
					for(k = 0; k < 20; k++)
					{
						if(temp_buf[j] != '\0')//DELIMITER)
						{
							// Validate that the data is all digits
							if(isdigit(temp_buf[j]))
							{
								data[k] = temp_buf[j++];
							}
							else
							{
								printf_P(PSTR("ERROR in parse_command(): not a number - not digit: %c\n"),temp_buf[j]);
								return;
							}

						}
						else
						{
							data[k] = '\0';
							//printf((const char *)data);
							//printf(" 3 \n");
							k = 0;
							j = 0;

					/*printf((const char *)command);
					printf(" - \n");
					printf((const char *)data);
					printf(" - \n");*/
							
							//Call the command - bail out if it isn't valid
							if(!call_command((const char *)command,(const char *)data))return;


							break;
						}



					}



					break;
				}
			}

		
		}
	}




	





			/**/			
		/*	//j = 0;
			for(j = 0; j < 20; j++)
			{
				// Extract the command name
				if(temp_buf[j] != SEPARATOR)
				{
					command[j] = temp_buf[j];
				}
				else
				{
					command[j] = '\0';
					printf((const char *)command);
					printf(" 3 \n");
				
				// Extract the number


					for(k = 0; k < 20; k++)
					{
						if(temp_buf[j] != '\0')
						{
							data[k] = temp_buf[j++];
						}
						else
						{
							data[k] = '\0';
							printf((const char *)data);
							printf(" 4 \n");

							//j = 20;
							//k = 20;
							break;
						}
					}			


					
				}
				
			}*/			



			/*for(j = 0; j < 20; j++)
			{
				if(temp_buf[j] != SEPARATOR)
				{
					command[j] = temp_buf[j];
				}
				else
				{
					printf((char *)command);
					for(k = 0; k < 20; k++)
					{
						if(temp_buf[j] != DELIMITER)
						{
							data[k] = temp_buf[j++];
						}
						else
						{
							k = 0;
							printf((char *)data);
						}
					}

				}
			}*/










	// Repeat until the terminator is found
	



/*	printf("before: %s\n",(const char*)usart0_receive_buffer);

	// Use strtok to replace the terminator with '\0'
	strtok((char *)usart0_receive_buffer,delim);

	printf("after: %s\n",(const char*)usart0_receive_buffer);
*/

	


/*    void (*p_func)(uint16_t);

	 for (i=0; pgm_read_word(&COMMANDS[i].PTEXT); i++)
	 {
	 	// Show the command name
		printf_P(PSTR("%s\n"),(char*)pgm_read_word(&COMMANDS[i].PTEXT));

		// Get the function and call it
	    p_func = (PGM_VOID_P)pgm_read_word(&COMMANDS[i].PFUNC); 
		p_func(i); 
	 }
*/




/*	printf("Received: %s\n",usart0_receive_buffer);

	char cbuf[10];

	// Replace the terminator with '\0'


	// Is it a valid command?
	int i = 0;
	while(COMMANDS[i])
	{
		strcpy_P(cbuf,COMMANDS[i]);

		printf_P(PSTR("The receive buffer contained: %s, the COMMANDS[%d] was %s\n"),(const char *)usart0_receive_buffer, i, cbuf);
			
		//if( strcmp_P("COMMAND2!" , COMMANDS[i] ) == 0)//(const char *)usart0_receive_buffer cbuf,"COMMAND2!"))//!strcmp(cbuf,(const char *)usart0_receive_buffer))
		if( strcmp_P((const char *)usart0_receive_buffer, COMMANDS[i]) == 0)//(const char *)usart0_receive_buffer cbuf,"COMMAND2!"))//!strcmp(cbuf,(const char *)usart0_receive_buffer))
		{
			printf_P(PSTR("Was a command\n"));//"Command = %s\n"),COMMANDS[i++]);
			// clear it
			//memset(usart0_receive_buffer, '\0',USART0_RECEIVE_BUFFER_LEN);
			i++;
			



		}
		else
		{
			printf_P(COMMANDS[i]);
			printf_P(PSTR("Not a command\n"));
			i++;

			//printf("Not %s\n",COMMANDS[i++]);
			//delay(1500);
		}		
	}

		delay(2000);

	// Report string length
	printf("Length: %d\n",strlen((const char *)usart0_receive_buffer));
	// Load into local string

	// clear it
	usart0_receive_buffer_clear();
	// refill it with'\0'
	memset(usart0_receive_buffer, '\0',USART0_RECEIVE_BUFFER_LEN);
*/
}
Ejemplo n.º 4
0
/* Process command */
void processCmd(uint8_t cmd)
{
	switch(cmd)
	{
		case '?':
			printf_P(PSTR("Commands are:\n\r"));
			printf_P(PSTR("? = Print available commands\n\r"));
			printf_P(PSTR("V = Print firmware version\n\r"));
			printf_P(PSTR("0 = Clear buffers\n\r"));
			printf_P(PSTR("1 = Dump raw ISO Stripe 1 bit buffer\n\r"));
			printf_P(PSTR("2 = Dump raw ISO Stripe 2 bit buffer\n\r"));
			printf_P(PSTR("3 = Dump raw ISO Stripe 3 bit buffer\n\r"));
			printf_P(PSTR("4 = Flip magstripe buffers\n\r"));
			printf_P(PSTR("5 = Decode ISO Stripe 1 data\n\r"));
			printf_P(PSTR("6 = Decode ISO Stripe 2 data\n\r"));
			printf_P(PSTR("7 = Decode ISO Stripe 3 data\n\r"));
			printf_P(PSTR("p = Switch USEROUT1 to low\n\r"));
			printf_P(PSTR("q = Switch USEROUT2 to low\n\r"));
			printf_P(PSTR("r = Switch USEROUT3 to low\n\r"));
			printf_P(PSTR("P = Switch USEROUT1 to high\n\r"));
			printf_P(PSTR("Q = Switch USEROUT2 to high\n\r"));
			printf_P(PSTR("R = Switch USEROUT3 to high\n\r"));
			printf_P(PSTR("u = Read USERIN1 status\n\r"));
			printf_P(PSTR("v = Read USERIN2 status\n\r"));
			printf_P(PSTR("w = Read USERIN3 status\n\r"));
			printf_P(PSTR("x = Disable USERIN1 pullup\n\r"));
			printf_P(PSTR("y = Disable USERIN2 pullup\n\r"));
			printf_P(PSTR("z = Disable USERIN3 pullup\n\r"));
			printf_P(PSTR("X = Enable USERIN1 pullup\n\r"));
			printf_P(PSTR("Y = Enable USERIN2 pullup\n\r"));
			printf_P(PSTR("Z = Enable USERIN3 pullup\n\r"));

		break;

		case 'V':
			printf_P(PSTR("1.1.0§\n\r"),magstripe3Data);
		break;


		/* Magstripe commands */
		case '0':
			magstripeInit();
			printf_P(PSTR("§\n\r"));
		break;

		case '1':
			magstripePrintRaw(1);
			printf_P(PSTR("§\n\r"));
		break;

		case '2':
			magstripePrintRaw(2);
			printf_P(PSTR("§\n\r"));
		break;

		case '3':
			magstripePrintRaw(3);
			printf_P(PSTR("§\n\r"));
		break;

		case '4':
			magstripeFlip();
			printf_P(PSTR("§\n\r"));
		break;

		case '5':
			magstripeDecode(1);
			printf_P(PSTR("%s§\n\r"),magstripeData);
		break;

		case '6':
			magstripeDecode(2);
			printf_P(PSTR("%s§\n\r"),magstripeData);
		break;

		case '7':
			magstripeDecode(3);
			printf_P(PSTR("%s§\n\r"),magstripeData);
		break;

		/* GPIO Commands */
		case 'p':
			userout(1,0);
			printf_P(PSTR("§\n\r"));
		break;

		case 'q':
			userout(2,0);
			printf_P(PSTR("§\n\r"));
		break;

		case 'r':
			userout(3,0);
			printf_P(PSTR("§\n\r"));
		break;

		case 'P':
			userout(1,1);
			printf_P(PSTR("§\n\r"));
		break;

		case 'Q':
			userout(2,1);
			printf_P(PSTR("§\n\r"));
		break;

		case 'R':
			userout(3,1);
			printf_P(PSTR("§\n\r"));
		break;


		case 'u':
			printf_P(PSTR("%i§\n\r"),userin(1));
		break;

		case 'v':
			printf_P(PSTR("%i§\n\r"),userin(2));
		break;

		case 'w':
			printf_P(PSTR("%i§\n\r"),userin(3));
		break;


		case 'x':
			userinPullup(1,0);
			printf_P(PSTR("§\n\r"));
		break;

		case 'y':
			userinPullup(2,0);
			printf_P(PSTR("§\n\r"));
		break;

		case 'z':
			userinPullup(3,0);
			printf_P(PSTR("§\n\r"));
		break;

		case 'X':
			userinPullup(1,1);
			printf_P(PSTR("§\n\r"));
		break;

		case 'Y':
			userinPullup(2,1);
			printf_P(PSTR("§\n\r"));
		break;

		case 'Z':
			userinPullup(3,1);
			printf_P(PSTR("§\n\r"));
		break;


		default:
			printf_P(PSTR("\n\r"),cmd);
		break;

	}
}
void command6(uint16_t data)
{
	printf_P(PSTR("command6 - data = %u\n"),data);
}
Ejemplo n.º 6
0
/** Task to print device information through the serial port, and open/close a test PIMA session with the
 *  attached Still Image device.
 */
void StillImageHost_Task(void)
{
	if (USB_HostState != HOST_STATE_Configured)
	  return;

	uint8_t ErrorCode;

	/* Indicate device busy via the status LEDs */
	LEDs_SetAllLEDs(LEDMASK_USB_BUSY);

	puts_P(PSTR("Retrieving Device Info...\r\n"));

	PIMA_SendBlock = (PIMA_Container_t)
		{
			.DataLength    = PIMA_COMMAND_SIZE(0),
			.Type          = PIMA_CONTAINER_CommandBlock,
			.Code          = PIMA_OPERATION_GETDEVICEINFO,
			.TransactionID = 0x00000000,
			.Params        = {},
		};

	/* Send the GETDEVICEINFO block */
	SImage_SendBlockHeader();

	/* Receive the response data block */
	if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
	{
		ShowCommandError(ErrorCode, false);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	/* Calculate the size of the returned device info data structure */
	uint16_t DeviceInfoSize = (PIMA_ReceivedBlock.DataLength - PIMA_COMMAND_SIZE(0));

	/* Create a buffer large enough to hold the entire device info */
	uint8_t DeviceInfo[DeviceInfoSize];

	/* Read in the data block data (containing device info) */
	SImage_ReadData(DeviceInfo, DeviceInfoSize);

	/* Once all the data has been read, the pipe must be cleared before the response can be sent */
	Pipe_ClearIN();

	/* Create a pointer for walking through the info dataset */
	uint8_t* DeviceInfoPos = DeviceInfo;

	/* Skip over the data before the unicode device information strings */
	DeviceInfoPos +=  8;                                          // Skip to VendorExtensionDesc String
	DeviceInfoPos += (1 + UNICODE_STRING_LENGTH(*DeviceInfoPos)); // Skip over VendorExtensionDesc String
	DeviceInfoPos +=  2;                                          // Skip over FunctionalMode
	DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1));      // Skip over Supported Operations Array
	DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1));      // Skip over Supported Events Array
	DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1));      // Skip over Supported Device Properties Array
	DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1));      // Skip over Capture Formats Array
	DeviceInfoPos += (4 + (*(uint32_t*)DeviceInfoPos << 1));      // Skip over Image Formats Array

	/* Extract and convert the Manufacturer Unicode string to ASCII and print it through the USART */
	char Manufacturer[*DeviceInfoPos];
	UnicodeToASCII(DeviceInfoPos, Manufacturer);
	printf_P(PSTR("   Manufacturer: %s\r\n"), Manufacturer);

	DeviceInfoPos += 1 + UNICODE_STRING_LENGTH(*DeviceInfoPos);   // Skip over Manufacturer String

	/* Extract and convert the Model Unicode string to ASCII and print it through the USART */
	char Model[*DeviceInfoPos];
	UnicodeToASCII(DeviceInfoPos, Model);
	printf_P(PSTR("   Model: %s\r\n"), Model);

	DeviceInfoPos += 1 + UNICODE_STRING_LENGTH(*DeviceInfoPos);   // Skip over Model String

	/* Extract and convert the Device Version Unicode string to ASCII and print it through the USART */
	char DeviceVersion[*DeviceInfoPos];
	UnicodeToASCII(DeviceInfoPos, DeviceVersion);
	printf_P(PSTR("   Device Version: %s\r\n"), DeviceVersion);

	/* Receive the final response block from the device */
	if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
	{
		ShowCommandError(ErrorCode, false);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	/* Verify that the command completed successfully */
	if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
	{
		ShowCommandError(PIMA_ReceivedBlock.Code, true);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	puts_P(PSTR("Opening Session...\r\n"));

	PIMA_SendBlock = (PIMA_Container_t)
		{
			.DataLength    = PIMA_COMMAND_SIZE(1),
			.Type          = PIMA_CONTAINER_CommandBlock,
			.Code          = PIMA_OPERATION_OPENSESSION,
			.TransactionID = 0x00000000,
			.Params        = {0x00000001},
		};

	/* Send the OPENSESSION block, open a session with an ID of 0x0001 */
	SImage_SendBlockHeader();

	/* Receive the response block from the device */
	if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
	{
		ShowCommandError(ErrorCode, false);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	/* Verify that the command completed successfully */
	if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
	{
		ShowCommandError(PIMA_ReceivedBlock.Code, true);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	puts_P(PSTR("Closing Session...\r\n"));

	PIMA_SendBlock = (PIMA_Container_t)
		{
			.DataLength    = PIMA_COMMAND_SIZE(1),
			.Type          = PIMA_CONTAINER_CommandBlock,
			.Code          = PIMA_OPERATION_CLOSESESSION,
			.TransactionID = 0x00000001,
			.Params        = {0x00000001},
		};

	/* Send the CLOSESESSION block, close the session with an ID of 0x0001 */
	SImage_SendBlockHeader();

	/* Receive the response block from the device */
	if ((ErrorCode = SImage_ReceiveBlockHeader()) != PIPE_RWSTREAM_NoError)
	{
		ShowCommandError(ErrorCode, false);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	/* Verify that the command completed successfully */
	if ((PIMA_ReceivedBlock.Type != PIMA_CONTAINER_ResponseBlock) || (PIMA_ReceivedBlock.Code != PIMA_RESPONSE_OK))
	{
		ShowCommandError(PIMA_ReceivedBlock.Code, true);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	puts_P(PSTR("Done.\r\n"));

	/* Indicate device no longer busy */
	LEDs_SetAllLEDs(LEDMASK_USB_READY);
	USB_Host_SetDeviceConfiguration(0);
}

/** Function to convert a given Unicode encoded string to ASCII. This function will only work correctly on Unicode
 *  strings which contain ASCII printable characters only.
 *
 *  \param[in] UnicodeString  Pointer to a Unicode encoded input string
 *  \param[out] Buffer        Pointer to a buffer where the converted ASCII string should be stored
 */
void UnicodeToASCII(uint8_t* UnicodeString,
                    char* Buffer)
{
	/* Get the number of characters in the string, skip to the start of the string data */
	uint8_t CharactersRemaining = *(UnicodeString++);

	/* Loop through the entire unicode string */
	while (CharactersRemaining--)
	{
		/* Load in the next unicode character (only the lower byte, as only Unicode coded ASCII is supported) */
		*(Buffer++) = *UnicodeString;

		/* Jump to the next unicode character */
		UnicodeString += 2;
	}

	/* Null terminate the string */
	*Buffer = 0;
}

/** Displays a PIMA command error via the device's serial port.
 *
 *  \param[in] ErrorCode          Error code of the function which failed to complete successfully
 *  \param[in] ResponseCodeError  Indicates if the error is due to a command failed indication from the device, or a communication failure
 */
void ShowCommandError(uint8_t ErrorCode,
                      bool ResponseCodeError)
{
	const char* FailureType = ((ResponseCodeError) ? PSTR("Response Code != OK") : PSTR("Transaction Fail"));

	printf_P(PSTR(ESC_FG_RED "Command Error (%S).\r\n"
	                         " -- Error Code %d\r\n" ESC_FG_WHITE), FailureType, ErrorCode);

	/* Indicate error via status LEDs */
	LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
}
Ejemplo n.º 7
0
int flashb_cmd(int argc, char * argv[])
{
	printf_P(PSTR("Start Xmodem of B Codes\n"));
	return Flash_serial_program(BCODE_FLASH_START);
}
Ejemplo n.º 8
0
void log_event(struct error * e, ...)
{
  PGM_P txt_sev;
  uint16_t flags;
  va_list ap;
  time_h tv;

  if( e->severity > log_level)
    return;

  // save flags
  flags = stdout->flags;

  va_start(ap, e);
  tv = time_get_time();
  
  // print timestamp
  printf_P(PSTR("%ld.%3.3ld | "), tv.s, (tv.us/1000UL));
  
  // print severity
  switch(e->severity)
  {
    case ERROR_SEVERITY_EMERG :   txt_sev = PSTR(ERROR_SEVTEXT_EMERG);   break;
    case ERROR_SEVERITY_ERROR :   txt_sev = PSTR(ERROR_SEVTEXT_ERROR);   break;
    case ERROR_SEVERITY_WARNING : txt_sev = PSTR(ERROR_SEVTEXT_WARNING); break;
    case ERROR_SEVERITY_NOTICE :  txt_sev = PSTR(ERROR_SEVTEXT_NOTICE);  break;
    case ERROR_SEVERITY_DEBUG :   txt_sev = PSTR(ERROR_SEVTEXT_DEBUG);   break;
    default :                     txt_sev = PSTR("XXX");                 break;
  }

  printf_P(txt_sev);
  printf_P(PSTR(": "));

  // print message
  vfprintf_P(stdout,e->text,ap);

  printf_P(PSTR("\n"));

  va_end(ap);

  // restore flags
  stdout->flags = flags;


  // dead end
  if( (e->severity == ERROR_SEVERITY_ERROR)
    ||(e->severity == ERROR_SEVERITY_EMERG) )
  {
    printf_P(PSTR("\nprogram stopped, strike a key other than 'x' to reset\n"));
    
#if 0  //TODO:temp
    //XXX Add shutdown procedures here XXX
    
    // breaking motors
    motor_cs_break(1);

    // killing cs & position tasks
    scheduler_del_event(event_cs);
  
    // wait for key
    uint8_t key;
    while(1)
    {
      key = cli_getkey();

      if( (key == -1)||(key == 'x'))
        continue;
      
      break;
    }
#endif
    uart_recv(1);

    // reset MCU 
    reset();
  }

}
Ejemplo n.º 9
0
int main( void )
{

   /* initialize host app, pins, watchdog, etc */
    // init_system();

    /* configure timer ISR to fire regularly */
    // init_timer_isr();
	
	// Configure CPU and peripherals clock
	xmega_set_cpu_clock_to_32MHz();
	
	// Enable interrupts
	PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
	
	// Power management - configure sleep mode to IDLE
	set_sleep_mode(SLEEP_SMODE_IDLE_gc);
	// Enable sleep mode
	sleep_enable();

#ifdef MMSN_DEBUG
	// Initialize serial communication terminal
	// usartCommTerminalInit();
	
	// Configure and initialize communication bus usart
	xmega_usart_configure();
		
	/* RS-485 PHYSICAL DEVICE CONFIGURATION */
	// Initialize GPIO related to RS-485 interface
	rs485_driver_gpio_initialize();
		
	// Enable driver to be able to send data
	rs485_driver_enable();

	// Redirect stream to standard output
	stdout = &mystdout;

	/* Print out welcome message */
	printf_P(PSTR("\nGeneric Board ver 1.00\n"));
#endif

	// Heartbeat timer - 8MHz prescales by 8 => 1MHz
	// Thus 1ms equals to 1000 ticks
	xmega_timer_config(&TIMER_HEARTBEAT, TC_CLKSEL_DIV8_gc, (TICKS_PER_MS * qt_measurement_period_msec));

	/* Initialize Touch sensors */
	touch_init();

	// Configure PIN6 as input
	PORT_DIRCLR(POWER_SUPPLY_MEASUREMENT_IO);
	
	// ADC conversion on pin 6
	uint16_t u16ConvResult = xmega_generate_adc_random_value(&ADCA, ADC_REFSEL_INT1V_gc | 0x02, ADC_CH_MUXPOS_PIN6_gc);
	printf("Power meter = %u\n", u16ConvResult);
	
	// Configure PIN5 as input
	PORT_DIRCLR(OPTO_IO);
	
	u16ConvResult = xmega_generate_adc_random_value(&ADCA, ADC_REFSEL_INT1V_gc | 0x02, ADC_CH_MUXPOS_PIN5_gc);
	printf("Opto = %u\n", u16ConvResult);

    /* loop forever */
    for(;;)
    {
        touch_measure();
		
		// Test every 2s
		if(gCounter >= 40)
		{
			printf("\n");
			printf("\nSensor[0]: %d - ", GET_SENSOR_STATE(0));
			printf("Sensor[1]: %d - ", GET_SENSOR_STATE(1));
			printf("Sensor[2]: %d - ", GET_SENSOR_STATE(2));
			printf("Sensor[3]: %d\n", GET_SENSOR_STATE(3));
			printf("Sensor[4]: %d - ", GET_SENSOR_STATE(4));
			printf("Sensor[5]: %d - ", GET_SENSOR_STATE(5));
			printf("Sensor[6]: %d - ", GET_SENSOR_STATE(6));
			printf("Sensor[7]: %d\n", GET_SENSOR_STATE(7));
			printf("Sensor[8]: %d - ", GET_SENSOR_STATE(8));
			printf("Sensor[9]: %d - ", GET_SENSOR_STATE(9));
			printf("Sensor[10]: %d - ", GET_SENSOR_STATE(10));
			printf("Sensor[11]: %d\n", GET_SENSOR_STATE(11));
			printf("Sensor[12]: %d - ", GET_SENSOR_STATE(12));
			printf("Sensor[13]: %d - ", GET_SENSOR_STATE(13));
			printf("Sensor[14]: %d - ", GET_SENSOR_STATE(14));
			printf("Sensor[15]: %d\n", GET_SENSOR_STATE(15));
			
			printf("Sensor[16]: %d - ", GET_SENSOR_STATE(16));
			printf("Sensor[17]: %d - ", GET_SENSOR_STATE(17));
			printf("Sensor[18]: %d - ", GET_SENSOR_STATE(18));
			printf("Sensor[19]: %d\n", GET_SENSOR_STATE(19));
			printf("Sensor[20]: %d - ", GET_SENSOR_STATE(20));
			printf("Sensor[21]: %d - ", GET_SENSOR_STATE(21));
			printf("Sensor[22]: %d - ", GET_SENSOR_STATE(22));
			printf("Sensor[23]: %d\n", GET_SENSOR_STATE(23));
			printf("Sensor[24]: %d - ", GET_SENSOR_STATE(24));
			printf("Sensor[25]: %d - ", GET_SENSOR_STATE(25));
			printf("Sensor[26]: %d - ", GET_SENSOR_STATE(26));
			printf("Sensor[27]: %d\n", GET_SENSOR_STATE(27));
			printf("Sensor[28]: %d - ", GET_SENSOR_STATE(28));
			printf("Sensor[29]: %d - ", GET_SENSOR_STATE(29));
			printf("Sensor[30]: %d - ", GET_SENSOR_STATE(30));
			printf("Sensor[31]: %d\n", GET_SENSOR_STATE(31));
			printf("\n");
			
			u16ConvResult = xmega_generate_adc_random_value(&ADCA, ADC_REFSEL_INT1V_gc, ADC_CH_MUXPOS_PIN5_gc);
			printf("Opto = %i\n", u16ConvResult);
			/*
			printf("\nCh_Sig[0]: %u	", qt_measure_data.channel_signals[0]);
			printf("Ch_Sig[1]: %u	", qt_measure_data.channel_signals[1]);
			printf("Ch_Sig[2]: %u	", qt_measure_data.channel_signals[2]);
			printf("Ch_Sig[3]: %u", qt_measure_data.channel_signals[3]);
			printf("\nCh_Sig[4]: %u	", qt_measure_data.channel_signals[4]);
			printf("Ch_Sig[5]: %u	", qt_measure_data.channel_signals[5]);
			printf("Ch_Sig[6]: %u	", qt_measure_data.channel_signals[6]);
			printf("Ch_Sig[7]: %u", qt_measure_data.channel_signals[7]);
			printf("\nCh_Sig[8]: %u	", qt_measure_data.channel_signals[8]);
			printf("Ch_Sig[9]: %u	", qt_measure_data.channel_signals[9]);
			
			printf("Ch_Sig[10]: %u	", qt_measure_data.channel_signals[10]);
			printf("Ch_Sig[11]: %u", qt_measure_data.channel_signals[11]);
			printf("\nCh_Sig[12]: %u	", qt_measure_data.channel_signals[12]);
			printf("Ch_Sig[13]: %u	", qt_measure_data.channel_signals[13]);
			printf("Ch_Sig[14]: %u	", qt_measure_data.channel_signals[14]);
			printf("Ch_Sig[15]: %u", qt_measure_data.channel_signals[15]);
			printf("\nCh_Sig[16]: %u	", qt_measure_data.channel_signals[16]);
			printf("Ch_Sig[17]: %u	", qt_measure_data.channel_signals[17]);
			printf("Ch_Sig[18]: %u	", qt_measure_data.channel_signals[18]);
			printf("Ch_Sig[19]: %u", qt_measure_data.channel_signals[19]);
			printf("\nCh_Sig[20]: %u	", qt_measure_data.channel_signals[20]);
			
			printf("Ch_Sig[21]: %u	", qt_measure_data.channel_signals[21]);
			printf("Ch_Sig[22]: %u	", qt_measure_data.channel_signals[22]);
			printf("Ch_Sig[23]: %u", qt_measure_data.channel_signals[23]);
			printf("\nCh_Sig[24]: %u	", qt_measure_data.channel_signals[24]);
			printf("Ch_Sig[25]: %u	", qt_measure_data.channel_signals[25]);
			printf("Ch_Sig[26]: %u	", qt_measure_data.channel_signals[26]);
			printf("Ch_Sig[27]: %u", qt_measure_data.channel_signals[27]);
			printf("\nCh_Sig[28]: %u	", qt_measure_data.channel_signals[28]);
			printf("Ch_Sig[29]: %u	", qt_measure_data.channel_signals[29]);
			printf("Ch_Sig[30]: %u	", qt_measure_data.channel_signals[30]);
			printf("Ch_Sig[31]: %u", qt_measure_data.channel_signals[31]); */
			
			printf("\ndelta[0]: %i	", qt_get_sensor_delta(0));
			printf("delta[1]: %i	", qt_get_sensor_delta(1));
			printf("delta[2]: %i	", qt_get_sensor_delta(2));
			printf("delta[3]: %i", qt_get_sensor_delta(3));
			printf("\ndelta[4]: %i	", qt_get_sensor_delta(4));
			printf("delta[5]: %i	", qt_get_sensor_delta(5));
			printf("delta[6]: %i	", qt_get_sensor_delta(6));
			printf("delta[7]: %i", qt_get_sensor_delta(7));
			printf("\ndelta[8]: %i	", qt_get_sensor_delta(8));
			printf("delta[9]: %i	", qt_get_sensor_delta(9));
			
			printf("delta[10]: %i	", qt_get_sensor_delta(10));
			printf("delta[11]: %i", qt_get_sensor_delta(11));
			printf("\ndelta[12]: %i	", qt_get_sensor_delta(12));
			printf("delta[13]: %i	", qt_get_sensor_delta(13));
			printf("delta[14]: %i	", qt_get_sensor_delta(14));
			printf("delta[15]: %i", qt_get_sensor_delta(15));
			printf("\ndelta[16]: %i	", qt_get_sensor_delta(16));
			printf("delta[17]: %i	", qt_get_sensor_delta(17));
			printf("delta[18]: %i	", qt_get_sensor_delta(18));
			printf("delta[19]: %i", qt_get_sensor_delta(19));
			printf("\ndelta[20]: %i	", qt_get_sensor_delta(20));
			
			printf("delta[21]: %i	", qt_get_sensor_delta(21));
			printf("delta[22]: %i	", qt_get_sensor_delta(22));
			printf("delta[23]: %i", qt_get_sensor_delta(23));
			printf("\ndelta[24]: %i	", qt_get_sensor_delta(24));
			printf("delta[25]: %i	", qt_get_sensor_delta(25));
			printf("delta[26]: %i	", qt_get_sensor_delta(26));
			printf("delta[27]: %i", qt_get_sensor_delta(27));
			printf("\ndelta[28]: %i	", qt_get_sensor_delta(28));
			printf("delta[29]: %i	", qt_get_sensor_delta(29));
			printf("delta[30]: %i	", qt_get_sensor_delta(30));
			printf("delta[31]: %i", qt_get_sensor_delta(31));
			
			gCounter = 0;
		}

    /*  Time Non-critical host application code goes here  */
    }
}
Ejemplo n.º 10
0
//***************************************************************************
//Function: to receive data from UART and write to multiple blocks of SD card
//Arguments: none
//return: uint8_t; will be 0 if no error,
// otherwise the response byte will be sent
//****************************************************************************
uint8_t SD_writeMultipleBlock(uint32_t startBlock, uint32_t totalBlocks)
{
	uint8_t response, data = 0;
	uint16_t i, retry=0;
	uint32_t blockCounter=0;

	response = SD_sendCommand(WRITE_MULTIPLE_BLOCKS, startBlock); 	//write a Block command

	if(response != 0x00) 
		return(response); 											//check for SD status: 0x00 - OK (No flags set)

	SD_CS_ASSERT;
	printf_P(PSTR("\n Enter text (End with ~): \n"));

	while( blockCounter < totalBlocks )
	{
		i=0;
//		do
//		{
//			data = receiveByte();
//			if(data == 0x08)											//'Back Space' key pressed
//			{ 
//				if(i != 0)
//				{ 
//					transmitByte(data);
//					transmitByte(' '); 
//					transmitByte(data); 
//					i--; 
//					size--;
//				} 
//				continue;     
//			}
//			transmitByte(data);
			buffer[i++] = data;
//			if(data == 0x0d)
//			{
//				transmitByte(0x0a);
//				buffer[i++] = 0x0a;
//			}
//			if(i == 512) break;
//		}while (data != '~');

		printf_P(PSTR("\n ---- \n"));
		
		SPI_Send8(0xfc,SD_SPI_PORT); 				//Send start block token 0xfc (0x11111100)

		for(i=0; i<512; i++) 			//send 512 bytes data
			SPI_Send8( buffer[i],SD_SPI_PORT);

		SPI_Send8(0xff,SD_SPI_PORT); 				//transmit dummy CRC (16-bit), CRC is ignored here
		SPI_Send8(0xff,SD_SPI_PORT);

		response = SPI_Receive8(SD_SPI_PORT);
		if( (response & 0x1f) != 0x05) //response= 0xXXX0AAA1 ; AAA='010' - data accepted
		{                              	//AAA='101'-data rejected due to CRC error
			SD_CS_DEASSERT;             //AAA='110'-data rejected due to write error
			return(response);
		}

		while(!SPI_Receive8(SD_SPI_PORT)) 			//wait for SD card to complete writing and get idle
			if(retry++ > 0xfffe)
			{
				SD_CS_DEASSERT; 
				return(1);
			}

		SPI_Receive8(SD_SPI_PORT); 				//extra 8 bits
		blockCounter++;
	}

	SPI_Send8(0xfd,SD_SPI_PORT); 					//send 'stop transmission token'

	retry = 0;

	while(!SPI_Receive8(SD_SPI_PORT)) 				//wait for SD card to complete writing and get idle
		if(retry++ > 0xfffe)
		{
			SD_CS_DEASSERT; 
			return(1);
		}

	SD_CS_DEASSERT;
	SPI_Send8(0xff,SD_SPI_PORT); 					//just spend 8 clock cycle delay before reasserting the CS signal
	SD_CS_ASSERT; 						//re assertion of the CS signal is required to verify if card is still busy

	while(!SPI_Receive8(SD_SPI_PORT)) 				//wait for SD card to complete writing and get idle
		if(retry++ > 0xfffe)
		{
			SD_CS_DEASSERT; 
			return(1);
		}
	SD_CS_DEASSERT;

	return(0);
}
Ejemplo n.º 11
0
int main(void)
{
	
	// INITIALISATIONS
	float x = 0.0;
	float y = 0.0;
	float theta = 0.0;
	float vel = 0.0;
	float velref = 0.0;
	float Mvel = 0.0;
	char* word_array[MAX_CMDS];
	int no_of_words = 0;
	int error = 1;


	DDRC |= 1 << 5; 	// PortC.5 as output 


	lb_init(&lb);		// init line buffer lb 
	uart_init(); 		// init USART
	enc_init();			// init Encoder
	ctrl_init();		// init Controller
	motor_init();		// init Motor
	sei();  			// enable interrupts

	printf_P(PSTR("Sup Bitches\nThis is Command\n"));


	for (;/*ever*/;)
	{
		while (uart_avail())
		{
			char c = uart_getc();		//gets character from circular buffer

			if (lb_append(&lb, c) == LB_BUFFER_FULL)		// Add character "c" to line buffer, report status(putc) and handle special characters(append)
			{
				lb_init(&lb); // Clear line  buffer, discards input
				printf_P(PSTR("\nMax line length exceeded\n"));
			}
		}
		error = 1;

		// Process command if line buffer is terminated by a line feed or carriage return
		if (lb_line_ready(&lb))		//if not empty and has null terminator
		{ 
			for (int j = 0; j < NUM_CMDS; j++)	//re-setting word_array to zero
			{
				word_array[j] = 0;
			}
			
			no_of_words = string_parser( lb_gets(&lb), word_array);		// gets serial, puts into word_array 

			for (int i=0; cmd_table[i].cmd != NULL; ++i)							// 
			{
				if( !strcmp(word_array[0], cmd_table[i].cmd))
		     	{
					error = 0;
                    cmd_table[i].func(no_of_words, word_array);
		       	}	
			}
			lb_init(&lb);

			// Error checking
			if(!no_of_words)
			{
				printf_P(PSTR("No Command Entered\n"));
			}
			if(error)
			{
				printf_P(PSTR("Invalid Command\n"));
			}



		/*	// Note: The following is a terrible way to process strings from the user
			//       See recommendations section of the lab guide for a better way to
			//       handle commands with arguments, which scales well to a large
			//       number of commands.
			if (!strncmp_P(lb_gets(&lb), PSTR("help"), 4))
			{
				printf_P(PSTR(
					"MCHA3000 RS232 lab help.\n"
					"Replace these lines with your own help instructions.\n"));
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("x="), 2))			// takes 'x' co-ordinate
			{
				x = atof(lb_gets_at(&lb, 2));
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("x?"), 2))			// prints 'x' co-ordinate to serial
			{
				printf_P(PSTR("x is %f\n"), x);
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("y="), 2))			// takes 'y' co-ordinate
			{
				y = atof(lb_gets_at(&lb, 2));
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("xy?"), 3))			// prints 'x'*'y' to serial
			{
				printf_P(PSTR("%f\n"), x*y);
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("theta="), 6))		// HIL: takes 'theta'
			{
				theta = atof(lb_gets_at(&lb, 6));
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("vel="), 4))			// HIL: takes 'vel'
			{
				vel = atof(lb_gets_at(&lb, 4));
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("velref="), 7))		// HIL: takes 'velref'
			{
				velref = atof(lb_gets_at(&lb, 7));
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("ctrl?"), 5))		// HIL: initialises feedback loop for cascade controller 
			{															// and prints control action to serial
				float outer_loop = velocity_controller(velref - vel);
				float inner_loop = angle_controller(outer_loop - theta);
				printf_P(PSTR("%g\n"), inner_loop);
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("ecount?"), 7))		// prints enc_count
			{
				printf_P(PSTR("Encoder1 Count =  %d\n"), enc_read1());
				printf_P(PSTR("Encoder2 Count =  %d\n"), enc_read2());
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("ereset"), 6))		// Resets enc_count then prints count
			{
				enc_reset();
				printf_P(PSTR("Encoder1 Count =  %d\n"), enc_read1());
				printf_P(PSTR("Encoder2 Count =  %d\n"), enc_read2());
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("mvel="), 5))		// Motor On/Off
			{
				Mvel=atof(lb_gets_at(&lb, 5));
				motor_vel(Mvel);
				printf_P(PSTR("Motor Velocity = %f\n"), Mvel);
			}
			else if (!strncmp_P(lb_gets(&lb), PSTR("I"), 1))			// Motor Current
			{
				printf_P(PSTR("Motor Current =  %f\n"), motor_current());
			}
			else														// WARNING: Unknown command
			{
				printf_P(PSTR("Unknown command: \"%s\"\n"), lb_gets(&lb));
			}

			lb_init(&lb);	// Reset line buffer 
			*/
		}
	}
	return 0;
}
/** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
 *  enumerated by the host and is now ready to be used by the application.
 */
void EVENT_USB_Host_DeviceEnumerationComplete(void)
{
	puts_P(PSTR("Getting Config Data.\r\n"));

	uint8_t ErrorCode;

	/* Get and process the configuration descriptor data */
	if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
	{
		if (ErrorCode == ControlError)
		  puts_P(PSTR(ESC_FG_RED "Control Error (Get Configuration).\r\n"));
		else
		  puts_P(PSTR(ESC_FG_RED "Invalid Device.\r\n"));

		printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);

		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	/* Set the device configuration to the first configuration (rarely do devices use multiple configurations) */
	if ((ErrorCode = USB_Host_SetDeviceConfiguration(1)) != HOST_SENDCONTROL_Successful)
	{
		printf_P(PSTR(ESC_FG_RED "Control Error (Set Configuration).\r\n"
		                         " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);

		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	/* Some printers use alternate settings to determine the communication protocol used - if so, send a SetInterface
	 * request to switch to the interface alternate setting with the Bidirectional protocol */
	if (PrinterAltSetting)
	{
		if ((ErrorCode = USB_Host_SetInterfaceAltSetting(PrinterInterfaceNumber, PrinterAltSetting)) != HOST_SENDCONTROL_Successful)
		{
			printf_P(PSTR(ESC_FG_RED "Control Error (Set Interface).\r\n"
			                         " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);

			LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
			USB_Host_SetDeviceConfiguration(0);
			return;
		}
	}

	puts_P(PSTR("Retrieving Device ID...\r\n"));

	char DeviceIDString[300];
	if ((ErrorCode = Printer_GetDeviceID(DeviceIDString, sizeof(DeviceIDString))) != HOST_SENDCONTROL_Successful)
	{
		printf_P(PSTR(ESC_FG_RED "Control Error (Get Device ID).\r\n"
		                         " -- Error Code: %d\r\n" ESC_FG_WHITE), ErrorCode);

		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	printf_P(PSTR("Printer Device ID: %s\r\n"), DeviceIDString);

	puts_P(PSTR("Printer Enumerated.\r\n"));
	LEDs_SetAllLEDs(LEDMASK_USB_READY);
}
Ejemplo n.º 13
0
/**
 * \b main_thread_func
 *
 * Entry point for main application thread.
 *
 * This is the first thread that will be executed when the OS is started.
 *
 * @param[in] data Unused (optional thread entry parameter)
 *
 * @return None
 */
static void main_thread_func (uint32_t data)
{
    uint32_t test_status;
    int sleep_ticks;

    /* Enable all LEDs (STK500-specific) */
    DDRB = 0xFF;
    PORTB = 0xFF;

    /* Initialise UART (9600bps) */
    if (uart_init(9600) != 0)
    {
        /* Error initialising UART */
    }

    /**
     * Redirect stdout via the UART. Note that the UART write routine
     * is protected via a semaphore, so the OS must be started before
     * use of the UART.
     */
    stdout = &uart_stdout;

    /* Put a message out on the UART */
    printf_P (PSTR("Go\n"));

    /* Start test. All tests use the same start API. */
   	test_status = 0;

    /* Check main thread stack usage (if enabled) */
#ifdef ATOM_STACK_CHECKING
    if (test_status == 0)
    {
        uint32_t used_bytes, free_bytes;

        /* Check idle thread stack usage */
        if (atomThreadStackCheck (&main_tcb, &used_bytes, &free_bytes) == ATOM_OK)
        {
            /* Check the thread did not use up to the end of stack */
            if (free_bytes == 0)
            {
                printf_P (PSTR("Main stack overflow\n"));
                test_status++;
            }

            /* Log the stack usage */
#ifdef TESTS_LOG_STACK_USAGE
            printf_P (PSTR("MainUse:%d\n"), used_bytes);
#endif
        }

    }
#endif

    /* Log final status */
    if (test_status == 0)
    {
        printf_P (PSTR("Pass\n"));
    }
    else
    {
        printf_P (PSTR("Fail(%d)\n"), test_status);
    }

    /* Flash LED once per second if passed, very quickly if failed */
    sleep_ticks = (test_status == 0) ? SYSTEM_TICKS_PER_SEC : (SYSTEM_TICKS_PER_SEC/8);

    /* Test finished, flash slowly for pass, fast for fail */
    while (1)
    {
        /* Toggle a LED (STK500-specific) */
        PORTB ^= (1 << 7);

        /* Sleep then toggle LED again */
        atomTimerDelay (sleep_ticks);
    }

}
Ejemplo n.º 14
0
/**
 * \brief Der Temp_Json Thread, wird zyklisch aufgerufen.
 * \return	void
 */
void temp_json_thread( void )
{
	int retval = LOGGER_ERROR;
	int Temp=0x8000;
	static char Sensor=0;
	char FILENAME[32];
	
	struct TEMP_JSON temp_json;
	temp_json.logger_entry.DataSize = sizeof( temp_json.temp );
	
	// Zeit holen
	struct TIME nowtime;
	CLOCK_GetTime ( &nowtime );

	// Update ?
	if ( ( nowtime.mm % 10 == 0 ) && ( lastmm != nowtime.mm ) )
	{
		Sensor = 0;
		lastmm = nowtime.mm ;
	}

	if( Sensor < TEMP_MAX_SENSORS )
	{
		Temp = TEMP_readtemp( Sensor );

		if ( Temp != TEMP_ERROR )
		{
			// erzeuge mal einen Dummydatensatz
			temp_logger_clean( &temp_json );
			// Dateinamen erzeigen zum Sensor
			sprintf_P( FILENAME, Templogfilename_P , Sensor );
			// Versuche letzten Datensatz zu holen
			retval = LOGGER_getlastDBEntry ( &temp_json.logger_entry , FILENAME );
			// Wenn letzter Eintrag nicht lesbar, neue NanoDB erzeugen
			if ( retval == LOGGER_ERROR )
			{
#if defined( DEBUG )
				printf_P( PSTR("Last DBEntry failed. Make new nano_DB %s.\r\n"), FILENAME );
#endif
				// Neue NanoDB erzeugen
				retval = LOGGER_addDBentry( &temp_json.logger_entry , FILENAME );
			}
			// Datenbankeintrag erzeugt oder gelesen ?
			if ( retval == LOGGER_OK )
			{
					// letzer Eintrag von heute?
				if ( ! ( temp_json.logger_entry.time.YY == nowtime.YY && temp_json.logger_entry.time.MM == nowtime.MM && temp_json.logger_entry.time.DD == nowtime.DD ) )
				{
#if defined( DEBUG )
				printf_P(PSTR("Add new DBEntry in %s.\r\n"), FILENAME );
#endif
					// Neue NanoDB erzeugen
					temp_logger_clean( &temp_json );
					retval = LOGGER_addDBentry( &temp_json.logger_entry , FILENAME );
				}
			}
#if defined( DEBUG )
			else
				printf_P(PSTR("Make new nano_DB %s failed.\r\n"), FILENAME );
#endif
					
			// alles Ok bis hier hin
			if ( retval == LOGGER_OK )
			{
#if defined( DEBUG )
				printf_P(PSTR("Write actual DBEntry in %s.\r\n"), FILENAME );
#endif
					// Temp speichern
				temp_json.temp[ ( nowtime.hh * 6 ) + ( nowtime.mm / 10 ) ] = Temp;
				// und sichern in Datenbank
				LOGGER_writeDBEntry( &temp_json.logger_entry, FILENAME );
			}
		}
		Sensor++;
	}
}
Ejemplo n.º 15
0
void main(void)
{
	clock_prescale_set(clock_div_1);

	// Timer 0 settings for approx. millisecond tracking
	TCCR0A = _BV(WGM01);
	TCCR0B = CLOCKSEL;
	TIMSK0 = _BV(OCIE0A);
	OCR0A = TICKS;

	// UART
	//PORTD |= _BV(PORTD0);
	//DDRD |= _BV(DDD1);
	UBRR0 = UBRR_VALUE;
#if USE_2X
	UCSR0A = _BV(U2X0);
#endif
	UCSR0B = _BV(TXEN0);
	
	// LED indicator
	DDRC |= _BV(DDC5);
	PORTC |= _BV(PORTC5);

	stdout = &uart_io;

	// Start up
	nRF905_init();

	// Set address of this device
	nRF905_setListenAddress(RXADDR);

	// Interrupts on
	sei();

	uint8_t counter = 0;
	uint32_t sent = 0;
	uint32_t replies = 0;
	uint32_t timeouts = 0;
	uint32_t invalids = 0;

	while(1)
	{
		// Make data
		char data[NRF905_MAX_PAYLOAD] = {0};
		sprintf_P(data, PSTR("test %hhu"), counter);
		counter++;
		
		packetStatus = PACKET_NONE;
		
		printf_P(PSTR("Sending data: %s\n"), data);

		uint32_t startTime = millis();

		// Send the data (send fails if other transmissions are going on, keep trying until success) and enter RX mode on completion
		while(!nRF905_TX(TXADDR, data, sizeof(data), NRF905_NEXTMODE_RX));
		sent++;

		puts_P(PSTR("Data sent, waiting for reply..."));

		uint8_t success;

		// Wait for reply with timeout
		uint32_t sendStartTime = millis();
		while(1)
		{
			success = packetStatus;
			if(success != PACKET_NONE)
				break;
			else if(millis() - sendStartTime > TIMEOUT)
				break;
		}

		if(success == PACKET_NONE)
		{
			puts_P(PSTR("Ping timed out"));
			timeouts++;
		}
		else if(success == PACKET_INVALID)
		{
			// Got a corrupted packet
			puts_P(PSTR("Invalid packet!"));
			invalids++;
		}
		else
		{
			// If success toggle LED and send ping time over UART
			uint16_t totalTime = millis() - startTime;
			PORTC ^= _BV(PORTC5);

			replies++;

			printf_P(PSTR("Ping time: %ums\n"), totalTime);

			// Get the ping data
			uint8_t replyData[NRF905_MAX_PAYLOAD];
			nRF905_read(replyData, sizeof(replyData));

			// Print out ping contents
			printf_P(PSTR("Data from server: "));
			for(uint8_t i=0;i<sizeof(replyData);i++)
				printf_P(PSTR("%c"), replyData[i]);
			puts_P(PSTR(""));
		}

		printf_P(PSTR("Totals: %lu Sent, %lu Replies, %lu Timeouts, %lu Invalid\n------\n"), sent, replies, timeouts, invalids);

		_delay_ms(1000);			
	}
}
Ejemplo n.º 16
0
/*------------------------------------------------------------------------------------------------------------*/
void cgi_cron( void * pStruct )
{
	int i;
	char string[32];
	int HH, MM;
	
	
	struct HTTP_REQUEST * http_request;
	http_request = (struct HTTP_REQUEST *) pStruct;
		
/*	printf_P( PSTR(	"<HTML>"
					"<HEAD>"
					"<TITLE>Cron</TITLE>"
					"</HEAD>\r"
					"<BODY>"));*/

	cgi_PrintHttpheaderStart();

	if ( http_request->argc == 0 )
	{
		printf_P( PSTR(	"<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\">" ));
		for( i = 0 ; i < MAX_CRON ; i++ )
		{
			if ( CRON_getentry( string, i) == 1 )
			{
				printf_P( PSTR(	"<tr>"
					   			"<td align=\"left\">%s</td>"
					   			"<td align=\"left\">"
								"<a href=\"cron.cgi?del=%d\" style=\"text-decoration:none\" title=\"Del\"><input type=\"button\" value=\"del\" class=\"actionBtn\"></a>"
								"</td>"
  								"</tr>"), string, i );
			}
		}

		printf_P( PSTR(	"<tr>"
			   			"<td align=\"left\">"
						"<a href=\"cron.cgi?addnew\" style=\"text-decoration:none\" title=\"Add\"><input type=\"button\" value=\"add new cron\" class=\"actionBtn\"></a>"
						"</td>"
						"</tr>"
						"</table>\r") );

	}
	else
	{
		if ( PharseCheckName_P( http_request, PSTR("addnew") ) )
		{
			printf_P( PSTR(	"<form action=\"cron.cgi\">"
					   		"<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\">"
							"<tr>"
						   	"<td align=\"right\">Stunde</td><td><input name=\"HH\" type=\"text\" size=\"3\" value=\"0\"maxlength=\"3\"></td>"
  							"</tr>"
							"<tr>"
						   	"<td align=\"right\">Minute</td>"
							"<td><input name=\"MM\" type=\"text\" size=\"3\" value=\"0\" maxlength=\"3\"></td>"
  							"</tr>"
							"<tr>"
						   	"<td align=\"right\">Command</td>"
							"<td><input name=\"CMD\" type=\"text\" size=\"30\" maxlength=\"30\"></td>"
  							"</tr>"
 							"<tr>"
   							"<td></td><td><input type=\"submit\" value=\" Eintrag sichern \"></td>"
  							"</tr>"
						   	"</table>"
							"</form>\r" ) );
		}
		else if ( PharseCheckName_P( http_request, PSTR("CMD") ) )
		{
			HH = atoi( http_request->argvalue[ PharseGetValue_P ( http_request, PSTR("HH") ) ] );
			MM = atoi( http_request->argvalue[ PharseGetValue_P ( http_request, PSTR("MM") ) ] );
			sprintf_P( string, PSTR("%d %d \"%s\""), HH, MM, http_request->argvalue[ PharseGetValue_P ( http_request, PSTR("CMD") ) ] );
			CRON_addentry( string );
			CRON_reloadcrontable();
			printf_P( PSTR("Einstellungen uebernommen!\r\n"));

		}
		else if ( PharseCheckName_P( http_request, PSTR("del") ) )
		{
			CRON_delentry( atoi( http_request->argvalue[ PharseGetValue_P ( http_request, PSTR("del") ) ] ) );
			CRON_reloadcrontable();
		}
	}

	cgi_PrintHttpheaderEnd();

/*	printf_P( PSTR( " </BODY>"
					"</HTML>\r\n"
					"\r\n")); */

}
Ejemplo n.º 17
0
/** Task to read in note on/off messages from the attached MIDI device and print it to the serial port.
 *  When the board joystick or buttons are pressed, note on/off messages are sent to the attached device.
 */
void MIDIHost_Task(void)
{
	if (USB_HostState != HOST_STATE_Configured)
	  return;

	Pipe_SelectPipe(MIDI_DATA_IN_PIPE);
	Pipe_Unfreeze();

	if (Pipe_IsINReceived())
	{
		MIDI_EventPacket_t MIDIEvent;

		Pipe_Read_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);

		if (!(Pipe_BytesInPipe()))
		  Pipe_ClearIN();

		bool NoteOnEvent  = (MIDIEvent.Event == MIDI_EVENT(0, MIDI_COMMAND_NOTE_ON));
		bool NoteOffEvent = (MIDIEvent.Event == MIDI_EVENT(0, MIDI_COMMAND_NOTE_OFF));

		if (NoteOnEvent || NoteOffEvent)
		{
			printf_P(PSTR("MIDI Note %s - Channel %d, Pitch %d, Velocity %d\r\n"), NoteOnEvent ? "On" : "Off",
																				   ((MIDIEvent.Data1 & 0x0F) + 1),
																				   MIDIEvent.Data2, MIDIEvent.Data3);
		}
	}
	
	Pipe_Freeze();

	Pipe_SelectPipe(MIDI_DATA_OUT_PIPE);
	Pipe_Unfreeze();

	if (Pipe_IsOUTReady())
	{
		uint8_t MIDICommand = 0;
		uint8_t MIDIPitch;

		static uint8_t PrevJoystickStatus;
		uint8_t JoystickStatus  = Joystick_GetStatus();
		uint8_t JoystickChanges = (JoystickStatus ^ PrevJoystickStatus);

		/* Get board button status - if pressed use channel 10 (percussion), otherwise use channel 1 */
		uint8_t Channel = ((Buttons_GetStatus() & BUTTONS_BUTTON1) ? MIDI_CHANNEL(10) : MIDI_CHANNEL(1));

		if (JoystickChanges & JOY_LEFT)
		{
			MIDICommand = ((JoystickStatus & JOY_LEFT)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
			MIDIPitch   = 0x3C;
		}

		if (JoystickChanges & JOY_UP)
		{
			MIDICommand = ((JoystickStatus & JOY_UP)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
			MIDIPitch   = 0x3D;
		}

		if (JoystickChanges & JOY_RIGHT)
		{
			MIDICommand = ((JoystickStatus & JOY_RIGHT)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
			MIDIPitch   = 0x3E;
		}

		if (JoystickChanges & JOY_DOWN)
		{
			MIDICommand = ((JoystickStatus & JOY_DOWN)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
			MIDIPitch   = 0x3F;
		}

		if (JoystickChanges & JOY_PRESS)
		{
			MIDICommand = ((JoystickStatus & JOY_PRESS)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
			MIDIPitch   = 0x3B;
		}

		/* Check if a MIDI command is to be sent */
		if (MIDICommand)
		{
			MIDI_EventPacket_t MIDIEvent = (MIDI_EventPacket_t)
				{
					.Event       = MIDI_EVENT(0, MIDICommand),

					.Data1       = MIDICommand | Channel,
					.Data2       = MIDIPitch,
					.Data3       = MIDI_STANDARD_VELOCITY,
				};

			/* Write the MIDI event packet to the pipe */
			Pipe_Write_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);

			/* Send the data in the pipe to the device */
			Pipe_ClearOUT();
		}

		Pipe_Freeze();

		/* Save previous joystick value for next joystick change detection */
		PrevJoystickStatus = JoystickStatus;
	}
}
void net_sendResultToDB(struct dummy_packet *packets, uint8_t board_addr){
  // Sends a set of 8 measurement results to the couchdb database

  int8_t sensor_index;
  int8_t comma_flag = 0;
  int16_t value;
  uint16_t len=0;
  PORTB &= ~(1<<PB1);
  PORTD &= ~(1<<PD5);
  if( W5100.readSnSR(DB_CLIENT_SOCK) != SnSR::ESTABLISHED ){
    if(!connect_db(cfg.port+1)){
      return;
    }
  }
  // Calculate length for the JSON header:
  for (sensor_index=0; sensor_index<8; sensor_index++){
    if(packets[sensor_index].header.error && packets[sensor_index].header.connected){
      // We do not send data, which might have an error
      continue;
    }
    if(packets[sensor_index].header.connected){
      switch(packets[sensor_index].header.type){
        case PACKET_TYPE_TSIC:
          len += JSON_TEMP_LEN;
          // length of "," or "}" at the end
          len++;
          break;
        case PACKET_TYPE_HYT:
          // There is no difference in temperature length
          // for HYT and TSIC.
          len += JSON_TEMP_LEN;
          len++;
          len += JSON_HUM_LEN;
          len++;
          break;
        default:
          break;
      }
    }
  }
  PORTB |= (1<<PB1);
  if(len==0){
    return;
  }
  len+=JSON_PREFIX_LEN;
  // length of "}" at the end
  len++;

  // Now we start sending data to couchdb
  stream_set_sock(DB_CLIENT_SOCK);
  net_sendHeadToDB(len);
#ifdef DEBUG
  printf_P(PSTR("Send Head \n\r"));
#endif

  /* convert packet data to json format
   * {"type":"value","data",{"bdddsdTEMP":"ddd.dd","bdddsdHUM":"ddd.dd"}}
   */
  fputs_P(PSTR(JSON_PREFIX), &sock_stream);
#ifdef DEBUG
  printf_P(PSTR("Send PREFIX \n\r"));
#endif
  comma_flag = 0;
  //puts_P(PSTR("+"));
  PORTB &= ~(1<<PB1);
  PORTD |= (1<<PD5);
  for (sensor_index=0;sensor_index<8;sensor_index++){
    if(packets[sensor_index].header.error && packets[sensor_index].header.connected){
      continue;
    }
    if(packets[sensor_index].header.connected){
      switch(packets[sensor_index].header.type){
        case PACKET_TYPE_TSIC:
          if(comma_flag){
            fputc(',', &sock_stream);
          }else{
            comma_flag = 1; 
          }
          value =  ((struct tsic_packet *)(packets))[sensor_index].temperature;
          fprintf_P(&sock_stream, PSTR(JSON_TEMP), JSON_OUTPUT);
#ifdef DEBUG
          printf_P(PSTR("Send temperature \n\r"));
#endif
          break;
        case PACKET_TYPE_HYT:
          if(comma_flag){
            fputc(',', &sock_stream);
          }else{
            comma_flag = 1; 
          }
          value = ((struct hyt_packet *)(packets))[sensor_index].temperature;
          fprintf_P(&sock_stream, PSTR(JSON_TEMP), JSON_OUTPUT);
          value = ((struct hyt_packet *)(packets) )[sensor_index].humidity;
          fputc(',', &sock_stream);
          fprintf_P(&sock_stream, PSTR(JSON_HUM), JSON_OUTPUT); 
          break;
        default:
          break;
      }
    }
  }
  fputc('}', &sock_stream);
  fputc('}', &sock_stream);
#ifdef DEBUG
  printf_P(PSTR("Send finished \n\r"));
#endif
  sock_stream_flush();
  PORTB |= (1<<PB1);
}
Ejemplo n.º 19
0
void UDP_echo_init( void )
{
	UDP_Socket = 0xffff;
	printf_P( PSTR("UDP-Echo Service gestartet auf Port %d.\r\n"),UDPPORT_ECHO);
	return;
}
Ejemplo n.º 20
0
Archivo: main.c Proyecto: maxxir/test1
int main(void)
{
    // INIT MCU
	avr_init();
	uint32_t prev_time = 0;
	float uptime_float = 0;
	//char msg[64] = "Unknown time\r\n";
	

	// Print program metrics
	/*
	USARTE0_WriteString_P(str_prog_name);// Название программы
	USARTE0_WriteString_P(PSTR("Compiled at: "));
	USARTE0_WriteString_P(compile_time); // Время компиляции
	USARTE0_WriteString_P(PSTR(" ")); 
	USARTE0_WriteString_P(compile_date); // Дата компиляции 
	USARTE0_WriteString_P(PSTR("\r\n"));
	*/
	//Working via printf
	printf_P(str_prog_name);// Название программы
	printf_P(PSTR("Compiled at: "));
	printf_P(compile_time); // Время компиляции
	printf_P(PSTR(" ")); 
	printf_P(compile_date); // Дата компиляции 
	printf_P(PSTR("\r\n"));
	
	
	// FreeRam DEBUG
	//sprintf_P(msg, PSTR(">>>Free RAM is: %u bytes\r\n\r\n"), freeRam());
	//USARTE0_WriteString(msg);
	printf_P(PSTR(">>>Free RAM is: %u bytes\r\n\r\n"), freeRam());
	
	
//***************************Profiling micros: BEGIN
//Accurate Measure time interval from 1us till ~ 65.5ms
	uint16_t _micros;
	
	
	// Profiling time for 10us
	_micros = TCD0.CNT;
	_delay_us(10);
	_micros = TCD0.CNT - _micros;
	printf_P(PSTR(">>>10us is: %u us\r\n"), _micros);


	// Profiling time for 100us
	_micros = TCD0.CNT;
	_delay_us(100);
	_micros = TCD0.CNT - _micros;
	printf_P(PSTR(">>>100us is: %u us\r\n"), _micros);


	// Profiling time for 1ms
	_micros = TCD0.CNT;
	_delay_ms(1);
	_micros = TCD0.CNT - _micros;
	printf_P(PSTR(">>>1ms is: %u us\r\n"), _micros);


	// Profiling time for 65ms
	_micros = TCD0.CNT;
	_delay_ms(65);
	_micros = TCD0.CNT - _micros;
	printf_P(PSTR(">>>65ms is: %u us\r\n"), _micros);

//***************************Profiling micros: END
	
	
	while(1);
	
    for(;;)
    {
		//Nothing to do
		//asm("nop");
		
		// Print OUT second tick & Received from RX
		if (prev_time != uptime)
		{
			// Here every second
			//!! Uptime Handle
			prev_time = uptime;
			//sprintf(msg, "Uptime is: %lu sec\r\n", prev_time);
			//USARTE0_WriteString(msg);
			printf_P(PSTR("Uptime is: %lu sec\r\n"), prev_time);
			uptime_float += 0.01;
			
			//!! Don't forget correct <makefile> PRINTF_LIB for:
			/*
			PRINTF_LIB = $(PRINTF_LIB_FLOAT)
			*/
			printf_P(PSTR("Uptime float is: %.2f \r\n"), uptime_float);
			
			//!! Received from RX Handle
			// Check received index
			if (USARTE0_rx_buf_idx > 0)
			{
				cli(); // Disable IRQ
				static char rx_buf[rx_buf_MAX+1];
				uint8_t idx = USARTE0_rx_buf_idx;
				memset(rx_buf, 0, sizeof(rx_buf)); // Fill RX_Buffer with Zeros
				memcpy(rx_buf, USARTE0_rx_buf, idx); // Transfer RX data to Temporary buffer
				USARTE0_rx_buf_idx = 0; // Set zero Received RX counter
				sei(); // Enable IRQ
				
				// Print OUT RX Received data
				//sprintf(msg, ">>RX: %s\r\n", rx_buf);
				//USARTE0_WriteString(msg);
				printf_P(PSTR(">>RX: %s\r\n"), rx_buf);
			}
		}
		/*
		// Not used because USARTE0_RX via IRQ
		else
		{
			// Check receive data from USARTE0 RX
			if (USARTE0_RX_Available())
			{
				//Print OUT recieved from USARTE0 RX
				rx_char[0] = USARTE0_ReadChar();
				sprintf(msg, ">> %s\r\n", rx_char);
				USARTE0_WriteString(msg);
			}
		}
		*/
    }
    return(0);
}
Ejemplo n.º 21
0
/* main ===================================================================== */
int
main (void) {
  int ret, c;
  int src, level, net;
  bool bPrintStat = true;
  bool bRxOn = true;
  bool bPromiscuous = true;

  // Configuration du port série par défaut (8N1, sans RTS/CTS)
  xSerialIos settings = SERIAL_SETTINGS (BAUDRATE);
  // Ouverture du port série en entrée et en sortie
  // FILE * serial_port = xFileOpen (PORT, O_RDWR | O_NONBLOCK, &settings);
  FILE * serial_port = xFileOpen (PORT, O_RDWR, &settings);
  stdout = serial_port; // le port série est la sortie standard
  stderr = serial_port; // le port série est la sortie d'erreur
  stdin = serial_port; // le port série est l'entrée standard

  // Affiche le menu
  printf_P (PSTR ("\n\n** Test Gateway RFM69 **\n"
                  "----------- Menu -----------\n"
                  "[space]: start/stop Rx\n"
                  "      p: toggle promiscous\n"
                  "      w: change power level\n"));

  xRf69 * rf = xRf69New (0, 0, DIO0_IRQ);
  assert (rf);

  ret = iRf69Open (rf, eRf69Band868Mhz, MYNODE_ID, NET_ID);
  assert (ret == 0);

  src = iRf69NodeId (rf);
  assert (src >= 0);

  net = iRf69NetworkId (rf);
  assert (net >= 0);

  for (;;) {

    if (iFileDataAvailable (stdin)) {

      c = getchar();
      // Commandes utilisateur
      switch (c) {
        case ' ':
          bRxOn = ! bRxOn;
          printf_P (PSTR ("\nTx %s\n"), bRxOn ? "On" : "Off");
          break;

        case 'p':
          bPromiscuous = ! bPromiscuous;
          ret = iRf69SetPromiscuous (rf, bPromiscuous);
          printf_P (PSTR ("\nPromiscuous %s\n"), bPromiscuous ? "On" : "Off");
          break;

        case 'w':
          ret = -1;
          do {
            printf_P (PSTR ("\nPower level [-18,13]? "), RF69_BROADCAST_ADDR);
            scanf ("%d", &ret);
          }
          while ( (ret < -18) || (ret > 13));
          level = ret + 18;
          ret = iRf69SetPowerLevel (rf, level);
          assert (ret == 0);
          bPrintStat = true;
          break;
        default:
          break;
      }
    }

    if (bPrintStat) {
      // Affiche les infos sur la liaison
      long frf = lRf69Frequency (rf);
      assert (frf >= 0);

      level = iRf69PowerLevel (rf);
      assert (level >= 0);
      ret = bRf69isHighPower (rf);
      assert (ret >= 0);
      if (ret) {

        level = level / 2 + 5;
      }
      else {
        level -= 18;
      }

      bPromiscuous = bRf69isPromiscuous (rf);

      printf_P (PSTR ("\nFrf: %lu kHz - Power Level: %d dBm - Promiscuous: %d\n"
                      "Own address: [%d]\n"
                      "Receiving data on network %d...\n"),
                frf / 1000, level, bPromiscuous, src, net);
      bPrintStat = false;
    }

    if (bRxOn) {
      // Réception des paquets

      ret = iRf69ReceiveDone (rf);
      assert (ret >= 0);

      if (ret) {
        int rssi = iRf69Rssi (rf, false);
        assert (rssi != INT_MAX);

        printf_P (PSTR ("R[%d]<[%d] "), iRf69TargetId (rf), iRf69SenderId (rf));
        if (iRf69DataLength (rf)) {

          printf_P (PSTR ("'%s'"), sRf69Data (rf));
        }

        ret = iRf69AckRequested (rf);
        assert (ret >= 0);

        if (ret) {

          ret = iRf69SendAck (rf, 0, 0);
          assert (ret == true);
          printf_P (PSTR (" > Ack")); //  > Ack [RSSI = -28]
        }
        printf_P (PSTR (" [RSSI = %d]\n"), rssi);
      }
    }
  }
  return 0;
}
Ejemplo n.º 22
0
void updateOWSensors()
{
	#ifdef OW_DEBUG
		printf_P(PSTR("Update onewire \r\n"));
	#endif

	uint8_t subzero, cel, cel_frac_bits;
	uint16_t maalt;

	if (!DS18B20Conv)
	{
		DS18B20Conv = true;
		
		for (uint8_t active_OW_channel=1; active_OW_channel<=3; active_OW_channel++)
		{
			OW_selectPort(active_OW_channel);
			DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL );
		}
		
	} else {
		DS18B20Conv = false;

		for (uint8_t active_OW_channel=1; active_OW_channel<=3; active_OW_channel++)
		{
			OW_selectPort(active_OW_channel);

		#ifdef OW_DEBUG
			printf_P(PSTR("Scanner for onewire sensore paa %d\r\n"),active_OW_channel);
		#endif
      	
	      int nSensors = search_sensors(MAXSENSORS);  //Finder alle sensore (op til max)

		#ifdef OW_DEBUG
			printf("Found %d sensors \r\n", nSensors);
		#endif

		for ( int i=0; i<nSensors; i++ ) {
			if (sensorScan[i*OW_ROMCODE_SIZE+0] == 0x10 || sensorScan[i*OW_ROMCODE_SIZE+0] == 0x28)
			{
				uint8_t sensorID[OW_ROMCODE_SIZE];
				for (uint8_t o=0; o<OW_ROMCODE_SIZE; o++)
				{
					sensorID[o] = sensorScan[i*OW_ROMCODE_SIZE+o];
				}

				if ( DS18X20_read_meas( sensorID, &subzero, &cel, &cel_frac_bits, &maalt) == DS18X20_OK ) {			
		  #ifdef OW_DEBUG							
			int frac = cel_frac_bits*DS18X20_FRACCONV;  //Ganger de sidste par bits, med det step DS18B20 bruger
		  #endif
						char sign = (subzero) ? '-' : '+';

          uint16_t pos = findSensor(
          sensorScan[i*OW_ROMCODE_SIZE+FAMILY],
          sensorScan[i*OW_ROMCODE_SIZE+ID1],
          sensorScan[i*OW_ROMCODE_SIZE+ID2],
          sensorScan[i*OW_ROMCODE_SIZE+ID3],
          sensorScan[i*OW_ROMCODE_SIZE+ID4],
          sensorScan[i*OW_ROMCODE_SIZE+ID5],
          sensorScan[i*OW_ROMCODE_SIZE+ID6],
          sensorScan[i*OW_ROMCODE_SIZE+CRC]
          );
      	
          sensorValues[(pos*SENSORSIZE)+VALUE1]     = cel;
          sensorValues[(pos*SENSORSIZE)+VALUE2]     = cel_frac_bits;
          sensorValues[(pos*SENSORSIZE)+SIGN]       = sign;
        
          #ifdef OW_DEBUG
      		printf_P(PSTR("Sensor# %d (%02X%02X%02X%02X%02X%02X%02X%02X) =  : %c%d.%04d\r\n"),i+1,
                sensorValues[(pos*SENSORSIZE)+FAMILY],
                sensorValues[(pos*SENSORSIZE)+ID1],
                sensorValues[(pos*SENSORSIZE)+ID2],
                sensorValues[(pos*SENSORSIZE)+ID3],
                sensorValues[(pos*SENSORSIZE)+ID4],
                sensorValues[(pos*SENSORSIZE)+ID5],
                sensorValues[(pos*SENSORSIZE)+ID6],
                sensorValues[(pos*SENSORSIZE)+CRC],
                sensorValues[(pos*SENSORSIZE)+SIGN],
                sensorValues[(pos*SENSORSIZE)+VALUE1],
                frac
                );
        	#endif
				}
				else 
					printf_P(PSTR("CRC Error (lost connection?)"));
			  }
			}
			}
		}
	}