コード例 #1
0
ファイル: gsmModem.c プロジェクト: WarrenDGreenway/pygmyos
void modemInit( void )
{
    
    //pinConfig( PA2, ALT );
    //pinConfig( PA3, IN );
   
    //USART2->BRR = 24000000/ 115200; //( ( (ulClock >> 3 ) / BOOT_BAUDRATE ) << 4 ) + ( ( ( ulClock / BOOT_BAUDRATE ) ) & 0x0007 );
    //USART2->CR3  = 0;//|= USART_ONEBITE;
    //USART2->CR1 = ( USART_UE | USART_RXNEIE | USART_TE | USART_RE  );

    comConfig( COM2, 0, RTS|CTS, 19200 );
    
    streamEnableActionChars( COM2 );
    streamSetActionChars( COM2, (u8*)AT_ACTIONCHARS );
    streamSetGet( MODEM_COM, cmdGetsModem );
    streamSetRXBuffer( MODEM_COM, globalCOM2RXBuffer, __PYGMYCOM2BUFFERLEN );
    streamSetPut( MODEM_COM, putsUSART2 );
    pinConfig( D1, OUT );
    pinConfig( D0, OUT );
    pinSet( D1, LOW );
    pinSet( D0, LOW );
    pinConfig( D3, IN );
    pinConfig( T1, OUT );
    
    //pinSet( D0, HIGH );
    //delay( 15000 );
    //pinSet( D0, LOW );
 
    pinInterrupt( blink, D3, TRIGGER_RISING|TRIGGER_FALLING, 7  );  
    cmdInitQueue( &globalModemQueue );
    taskNew( "modemcmd", 500, 500, 0, (void*)DriverThread_ProcessCommands );
}
コード例 #2
0
/**
  * @brief  digitalWrite Write value to GPIO Arduino pin 
  * @param  pin number, value to write HIGH or LOW
  * @retval None
  */
void digitalWrite(uint16_t pin, uint16_t value) {
  uint16_t L_oldType = ArduinoPort[pin].PinMode; //Does the pin already configured
  /* Check the parameters */
  assert_param(IS_ARDUINO_PIN(pin));

  
  //If pin has not been configured or configured as INPUT only
  if(L_oldType == INPUT || L_oldType == NOT_CONFIGURED) { 
    //Set the pull_up/down regarding value to write
    if(value == HIGH) {
      pinConfig(pin,INPUT_PU);
    }
    if(value == LOW) {
      pinConfig(pin,INPUT_PD);
    }    
  }
  if(!(L_oldType & 0x0001)) {
    //If pin is configured as OUTPUT mode but not AF or AN
    if(L_oldType != OUTPUT_AF && L_oldType != OUTPUT_AN) {
      if(value == HIGH) {
        GPIO_SetBits(ArduinoPort[pin].GPIOx, ArduinoPort[pin].PinNum);
      }
      if(value == LOW) {
        GPIO_ResetBits(ArduinoPort[pin].GPIOx, ArduinoPort[pin].PinNum);
      }     
    }
  }
    
}
コード例 #3
0
ファイル: hih5030.c プロジェクト: WarrenDGreenway/pygmyos
void hih5030Init( u8 ucAnalogPin, u8 ucPowerPin )
{
    globalHumidityCR = 1;
    globalHumidityPin = ucAnalogPin;
    globalHumidityPower = ucPowerPin;
    pinConfig( ucAnalogPin, ANALOG );
    if( ucPowerPin != NONE ){
        pinConfig( ucPowerPin, OUT );
        pinSet( ucPowerPin, HIGH );
    } // if
}
コード例 #4
0
ファイル: memreg.c プロジェクト: TiddoLangerak/mmc_test
/******************************************************************************
 *
 * Description:
 *    Initialize the NOR Flash
 *
 *****************************************************************************/
uint32_t memreg_init (void)
{
  LPC_SC->PCONP      |= 0x00000800;

  LPC_EMC->Control = 0x00000001;

  LPC_EMC->Config  = 0x00000000;


  pinConfig();

  LPC_EMC->StaticConfig2   = 0x00000001;
#if 0
  LPC_EMC->StaticWaitWen2  = 0x00000003; /* ( n + 1 ) -> 4 clock cycles */
  LPC_EMC->StaticWaitOen2  = 0x00000003; /* ( n ) -> 0 clock cycles */
  LPC_EMC->StaticWaitRd2   = 0x00000006; /* ( n + 1 ) -> 7 clock cycles */
  LPC_EMC->StaticWaitPage2 = 0x00000003; /* ( n + 1 ) -> 4 clock cycles */
  LPC_EMC->StaticWaitWr2   = 0x00000005; /* ( n + 2 ) -> 7 clock cycles */
  LPC_EMC->StaticWaitTurn2 = 0x00000003; /* ( n + 1 ) -> 4 clock cycles */
#endif



  return FALSE;
}
コード例 #5
0
/**
  * @brief  pwmFrequency set pwm output frequency  
  * @param  pin number,  frequency in Hz
  * @retval None
  */
void pwmFrequency(uint16_t pin, uint16_t frequency){
  uint16_t L_oldType = ArduinoPort[pin].PinMode; //Does the pin already configured?
  /* Check the parameters */
  assert_param(IS_PWM_PIN(pin));

  if(L_oldType != OUTPUT_AF){
  //Pin was not correctly configured! Do it first!
    pinConfig(pin, OUTPUT_AF);
  }
  
  //Set pwm frequency 
   ArduinoPort[pin].pwmPeriod = (SystemCoreClock / frequency ) - 1;
   switch(pin){
      case 3:
        TIM2->ARR = ArduinoPort[pin].pwmPeriod;
        break;
      case 5:
        TIM17->ARR = ArduinoPort[pin].pwmPeriod;
        break;
      case 6:
        TIM16->ARR = ArduinoPort[pin].pwmPeriod;
        break;
      case 9:
        TIM14->ARR = ArduinoPort[pin].pwmPeriod;
        break;
      case 10:
        TIM1->ARR = ArduinoPort[pin].pwmPeriod;
        break;
      case 11:
        TIM3->ARR = ArduinoPort[pin].pwmPeriod;
        break;
      default:
        break;
    }       
}
コード例 #6
0
ファイル: device.cpp プロジェクト: Inner-room/libdshowcapture
bool HDevice::SetupAudioCapture(IBaseFilter *filter, AudioConfig &config)
{
	ComPtr<IPin>  pin;
	MediaTypePtr  defaultMT;
	bool          success;
	HRESULT       hr;

	success = GetFilterPin(filter, MEDIATYPE_Audio, PIN_CATEGORY_CAPTURE,
			PINDIR_OUTPUT, &pin);
	if (!success) {
		Error(L"Could not get audio pin");
		return false;
	}

	ComQIPtr<IAMStreamConfig> pinConfig(pin);

	if (config.useDefaultConfig) {
		MediaTypePtr defaultMT;

		if (pinConfig && SUCCEEDED(pinConfig->GetFormat(&defaultMT))) {
			audioMediaType = defaultMT;
		} else {
			if (!SetupExceptionAudioCapture(pin)) {
				Error(L"Could not get default format for "
				      L"audio pin");
				return false;
			}
		}
	} else {
		if (!GetClosestAudioMediaType(filter, config, audioMediaType)) {
			Error(L"Could not get closest audio media type");
			return false;
		}
	}

	if (!!pinConfig) {
		hr = pinConfig->SetFormat(audioMediaType);

		if (FAILED(hr) && hr != E_NOTIMPL) {
			Error(L"Could not set audio format");
			return false;
		}
	}

	ConvertAudioSettings();

	PinCaptureInfo info;
	info.callback          = [this] (IMediaSample *s) {Receive(false, s);};
	info.expectedMajorType = audioMediaType->majortype;
	info.expectedSubType   = audioMediaType->subtype;

	audioCapture = new CaptureFilter(info);
	audioFilter  = filter;
	audioConfig  = config;

	graph->AddFilter(audioCapture, L"Audio Capture Filter");
	if (!config.useVideoDevice)
		graph->AddFilter(audioFilter, L"Audio Filter");
	return true;
}
コード例 #7
0
void lcdInit( void )
{
    pinConfig( LCD_SDA, OUT );
    pinConfig( LCD_SCL, OUT );
    pinConfig( LCD_RS, OUT );
    pinConfig( LCD_CS, OUT );
    pinConfig( LCD_PSB, OUT );
    pinConfig( LCD_PSI2B, OUT );
    pinConfig( LCD_BL, OUT );
    pinSet( LCD_BL, HIGH );
    pinSet( LCD_RS, HIGH );
    pinSet( LCD_CS, HIGH );
    // SPI
    pinSet( LCD_PSB, LOW );
    pinSet( LCD_PSI2B, HIGH );

    lcdWriteCommand( 0x38 );   //FUNCTION SET 8 bit,N=1 2-line display mode,5*7dot
    delay( 100 );
    lcdWriteCommand( 0x39 );  //FUNCTION SET 8 bit,N=1 2-line display mode,5*7dot IS=1
    delay( 100 );
    lcdWriteCommand( 0x1c );   //Internal OSC frequency adjustment 183HZ    bias will be 1/4
    delay( 100 );
    lcdWriteCommand( 0x73 );    //Contrast control  low byte
    delay( 100 );
    lcdWriteCommand( 0x57 );    //booster circuit is turn on.    /ICON display off. /Contrast control   high byte
    delay( 100 );
    lcdWriteCommand( 0x6c );  //Follower control
    delay( 1000 );
    lcdWriteCommand( 0x0c );    //DISPLAY ON
    delay( 100 );
    lcdWriteCommand( 0x01 );   //CLEAR DISPLAY
    delay( 10000 );
    lcdWriteCommand( 0x06 );   //ENTRY MODE SET  CURSOR MOVES TO RIGHT
    delay( 100 );
}
コード例 #8
0
ファイル: pin.c プロジェクト: LORDofDOOM/LARD
uint32 pinSetAsDigitalOutput(uint32 pin) {

	uint32 retval = 0;

	retval |= _pinSetGpioBit (pin, GPIOREG_DIR);
	retval |= pinFunc (pin, FUNC_GPIO);
	retval |= pinConfig (pin, PIN_ADMODE_DISABLED);

	return (retval);

}
コード例 #9
0
ファイル: pin.c プロジェクト: LORDofDOOM/LARD
uint32 pinSetAsAnalogInput(uint32 pin) {

	uint32 retval = 0;

	retval |= _pinClearGpioBit (pin, GPIOREG_DIR);
	retval |= pinFunc (pin, FUNC_ADC);
	retval |= pinConfig (pin, PIN_ADMODE_ENABLED | PIN_MODE_NOPULLUP);

	return (retval);

}
コード例 #10
0
ファイル: pygmy_rf.c プロジェクト: WarrenDGreenway/pygmyos
void rfInit( void )
{
    spiConfig( &pygmyRFSPI, RF_CS, RF_SCK, RF_MISO, RF_MOSI, 0 );
    pinConfig( RF_EN, OUT );
    RF_EN_LOW;
    pinConfig( RF_IRQ, PULLUP );
    pinInterrupt( rfRX, RF_IRQ, TRIGGER_FALLING, 3 );
    //spiPutChar( &pygmyRFSPI, RF_WRITE|RF_REG_SETUP_RETR, 0x0F );
    RF_CS_LOW;
    spiWriteByte( &pygmyRFSPI, RF_WRITE|RF_REG_SETUP_RETR );
    spiWriteByte( &pygmyRFSPI, 0x0F ); // 15 retries, 250 microsec delay between tries
    RF_CS_HIGH;
    //rfSetTXPower( RF_2MBPS, 0 );
    //spiPutChar( &pygmyRFSPI, RF_WRITE|RF_REG_ENRXADDR, BIT0 );
    RF_CS_LOW;
    spiWriteByte( &pygmyRFSPI, RF_WRITE|RF_REG_ENRXADDR );
    spiWriteByte( &pygmyRFSPI, BIT0 );
    RF_CS_HIGH;
    //spiPutChar( &pygmyRFSPI, RF_WRITE|RF_REG_DYNPD, BIT0 );
    RF_CS_LOW;
    spiWriteByte( &pygmyRFSPI, RF_WRITE|RF_REG_DYNPD );
    spiWriteByte( &pygmyRFSPI, BIT0 );
    RF_CS_HIGH;
    //spiPutChar( &pygmyRFSPI, RF_WRITE|RF_REG_FEATURE, RF_REG_FEATURE_EN_DPL );
    RF_CS_LOW;
    spiWriteByte( &pygmyRFSPI, RF_WRITE|RF_REG_FEATURE );
    spiWriteByte( &pygmyRFSPI, RF_REG_FEATURE_EN_DPL );
    RF_CS_HIGH;
    //spiPutChar( &pygmyRFSPI, RF_WRITE|RF_REG_ENAA, BIT0 );
    RF_CS_LOW;
    spiWriteByte( &pygmyRFSPI, RF_WRITE|RF_REG_ENAA );
    spiWriteByte( &pygmyRFSPI, BIT0 );
    RF_CS_HIGH;
    rfFlushTX();
    rfFlushRX();
    
    rfWriteAddress( RF_REG_TXADDR, (u8*)ucAddrP0 );
    rfWriteAddress( RF_REG_RXADDR_P0, (u8*)ucAddrP0 );
    rfSetRX();
}
コード例 #11
0
ファイル: main.cpp プロジェクト: sensaura-public/sensnode
/** Program entry point
 */
int main() {
  // First configure and latch our power pin.
  pinConfig(PIN_LATCH, DIGITAL_OUTPUT, 1);
  pinWrite(PIN_LATCH, true);
  // Call all the constructors
  for(void (**p)() = __init_array_start; p < __init_array_end; ++p)
    (*p)();
  // Set up the rest of the power head pins
  pinConfig(PIN_INDICATOR, DIGITAL_OUTPUT, 0);
  pinWrite(PIN_INDICATOR, false);
  pinConfig(PIN_ACTION, DIGITAL_INPUT, WAKEUP);
  pinConfig(PIN_BATTERY, ANALOG);
  // Show we are on (2s indicator LED)
//  indicate(PATTERN_FULL, false);
  // TODO: Internal setup
  // Application setup
  setup();
  // Main loop
  while(true)
    mainLoop(true);
  return 0;
  }
コード例 #12
0
ファイル: nokia5110.c プロジェクト: WarrenDGreenway/pygmyos
void lcdInit( void )
{	
    spiConfig( &pygmyLCD, LCD_CS, LCD_SCK, NONE, LCD_MOSI );
    pinConfig( LCD_RESET, OUT ); // We will use USART1_RTS as CS
    pinConfig( LCD_A0, OUT );
   
    pinSet( LCD_RESET, LOW );
    delay( 2000 ); // microseconds
    pinSet( LCD_RESET, HIGH );
    delay( 2000 ); // microseconds
    lcdWriteCommand( LCD_FUNCSET | LCD_FUNCSET_H ); 
    lcdWriteCommand( LCD_SETVOP | 55 );   
    lcdWriteCommand( LCD_TEMPCONTROL ); 
    lcdWriteCommand( LCD_BIAS | LCD_BIAS_BS1|LCD_BIAS_BS0 );
    lcdWriteCommand( LCD_FUNCSET ); 
    lcdWriteCommand( LCD_DISPCONTROL | LCD_DISPCONTROL_D ); 
    lcdSetBPP( PYGMY_PBM_1BPP );
    lcdSetColor( 0xFF, 0xFF, 0xFF );
    lcdBackColor( 0x00, 0x00, 0x00 );
    lcdClear();
    drawAll();
}
コード例 #13
0
/** Initialise the LCD display
 *
 * @param dc the comand/data pin
 * @param reset the reset pin
 * @param sel device select pin
 */
void lcdInit(PIN dc, PIN reset, PIN sel) {
  // Save the pins
  pinConfig(dc, DIGITAL_OUTPUT, 0);
  g_dc = dc;
  pinConfig(reset, DIGITAL_OUTPUT, 0);
  g_reset = reset;
  pinConfig(sel, DIGITAL_OUTPUT, 1);
  g_sel = sel;
  // Reset the LCD
  pinWrite(g_reset, true);
  // Initialise the LCD
  spiConfig(false, true, true);
  pinWrite(g_sel, false);
  sendCommand(0x21);  // LCD Extended Commands.
  sendCommand(0xB1);  // Set LCD Vop (Contrast) 0xB1/0xA1.
  sendCommand(0x04);  // Set Temp coefficent. //0x04
  sendCommand(0x14);  // LCD bias mode 1:48. //0x13
  sendCommand(0x0C);  // Normal display, horizontal addressing
  sendCommand(0x20);  // LCD Normal commands
  sendCommand(0x0C);  // Normal display, horizontal addressing
  // Deselect the display
  pinWrite(g_sel, true);
  }
コード例 #14
0
// Un-export any Sysfs pins used; don't leave filesystem cruft.  Also
// restores any GND pins to inputs.  Write errors are ignored as pins
// may be in a partially-initialized state.
void cleanup() {
	char buf[50];
	int  fd, i;
	sprintf(buf, "%s/unexport", sysfs_root);
	if((fd = open(buf, O_WRONLY)) >= 0) {
		for(i=0; i<IOLEN; i++) {
			// Restore GND items to inputs
			if(io[i].key == GND)
				pinConfig(io[i].pin, "direction", "in");
			// And un-export all items regardless
			sprintf(buf, "%d", io[i].pin);
			write(fd, buf, strlen(buf));
		}
		close(fd);
	}
}
コード例 #15
0
ファイル: main.c プロジェクト: jkitt84/code_compose_workspace
void main(void)
{
 // setup
 WDTCTL = WDTPW + WDTHOLD;
 clockConfig();
 pinConfig();
 spiConfig();
    // program execution loop
 while (1)
 {
setPotValue(potLevel);
   __delay_cycles(100000); // I know, there are better ways...
    }



}
コード例 #16
0
/**
 *	Initializes the hardware/software SD card module. If the SD card is not 
 *	inserted, loops waiting to mount it until the SD ready is ready.
 *
 *	\param int pin_sck - pin used as SPI SCLK signal
 *	\param int pin_si  - pin used as SPI MISO signal
 *	\param int pin_so  - pin used as SPI MOSI  signal
 *	\param int pin_cs  - pin used as SD Chip Select signal
 *	\param int pin_cd  - pin used as SD Card Detect signal
 *	\param BYTE _nTimeout - timeout of operation (expressed in about 0.1 sec scale, 255 to wait forever)
 *	\return
 *	BOOL result of operation
 */	
BOOL SDInit(int pin_sck, int pin_si, int pin_so, int pin_cs, int pin_cd, BYTE timeout)
{
	BYTE timecnt = 0;
	//	SD hardware initialization
	pinConfig(pin_sck, pin_si, pin_so, pin_cs, pin_cd);
			
	SDdebug("Initializing SD card...\r\n");

	if (diskMount())
		SDdebug("SD software module initialized!\r\n");
	else
		SDdebug("SD software module NOT initialized!\r\n");
		
	// Check to detect SD card insertion
	while (disk_status(0))
	{
		diskUnmount();
		vTaskDelay(5);
		SDdebug(".");
		diskMount();
		timecnt++;
		if ( (timecnt == timeout) && (timeout < 255) )
			break;
		vTaskDelay(5);
	}
	
	if (!disk_status(0))
	{
		SDdebug("SD card initialized and ready!\r\n");
		setSdErr(0);
		fileInit();
		sdInitOk = TRUE;
		return TRUE;
	}
	else 
	{
		SDdebug("ERROR\n");
		if (sdDetect())
			setSdErr(SD_FS_NOT_INIT);
		else
			setSdErr(SD_NOT_PRESENT);
		sdInitOk = FALSE;
		return FALSE;
	}
}
コード例 #17
0
/******************************************************************************
 *
 * Description:
 *    Initialize the touch controller
 *
 *****************************************************************************/
void touch_init (void)
{
  uint8_t data[3];
  //SSP_CFG_Type SSP_ConfigStruct;
  //SSP_DATA_SETUP_Type sspCfg;

  pinConfig();
  CS_OFF;

	// initialize SSP configuration structure to default
	//SSP_ConfigStructInit(&SSP_ConfigStruct);

  // set clock rate
//  SSP_ConfigStruct.ClockRate = SSP_CLOCK;
//  SSP_ConfigStruct.CPHA = SSP_CPHA_SECOND;
//  SSP_ConfigStruct.CPOL = SSP_CPOL_LO;
//
//	// Initialize SSP peripheral with parameter given in structure above
//	SSP_Init(SSP_PORT, &SSP_ConfigStruct);
//
//	// Enable SSP peripheral
//	SSP_Cmd(SSP_PORT, ENABLE);

  // initialize SSP
  Chip_SSP_Init(SSP_ID);
  Chip_SSP_SetMaster(SSP_ID, true);
  Chip_SSP_SetBitRate(SSP_ID, SSP_CLOCK);
  Chip_SSP_SetFormat(SSP_ID, SSP_BITS_8, SSP_FRAMEFORMAT_SPI, SSP_CLOCK_MODE3);
  Chip_SSP_Enable(SSP_ID);


  data[0] = REF_ON;
  data[1] = (READ_12BIT_SER(ADS_A2A1A0_vaux) | ADS_PD10_ALL_ON);
  data[2] = PWRDOWN;
  CS_ON;

  //sspCfg.tx_data = data;
  //sspCfg.rx_data = NULL;
  //sspCfg.length  = 3;

  //SSP_ReadWrite (SSP_PORT, &sspCfg, SSP_TRANSFER_POLLING);
  Chip_SSP_WriteFrames_Blocking(SSP_ID, data, 3);
  CS_OFF;
}
コード例 #18
0
/**
  * @brief  analogWrite generate pwm output based on value  
  * @param  pin number, value = % of max possible output 
  * @retval None
  */
void analogWrite(uint16_t pin, uint16_t value){
  uint16_t L_oldType = ArduinoPort[pin].PinMode; //Does the pin already configured?
  uint16_t ChannelPulse;
  /* Check the parameters */
  assert_param(IS_PWM_PIN(pin));

  if(L_oldType != OUTPUT_AF){
  //Pin was not correctly configured! Do it first!
    pinConfig(pin, OUTPUT_AF);
  }
  
  ChannelPulse = (uint16_t) (((uint32_t)value * (ArduinoPort[pin].pwmPeriod - 1)) / 100);
   switch(pin){
      case 3:
        TIM2->CCR4 = ChannelPulse;
        break;
      case 5:
        TIM17->CCR1 = ChannelPulse;
        break;
      case 6:
        TIM16->CCR1 = ChannelPulse;
        break;
      case 9:
        TIM14->CCR1 = ChannelPulse;
        break;
      case 10:
        TIM1->CCR4 = ChannelPulse;
        break;
      case 11:
        TIM3->CCR2 = ChannelPulse;
        break;
      default:
        break;
    } 
   
}
コード例 #19
0
ファイル: main.c プロジェクト: mattairtech/ArduinoCore-samd
/**
 *  \brief SAMD21 SAM-BA Main loop.
 *  \return Unused (ANSI-C compatibility).
 */
int main(void)
{
#if SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY  ||  SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES
  P_USB_CDC pCdc;
#endif
  DEBUG_PIN_HIGH;

  /* Jump in application if condition is satisfied */
  check_start_application();

  /* We have determined we should stay in the monitor. */

  /* System initialization */
  board_init();
  __enable_irq();

  /* Initialize LEDs */
  LED_init();
  #if !defined(BOARD_LED_FADE_ENABLED)
  LED_on();
  #endif
  LEDRX_init();
  LEDRX_off();
  LEDTX_init();
  LEDTX_off();

  /* Start the sys tick (20 us) */
  SysTick_Config(VARIANT_MCK / 50000);


/* If SDCARD_ENABLED defined, read optional external pins and run SD Card bootloader (if enabled).
 */
  #if defined(SDCARD_ENABLED)
    uint8_t bootloaderMode = SD_BOOTLOADER_MODE_NO_UPDATE;
    #if defined(SAM_BA_INTERFACE_USE_PIN)
      uint8_t sdcardStatus = SD_BOOTLOADER_NOT_CALLED;
    #endif

    #if defined(SDCARD_USE_PIN1)
      pinConfig(SDCARD_PIN1_PORT, SDCARD_PIN1_PIN, SDCARD_PIN1_CONFIG);
    #endif
    #if defined(SDCARD_USE_PIN2)
      #if !defined(SDCARD_USE_PIN1)
        #error "main.c: When SDCARD_USE_PIN2 is defined, SDCARD_USE_PIN1 must also be defined"
      #endif
      pinConfig(SDCARD_PIN2_PORT, SDCARD_PIN2_PIN, SDCARD_PIN2_CONFIG);
    #endif

    #if (defined(SDCARD_USE_PIN1) && defined(SDCARD_USE_PIN2))
      bool pin1 = isPinActive(SDCARD_PIN1_PORT, SDCARD_PIN1_PIN, SDCARD_PIN1_POLARITY);
      bool pin2 = isPinActive(SDCARD_PIN2_PORT, SDCARD_PIN2_PIN, SDCARD_PIN2_POLARITY);
      if (pin1) {
        bootloaderMode = SD_BOOTLOADER_MODE_UPDATE;
      } else if (pin2) {
        bootloaderMode = SD_BOOTLOADER_MODE_UPDATE2;
      }
    #elif defined(SDCARD_USE_PIN1)
      if (isPinActive(SDCARD_PIN1_PORT, SDCARD_PIN1_PIN, SDCARD_PIN1_POLARITY)) {
        bootloaderMode = SD_BOOTLOADER_MODE_UPDATE;
      }
    #else
      bootloaderMode = SD_BOOTLOADER_MODE_UPDATE;
    #endif

    if (bootloaderMode != SD_BOOTLOADER_MODE_NO_UPDATE) {
    #if defined(SAM_BA_INTERFACE_USE_PIN)
      sdcardStatus = sdBootloader(bootloaderMode);
    #else
      sdBootloader(bootloaderMode);
    #endif
    }
  #endif

/* When using SAM_BA_INTERFACE_USE_PIN, check the pin to determine which SAM-BA interface to use.
 */
#if defined(SAM_BA_INTERFACE_USE_PIN)
  uint8_t sambaInterface = SAM_BA_NONE;
  pinConfig(SAM_BA_INTERFACE_PIN_PORT, SAM_BA_INTERFACE_PIN_PIN, SAM_BA_INTERFACE_PIN_CONFIG);

  if (isPinActive(SAM_BA_INTERFACE_PIN_PORT, SAM_BA_INTERFACE_PIN_PIN, PIN_POLARITY_ACTIVE_LOW)) {      // pin is low
  #if ((SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES) && (SAM_BA_INTERFACE_PIN_POLARITY == PIN_POLARITY_USBCDC_LOW))
    sambaInterface = SAM_BA_USBCDC_ONLY;
  #elif ((SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY) && (SAM_BA_INTERFACE_PIN_POLARITY == PIN_POLARITY_ACTIVE_LOW))
    sambaInterface = SAM_BA_USBCDC_ONLY;
  #elif ((SAM_BA_INTERFACE == SAM_BA_UART_ONLY) && (SAM_BA_INTERFACE_PIN_POLARITY == PIN_POLARITY_ACTIVE_LOW))
    sambaInterface = SAM_BA_UART_ONLY;
  #endif
  } else {      // pin is high
  #if ((SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES) && (SAM_BA_INTERFACE_PIN_POLARITY == PIN_POLARITY_USBCDC_HIGH))
    sambaInterface = SAM_BA_USBCDC_ONLY;
  #elif ((SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY) && (SAM_BA_INTERFACE_PIN_POLARITY == PIN_POLARITY_ACTIVE_HIGH))
    sambaInterface = SAM_BA_USBCDC_ONLY;
  #elif ((SAM_BA_INTERFACE == SAM_BA_UART_ONLY) && (SAM_BA_INTERFACE_PIN_POLARITY == PIN_POLARITY_ACTIVE_HIGH))
    sambaInterface = SAM_BA_UART_ONLY;
  #endif
  }
#endif

/* Check if we should continue with a SAM-BA interface (if compiled and enabled).
 * Only show LED_STATUS_FILE_NOT_FOUND if a SAM-BA interface is not available.
 * LED_STATUS_FILE_NOT_FOUND occurs if there is no SD Card, no FAT16/FAT32
 * filesystem, or no file (UPDATE.BIN or UPDATE2.BIN) in the root directory.
 */
#if defined(SAM_BA_INTERFACE_USE_PIN)
  #if defined(SDCARD_ENABLED)
  if (sambaInterface == SAM_BA_NONE) {
    if (sdcardStatus == SD_BOOTLOADER_FILE_NOT_FOUND) {
      LED_status(LED_STATUS_FILE_NOT_FOUND);
    } else if (sdcardStatus == SD_BOOTLOADER_NOT_CALLED) {
      LED_status(LED_STATUS_NO_SAM_BA_INTERFACE);
    }
  }
  #else
    #if (SAM_BA_INTERFACE == SAM_BA_NONE)
      LED_status(LED_STATUS_NO_SAM_BA_INTERFACE);
    #else
    if (sambaInterface == SAM_BA_NONE) {
      LED_status(LED_STATUS_NO_SAM_BA_INTERFACE);
    }
    #endif
  #endif
#else
  #if (SAM_BA_INTERFACE == SAM_BA_NONE)
    LED_status(LED_STATUS_NO_SAM_BA_INTERFACE);
  #endif
#endif

/* Enable the appropriate SAM-BA interfaces. When using SAM_BA_INTERFACE_USE_PIN,
 * the peripheral and pins are only setup for the selected/enabled interface.
 */
#if defined(SAM_BA_INTERFACE_USE_PIN)
  if (sambaInterface == SAM_BA_UART_ONLY) {
#endif

#if SAM_BA_INTERFACE == SAM_BA_UART_ONLY  ||  SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES
  /* UART is enabled in all cases */
    serial_open();
#endif

#if defined(SAM_BA_INTERFACE_USE_PIN)
  } else if (sambaInterface == SAM_BA_USBCDC_ONLY) {
#endif

#if SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY  ||  SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES
    pCdc = usb_init();
#endif

#if defined(SAM_BA_INTERFACE_USE_PIN)
  }
#endif


  ledDirection = 4;
  DEBUG_PIN_LOW;

  /* Wait for a complete enum on usb or a '#' char on serial line */
  while (1)
  {
#if defined(SAM_BA_INTERFACE_USE_PIN)
    if (sambaInterface == SAM_BA_USBCDC_ONLY) {
#endif

#if SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY  ||  SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES
    if (pCdc->IsConfigured(pCdc) != 0)
    {
      main_b_cdc_enable = true;
    }

    /* Check if a USB enumeration has succeeded and if comm port has been opened */
    if (main_b_cdc_enable)
    {
      sam_ba_monitor_init(SAM_BA_INTERFACE_USBCDC);
      /* SAM-BA on USB loop */
      while( 1 )
      {
        sam_ba_monitor_run();
      }
    }
#endif

#if defined(SAM_BA_INTERFACE_USE_PIN)
    } else if (sambaInterface == SAM_BA_UART_ONLY) {
#endif

#if SAM_BA_INTERFACE == SAM_BA_UART_ONLY  ||  SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES
    /* Check if a '#' has been received */
    if (!main_b_cdc_enable && serial_sharp_received())
    {
      sam_ba_monitor_init(SAM_BA_INTERFACE_USART);
      /* SAM-BA on Serial loop */
      while(1)
      {
        sam_ba_monitor_run();
      }
    }
#endif

#if defined(SAM_BA_INTERFACE_USE_PIN)
    }
#endif
  }
}
コード例 #20
0
/**
  * @brief  pinMode Arduino pin configuration
  * @param  INPUT or OUTPUT
  * @retval None
  */
void pinMode(uint16_t pin, uint16_t mode){
  /* Check the parameters */
  assert_param(IS_ARDUINO_PIN(pin));
  assert_param(IS_ARDUINO_MODE(mode));
  pinConfig(pin, mode);
}
コード例 #21
0
ファイル: device.cpp プロジェクト: Inner-room/libdshowcapture
bool HDevice::SetupVideoCapture(IBaseFilter *filter, VideoConfig &config)
{
	ComPtr<IPin>  pin;
	HRESULT       hr;
	bool          success;

	if (config.name.find(L"C875") != std::string::npos ||
	    config.name.find(L"C835") != std::string::npos)
		return SetupEncodedVideoCapture(filter, config, AV_LGP);

	else if (config.name.find(L"IT9910") != std::string::npos)
		return SetupEncodedVideoCapture(filter, config, HD_PVR_Rocket);

	else if (config.name.find(HD_PVR1_NAME) != std::string::npos)
		return SetupEncodedVideoCapture(filter, config, HD_PVR1);

	success = GetFilterPin(filter, MEDIATYPE_Video, PIN_CATEGORY_CAPTURE,
			PINDIR_OUTPUT, &pin);
	if (!success) {
		if (SetupExceptionVideoCapture(filter, config)) {
			return true;
		} else {
			Error(L"Could not get video pin");
			return false;
		}
	}

	ComQIPtr<IAMStreamConfig> pinConfig(pin);
	if (pinConfig == NULL) {
		Error(L"Could not get IAMStreamConfig for device");
		return false;
	}

	if (config.useDefaultConfig) {
		MediaTypePtr defaultMT;

		hr = pinConfig->GetFormat(&defaultMT);
		if (hr == E_NOTIMPL) {
			if (!GetPinMediaType(pin, videoMediaType)) {
				Error(L"Couldn't get pin media type");
				return false;
			}

		} else if (FAILED(hr)) {
			ErrorHR(L"Could not get default format for video", hr);
			return false;

		} else {
			videoMediaType = defaultMT;
		}

		ConvertVideoSettings();

		config.format = config.internalFormat = VideoFormat::Any;
	}

	if (!GetClosestVideoMediaType(filter, config, videoMediaType)) {
		Error(L"Could not get closest video media type");
		return false;
	}

	hr = pinConfig->SetFormat(videoMediaType);
	if (FAILED(hr) && hr != E_NOTIMPL) {
		ErrorHR(L"Could not set video format", hr);
		return false;
	}

	ConvertVideoSettings();

	PinCaptureInfo info;
	info.callback          = [this] (IMediaSample *s) {Receive(true, s);};
	info.expectedMajorType = videoMediaType->majortype;

	/* attempt to force intermediary filters for these types */
	if (videoConfig.format == VideoFormat::XRGB)
		info.expectedSubType = MEDIASUBTYPE_RGB32;
	else if (videoConfig.format == VideoFormat::ARGB)
		info.expectedSubType = MEDIASUBTYPE_ARGB32;
	else if (videoConfig.format == VideoFormat::YVYU)
		info.expectedSubType = MEDIASUBTYPE_YVYU;
	else if (videoConfig.format == VideoFormat::YUY2)
		info.expectedSubType = MEDIASUBTYPE_YUY2;
	else if (videoConfig.format == VideoFormat::UYVY)
		info.expectedSubType = MEDIASUBTYPE_UYVY;
	else
		info.expectedSubType = videoMediaType->subtype;

	videoCapture = new CaptureFilter(info);
	videoFilter  = filter;

	graph->AddFilter(videoCapture, L"Video Capture Filter");
	graph->AddFilter(videoFilter, L"Video Filter");
	return true;
}
コード例 #22
0
int main(int argc, char *argv[]) {

	// A few arrays here are declared with 32 elements, even though
	// values aren't needed for io[] members where the 'key' value is
	// GND.  This simplifies the code a bit -- no need for mallocs and
	// tests to create these arrays -- but may waste a handful of
	// bytes for any declared GNDs.
	char                   buf[50],      // For sundry filenames
	                       c,            // Pin input value ('0'/'1')
	                       board;        // 0=Pi1Rev1, 1=Pi1Rev2, 2=Pi2
	int                    fd,           // For mmap, sysfs, uinput
	                       i, j,         // Asst. counter
	                       bitmask,      // Pullup enable bitmask
	                       timeout = -1, // poll() timeout
	                       intstate[32], // Last-read state
	                       extstate[32], // Debounced state
	                       lastKey = -1; // Last key down (for repeat)
	unsigned long          bitMask, bit; // For Vulcan pinch detect
	volatile unsigned char shortWait;    // Delay counter
	struct input_event     keyEv, synEv; // uinput events
	struct pollfd          p[32];        // GPIO file descriptors

	progName = argv[0];             // For error reporting
	signal(SIGINT , signalHandler); // Trap basic signals (exit cleanly)
	signal(SIGKILL, signalHandler);

//not needed
/*
	// Select io[] table for Cupcade (TFT) or 'normal' project.
	io = (access("/etc/modprobe.d/adafruit.conf", F_OK) ||
	      access("/dev/fb1", F_OK)) ? ioStandard : ioTFT;
*/
	io = ioStandard;
	// If this is a "Revision 1" Pi board (no mounting holes),
	// remap certain pin numbers in the io[] array for compatibility.
	// This way the code doesn't need modification for old boards.
	board = boardType();
	if(board == 0) {
		for(i=0; io[i].pin >= 0; i++) {
			if(     io[i].pin ==  2) io[i].pin = 0;
			else if(io[i].pin ==  3) io[i].pin = 1;
			else if(io[i].pin == 27) io[i].pin = 21;
		}
	}

	// ----------------------------------------------------------------
	// Although Sysfs provides solid GPIO interrupt handling, there's
	// no interface to the internal pull-up resistors (this is by
	// design, being a hardware-dependent feature).  It's necessary to
	// grapple with the GPIO configuration registers directly to enable
	// the pull-ups.  Based on GPIO example code by Dom and Gert van
	// Loo on elinux.org

	if((fd = open("/dev/mem", O_RDWR | O_SYNC)) < 0)
		err("Can't open /dev/mem");
	gpio = mmap(            // Memory-mapped I/O
	  NULL,                 // Any adddress will do
	  BLOCK_SIZE,           // Mapped block length
	  PROT_READ|PROT_WRITE, // Enable read+write
	  MAP_SHARED,           // Shared with other processes
	  fd,                   // File to map
	  (board == 2) ?
	   PI2_GPIO_BASE :      // -> GPIO registers
	   PI1_GPIO_BASE);

	close(fd);              // Not needed after mmap()
	if(gpio == MAP_FAILED) err("Can't mmap()");
	// Make combined bitmap of pullup-enabled pins:
	for(bitmask=i=0; io[i].pin >= 0; i++)
		if(io[i].key != GND) bitmask |= (1 << io[i].pin);
	gpio[GPPUD]     = 2;                    // Enable pullup
	for(shortWait=150;--shortWait;);        // Min 150 cycle wait
	gpio[GPPUDCLK0] = bitmask;              // Set pullup mask
	for(shortWait=150;--shortWait;);        // Wait again
	gpio[GPPUD]     = 0;                    // Reset pullup registers
	gpio[GPPUDCLK0] = 0;
	(void)munmap((void *)gpio, BLOCK_SIZE); // Done with GPIO mmap()


	// ----------------------------------------------------------------
	// All other GPIO config is handled through the sysfs interface.

	sprintf(buf, "%s/export", sysfs_root);
	if((fd = open(buf, O_WRONLY)) < 0) // Open Sysfs export file
		err("Can't open GPIO export file");
	for(i=j=0; io[i].pin >= 0; i++) { // For each pin of interest...
		sprintf(buf, "%d", io[i].pin);
		write(fd, buf, strlen(buf));             // Export pin
		pinConfig(io[i].pin, "active_low", "0"); // Don't invert
		if(io[i].key == GND) {
			// Set pin to output, value 0 (ground)
			if(pinConfig(io[i].pin, "direction", "out") ||
			   pinConfig(io[i].pin, "value"    , "0"))
				err("Pin config failed (GND)");
		} else {
			// Set pin to input, detect rise+fall events
			if(pinConfig(io[i].pin, "direction", "in") ||
			   pinConfig(io[i].pin, "edge"     , "both"))
				err("Pin config failed");
			// Get initial pin value
			sprintf(buf, "%s/gpio%d/value",
			  sysfs_root, io[i].pin);
			// The p[] file descriptor array isn't necessarily
			// aligned with the io[] array.  GND keys in the
			// latter are skipped, but p[] requires contiguous
			// entries for poll().  So the pins to monitor are
			// at the head of p[], and there may be unused
			// elements at the end for each GND.  Same applies
			// to the intstate[] and extstate[] arrays.
			if((p[j].fd = open(buf, O_RDONLY)) < 0)
				err("Can't access pin value");
			intstate[j] = 0;
			if((read(p[j].fd, &c, 1) == 1) && (c == '0'))
				intstate[j] = 1;
			extstate[j] = intstate[j];
			p[j].events  = POLLPRI; // Set up poll() events
			p[j].revents = 0;
			j++;
		}
	} // 'j' is now count of non-GND items in io[] table
	close(fd); // Done exporting


	// ----------------------------------------------------------------
	// Set up uinput

#if 1
	// Retrogame normally uses /dev/uinput for generating key events.
	// Cupcade requires this and it's the default.  SDL2 (used by
	// some newer emulators) doesn't like it, wants /dev/input/event0
	// instead.  Enable that code by changing to "#if 0" above.
	if((fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK)) < 0)
		err("Can't open /dev/uinput");
	if(ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0)
		err("Can't SET_EVBIT");
	for(i=0; io[i].pin >= 0; i++) {
		if(io[i].key != GND) {
			if(ioctl(fd, UI_SET_KEYBIT, io[i].key) < 0)
				err("Can't SET_KEYBIT");
		}
	}
	if(ioctl(fd, UI_SET_KEYBIT, vulcanKey) < 0) err("Can't SET_KEYBIT");
	struct uinput_user_dev uidev;
	memset(&uidev, 0, sizeof(uidev));
	snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "retrogame");
	uidev.id.bustype = BUS_USB;
	uidev.id.vendor  = 0x1;
	uidev.id.product = 0x1;
	uidev.id.version = 1;
	if(write(fd, &uidev, sizeof(uidev)) < 0)
		err("write failed");
	if(ioctl(fd, UI_DEV_CREATE) < 0)
		err("DEV_CREATE failed");
#else // SDL2 prefers this event methodology
	if((fd = open("/dev/input/event0", O_WRONLY | O_NONBLOCK)) < 0)
		err("Can't open /dev/input/event0");
#endif

	// Initialize input event structures
	memset(&keyEv, 0, sizeof(keyEv));
	keyEv.type  = EV_KEY;
	memset(&synEv, 0, sizeof(synEv));
	synEv.type  = EV_SYN;
	synEv.code  = SYN_REPORT;
	synEv.value = 0;

	// 'fd' is now open file descriptor for issuing uinput events


	// ----------------------------------------------------------------
	// Monitor GPIO file descriptors for button events.  The poll()
	// function watches for GPIO IRQs in this case; it is NOT
	// continually polling the pins!  Processor load is near zero.

	while(running) { // Signal handler can set this to 0 to exit
		// Wait for IRQ on pin (or timeout for button debounce)
		if(poll(p, j, timeout) > 0) { // If IRQ...
			for(i=0; i<j; i++) {       // Scan non-GND pins...
				if(p[i].revents) { // Event received?
					// Read current pin state, store
					// in internal state flag, but
					// don't issue to uinput yet --
					// must wait for debounce!
					lseek(p[i].fd, 0, SEEK_SET);
					read(p[i].fd, &c, 1);
					if(c == '0')      intstate[i] = 1;
					else if(c == '1') intstate[i] = 0;
					p[i].revents = 0; // Clear flag
				}
			}
			timeout = debounceTime; // Set timeout for debounce
			c       = 0;            // Don't issue SYN event
			// Else timeout occurred
		} else if(timeout == debounceTime) { // Button debounce timeout
			// 'j' (number of non-GNDs) is re-counted as
			// it's easier than maintaining an additional
			// remapping table or a duplicate key[] list.
			bitMask = 0L; // Mask of buttons currently pressed
			bit     = 1L;
			for(c=i=j=0; io[i].pin >= 0; i++, bit<<=1) {
				if(io[i].key != GND) {
					// Compare internal state against
					// previously-issued value.  Send
					// keystrokes only for changed states.
					if(intstate[j] != extstate[j]) {
						extstate[j] = intstate[j];
						keyEv.code  = io[i].key;
						keyEv.value = intstate[j];
						if ((keyEv.code==KEY_0)&&(keyEv.value==1))
						{
							system("sudo halt");
							//system("echo \"that works\"");
						}
						else
						{
							write(fd, &keyEv,
							sizeof(keyEv));
						}
						//write(fd, &keyEv,
						//sizeof(keyEv));
						c = 1; // Follow w/SYN event
						if(intstate[j]) { // Press?
							// Note pressed key
							// and set initial
							// repeat interval.
							lastKey = i;
							timeout = repTime1;
						} else { // Release?
							// Stop repeat and
							// return to normal
							// IRQ monitoring
							// (no timeout).
							lastKey = timeout = -1;
						}
					}
					j++;
					if(intstate[i]) bitMask |= bit;
				}
			}

			// If the "Vulcan nerve pinch" buttons are pressed,
			// set long timeout -- if this time elapses without
			// a button state change, esc keypress will be sent.
			if((bitMask & vulcanMask) == vulcanMask)
				timeout = vulcanTime;
		} else if(timeout == vulcanTime) { // Vulcan timeout occurred
			// Send keycode (MAME exits or displays exit menu)
			keyEv.code = vulcanKey;
			for(i=1; i>= 0; i--) { // Press, release
				keyEv.value = i;
				write(fd, &keyEv, sizeof(keyEv));
				usleep(10000); // Be slow, else MAME flakes
				write(fd, &synEv, sizeof(synEv));
				usleep(10000);
			}
			timeout = -1; // Return to normal processing
			c       = 0;  // No add'l SYN required
		} else if(lastKey >= 0) { // Else key repeat timeout
			if(timeout == repTime1) timeout = repTime2;
			else if(timeout > 30)   timeout -= 5; // Accelerate
			c           = 1; // Follow w/SYN event
			keyEv.code  = io[lastKey].key;
			keyEv.value = 2; // Key repeat event
			write(fd, &keyEv, sizeof(keyEv));
		}
		if(c) write(fd, &synEv, sizeof(synEv));
	}

	// ----------------------------------------------------------------
	// Clean up

	ioctl(fd, UI_DEV_DESTROY); // Destroy and
	close(fd);                 // close uinput
	cleanup();                 // Un-export pins

	puts("Done.");

	return 0;
}
コード例 #23
0
int main(int argc, char *argv[]) {

	// A few arrays here are declared with IOLEN elements, even though
	// values aren't needed for io[] members where the 'key' value is
	// GND.  This simplifies the code a bit -- no need for mallocs and
	// tests to create these arrays -- but may waste a handful of
	// bytes for any declared GNDs.
	char                   buf[50],         // For sundry filenames
	                       c;               // Pin input value ('0'/'1')
	int                    fd,              // For mmap, sysfs, uinput
	                       i, j,            // Asst. counter
	                       bitmask,         // Pullup enable bitmask
	                       timeout = -1,    // poll() timeout
	                       intstate[IOLEN], // Last-read state
	                       extstate[IOLEN]; // Debounced state
	volatile unsigned char shortWait;       // Delay counter
	struct uinput_user_dev uidev;           // uinput device
	struct input_event     keyEv, synEv;    // uinput events
	struct pollfd          p[IOLEN];        // GPIO file descriptors

	progName = argv[0];             // For error reporting
	signal(SIGINT , signalHandler); // Trap basic signals (exit cleanly)
	signal(SIGKILL, signalHandler);


	// ----------------------------------------------------------------
	// Although Sysfs provides solid GPIO interrupt handling, there's
	// no interface to the internal pull-up resistors (this is by
	// design, being a hardware-dependent feature).  It's necessary to
	// grapple with the GPIO configuration registers directly to enable
	// the pull-ups.  Based on GPIO example code by Dom and Gert van
	// Loo on elinux.org

	if((fd = open("/dev/mem", O_RDWR | O_SYNC)) < 0)
		err("Can't open /dev/mem");
	gpio = mmap(            // Memory-mapped I/O
	  NULL,                 // Any adddress will do
	  BLOCK_SIZE,           // Mapped block length
	  PROT_READ|PROT_WRITE, // Enable read+write
	  MAP_SHARED,           // Shared with other processes
	  fd,                   // File to map
	  GPIO_BASE );          // Offset to GPIO registers
	close(fd);              // Not needed after mmap()
	if(gpio == MAP_FAILED) err("Can't mmap()");
	// Make combined bitmap of pullup-enabled pins:
	for(bitmask=i=0; i<IOLEN; i++)
		if(io[i].key != GND) bitmask |= (1 << io[i].pin);
	gpio[GPPUD]     = 2;                    // Enable pullup
	for(shortWait=150;--shortWait;);        // Min 150 cycle wait
	gpio[GPPUDCLK0] = bitmask;              // Set pullup mask
	for(shortWait=150;--shortWait;);        // Wait again
	gpio[GPPUD]     = 0;                    // Reset pullup registers
	gpio[GPPUDCLK0] = 0;
	(void)munmap((void *)gpio, BLOCK_SIZE); // Done with GPIO mmap()


	// ----------------------------------------------------------------
	// All other GPIO config is handled through the sysfs interface.

	sprintf(buf, "%s/export", sysfs_root);
	if((fd = open(buf, O_WRONLY)) < 0) // Open Sysfs export file
		err("Can't open GPIO export file");
	for(i=j=0; i<IOLEN; i++) { // For each pin of interest...
		sprintf(buf, "%d", io[i].pin);
		write(fd, buf, strlen(buf));             // Export pin
		pinConfig(io[i].pin, "active_low", "0"); // Don't invert
		if(io[i].key == GND) {
			// Set pin to output, value 0 (ground)
			if(pinConfig(io[i].pin, "direction", "out") ||
			   pinConfig(io[i].pin, "value"    , "0"))
				err("Pin config failed (GND)");
		} else {
			// Set pin to input, detect rise+fall events
			if(pinConfig(io[i].pin, "direction", "in") ||
			   pinConfig(io[i].pin, "edge"     , "both"))
				err("Pin config failed");
			// Get initial pin value
			sprintf(buf, "%s/gpio%d/value",
			  sysfs_root, io[i].pin);
			// The p[] file descriptor array isn't necessarily
			// aligned with the io[] array.  GND keys in the
			// latter are skipped, but p[] requires contiguous
			// entries for poll().  So the pins to monitor are
			// at the head of p[], and there may be unused
			// elements at the end for each GND.  Same applies
			// to the intstate[] and extstate[] arrays.
			if((p[j].fd = open(buf, O_RDONLY)) < 0)
				err("Can't access pin value");
			intstate[j] = 0;
			if((read(p[j].fd, &c, 1) == 1) && (c == '0'))
				intstate[j] = 1;
			extstate[j] = intstate[j];
			p[j].events  = POLLPRI; // Set up poll() events
			p[j].revents = 0;
			j++;
		}
	} // 'j' is now count of non-GND items in io[] table
	close(fd); // Done exporting


	// ----------------------------------------------------------------
	// Set up uinput

	if((fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK)) < 0)
		err("Can't open /dev/uinput");
	if(ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0)
		err("Can't SET_EVBIT");
	for(i=0; i<IOLEN; i++) {
		if(io[i].key != GND) {
			if(ioctl(fd, UI_SET_KEYBIT, io[i].key) < 0)
				err("Can't SET_KEYBIT");
		}
	}
	memset(&uidev, 0, sizeof(uidev));
	snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "retrogame");
	uidev.id.bustype = BUS_USB;
	uidev.id.vendor  = 0x1;
	uidev.id.product = 0x1;
	uidev.id.version = 1;
	if(write(fd, &uidev, sizeof(uidev)) < 0)
		err("write failed");
	if(ioctl(fd, UI_DEV_CREATE) < 0)
		err("DEV_CREATE failed");
	// Initialize input event structures
	memset(&keyEv, 0, sizeof(keyEv));
	keyEv.type  = EV_KEY;
	memset(&synEv, 0, sizeof(synEv));
	synEv.type  = EV_SYN;
	synEv.code  = SYN_REPORT;
	synEv.value = 0;

	// 'fd' is now open file descriptor for issuing uinput events


	// ----------------------------------------------------------------
	// Monitor GPIO file descriptors for button events.  The poll()
	// function watches for GPIO IRQs in this case; it is NOT
	// continually polling the pins!  Processor load is near zero.

	while(running) { // Signal handler can set this to 0 to exit
		// Wait for IRQ on pin (or timeout for button debounce)
		if(poll(p, j, timeout) > 0) { // If IRQ...
			for(i=0; i<j; i++) {       // Scan non-GND pins...
				if(p[i].revents) { // Event received?
					// Read current pin state, store
					// in internal state flag, but
					// don't issue to uinput yet --
					// must wait for debounce!
					lseek(p[i].fd, 0, SEEK_SET);
					read(p[i].fd, &c, 1);
					if(c == '0')      intstate[i] = 1;
					else if(c == '1') intstate[i] = 0;
					p[i].revents = 0; // Clear flag
				}
			}
			timeout = 20; // Set timeout for debounce
		} else { // Else timeout occurred; input is debounced
			// 'j' (number of non-GNDs) is re-counted as
			// it's easier than maintaining an additional
			// remapping table or a duplicate key[] list.
			for(c=i=j=0; i<IOLEN; i++) {
				if(io[i].key != GND) {
					// Compare internal state against
					// previously-issued value.  Send
					// keystrokes only for changed states.
					if(intstate[j] != extstate[j]) {
						extstate[j] = intstate[j];
						keyEv.code  = io[i].key;
						keyEv.value = intstate[j];
						write(fd, &keyEv,
						  sizeof(keyEv));
						c = 1; // Follow w/SYN event
					}
					j++;
				}
			}
			if(c) write(fd, &synEv, sizeof(synEv));
			timeout = -1; // Return to normal IRQ monitoring
		}
	}

	// ----------------------------------------------------------------
	// Clean up

	ioctl(fd, UI_DEV_DESTROY); // Destroy and
	close(fd);                 // close uinput
	cleanup();                 // Un-export pins

	puts("Done.");

	return 0;
}
コード例 #24
0
int main(void)
{

		// uint8_t test_comms = 'z';
		// uint8_t setupState = 1;
		// uint8_t *setupData; // Pointer to hold setup data

		USART_Init(BAUD_PRESCALE);  // Initialise USART
		pinConfig(); // Initialize Pin Configuration

		// Main loop
		while(1)
		{

			// while(setupState) // Wait in this while loop while waiting for user conig
			// {
			// 	setupData = getSetup();
			// 	if ((*setupData + 0) == 1) // 3rd Element of pointer is init flag. If true break while loop and start.
			// 	{
			// 		setupState = 0;
			// 	}
			// }

			// PORTB |= (1<<PB3);
			// _delay_ms(1000);
			// PORTB &= ~(1<<PB3);

			if (PINC & (1<<PC0)) {
				PORTB |= (1<<PB3);

				// u8temp = running_count == 0? 't' : 'm';
					if (tst_count < 1)
					{
						for(uint8_t i = RxBuffer.index; i > 0; i--)
						{
						u8test = RxBuffer.buffer[i-1];
						TxBufferWrite(&TxBuffer, u8test);
						tst_count++;
						}
					}
					running_count++;
			}
			else
			{
				PORTB &= ~(1<<PB3);
				tst_count = 0;
			}

			if (PINC & (1<<PC7))
			{
					if(tst_count_2 < 1){
					PORTB |= (1<<PB3);
					// uint8_t test_data = 8;
					// USART_Test_Transmit(tst_value);
					USART_Transmit(&TxBuffer);
					RxBufferReset(&RxBuffer);
					// USART_Transmit(&RxBuffer);
					tst_count_2++;
				}

			}
			else {
				PORTB &= ~(1<<PB3);
				tst_count_2 = 0;
			}

			// if (receivedByte == 'k') {
			// 	PORTB |= (1<<PB3);
			// }
			// else {
			// 	PORTB &= ~(1<<PB3);
			// }

		}
}
コード例 #25
0
ファイル: main.c プロジェクト: mattairtech/ArduinoCore-samd
/**
 * \brief Check the application startup condition
 *
 */
static void check_start_application(void)
{
#if (!defined DEBUG) || ((defined DEBUG) && (DEBUG == 0))
uint32_t* pulSketch_Start_Address;
#endif

  /*
   * Test sketch stack pointer @ &__sketch_vectors_ptr
   * Stay in SAM-BA if value @ (&__sketch_vectors_ptr) == 0xFFFFFFFF (Erased flash cell value)
   */
  if (__sketch_vectors_ptr == 0xFFFFFFFF)
  {
    /* Stay in bootloader */
    return;
  }

  /*
   * Load the sketch Reset Handler address
   * __sketch_vectors_ptr is exported from linker script and point on first 32b word of sketch vector table
   * Remember, variables exported from a linker script are different than normal variables (only address, no value)
   * First 32b word is sketch stack
   * Second 32b word is sketch entry point: Reset_Handler()
   */
  pulSketch_Start_Address = &__sketch_vectors_ptr ;
  pulSketch_Start_Address++ ;

  /*
   * Test vector table address of sketch @ &__sketch_vectors_ptr
   * Stay in SAM-BA if this function is not aligned enough, ie not valid
   */
  if ( ((uint32_t)(&__sketch_vectors_ptr) & ~SCB_VTOR_TBLOFF_Msk) != 0x00)
  {
    /* Stay in bootloader */
    return;
  }

#if defined(BOOT_LOAD_PIN_ENABLED)
  pinConfig(BOOT_LOAD_PIN_PORT, BOOT_LOAD_PIN, BOOT_LOAD_PIN_CONFIG);

  /* Allow time for debouncing capacitor (if using a button) to charge (10ms) */
  delayUs(10000UL);

  // Read the BOOT_LOAD_PIN status
  if (isPinActive(BOOT_LOAD_PIN_PORT, BOOT_LOAD_PIN, BOOT_LOAD_PIN_POLARITY))
  {
    // Stay in bootloader
    return;
  }
#endif

#if defined(BOOT_DOUBLE_TAP_ENABLED)
  #define DOUBLE_TAP_MAGIC 0x07738135

#if (SAMD21 || SAMD11)
  if (PM->RCAUSE.bit.POR)
#elif (SAML21 || SAMC21 || SAMD51)
  if (RSTC->RCAUSE.bit.POR)
#else
  #error "main.c: Missing dependency or unsupported chip. Please install CMSIS-Atmel from MattairTech (see Prerequisites for Building in README.md)."
#endif

  {
    /* On power-on initialize double-tap */
    BOOT_DOUBLE_TAP_DATA = 0;
  }
  else
  {
    if (BOOT_DOUBLE_TAP_DATA == DOUBLE_TAP_MAGIC)
    {
      /* Second tap, stay in bootloader */
      BOOT_DOUBLE_TAP_DATA = 0;
      return;
    }

    /* First tap */
    BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC;

    /* Wait 0.5sec to see if the user tap reset again */
    delayUs(500000UL);

    /* Timeout happened, continue boot... */
    BOOT_DOUBLE_TAP_DATA = 0;
  }
#endif

  /* Rebase the Stack Pointer */
  __set_MSP( (uint32_t)(__sketch_vectors_ptr) );

  /* Rebase the vector table base address */
  SCB->VTOR = ((uint32_t)(&__sketch_vectors_ptr) & SCB_VTOR_TBLOFF_Msk);

  /* Jump to application Reset Handler in the application */
  asm("bx %0"::"r"(*pulSketch_Start_Address));
}
コード例 #26
0
ファイル: main.c プロジェクト: pygmyos/testcode
void main( void )
{
    u8 i, ucChar, *ucEeproms, ucBuffer[ 40 ];

    sysInit();
    socketInit();
    rfInit();
    print( COM3, "\rV2 RFID: 0x%X", socketGetID());
    //mpl115a2Init( TX1, RX1, NONE, NONE );
    //print( COM3, "\rPressure: %f", mpl115a2ReadkPa() );
    //print( COM3, "\rTemp: %f", mpl115a2ReadTemp() );
    //i2cConfig( &globalGasSensorDigipot, DIGIPOT_BASEADDRESS|3, TX1, RX1, I2CSPEEDFAST );
    //digipotSetWiper( &globalGasSensorDigipot, 2, 0 );
    //eepromOpen( 0x2F, TX1, RX1, NONE );
    //eepromPutString( 0, "Test" );
    pinConfig( MCO, OUT );
    pinSet( MCO, HIGH );
    gasSensorInit();
    //print( COM3, "\rGas Sensor: %f", gasSensorRead() );
    //gasSensorSetGain( 0,0 );
    //print( COM3, "\rGas Sensor: %f", gasSensorRead() );
    //gasSensorSetGain( 200,200 );
    //print( COM3, "\rGas Sensor: %f", gasSensorRead() );
    //eepromGetBuffer( 0, ucBuffer, len( "test" ) );
    //print( COM3, "\rEeprom: ucBuffer );
    //print( COM3, "\rEEPROM Direct Read: " );
    /*for( i = 0; i < len( "test" ); i++ ){
        ucChar = eepromGetChar( i );
        if( isAlphaOrNumeric( ucChar ) ) {
            print( COM3, "%c", ucChar );
        } else{
            print( COM3, "(%d)", ucChar  );//ucBuffer, len( "humidity" ) );
        } // else
    } // for
    */
    /* 
    // Test for LCD code
    if( isStringSame( ucBuffer, "<shield lcd>" ) ){
        print( COM3, "\rLCD Shield Detected" );
        fileOpenResource( &fileFont, (u8*)PYGMY_orbitron18 );
        fontLoad( &fileFont, &fontOrbitron18 );
        fontSetAll( &fontOrbitron18 );
    
        pinConfig( A0, PULLUP );
        pinConfig( D3, PULLUP );
        pinConfig( TA0, PULLUP );
        pinConfig( DAC1, PULLUP );
        pinConfig( DAC2, PULLUP );
        pinConfig( TX2, PULLUP );
        pinConfig( RX2, PULLUP );
        drawMainMenu();
    } else{
        hih5030Init( A2, A3 );
    } // else
    */
    
    //taskNewSimple( "humidity", 1000, (void*)threadRFHumiditySave );
    
    //gemInit();
    //fileOpen( &pygmyFile, "picon128", READ );
    //drawImage( 0,0, &pygmyFile, 0 );
    /*ucBuffer = sysAllocate( 5 );
    copyString( "Test", ucBuffer );
    ucBuffer = sysReallocate( ucBuffer, 20 );
    appendString( "ThisToo", ucBuffer );
    print( COM3, "\rTest String: %s", ucBuffer );*/
    //pinConfig( SHIELD_CENTER, PULLUP );
    //pinInterrupt( gemClickMenu, SHIELD_CENTER,  TRIGGER_RISING|TRIGGER_FALLING );
    //drawRect( 0, 20, 127, 40, VISIBLE|BORDER|ROUNDED, 8); 
    //gemDrawMenu();
    //drawWidget( &btnOK );
    //gemInit();
    
    
    //sysFree( ucBuffer );
    //fileOpen( &pygmyFile, "jpeg", READ );
    //drawJPEG( &pygmyFile, 0, 0 );
    //drawPNG( &pygmyFile, 0, 0 ); 
    /*mstatsTemp mstats();
    print( COM3, "\rbytes_total: %d", bytes_total );
    print( COM3, "\rchunks_used: %d", chunks_used );
    print( COM3, "\rbytes_used: %d", bytes_used );
    print( COM3, "\rchunks_free: %d", chunks_free );
    print( COM3, "\rbytes_free: %d", bytes_free );*/
    while(1){;}
}