Example #1
0
void 
Menu::Walker::on_key_down(uint8_t nr)
{
  // Access the current menu item
  Menu::item_list_P menu = m_stack[m_top];
  Menu::item_vec_P list = (Menu::item_vec_P) pgm_read_word(&menu->list);
  Menu::item_P item = (Menu::item_P) pgm_read_word(&list[m_ix]);
  Menu::type_t type = (Menu::type_t) pgm_read_byte(&item->type);
  
  // React to key event
  switch (nr) {
  case NO_KEY: 
    break;
  case SELECT_KEY: 
  case RIGHT_KEY:
    switch (type) {
    case Menu::ZERO_OR_MANY:
      // Select zero-or-many variable or toggle current item
      {
	if (!m_selected) {
	  m_selected = true;
	  m_bv = 0;
	  break;
	}
	Menu::zero_or_many_P var = (Menu::zero_or_many_P) item;
	uint16_t* vp = (uint16_t*) pgm_read_word(&var->value);
	list = (Menu::item_vec_P) pgm_read_word(&var->list);	  
	item = (Menu::item_P) pgm_read_word(&list[m_bv]);
	uint16_t value = *vp;
	if ((value & _BV(m_bv)) == 0)
	  *vp = (value | _BV(m_bv));
	else 
	  *vp = (value & ~_BV(m_bv));
      }
      break;
    case Menu::ITEM_LIST:
      // Walk into sub-menu
      {
	m_stack[++m_top] = (Menu::item_list_P) item;
	m_ix = 0;
      }
      break;
    case Menu::ACTION:
      // Execute action and fall back to menu root
      {
	Menu::action_P action = (Menu::action_P) item;
	Menu::Action* obj = (Menu::Action*) pgm_read_word(&action->obj);
	bool res = obj->run(item);
	m_top = 0;
	m_ix = 0;
	if (!res) return;
      }
      break;
    default:
      // Enter item modification mode
      m_selected = !m_selected;
      m_bv = 0;
    }
    break;
  case LEFT_KEY: 
    // Exit item modification mode or walk back
    if (m_selected) {
      m_selected = false;
    } 
    else if (m_top > 0) {
      m_top -= 1;
      m_ix = 0;
    }
    break;
  case DOWN_KEY: 
    // Step to the next menu item or value in item modification mode
    if (!m_selected) {
      m_ix += 1;
      item = (Menu::item_P) pgm_read_word(&list[m_ix]);
      if (item == 0) m_ix -= 1;
    }
    else {
      switch (type) {
      case Menu::ONE_OF:
	// Step to the next enumeration value
	{
	  Menu::one_of_P evar = (Menu::one_of_P) item;
	  uint16_t* vp = (uint16_t*) pgm_read_word(&evar->value);
	  uint16_t value = *vp + 1;
	  list = (Menu::item_vec_P) pgm_read_word(&evar->list);	  
	  item = (Menu::item_P) pgm_read_word(&list[value]);
	  if (item == 0) break;
	  *vp = value;
	}
	break;
      case Menu::ZERO_OR_MANY:
	// Step to the next item
	{
	  Menu::zero_or_many_P bitset = (Menu::zero_or_many_P) item;
	  list = (Menu::item_vec_P) pgm_read_word(&bitset->list);	  
	  item = (Menu::item_P) pgm_read_word(&list[m_bv + 1]);
	  if (item == 0) break;
	  m_bv += 1;
	}
	break;
      case Menu::INT_RANGE:
	// Decrement the integer variable if within the range
	{
	  Menu::int_range_P range = (Menu::int_range_P) item;
	  int16_t* vp = (int16_t*) pgm_read_word(&range->value);
	  int value = *vp;
	  int low = (int) pgm_read_word(&range->low);
	  if (value == low) break;
	  *vp = value - 1;
	}
	break;
      default:
	;
      }
    }
    break;
  case UP_KEY: 
    // Step to the previous menu item or value in item modification mode
    if (!m_selected) {
      if (m_ix > 0) 
	m_ix -= 1;
      else if (m_top > 0) {
	m_top -= 1;
      }
    }
    else {
      switch (type) {
      case Menu::ONE_OF:
	// Step to the previous enumeration value
	{
	  Menu::one_of_P evar = (Menu::one_of_P) item;
	  uint16_t* vp = (uint16_t*) pgm_read_word(&evar->value);
	  uint16_t value = *vp;
	  if (value == 0) break;
	  value -= 1;
	  list = (Menu::item_vec_P) pgm_read_word(&evar->list);	  
	  item = (Menu::item_P) pgm_read_word(&list[value]);
	  *vp = value;
	}
	break;
      case Menu::ZERO_OR_MANY:
	// Step to the previous bitset value
	{
	  if (m_bv == 0) {
	    m_selected = 0;
	    break;
	  }
	  m_bv -= 1;
	}
	break;
      case Menu::INT_RANGE:
	// Increment the integer variable in within range
	{
	  Menu::int_range_P range = (Menu::int_range_P) item;
	  int16_t* vp = (int16_t*) pgm_read_word(&range->value);
	  int value = *vp;
	  int high = (int) pgm_read_word(&range->high);
	  if (value == high) break;
	  *vp = value + 1;
	}
	break;
      default:
	;
      }
    }
    break;
  }

  // Display the new walker state
  m_out << clear << *this;
}
Example #2
0
uint8_t keymap_fn_layer(uint8_t index)
{
    return pgm_read_byte(&fn_layer[index]);
}
Example #3
0
void TinyXML::processChar(uint8_t ch)
{
    uint16_t chToParse;
    boolean bMatch=false;
    while (!bMatch)
    {
        chToParse = pgm_read_word(&(pTable[currentState].charToParse));
        switch ( chToParse )
        {
        case whiteSpace:
            if (ch == ' ' || ch == '\t' || ch == '\n' | ch == '\r') bMatch=true;
            break;
        case alpha:
            if (isAlpha(ch))  bMatch=true;
            break;
        case alphanum:
            if (isAlpha(ch) || isNumeric(ch) || (ch == ':') || (ch == '_') || (ch == '-'))  bMatch=true;
            break;
        case quote:
            if (ch == '"' || ch == '\'')
            {
                matchQuote = ch;
                bMatch=true;
            }
            break;
        case matchingquote:
            if (ch == matchQuote) bMatch=true;
            break;
        case anychar:
            bMatch=true;
            break;
        default:
            if (ch == chToParse) bMatch=true;
            break;
        }
        if (!bMatch)
        {
#if DEBUG > 3
            Serial.print("Non-matching state:");
            Serial.print(currentState,DEC);
            Serial.print(" ch:");
            Serial.print(ch,HEX);
            Serial.print(" match criteria:");
            Serial.print(chToParse,HEX);
            Serial.print(" new state:");
            Serial.println(currentState+1,DEC);
#endif
            currentState++;
        }
    } // as every table enry must end in anychar we must get out of here

#if DEBUG > 2
    Serial.print("Matching state:");
    Serial.print(currentState,DEC);
    Serial.print(" ch:");
    Serial.print(ch,HEX);
    Serial.print(" match criteria:");
    Serial.print(chToParse,HEX);
    Serial.print(" tagBufferPtr:");
    Serial.print(tagBufferPtr,DEC);
    Serial.print(" new state:");
    Serial.println(pgm_read_byte(&(pTable[currentState].nextState)),DEC);
#endif
    action(ch, pgm_read_byte(&(pTable[currentState].actionNumber)));
    action(ch, pgm_read_byte(&(pTable[currentState].actionNumber2)));

    currentState=pgm_read_byte(&(pTable[currentState].nextState));
}
Example #4
0
void USB_sendstring_P(PGM_P s)	/// send string from PROGMEM
{
	uint8_t b;
	while ( (b = pgm_read_byte(s++)) ) RingBuffer_Insert(&USARTtoUSB_Buffer, b);
}
//converts temp from ADC reading to temp in F
uint16_t convert_temp(uint16_t sample)
{
    uint16_t ret;
    ret = pgm_read_byte(&temps_vals[sample]);
    return ret; 
}
Example #6
0
void radio_set_param(radio_attribute_t attr, radio_param_t parm)
{
    switch (attr)
    {
        case phyCurrentChannel:
            if (((int)parm.channel >= TRX_MIN_CHANNEL) &&
                ((int)parm.channel <= TRX_MAX_CHANNEL))
            {
                trx_bit_write(SR_CHANNEL, parm.channel);
                radiostatus.channel = parm.channel;
            }
            else
            {
                radio_error(SET_PARM_FAILED);
            }
            break;

        case phyTransmitPower:
            if (parm.tx_pwr >= -17 && parm.tx_pwr <= 3)
            {
                /** @todo move this into a radio-specific header file */
                static const uint8_t pwrtable[] =
                {
                    0x0F, 0x0F, 0x0F, 0x0F, 0x0F, /* -17...-13 dBm */
                    0x0E, 0x0E, 0x0E,             /* -12...-10 dBm */
                    0x0D, 0x0D,                   /* -9...-8 dBm */
                    0x0C, 0x0C,                   /* -7...-6 dBm */
                    0x0B,                         /* -5 dBm */
                    0x0A,                         /* -4 dBm */
                    0x09,                         /* -3 dBm */
                    0x08,                         /* -2 dBm */
                    0x07,                         /* -1 dBm */
                    0x06,                         /* 0 dBm */
                    0x04,                         /* 1 dBm */
                    0x02,                         /* 2 dBm */
                    0x00                          /* 3 dBm */
                };
                radiostatus.tx_pwr = parm.tx_pwr;
                uint8_t idx = parm.tx_pwr + 17;
                uint8_t pwrval = pgm_read_byte(pwrtable[idx]);
                trx_bit_write(SR_TX_PWR, pwrval);
            }
            else
            {
                radio_error(SET_PARM_FAILED);
            }
            break;

        case phyCCAMode:
            if (parm.cca_mode <= 3)
            {
                radiostatus.cca_mode = parm.cca_mode;
                trx_bit_write(SR_CCA_MODE, radiostatus.cca_mode);
            }
            else
            {
                radio_error(SET_PARM_FAILED);
            }
            break;

        case phyIdleState:
            radiostatus.idle_state = parm.idle_state;
            radio_set_state(parm.idle_state);
            break;

        case phyChannelsSupported:
            break;

        case phyPanId:
            trx_set_panid(parm.pan_id);
            break;

        case phyShortAddr:
            trx_set_shortaddr(parm.short_addr);
            break;

        case phyLongAddr:
        {
            uint8_t regno, *ap;
            for (regno = RG_IEEE_ADDR_0, ap = (uint8_t *)parm.long_addr;
                 regno <= RG_IEEE_ADDR_7;
                 regno++, ap++)
                trx_reg_write(regno, *ap);
            break;
        }

        case phyDataRate:
            trx_set_datarate(parm.data_rate);
            break;

        default:
            radio_error(SET_PARM_FAILED);
            break;
    }
}
uint8_t REDFLY::cmd(uint8_t *dst, uint8_t dst_size, PGM_P p1, char *v1, PGM_P p2, uint8_t *v2, uint16_t v2_size)
{
  uint8_t c, i;
  uint32_t ms;
  uint32_t timeout;
  uint8_t buf[8]; //ERRORx

  if(read_state == 2) //currently receiving data?
  {
    return 0xFF;
  }
  else if(available()) //check for new data
  {
    uint8_t sock=INVALID_SOCKET;
    uint16_t len=0;
    socketRead(&sock, &len, 0, 0, 0, 0);
    if(len != 0) //rx data found
    {
      return 0xFF;
    }
  }

  //send p1 command
  c = pgm_read_byte(p1++);
  while(c != 0)
  {
    write(c);
    c = pgm_read_byte(p1++);
  }

  //send v1 parameter 1
  if(v1)
  {
    while(*v1)
    {
      write(*v1++);
    }
  }

  //send p2 parameter 2
  if(p2)
  {
    c = pgm_read_byte(p2++);
    while(c != 0)
    {
      if(c == 0xDB) //0xDB -> 0xDB 0xDD
      {
        write(0xDB);
        write(0xDD);
        c = pgm_read_byte(p2++);
      }
      else if((c == 0x0D) && (pgm_read_byte(p2) == 0x0A)) //\r\n -> 0xDB 0xDC
      {
        write(0xDB);
        write(0xDC);
        p2++;
        c = pgm_read_byte(p2++);
      }
      else
      {
        write(c);
        c = pgm_read_byte(p2++);
      }
    }
  }

  //send v2 parameter 3
  if(v2_size)
  {
    while(v2_size)
    {
      if(v2[0] == 0xDB) //0xDB -> 0xDB 0xDD
      {
        write(0xDB);
        write(0xDD);
        v2++; v2_size--;
      }
      else if((v2[0] == 0x0D) && (v2[1] == 0x0A) && (v2_size >= 2)) //\r\n -> 0xDB 0xDC
      {
        write(0xDB);
        write(0xDC);
        v2+=2; v2_size-=2;
      }
      else
      {
        write(*v2++);
        v2_size--;
      }
    }
  }

  //flush rx and tx buffer
  flush_nowait();

  //send end characters of command
  write('\r');
  write('\n');

  //read response
  timeout = 10000; //default timeout: 10s
  if(dst_size == 0) //dont save response
  {
    buf[0] = 0;
    buf[5] = 0;
    for(i=0, ms=millis(); (millis()-ms) < timeout;)
    {
      if(available())
      {
        c = read();
        if(i < 8)
        {
          buf[i++] = c;
          if((buf[0] != 'O') && (buf[0] != 'E')) //OK or ERROR
          {
            i = 0;
          }
        }
        ms = millis();
        timeout = 3; //3 ms timeout
      }
    }
  }
  else //save response to dst
  {
    dst[0] = 0;
    dst[5] = 0;
    for(i=0, ms=millis(); (millis()-ms) < timeout;)
    {
      if(available())
      {
        c = read();
        if(i < dst_size)
        {
          dst[i++] = c;
          if((dst[0] != 'O') && (dst[0] != 'E')) //OK or ERROR
          {
            i = 0;
          }
        }
        ms = millis();
        timeout = 3; //3 ms timeout
      }
    }
    buf[0] = dst[0];
    buf[1] = dst[1];
    buf[5] = dst[5];
  }

  //check response
  if((buf[0] == 'O') && (buf[1] == 'K'))
  {
    return 0; //OK
  }
  else if((buf[0] == 'E') && (buf[1] == 'R') && (buf[5] != 0) && (buf[5] != '\r'))
  {
    return buf[5]; //ERROR code
  }

  return 0xFF;
}
void printPSTR1 ( PGM_P s) 
{
  char c;
  while ((c=pgm_read_byte(s++)) != 0)
    Serial.print (c);
} 
Example #9
0
uint8_t gamma_correct(uint8_t input) { return pgm_read_byte(&gamma[input]); }
Example #10
0
/** 
 *	This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
 *  documentation) by the application code so that the address and size of a requested descriptor can be given
 *  to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
 *  is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
 *  USB host.
 */
uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
                                    const uint8_t wIndex,
                                    void** const DescriptorAddress)
{
	const uint8_t  DescriptorType   = (wValue >> 8);
	const uint8_t  DescriptorNumber = (wValue & 0xFF);

	void*    Address = NULL;
	uint16_t Size    = NO_DESCRIPTOR;

	switch (DescriptorType)
	{
		case DTYPE_Device: 
			Address = (void*)&DeviceDescriptor;
			Size    = sizeof(USB_Descriptor_Device_t);
			break;

		case DTYPE_Configuration: 
			if (g_bAttackMode == 0)
			{
				Address = (void*)&ConfigurationDescriptorForNormal;
				Size    = sizeof(USB_Descriptor_Configuration_Normal_t);
			}
			else
			{
				Address = (void*)&ConfigurationDescriptorForAttack;
				Size    = sizeof(USB_Descriptor_Configuration_Attack_t);
			}
			break;

		case DTYPE_String: 
			switch (DescriptorNumber)
			{
				case 0x00: 
					Address = (void*)&LanguageString;
					Size    = pgm_read_byte(&LanguageString.Header.Size);
					break;
				case 0x01: 
					Address = (void*)&ManufacturerString;
					Size    = pgm_read_byte(&ManufacturerString.Header.Size);
					break;
				case 0x02: 
					Address = (void*)&ProductString;
					Size    = pgm_read_byte(&ProductString.Header.Size);
					break;
			}
			break;

		case DTYPE_HID:
			if (g_bAttackMode == 0)
			{
				Address = (void*)&ConfigurationDescriptorForNormal.HID_KeyboardHID;
			}
			else
			{
				Address = (void*)&ConfigurationDescriptorForAttack.HID_KeyboardHID;
			}
			Size    = sizeof(USB_HID_Descriptor_t);
			break;

		case DTYPE_Report:
			if (wIndex == USER_IFNUM)
			{
				Address = (void*)&VendorReport;
				Size    = sizeof(VendorReport);
			}
			else
			{
				Address = (void*)&KeyboardReport;
				Size    = sizeof(KeyboardReport);
			}
			break;
	}
	
	*DescriptorAddress = Address;
	return Size;
}
Example #11
0
/**
 * This function is called whenever we receive a setup request via USB.
 * \param data[8] eight bytes of data we received
 * \return number of bytes to use, or 0xff if usbFunctionWrite() should be
 * called
 */
usbMsgLen_t usbFunctionSetup(uint8_t data[8]) {

    delegateInterfaceReadyUsb();

    usbRequest_t *rq = (void *)data;
    DBG1(0xCC, data, 8);

    if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {
        // class request type
        if (rq->bRequest == USBRQ_HID_GET_REPORT) {
            if (rq->wValue.word == HID_REPORT_KEBOARD)
            {
                // wValue: ReportType (highbyte), ReportID (lowbyte)
                usbMsgPtr = (usbMsgPtr_t)&reportKeyboard;
                return sizeof(reportKeyboard);
            }else if(rq->wValue.word == HID_REPORT_BOOT){

            	if(rq->wLength.word == LED2_GET_REPORT_LENGTH_RAINBOW){	// ready for rainbow color setting;
            		readyForRainbowColor = 1;
            	}
//                // boot
//            	static uchar    optionsBuffer[0x84];
//
//            	memset(optionsBuffer, 0, 0x83);
//            	optionsBuffer[0]       = REPORT_ID_BOOT;	// LED options
//            	/* LED options */
//            	optionsBuffer[0x83] = 0x84;
//            	usbMsgPtr = (usbMsgPtr_t)optionsBuffer;

//            	return sizeof(optionsBuffer);
            }else if(rq->wValue.word == HID_REPORT_OPTION){
            	// length : rq->wLength.word 필요한 리포트를 length로 구분한다.

        		uint8_t k, j, i = 0;
        		static uchar    led2Buffer[CUSTOM_MACRO_SIZE_MAX];
            	if(rq->wLength.word == LED2_GET_REPORT_LENGTH_INFO){
            		// report led2 info
            		getLed2((led2_info_t *)led2Buffer);
            		usbMsgPtr = (usbMsgPtr_t)led2Buffer;
            		return LED2_GET_REPORT_LENGTH_INFO; 	//sizeof(led2Buffer);
            	}else if(rq->wLength.word >= LED2_GET_REPORT_LENGTH_KEYMAP_LAYER1 && rq->wLength.word <= LED2_GET_REPORT_LENGTH_KEYMAP_LAYER4){
            		// keymap
					for(k = 0; k < ROWS; ++k){
						for (j = 0; j < COLUMNS; ++j)
						{
							led2Buffer[i++] = pgm_read_byte(KEYMAP_ADDRESS+(ROWS * COLUMNS * (rq->wLength.word - LED2_GET_REPORT_LENGTH_KEYMAP_LAYER1))+(k * COLUMNS + j));
						}
					}
//					DBG1(0x89, led2Buffer, 120);
					usbMsgPtr = (usbMsgPtr_t)led2Buffer;
					return LED2_GET_REPORT_LENGTH_KEYMAP;
            	}else if(rq->wLength.word >= LED2_GET_REPORT_LENGTH_MACRO1 && rq->wLength.word <= LED2_GET_REPORT_LENGTH_MACRO12){
            		// cst macro
            		for(k = 0; k < CUSTOM_MACRO_SIZE_MAX; ++k){
            			led2Buffer[i++] = pgm_read_byte(CUSTOM_MACRO_ADDRESS+(CUSTOM_MACRO_SIZE_MAX * (rq->wLength.word - LED2_GET_REPORT_LENGTH_MACRO1))+(k));
            		}
            		usbMsgPtr = (usbMsgPtr_t)led2Buffer;
					return CUSTOM_MACRO_SIZE_MAX;
            	}else {
            		return rq->wLength.word;
            	}
            }
        } else if (rq->bRequest == USBRQ_HID_SET_REPORT) {
        	DBG1(0xAA, (uchar *)&rq->wValue.word, 2);
        	// 02 03 : Report Type: 0x03,  ReportID: 0x02
        	// 01 03 : Report Type: 0x03,  ReportID: 0x01
            // Report Type: 0x02(Out)/ReportID: 0x00(none) && Interface: 0(keyboard)
            if (rq->wValue.word == HID_REPORT_KEBOARD && rq->wIndex.word == 0)
            {
                // We expect one byte reports
                expectReport = 1;
                return USB_NO_MSG; // Call usbFunctionWrite with data
            }else if(rq->wValue.word == HID_REPORT_BOOT){
                // boot
//                isStart = 1;
                if(readyForRainbowColor==1){
                	data[1] = LED2_INDEX_COLOR_RAINBOW_INIT;
                	setLed2((uint8_t *)data);
                	expectReport = 4;
                }else{
                	expectReport = 3;
                }
                readyForRainbowColor = 0;
                return USB_NO_MSG; // Call usbFunctionWrite with data
            }else if(rq->wValue.word == HID_REPORT_OPTION){
            	// options
                expectReport = 2;

                return USB_NO_MSG; // Call usbFunctionWrite with data
            }
        } else if (rq->bRequest == USBRQ_HID_GET_IDLE) {
            usbMsgPtr = idleRate;
            return 1;
        } else if (rq->bRequest == USBRQ_HID_SET_IDLE) {

            delegateInitInterfaceUsb();

            idleRate = rq->wValue.bytes[1];
        } else if (rq->bRequest == USBRQ_HID_GET_PROTOCOL) {
            if (rq->wValue.bytes[1] < 1) {
                protocolVer = rq->wValue.bytes[1];
            }
        } else if(rq->bRequest == USBRQ_HID_SET_PROTOCOL) {
            usbMsgPtr = protocolVer;
            return 1;
        }
    } else {        
        // no vendor specific requests implemented
    }

    return 0;
}
Example #12
0
void backlight_set(uint8_t level)
{
#ifdef SOFTPWM_LED_ENABLE
    softpwm_enable();
#endif
#ifdef BREATHING_LED_ENABLE
    switch (level) {
        case 1:
        case 2:
        case 3:
#ifdef SOFTPWM_LED_ENABLE
            softpwm_led_enable_all();
#ifdef FADING_LED_ENABLE
            fading_led_disable_all();
#endif
            breathing_led_disable_all();
#else
            backlight_enable();
            breathing_led_disable();
#endif
            backlight_brightness = pgm_read_byte(&backlight_table[level]);
            backlight_set_raw(backlight_brightness);
            break;
        case 4:
        case 5:
        case 6:
#ifdef SOFTPWM_LED_ENABLE
            softpwm_led_enable_all();
#ifdef FADING_LED_ENABLE
            fading_led_disable_all();
#endif
            breathing_led_enable_all();
#else
            backlight_enable();
            breathing_led_enable();
#endif
            breathing_led_set_duration(6 - level);
            break;
#ifdef SOFTPWM_LED_ENABLE
#ifdef FADING_LED_ENABLE
        case 7:
            softpwm_led_enable_all();
            fading_led_enable_all();
            breathing_led_disable_all();
            fading_led_set_direction_all(FADING_LED_FADE_IN);
            fading_led_set_duration(3);
            break;
        case 8:
            softpwm_led_enable_all();
            fading_led_enable_all();
            breathing_led_disable_all();
            fading_led_set_direction_all(FADING_LED_FADE_OUT);
            fading_led_set_duration(3);
            break;
#endif
#endif
        case 0:
        default:
#ifdef SOFTPWM_LED_ENABLE
#ifdef FADING_LED_ENABLE
            fading_led_disable_all();
#endif
            breathing_led_disable_all();
            backlight_brightness = 0;
            backlight_set_raw(backlight_brightness);
            softpwm_led_disable_all();
#else
            breathing_led_disable();
            backlight_disable();
#endif
            break;
    }
#else
    if (level > 0) {
        backlight_enable();
        backlight_set_raw(pgm_read_byte(&backlight_table[level]));
    }
    else {
        backlight_disable();
    }
#endif
}
Example #13
0
//initialise spi & enc28j60
void enc28j60_init(void)
{
  unsigned char i;
  unsigned int timeout=0;
  
  //set bank to invalid value -> bank set will update in any case:
  enc28j60_current_bank = 0xFF;
  
  //set up port directions:
  ENC28J60_DDR |= (1<<ENC28J60_PIN_CS);
  
  //deselect enc28j60:
  ENC28J60_CS_HI();
  
  //SPI init
  // initialize I/O
  PORTB |= (1<<ENC28J60_PIN_SCK); //sck = hi
  
  //spi = output
  DDRB |= (1<<ENC28J60_PIN_SS)|(1<<ENC28J60_PIN_CS)|(1<<ENC28J60_PIN_MOSI)|(1<<ENC28J60_PIN_SCK); //SS,MOSI,SCK = OUT
  DDRB &= ~(1<<ENC28J60_PIN_MISO); //MISO = IN
  
  //SPI init:
  // - master mode
  // - positive clock phase
  // - msb first
  // - maximum SPI speed (fosc/2)
  // - enable spi
  SPCR = (0<<SPIE)|(1<<SPE)|(0<<DORD)|(1<<MSTR)|(0<<CPOL)|(0<<CPHA)|(0<<SPR1)|(0<<SPR0);
  SPSR = (1<<SPI2X);
  
  delay(200000);
  enc28j60_spi_write_word (ENC28J60_SOFT_RESET, ENC28J60_SOFT_RESET);
  // check CLKRDY bit to see if reset is complete
  delay(200000);
  
  //wait for ready flag
  while((!(enc28j60_read_address(ENC28J60_REG_ESTAT) & 0x01)) && (timeout<65000)){timeout++;};
  if(timeout>=65000){timeout=0;}
  
  //set up rx pointer:
  enc28j60_next_packet_ptr = ENC28J60_RX_BUFFER_START;
  //enc28j60_next_packet_ptr = 0x0602;
  
  //copy config from progmem to enc28j60:
  for(i=0; i<2*22; i+=2){
    enc28j60_write_address(pgm_read_byte(&enc28j60_config[i+0]),pgm_read_byte(&enc28j60_config[i+1]));
  }
  
  //setup phy:
  enc28j60_write_phy(ENC28J60_PHY_PHCON2, (1<<ENC28J60_BIT_HDLDIS)); //=no loopback of transmitted frames
  
  //enable interrups
  enc28j60_write_address(ENC28J60_REG_EIE, (1<<ENC28J60_EIE_INTIE)|(1<<ENC28J60_EIE_PKTIE));
  
  //enable rx
  //enc28j60_write_address(ENC28J60_REG_ECON1, (1<<ENC28J60_BIT_RXEN));
  enc28j60_spi_write_word(ENC28J60_OP_BFS|ENC28J60_REG_ECON1, (1<<ENC28J60_BIT_RXEN));
  
  //set up leds: LEDB: link status, LEDA: RX&TX activity, stretch 40ms, stretch enable
  enc28j60_write_phy(ENC28J60_PHY_PHLCON, 0x374A); //cave: Table3-3: reset value is 0x3422, do not modify the reserved "3"!! 
  //RevA Datasheet page 9: write as '0000', see RevB Datasheet: write 0011!
  //read silicon revision
  //was geht hier vor?? Trotzdem die Bank 2 ist (0x40), gibt er beim Lesen 
  //der RevID keine neue Bank aus, trotzdem kommt der Wert 05.
  //Vielleicht ist es gar keine Rev05??
  enc28j60_revision = enc28j60_read_address(ENC28J60_REG_ECON1);   //um die aktuelle Banknummer zu sehen
  enc28j60_revision = enc28j60_read_address(ENC28J60_REG_EREVID);
}
Example #14
0
/**
 * %Print a string in flash memory to the serial port.
 *
 * \param[in] str Pointer to string stored in flash memory.
 */
void SerialPrint_P(PGM_P str)
{
  for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.print(c);
}
Example #15
0
  0b10111110, 0b11100000, 0b11111110, 0b11110110, 0b11101110, 0b111110,
  0b10011100, 0b1111010,  0b10011110, 0b10001110};

/*******************************************************************************
*  Implementation
******************************************************************************/
void lad_init()
{
  SETBITMASK(LAD_OUT_DIR, 0b11111111);
  SETBITMASK(LAD_PINS_DIR, LAD_PINS_MASK);
}

void lad_display_dec(uint8_t number)
{
  uint8_t MSDigit = number / 10;
  number -= MSDigit * 10;
  uint8_t LSDigit = number;

  lad_ledsArray[LAD_INDEX_LSD] = pgm_read_byte(&lad_decDigits[LSDigit]);
  lad_ledsArray[LAD_INDEX_MSD] = pgm_read_byte(&lad_decDigits[MSDigit]);
}

void lad_display_hex(uint8_t number)
{
  uint8_t MSDigit = number >> 4;
  number -= MSDigit << 4;
  uint8_t LSDigit = number;

  lad_ledsArray[LAD_INDEX_LSD] = pgm_read_byte(&lad_hexDigits[LSDigit]);
  lad_ledsArray[LAD_INDEX_MSD] = pgm_read_byte(&lad_hexDigits[MSDigit]);
}
uint8_t text_decode (uint8_t *buffer, uint8_t *cmd_argument)
{

 uint8_t  found,ch,ch2,cmd_no,j,k,index,cmd_complete;
 uint8_t  state = WAIT_CMD_STATE, quote  = 0;
 static uint16_t i=0; // Keep pointer for next command decode
 cmd_complete = 0;
 cmd_no 	= 0;
 index 		= 0;
 
 cmd_argument  = buffer;
 
 while (*(buffer+i))	  		//End with NULL
 {
// Check with delimiter

 	 j = 0;
	 found = 0;
	
	switch (state)
	{
	  case WAIT_CMD_STATE:   // If found first character in command table  then go to get_cmd state
 		j = 0;
		while ((ch = pgm_read_byte(&text_cmd[j][0])))     //Check first charaters in cmd table
		{ 
		  if (*(buffer+i) == ch)
		  {
			state = GET_CMD_STATE;   // Found delimiter
			*(cmd_argument) = ch;
			index = 1;
			break; 
		  }
		 j++;
		}  
	    break;
	  case GET_CMD_STATE:
	    ch = *(buffer+i);
        j = 0; 
		found = 0;
	  	while ((ch2 = pgm_read_byte(&delimiter[j])))   //Check delimiter End with NULL
		{  
		   if ( ch == ch2)
		   {
              found = 1;
              break;
		   } 	 
           j++;	
		}
		if (found)
		{
        	*(cmd_argument+index) = 0x00;
		     if (ch == '=')
			 {
// Check command number 
  				for (k = 0; k < CMD_NUM ; k++)
				{
					if (!(strcasecmp_P(cmd_argument,&text_cmd[k][0])))  // Found then keep command
					{
						cmd_no  = k+1;   // Start from 0 
						break;
					}
				}
// clear index
  				index = 0;
			    state = WAIT_ARG_STATE;	
			 }	
		}
		else
		{
			*(cmd_argument+index) = ch;
			index++;		
		}
		break;
		
	  case WAIT_ARG_STATE:
		ch = *(buffer+i);
        j = 0; 
		found = 0;
	  	while ((ch2 = pgm_read_byte(&delimiter[j])))   //Check delimiter End with NULL
		{  
		   if ( ch == ch2)
		   {
              found = 1;
              break;
		   } 	 
           j++;	
		}
				
		if ( ch == '"')   // Start quote
		{
			quote ^= 1;   // Toggle quote	
			state = GET_ARG_STATE;   
 			index = 0;
		}
		
		if (!found)    // Not delimiter start get Argument
		{
			state = GET_ARG_STATE;   
			*(cmd_argument) = ch;
			index = 1;
		}
		break;	
	  case	GET_ARG_STATE:
	  	ch = *(buffer+i);
        j = 0; 
		found = 0;
	  	while ((ch2 = pgm_read_byte(&delimiter[j])))   //Check delimiter End with NULL
		{  
		   if ( ch == ch2)
		   {
              found = 1;
              break;
		   } 	 
           j++;	
		}
 		if ( ch == '"')     // End quote
		{
			quote ^= 1;   // Toggle quote	
   		}
		if ( quote)
		{
         	found = 0; //  ignore all characters after the quote until found quote again
// Cancel quote
            
		}	
		if (found)
		{	
            cmd_complete = 1;
			*(cmd_argument+index) = 0;
		    state = WAIT_CMD_STATE;
		}
		else
		{
			*(cmd_argument+index) = ch;
			index++;		
		}  
		break;
	}
	
	if(cmd_complete)   // COmmand both cmd number and argument
	{
		return cmd_no;	 	 
	}
	i++;
 }
  i = 0;
  return 0xFF;  // End of Buffer

}
Example #17
0
void
BetterStream::_vprintf (unsigned char in_progmem, const char *fmt, va_list ap)
{
        unsigned char c;        /* holds a char from the format string */
        unsigned char flags;
        unsigned char width;
        unsigned char prec;
        unsigned char buf[11];  /* size for -1 in octal, without '\0'   */

        for (;;) {

                /*
                 * Process non-format characters
                 */
                for (;;) {
                        c = GETBYTE (in_progmem, 1, fmt);
                        if (!c) return;
                        if (c == '%') {
                                c = GETBYTE (in_progmem, 1, fmt);
                                if (c != '%') break;
                        }
                        /* emit cr before lf to make most terminals happy */
                        if (c == '\n')
                                write('\r');
                        write(c);
                }

                flags = 0;
                width = 0;
                prec = 0;
                
                /*
                 * Process format adjustment characters, precision, width.
                 */
                do {
                        if (flags < FL_WIDTH) {
                                switch (c) {
                                case '0':
                                        flags |= FL_ZFILL;
                                        continue;
                                case '+':
                                        flags |= FL_PLUS;
                                        /* FALLTHROUGH */
                                case ' ':
                                        flags |= FL_SPACE;
                                        continue;
                                case '-':
                                        flags |= FL_LPAD;
                                        continue;
                                case '#':
                                        flags |= FL_ALT;
                                        continue;
                                }
                        }

                        if (flags < FL_LONG) {
                                if (c >= '0' && c <= '9') {
                                        c -= '0';
                                        if (flags & FL_PREC) {
                                                prec = 10*prec + c;
                                                continue;
                                        }
                                        width = 10*width + c;
                                        flags |= FL_WIDTH;
                                        continue;
                                }
                                if (c == '.') {
                                        if (flags & FL_PREC)
                                                return;
                                        flags |= FL_PREC;
                                        continue;
                                }
                                if (c == 'l') {
                                        flags |= FL_LONG;
                                        continue;
                                }
                                if (c == 'h')
                                        continue;
                        }
            
                        break;
                } while ( (c = GETBYTE (in_progmem, 1, fmt)) != 0);

                /*
                 * Handle floating-point formats E, F, G, e, f, g.
                 */
                if (c >= 'E' && c <= 'G') {
                        flags |= FL_FLTUPP;
                        c += 'e' - 'E';
                        goto flt_oper;

                } else if (c >= 'e' && c <= 'g') {

                        int exp;                /* exponent of master decimal digit     */
                        int n;
                        unsigned char vtype;    /* result of float value parse  */
                        unsigned char sign;     /* sign character (or 0)        */
                        unsigned char ndigs;

                        flags &= ~FL_FLTUPP;

                flt_oper:
                        if (!(flags & FL_PREC))
                                prec = 6;
                        flags &= ~(FL_FLTEXP | FL_FLTFIX);
                        if (c == 'e')
                                flags |= FL_FLTEXP;
                        else if (c == 'f')
                                flags |= FL_FLTFIX;
                        else if (prec > 0)
                                prec -= 1;

                        if (flags & FL_FLTFIX) {
                                vtype = 7;              /* 'prec' arg for 'ftoa_engine' */
                                ndigs = prec < 60 ? prec + 1 : 60;
                        } else {
                                if (prec > 7) prec = 7;
                                vtype = prec;
                                ndigs = 0;
                        }
                        exp = __ftoa_engine (va_arg(ap,double), (char *)buf, vtype, ndigs);
                        vtype = buf[0];
    
                        sign = 0;
                        if ((vtype & FTOA_MINUS) && !(vtype & FTOA_NAN))
                                sign = '-';
                        else if (flags & FL_PLUS)
                                sign = '+';
                        else if (flags & FL_SPACE)
                                sign = ' ';

                        if (vtype & (FTOA_NAN | FTOA_INF)) {
                                const char *p;
                                ndigs = sign ? 4 : 3;
                                if (width > ndigs) {
                                        width -= ndigs;
                                        if (!(flags & FL_LPAD)) {
                                                do {
                                                        write(' ');
                                                } while (--width);
                                        }
                                } else {
                                        width = 0;
                                }
                                if (sign)
                                        write(sign);
                                p = PSTR("inf");
                                if (vtype & FTOA_NAN)
                                        p = PSTR("nan");
                                while ( (ndigs = pgm_read_byte((const prog_char *)p)) != 0) {
                                        if (flags & FL_FLTUPP)
                                                ndigs += 'I' - 'i';
                                        write(ndigs);
                                        p++;
                                }
                                goto tail;
                        }

                        /* Output format adjustment, number of decimal digits in buf[] */
                        if (flags & FL_FLTFIX) {
                                ndigs += exp;
                                if ((vtype & FTOA_CARRY) && buf[1] == '1')
                                        ndigs -= 1;
                                if ((signed char)ndigs < 1)
                                        ndigs = 1;
                                else if (ndigs > 8)
                                        ndigs = 8;
                        } else if (!(flags & FL_FLTEXP)) {              /* 'g(G)' format */
                                if (exp <= prec && exp >= -4)
                                        flags |= FL_FLTFIX;
                                while (prec && buf[1+prec] == '0')
                                        prec--;
                                if (flags & FL_FLTFIX) {
                                        ndigs = prec + 1;               /* number of digits in buf */
                                        prec = prec > exp
                                                ? prec - exp : 0;       /* fractional part length  */
                                }
                        }
    
                        /* Conversion result length, width := free space length */
                        if (flags & FL_FLTFIX)
                                n = (exp>0 ? exp+1 : 1);
                        else
                                n = 5;          /* 1e+00 */
                        if (sign) n += 1;
                        if (prec) n += prec + 1;
                        width = width > n ? width - n : 0;
    
                        /* Output before first digit    */
                        if (!(flags & (FL_LPAD | FL_ZFILL))) {
                                while (width) {
                                        write(' ');
                                        width--;
                                }
                        }
                        if (sign) write(sign);
                        if (!(flags & FL_LPAD)) {
                                while (width) {
                                        write('0');
                                        width--;
                                }
                        }
    
                        if (flags & FL_FLTFIX) {                /* 'f' format           */

                                n = exp > 0 ? exp : 0;          /* exponent of left digit */
                                do {
                                        if (n == -1)
                                                write('.');
                                        flags = (n <= exp && n > exp - ndigs)
                                                ? buf[exp - n + 1] : '0';
                                        if (--n < -prec)
                                                break;
                                        write(flags);
                                } while (1);
                                if (n == exp
                                    && (buf[1] > '5'
                                        || (buf[1] == '5' && !(vtype & FTOA_CARRY))) )
                                        {
                                                flags = '1';
                                        }
                                write(flags);
        
                        } else {                                /* 'e(E)' format        */

                                /* mantissa     */
                                if (buf[1] != '1')
                                        vtype &= ~FTOA_CARRY;
                                write(buf[1]);
                                if (prec) {
                                        write('.');
                                        sign = 2;
                                        do {
                                                write(buf[sign++]);
                                        } while (--prec);
                                }

                                /* exponent     */
                                write(flags & FL_FLTUPP ? 'E' : 'e');
                                ndigs = '+';
                                if (exp < 0 || (exp == 0 && (vtype & FTOA_CARRY) != 0)) {
                                        exp = -exp;
                                        ndigs = '-';
                                }
                                write(ndigs);
                                for (ndigs = '0'; exp >= 10; exp -= 10)
                                        ndigs += 1;
                                write(ndigs);
                                write('0' + exp);
                        }

                        goto tail;
                }

                /*
                 * Handle string formats c, s, S.
                 */
                {
                        const char * pnt;
                        size_t size;

                        switch (c) {

                        case 'c':
                                buf[0] = va_arg (ap, int);
                                pnt = (char *)buf;
                                size = 1;
                                goto no_pgmstring;

                        case 's':
                                pnt = va_arg (ap, char *);
                                size = strnlen (pnt, (flags & FL_PREC) ? prec : ~0);
                        no_pgmstring:
                                flags &= ~FL_PGMSTRING;
                                goto str_lpad;

                        case 'S':
                        // pgmstring: // not yet used
                                pnt = va_arg (ap, char *);
                                size = strnlen_P (pnt, (flags & FL_PREC) ? prec : ~0);
                                flags |= FL_PGMSTRING;

                        str_lpad:
                                if (!(flags & FL_LPAD)) {
                                        while (size < width) {
                                                write(' ');
                                                width--;
                                        }
                                }
                                while (size) {
                                        write(GETBYTE (flags, FL_PGMSTRING, pnt));
                                        if (width) width -= 1;
                                        size -= 1;
                                }
                                goto tail;
                        }
                }

                /*
                 * Handle integer formats variations for d/i, u, o, p, x, X.
                 */
                if (c == 'd' || c == 'i') {
                        long x = (flags & FL_LONG) ? va_arg(ap,long) : va_arg(ap,int);
                        flags &= ~(FL_NEGATIVE | FL_ALT);
                        if (x < 0) {
                                x = -x;
                                flags |= FL_NEGATIVE;
                        }
                        c = __ultoa_invert (x, (char *)buf, 10) - (char *)buf;

                } else {
Example #18
0
// sends commands to the motors
// TODO pull code that is common to output_armed_not_stabilizing into helper functions
void AP_MotorsTri::output_armed_stabilizing()
{
    int16_t roll_pwm;                                               // roll pwm value, initially calculated by calc_roll_pwm() but may be modified after, +/- 400
    int16_t pitch_pwm;                                              // pitch pwm value, initially calculated by calc_roll_pwm() but may be modified after, +/- 400
    int16_t throttle_radio_output;                                  // total throttle pwm value, summed onto throttle channel minimum, typically ~1100-1900
    int16_t yaw_radio_output;                                       // final yaw pwm value sent to motors, typically ~1100-1900
    int16_t out_min = _throttle_radio_min + _min_throttle;
    int16_t out_max = _throttle_radio_max;
    int16_t motor_out[AP_MOTORS_MOT_4+1];

    // initialize limits flags
    limit.roll_pitch = false;
    limit.yaw = false;
    limit.throttle_lower = false;
    limit.throttle_upper = false;

    // Throttle is 0 to 1000 only
    int16_t thr_in_min = rel_pwm_to_thr_range(_min_throttle);
    if (_throttle_control_input <= thr_in_min) {
        _throttle_control_input = thr_in_min;
        limit.throttle_lower = true;
    }
    if (_throttle_control_input >= _max_throttle) {
        _throttle_control_input = _max_throttle;
        limit.throttle_upper = true;
    }

    // tricopters limit throttle to 80%
    // To-Do: implement improved stability patch and remove this limit
    if (_throttle_control_input > 800) {
        _throttle_control_input = 800;
        limit.throttle_upper = true;
    }

    roll_pwm = calc_roll_pwm();
    pitch_pwm = calc_pitch_pwm();
    throttle_radio_output = calc_throttle_radio_output();
    yaw_radio_output = calc_yaw_radio_output();

    // if we are not sending a throttle output, we cut the motors
    if( is_zero(_throttle_control_input) ) {
        // range check spin_when_armed
        if (_spin_when_armed_ramped < 0) {
            _spin_when_armed_ramped = 0;
        }
        if (_spin_when_armed_ramped > _min_throttle) {
            _spin_when_armed_ramped = _min_throttle;
        }
        motor_out[AP_MOTORS_MOT_1] = _throttle_radio_min + _spin_when_armed_ramped;
        motor_out[AP_MOTORS_MOT_2] = _throttle_radio_min + _spin_when_armed_ramped;
        motor_out[AP_MOTORS_MOT_4] = _throttle_radio_min + _spin_when_armed_ramped;

    }else{
        int16_t roll_out            = (float)(roll_pwm * 0.866f);
        int16_t pitch_out           = pitch_pwm / 2;

        // check if throttle is below limit
        if (_throttle_control_input <= _min_throttle) {
            limit.throttle_lower = true;
            _throttle_control_input = _min_throttle;
            throttle_radio_output = calc_throttle_radio_output();
        }

        // TODO: set limits.roll_pitch and limits.yaw

        //left front
        motor_out[AP_MOTORS_MOT_2] = throttle_radio_output + roll_out + pitch_out;
        //right front
        motor_out[AP_MOTORS_MOT_1] = throttle_radio_output - roll_out + pitch_out;
        // rear
        motor_out[AP_MOTORS_MOT_4] = throttle_radio_output - pitch_pwm;

        // Tridge's stability patch
        if(motor_out[AP_MOTORS_MOT_1] > out_max) {
            motor_out[AP_MOTORS_MOT_2] -= (motor_out[AP_MOTORS_MOT_1] - out_max);
            motor_out[AP_MOTORS_MOT_4] -= (motor_out[AP_MOTORS_MOT_1] - out_max);
            motor_out[AP_MOTORS_MOT_1] = out_max;
        }

        if(motor_out[AP_MOTORS_MOT_2] > out_max) {
            motor_out[AP_MOTORS_MOT_1] -= (motor_out[AP_MOTORS_MOT_2] - out_max);
            motor_out[AP_MOTORS_MOT_4] -= (motor_out[AP_MOTORS_MOT_2] - out_max);
            motor_out[AP_MOTORS_MOT_2] = out_max;
        }

        if(motor_out[AP_MOTORS_MOT_4] > out_max) {
            motor_out[AP_MOTORS_MOT_1] -= (motor_out[AP_MOTORS_MOT_4] - out_max);
            motor_out[AP_MOTORS_MOT_2] -= (motor_out[AP_MOTORS_MOT_4] - out_max);
            motor_out[AP_MOTORS_MOT_4] = out_max;
        }

        // adjust for thrust curve and voltage scaling
        motor_out[AP_MOTORS_MOT_1] = apply_thrust_curve_and_volt_scaling(motor_out[AP_MOTORS_MOT_1], out_min, out_max);
        motor_out[AP_MOTORS_MOT_2] = apply_thrust_curve_and_volt_scaling(motor_out[AP_MOTORS_MOT_2], out_min, out_max);
        motor_out[AP_MOTORS_MOT_4] = apply_thrust_curve_and_volt_scaling(motor_out[AP_MOTORS_MOT_4], out_min, out_max);

        // ensure motors don't drop below a minimum value and stop
        motor_out[AP_MOTORS_MOT_1] = max(motor_out[AP_MOTORS_MOT_1],    out_min);
        motor_out[AP_MOTORS_MOT_2] = max(motor_out[AP_MOTORS_MOT_2],    out_min);
        motor_out[AP_MOTORS_MOT_4] = max(motor_out[AP_MOTORS_MOT_4],    out_min);
    }

    // send output to each motor
    hal.rcout->write(pgm_read_byte(&_motor_to_channel_map[AP_MOTORS_MOT_1]), motor_out[AP_MOTORS_MOT_1]);
    hal.rcout->write(pgm_read_byte(&_motor_to_channel_map[AP_MOTORS_MOT_2]), motor_out[AP_MOTORS_MOT_2]);
    hal.rcout->write(pgm_read_byte(&_motor_to_channel_map[AP_MOTORS_MOT_4]), motor_out[AP_MOTORS_MOT_4]);

    // send out to yaw command to tail servo
    hal.rcout->write(AP_MOTORS_CH_TRI_YAW, yaw_radio_output);
}
Example #19
0
void usb_serial_write_P(const char* data)
{
  while(pgm_read_byte(data) != 0)
    usb_serial_putchar(pgm_read_byte(data++));
}
Example #20
0
void Tone::begin(uint8_t tonePin)
{
  if (_tone_pin_count < AVAILABLE_TONE_PINS)
  {
    _pin = tonePin;
    _timer = pgm_read_byte(tone_pin_to_timer_PGM + _tone_pin_count);
    _tone_pin_count++;

    // Set timer specific stuff
    // All timers in CTC mode
    // 8 bit timers will require changing prescalar values,
    // whereas 16 bit timers are set to either ck/1 or ck/64 prescalar
    switch (_timer)
    {
#if !defined(__AVR_ATmega8__)
      case 0:
        // 8 bit timer
        TCCR0A = 0;
        TCCR0B = 0;
        bitWrite(TCCR0A, WGM01, 1);
        bitWrite(TCCR0B, CS00, 1);
        timer0_pin_port = portOutputRegister(digitalPinToPort(_pin));
        timer0_pin_mask = digitalPinToBitMask(_pin);
        break;
#endif

      case 1:
        // 16 bit timer
        TCCR1A = 0;
        TCCR1B = 0;
        bitWrite(TCCR1B, WGM12, 1);
        bitWrite(TCCR1B, CS10, 1);
        timer1_pin_port = portOutputRegister(digitalPinToPort(_pin));
        timer1_pin_mask = digitalPinToBitMask(_pin);
        break;
      case 2:
        // 8 bit timer
        TCCR2A = 0;
        TCCR2B = 0;
        bitWrite(TCCR2A, WGM21, 1);
        bitWrite(TCCR2B, CS20, 1);
        timer2_pin_port = portOutputRegister(digitalPinToPort(_pin));
        timer2_pin_mask = digitalPinToBitMask(_pin);
        break;

#if defined(__AVR_ATmega1280__)
      case 3:
        // 16 bit timer
        TCCR3A = 0;
        TCCR3B = 0;
        bitWrite(TCCR3B, WGM32, 1);
        bitWrite(TCCR3B, CS30, 1);
        timer3_pin_port = portOutputRegister(digitalPinToPort(_pin));
        timer3_pin_mask = digitalPinToBitMask(_pin);
        break;
      case 4:
        // 16 bit timer
        TCCR4A = 0;
        TCCR4B = 0;
        bitWrite(TCCR4B, WGM42, 1);
        bitWrite(TCCR4B, CS40, 1);
        timer4_pin_port = portOutputRegister(digitalPinToPort(_pin));
        timer4_pin_mask = digitalPinToBitMask(_pin);
        break;
      case 5:
        // 16 bit timer
        TCCR5A = 0;
        TCCR5B = 0;
        bitWrite(TCCR5B, WGM52, 1);
        bitWrite(TCCR5B, CS50, 1);
        timer5_pin_port = portOutputRegister(digitalPinToPort(_pin));
        timer5_pin_mask = digitalPinToBitMask(_pin);
        break;
#endif
    }
  }
  else
  {
    // disabled
    _timer = -1;
  }
}
Example #21
0
//------------------------------------------------------------------------------
void usart_write_P (const char *Buffer,...)
{
	va_list ap;
	va_start (ap, Buffer);	
	
	int format_flag;
	char str_buffer[10];
	char str_null_buffer[10];
	char move = 0;
	char Base = 0;
	int tmp = 0;
	char by;
	char *ptr;
		
	//Ausgabe der Zeichen
    for(;;)
	{
		by = pgm_read_byte(Buffer++);
		if(by==0) break; // end of format string
            
		if (by == '%')
		{
            by = pgm_read_byte(Buffer++);
			if (isdigit(by)>0)
				{
                                 
 				str_null_buffer[0] = by;
				str_null_buffer[1] = '\0';
				move = atoi(str_null_buffer);
                by = pgm_read_byte(Buffer++);
				}

			switch (by)
				{
                case 's':
                    ptr = va_arg(ap,char *);
                    while(*ptr) { usart_write_char(*ptr++); }
                    break;
				case 'b':
					Base = 2;
					goto ConversionLoop;
				case 'c':
					//Int to char
					format_flag = va_arg(ap,int);
					usart_write_char (format_flag++);
					break;
				case 'i':
					Base = 10;
					goto ConversionLoop;
				case 'o':
					Base = 8;
					goto ConversionLoop;
				case 'x':
					Base = 16;
					//****************************
					ConversionLoop:
					//****************************
					itoa(va_arg(ap,int),str_buffer,Base);
					int b=0;
					while (str_buffer[b++] != 0){};
					b--;
					if (b<move)
						{
						move -=b;
						for (tmp = 0;tmp<move;tmp++)
							{
							str_null_buffer[tmp] = '0';
							}
						//tmp ++;
						str_null_buffer[tmp] = '\0';
						strcat(str_null_buffer,str_buffer);
						strcpy(str_buffer,str_null_buffer);
						}
					usart_write_str (str_buffer);
					move =0;
					break;
				}
			
			}	
		else
		{
Example #22
0
File: lcd.c Project: brfghb/LXR
void lcd_string_F( const char *data )
{
  while (pgm_read_byte(&(*data))!= '\0')
   lcd_data(pgm_read_byte(&(*data++)));
};
Example #23
0
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
unsigned char GLCD_ReadByteFromROMMemory(char * ptr)
{
return pgm_read_byte(ptr);
}
void TFT_ScaleFonts::printChar(byte c, int x, int y, int S)
{
  if (S < 1) S = 1;

  if (S == 1)
  {
    _Disp->printChar(c, x, y);
    return;
  }

  word temp;
  unsigned char ch;

  cbi(_Disp->P_CS, _Disp->B_CS);

  temp = ((c - _Disp->cfont.offset) * ((_Disp->cfont.x_size / 8) * _Disp->cfont.y_size)) + 4;

  for (int Y = 0; Y < ((_Disp->cfont.x_size / 8) * _Disp->cfont.y_size)*S; Y += (_Disp->cfont.x_size / 8) * S)
  {
    for (byte s = 0; s < S; s++)
    {
      _Disp->setXY(x, y + s + (Y / (_Disp->cfont.x_size / 8)), x + _Disp->cfont.x_size * S - 1, y + s + (Y / (_Disp->cfont.x_size / 8)));

      for (int xx = (_Disp->cfont.x_size / 8) - 1; xx >= 0; xx--)
      {
        if (_Disp->orient == LANDSCAPE)
        {
          ch = pgm_read_byte(&_Disp->cfont.font[temp + xx]);
          for (byte i = 0; i < (8 * S) ; i++)
          {
            if ((ch & (1 << (i / S))) != 0)
            {
              _Disp->setPixel((_Disp->fch << 8) | _Disp->fcl);
            }
            else
            {
              if (!_Disp->_transparent)
                _Disp->setPixel((_Disp->bch << 8) | _Disp->bcl);
            }
          }
        }
        else
        {
          ch = pgm_read_byte(&_Disp->cfont.font[temp + 1 - xx]);
          for (byte i = (8 * S) - 1; i > 0 ; i--)
          {
            if ((ch & (1 << (i / S))) != 0)
            {
              _Disp->setPixel((_Disp->fch << 8) | _Disp->fcl);
            }
            else
            {
              if (!_Disp->_transparent)
                _Disp->setPixel((_Disp->bch << 8) | _Disp->bcl);
            }
          }
        }
      }
    }
    temp += (_Disp->cfont.x_size / 8);
  }

  sbi(_Disp->P_CS, _Disp->B_CS);
  _Disp->clrXY();
}
Example #25
0
uint8_t keymap_get_keycode(uint8_t layer, uint8_t row, uint8_t col)
{
    return pgm_read_byte(&keymaps[(layer)][(row)][(col)]);
}
Example #26
0
void parse_SER_buffer(uint8_t EGT_H, uint8_t EGT_L, uint8_t CHT_H, uint8_t CHT_L, uint32_t total_time_RPM)
{
	uint8_t OBD_headers = 0;
	uint16_t RPM_calc;
	uint8_t temp_ringer;
	uint8_t temp_mode;
	uint16_t tempEGTCHT1;
	uint16_t tempEGTCHT2;

	uint8_t ascii_1;
	uint8_t ascii_2;
	uint8_t ascii_3;
	uint8_t ascii_4;
	
	if( (!(RingBuffer_IsEmpty(&BTtoFF_Buffer))))
	{
		
		temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
		
		if(temp_ringer == 'A')
		{
			temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
			
			if(temp_ringer == 'T')	// We now have an AT command to parse
			{
				temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
				
				if(temp_ringer == 'Z')	// Reset command, fake it
				{
					//Serial_SendString_P(ELM327_ID);
					RingBuffer_Insert(&FFtoBT_Buffer,'E');
					RingBuffer_Insert(&FFtoBT_Buffer,'L');
					RingBuffer_Insert(&FFtoBT_Buffer,'M');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					RingBuffer_Insert(&FFtoBT_Buffer,'2');
					RingBuffer_Insert(&FFtoBT_Buffer,'7');
					RingBuffer_Insert(&FFtoBT_Buffer,0X20);	// space
					RingBuffer_Insert(&FFtoBT_Buffer,'v');
					RingBuffer_Insert(&FFtoBT_Buffer,'1');
					RingBuffer_Insert(&FFtoBT_Buffer,'.');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					send_ELM327_CR();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				}
				else if(temp_ringer == 'E')	// Echo Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'M')	// Protocol Memory Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'L')	// Line Feed Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'S')	// Blank Spaces or Store Protocol Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					if(temp_ringer == 'H')	// Set Header
					{
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					}
					else if(temp_ringer == 'P')	// Set Protocol
					{
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// 0 or 1
					}
					
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer		
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'H')	// Headers Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					if(temp_ringer == '1')
					{
						OBD_headers = 1;
					}
					else
					{
						OBD_headers = 0;
					}
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				
				else if(temp_ringer == 'R')	// Responses Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					if(temp_ringer == 'V')
					{
						//Serial_SendString_P(FAKE_VOLTAGE);
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'2');
						RingBuffer_Insert(&FFtoBT_Buffer,'.');
						RingBuffer_Insert(&FFtoBT_Buffer,'6');
						RingBuffer_Insert(&FFtoBT_Buffer,'V');
						send_ELM327_CR();
						send_ELM327_prompt();
					}
					else
					{					
						send_ELM327_OK();
						send_ELM327_prompt();
					}
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'V')	// Variable DLC Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
					
				}
				else if(temp_ringer == '1')	// ATAT1 Adaptive headers Command
				{
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flagg
				
				}
				else if(temp_ringer == '@')	// Blank Spaces Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					if(temp_ringer == '1')	// Descriptor
					{
						//Serial_SendString_P(FF_mini);
						RingBuffer_Insert(&FFtoBT_Buffer,'F');
						RingBuffer_Insert(&FFtoBT_Buffer,'F');
						RingBuffer_Insert(&FFtoBT_Buffer,'m');
						RingBuffer_Insert(&FFtoBT_Buffer,'i');
						RingBuffer_Insert(&FFtoBT_Buffer,'n');
						RingBuffer_Insert(&FFtoBT_Buffer,'i');
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
					else
					{
						send_ELM327_OK();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				
				}
				else if(temp_ringer == 'I')	// ID Yourself command
				{
					//Serial_SendString_P(ELM327_ID);
					RingBuffer_Insert(&FFtoBT_Buffer,'E');
					RingBuffer_Insert(&FFtoBT_Buffer,'L');
					RingBuffer_Insert(&FFtoBT_Buffer,'M');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					RingBuffer_Insert(&FFtoBT_Buffer,'2');
					RingBuffer_Insert(&FFtoBT_Buffer,'7');
					RingBuffer_Insert(&FFtoBT_Buffer,0X20);	// space
					RingBuffer_Insert(&FFtoBT_Buffer,'v');
					RingBuffer_Insert(&FFtoBT_Buffer,'1');
					RingBuffer_Insert(&FFtoBT_Buffer,'.');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					send_ELM327_CR();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
			
			}
		}
	//***********************************************************
	//	Didnt find AT command, so look for OBD command
	//***********************************************************
		else if (temp_ringer == '0')
		{
			temp_mode = RingBuffer_Remove(&BTtoFF_Buffer);
			//SendSERBuffer[temp_USB_indexer++]  = temp_mode;
			switch (temp_mode)
			{
				case '1':	// Mode 01
				temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
				//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
				if ((RingBuffer_Peek(&BTtoFF_Buffer)== '0'))
				{
					RingBuffer_Remove(&BTtoFF_Buffer);	// Removes peeked value above
					//SendSERBuffer[temp_USB_indexer++]  = '0';
					if(temp_ringer == '0')	// What PIDS are supported	0100
					{
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						
						if(OBD_headers)
						{
							send_ELM327_header();		
						}
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						// Supported PIDS below
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('1');	// Support for RPM PID 0x0C
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
					else if (temp_ringer == '2')	// 0120, PIDS 21-40 supported bit mask
					{
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						//Serial_SendByte('2');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'2');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');						
						// Supported PIDS below
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');	// Support for EGT bank PID 0x78
						//Serial_SendByte('1');
						//Serial_SendByte('8');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'8');
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				
					else    // kind of assuming its asking for what we support
					{
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						//Serial_SendByte(temp_ringer);
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,temp_ringer);
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						// Supported PIDS below
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						send_ELM327_CR();	//	CR
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				
				}
			
				else if (temp_ringer == '0')	// 010x
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					
					if(temp_ringer == 'C')		// 010C
					{
						// RPM request
						//if((!first_cycle)&&(total_time_RPM))
						if(total_time_RPM)
						{
							//	This takes the total_time = timer1_OVF + timer1_HIGH + timer1_LOW
							//	and converts to the format required for OBD msg
							//	AND IT NEEDS TO BE OPTIMIZED TOO LARGE!!
							RPM_calc = (uint16_t)(((0xE4E1C000)/total_time_RPM));	
							ascii_4 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
							RPM_calc >>=0x04;
							ascii_3 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
							RPM_calc >>=0x04;
							ascii_2 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
							RPM_calc >>=0x04;
							ascii_1 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
						}
						else
						{
							// IDLE
							ascii_1 = '0';
							ascii_2 = '0';
							ascii_3 = '0';
							ascii_4 = '0';
						}
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						//Serial_SendByte('0');
						//Serial_SendByte('C');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'C');
						//Serial_SendByte(ascii_1);
						//Serial_SendByte(ascii_2);
						//Serial_SendByte(ascii_3);
						//Serial_SendByte(ascii_4);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_1);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_2);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_3);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_4);
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				}
Example #27
0
uint8_t keymap_fn_keycode(uint8_t index)
{
    return pgm_read_byte(&fn_keycode[index]);
}
Example #28
0
/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
 *  documentation) by the application code so that the address and size of a requested descriptor can be given
 *  to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
 *  is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
 *  USB host.
 */
uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
                                    const uint8_t wIndex,
                                    const void** const DescriptorAddress)
{
	const uint8_t  DescriptorType   = (wValue >> 8);
	const uint8_t  DescriptorNumber = (wValue & 0xFF);

	const void* Address = NULL;
	uint16_t    Size    = NO_DESCRIPTOR;

	switch (DescriptorType)
	{
		case DTYPE_Device:
			Address = &DeviceDescriptor;
			Size    = sizeof(USB_Descriptor_Device_t);
			break;
		case DTYPE_Configuration:
			Address = &ConfigurationDescriptor;
			Size    = sizeof(USB_Descriptor_Configuration_t);
			break;
		case DTYPE_String:
			switch (DescriptorNumber)
			{
				case 0x00:
					Address = &LanguageString;
					Size    = pgm_read_byte(&LanguageString.Header.Size);
					break;
				case 0x01:
					Address = &ManufacturerString;
					Size    = pgm_read_byte(&ManufacturerString.Header.Size);
					break;
				case 0x02:
					Address = &ProductString;
					Size    = pgm_read_byte(&ProductString.Header.Size);
					break;
			}

			break;
/*		case HID_DTYPE_HID:
			Address = &ConfigurationDescriptor.HID_HIDData;
			Size    = sizeof(USB_HID_Descriptor_HID_t);			
			break;
		case HID_DTYPE_Report:
			Address = &HIDReport;
			Size    = sizeof(HIDReport);
			break; */
		case HID_DTYPE_HID:
			if (wIndex == 0)
			{
				Address = &ConfigurationDescriptor.HID1_KeyboardHID;
				Size    = sizeof(USB_HID_Descriptor_HID_t);
			}
			else if (wIndex == 1)
			{
				Address = &ConfigurationDescriptor.HID2_MacroHID;
				Size    = sizeof(USB_HID_Descriptor_HID_t);
			}
			else //wIndex is 2; media report
			{
				Address = &ConfigurationDescriptor.HID3_MediaHID;
				Size    = sizeof(USB_HID_Descriptor_HID_t);
			}

			break;
		case HID_DTYPE_Report:
			if (wIndex == 0)
			{
				Address = &KeyboardReport;
				Size    = sizeof(KeyboardReport);
			}
			else if (wIndex == 1)
			{
				Address = &MacroReport;
				Size    = sizeof(MacroReport);
			}
			else //wIndex is 2; media report
			{
				Address = &MediaReport;
				Size    = sizeof(MediaReport);
			}

			break;
	}

	*DescriptorAddress = Address;
	return Size;
}
Example #29
0
char Stepper::get_current_output()
{
	return pgm_read_byte(&OUTPUT_VALUES[this->current_step]);
}
Example #30
0
/**
 * commandParser parse commands received by the twi interface and trigger the
 * associated functions
 */
void parse_cmd(uint8_t cmd[CMD_SIZE])
{
    uint8_t i;

    /* Check new conditions and update status from tuxaudio */
    if (cmd[0] == SEND_AUDIOSENSORS_CMD)
    {
        if ((cmd[1] & STATUS_HEADBTN_MK)
            && !(gStatus.sw & GSTATUS_HEADBTN_MK))
            cond_flags.head = 1;
        if ((cmd[1] & STATUS_LEFTWINGBTN_MK)
            && !(gStatus.sw & GSTATUS_LEFTWINGBTN_MK))
            cond_flags.left_flip = 1;
        if ((cmd[1] & STATUS_RIGHTWINGBTN_MK)
            && !(gStatus.sw & GSTATUS_RIGHTWINGBTN_MK))
            cond_flags.right_flip = 1;
        if ((cmd[1] & STATUS_CHARGER_MK)
            && !(gStatus.sw & GSTATUS_CHARGER_MK))
            cond_flags.charger_start = 1;
        if (!(cmd[1] & STATUS_POWERPLUGSW_MK)
            && (gStatus.sw & GSTATUS_POWERPLUGSW_MK))
            cond_flags.unplug = 1;
        if ((cmd[1] & STATUS_RF_MK) && !(gStatus.sw & GSTATUS_RF_MK))
        {
            cond_flags.rf_conn = 1;
            cond_flags.rf_disconn = 0;
        }
        if (!(cmd[1] & STATUS_RF_MK) && (gStatus.sw & GSTATUS_RF_MK))
        {
            cond_flags.rf_conn = 0;
            cond_flags.rf_disconn = 1;
        }
        gStatus.sw = cmd[1];
        gStatus.audio_play = cmd[2];
        gStatus.audio_status = cmd[3];
        return;
    }
    /* Ping */
    else if (cmd[0] == PING_CMD)
    {
        pingCnt = cmd[1];
        return;
    }
    /* Sound */
    else if (cmd[0] == PLAY_SOUND_CMD)
    {
        /* Forward the cmd to the audio CPU. */
        queue_cmd(cmd);
        return;
    }
    else if (cmd[0] == MUTE_CMD)
    {
        /* Forward the cmd to the audio CPU. */
        queue_cmd(cmd);
        return;
    }
    /* Sleep mode */
    else if (cmd[0] == SLEEP_CMD)
    {
        cond_flags.sleep = true;
        return;
    }
    /* Version */
    else if (cmd[0] == INFO_TUXCORE_CMD)
    {
        uint8_t *p = (uint8_t *) &tag_version;
        uint8_t info[12];

        for (i = 0; i < 12; i++)
            info[i] = pgm_read_byte(p++);
        queue_cmd(&info[0]);
        queue_cmd(&info[4]);
        queue_cmd(&info[8]);
        return;
    }
    /* Reset condition flags */
    else if (cmd[0] == COND_RESET_CMD)
    {
        uint8_t *addr = (uint8_t *) & cond_flags;

        for (i = 0; i < COND_RESET_NBR; i++)
            *addr++ = 0;
        return;
    }
    else if (cmd[0] == LED_FADE_SPEED_CMD)
    {
        led_set_fade_speed(cmd[1], cmd[2], cmd[3]);
    }
    else if (cmd[0] == LED_SET_CMD)
    {
        led_set_intensity(cmd[1], cmd[2]);
    }
    else if (cmd[0] == IR_SEND_RC5_CMD)
    {
        irSendRC5(cmd[1], cmd[2]);
    }
    else if (cmd[0] == MOTORS_CONFIG_CMD)
    {
        motors_config(cmd[1], cmd[2]);
    }
    /* Leds */
    else if (cmd[0] == LED_PULSE_RANGE_CMD)
    {
        led_pulse_range(cmd[1], cmd[2], cmd[3]);
    }
    /* Move */
    else
    {
        if (cmd[0] == MOTORS_SET_CMD)
        {
            motors_run(cmd[1], cmd[2], cmd[3]);
        }
        else if (cmd[0] == LED_PULSE_CMD)
        {
            led_pulse(cmd[1], cmd[2], cmd[3]);
        }

        /* Deprecated functions, though they can be kept for the standalone as
         * they're simpler than the other LED functions. */
        else if (cmd[0] == LED_ON_CMD)
        {
            led_set_intensity(LED_BOTH, 0xFF);
        }
        else if (cmd[0] == LED_OFF_CMD)
        {
            led_set_intensity(LED_BOTH, 0x0);
        }
        else if (cmd[0] == LED_TOGGLE_CMD)
        {
            leds_toggle(cmd[1], cmd[2]);
        }
        /* Moves */
        else if (cmd[0] == BLINK_EYES_CMD)
        {
            blink_eyes(cmd[1]);
        }
        else if (cmd[0] == STOP_EYES_CMD)
        {
            stop_eyes();
        }
        else if (cmd[0] == OPEN_EYES_CMD)
        {
            open_eyes();
        }
        else if (cmd[0] == CLOSE_EYES_CMD)
        {
            close_eyes();
        }
        else if (cmd[0] == MOVE_MOUTH_CMD)
        {
            move_mouth(cmd[1]);
        }
        else if (cmd[0] == OPEN_MOUTH_CMD)
        {
            open_mouth();
        }
        else if (cmd[0] == CLOSE_MOUTH_CMD)
        {
            close_mouth();
        }
        else if (cmd[0] == STOP_MOUTH_CMD)
        {
            stop_mouth();
        }
        else if (cmd[0] == WAVE_WINGS_CMD)
        {
            wave_flippers(cmd[1], cmd[2]);
        }
        else if (cmd[0] == RAISE_WINGS_CMD)
        {
            raise_flippers();
        }
        else if (cmd[0] == LOWER_WINGS_CMD)
        {
            lower_flippers();
        }
        else if (cmd[0] == RESET_WINGS_CMD)
        {
            reset_flippers();
        }
        else if (cmd[0] == STOP_WINGS_CMD)
        {
            stop_flippers();
        }
        else if (cmd[0] == SPIN_LEFT_CMD)
        {
            spin_left(cmd[1], cmd[2]);
        }
        else if (cmd[0] == SPIN_RIGHT_CMD)
        {
            spin_right(cmd[1], cmd[2]);
        }
        else if (cmd[0] == STOP_SPIN_CMD)
        {
            stop_spinning();
        }
        /* Undefined commands */
        else
            return;                 /* simply drop it */

        /* Send an updated status here for functions that need it */
        updateStatusFlag = 1;
    }
}