/**
 * Application setup
 */
void setup()
{
    bcu.begin(4, 0x7054, 2); // We are a "Jung 2118" device, version 0.2

    pinMode(PIO_LED, OUTPUT);
    digitalWrite(PIO_LED, 1);

    // Configure the input pins and initialize the debouncers with the current
    // value of the pin.
    for (int channel = 0; channel < NUM_CHANNELS; ++channel)
    {
        pinMode(inputPins[channel], INPUT | HYSTERESIS | PULL_UP);
        inputDebouncer[channel].init(digitalRead(inputPins[channel]));
    }

    // Handle configured power-up delay
    unsigned int startupTimeout = calculateTime
            ( userEeprom[EE_BUS_RETURN_DELAY_BASE] >> 4
            , userEeprom[EE_BUS_RETURN_DELAY_FACT] &  0x7F
            );
    Timeout delay;
    int debounceTime = userEeprom[EE_INPUT_DEBOUNCE_TIME] >> 1;
    delay.start(startupTimeout);
    while (delay.started() && !delay.expired())
    {   // while we wait for the power on delay to expire we debounce the input channels
        for (int channel = 0; channel < NUM_CHANNELS; ++channel)
        {
            inputDebouncer[channel].debounce(digitalRead(inputPins[channel]), debounceTime);
        }
        waitForInterrupt();
    }

    initApplication();
}
/**
 * The application's main.
 */
void loop()
{
    int debounceTime = userEeprom[EE_INPUT_DEBOUNCE_TIME] >> 1;
    int objno, channel, value, lastValue;

    // Handle the input pins
    for (channel = 0; channel < NUM_CHANNELS; ++channel)
    {
        lastValue = inputDebouncer[channel].value();
        value = inputDebouncer[channel].debounce(digitalRead(inputPins[channel]), debounceTime);

        if (lastValue != value)
            inputChanged(channel, value);
    }

    // Handle updated communication objects
    while ((objno = nextUpdatedObject()) >= 0)
    {
        objectUpdated(objno);
    }

    // Handle timed functions (e.g. periodic update)
    handlePeriodic();

    // Sleep up to 1 millisecond if there is nothing to do
    if (bus.idle())
        waitForInterrupt();
}
Esempio n. 3
0
void bootstrap(void) {
	earlysetup();

	//Set STKALIGN in NVIC. Not stritly necessary, but good to do. TODO: Make more readable, place definition at a proper place
#define NVIC_CCR ((volatile unsigned long *)(0xE000ED14))
//	*NVIC_CCR = *NVIC_CCR | 0x200;

	//copy initial values of variables (non-const globals and static variables) from FLASH to RAM
	uint8_t* mirror = &_LD_END_OF_TEXT; //copy from here
	uint8_t* ram = &_LD_START_OF_DATA;	//copy to here
	while (ram < (&_LD_END_OF_DATA)) *(ram++) = *(mirror++);

	//set uninitialized globals (and globals initialized to zero) to zero
	while (ram < (&_LD_END_OF_BSS)) *(ram++) = 0;

  //call global scope constructors
  init_func* i;
  for (i = &_LD_INIT_ARRAY_START; i != &_LD_INIT_ARRAY_END; i++) (*i)();

	//jump into main user code (which should setup needed timers and interrupts or not return at all)
	main();

	//after main, sleep until an interrupt occurs
	while (true) {
		waitForInterrupt();
	}
}
Esempio n. 4
0
/* Attaches an interrupt handler to a specific GPIO pin
   Whenever an rising, falling or changing interrupt occurs
   the function given as the last argument will be called */
int irq_read(int gpio) {
	if(waitForInterrupt(gpio, -1) > 0) {
		struct timeval tv;
		gettimeofday(&tv, NULL);
		timestamp.first = timestamp.second;
		timestamp.second = 1000000 * (unsigned int)tv.tv_sec + (unsigned int)tv.tv_usec;
		return (int)timestamp.second-(int)timestamp.first;
	}
	return EXIT_FAILURE;
}
/**
 * In synchronous mode, wait for the defined interrupt to occur. You should <b>NOT</b> attempt to read the
 * sensor from another thread while waiting for an interrupt. This is not threadsafe, and can cause 
 * memory corruption
 * @param timeout Timeout in seconds
 * @param ignorePrevious If true, ignore interrupts that happened before
 * WaitForInterrupt was called.
 * @return What interrupts fired
 */
InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt(float timeout, bool ignorePrevious)
{
	if (StatusIsFatal()) return InterruptableSensorBase::kTimeout;
	wpi_assert(m_interrupt != NULL);
	int32_t status = 0;
	uint32_t result;

	result = waitForInterrupt(m_interrupt, timeout, ignorePrevious, &status);
	wpi_setErrorWithContext(status, getHALErrorMessage(status));

	return static_cast<WaitResult>(result);
}
Esempio n. 6
0
void Tasks::idle(uint32_t exclude)
{
    /*
     * Run pending tasks, OR if no tasks are pending, wait for interrupts.
     * This is the correct way to block the main thread of execution while
     * waiting for a condition, as it avoids unnecessary WFIs when the
     * caller is waiting on something which requires Tasks to execute.
     */

    if (!work(exclude))
        waitForInterrupt();
}
Esempio n. 7
0
void *interrupt(void *gpio_void_ptr) {
	int i = 0;
	int gpio = *(int *)gpio_void_ptr;

	while(++i < 20) {
		if(waitForInterrupt(gpio, 1000) > 0) {
			printf(">>Interrupt on GPIO %d\n", gpio);
		} else {
			printf("  Timeout on GPIO %d\n", gpio);
		}
	}
	return 0;
}
Esempio n. 8
0
/*
 * Class:     edu_wpi_first_wpilibj_hal_InterruptJNI
 * Method:    waitForInterrupt
 * Signature: (JD)V
 */
JNIEXPORT int JNICALL Java_edu_wpi_first_wpilibj_hal_InterruptJNI_waitForInterrupt
  (JNIEnv * env, jclass, jlong interrupt_pointer, jdouble timeout, jboolean ignorePrevious)
{
  INTERRUPTJNI_LOG(logDEBUG) << "Calling INTERRUPTJNI waitForInterrupt";
  INTERRUPTJNI_LOG(logDEBUG) << "Interrupt Ptr = " << (void*)interrupt_pointer;

  int32_t status = 0;
  int result = waitForInterrupt((void*)interrupt_pointer, timeout,
                                ignorePrevious, &status);

  INTERRUPTJNI_LOG(logDEBUG) << "Status = " << status;

  CheckStatus(env, status);
  return result;
}
Esempio n. 9
0
/* waitForInterrupt
 *
 * Parameters:
 * - pin: int
 * - mS: int
 * Return Type: int
 */
mrb_value
mrb_Pi_waitForInterrupt(mrb_state* mrb, mrb_value self) {
  mrb_int native_pin;
  mrb_int native_mS;

  /* Fetch the args */
  mrb_get_args(mrb, "ii", &native_pin, &native_mS);

  /* Invocation */
  int result = waitForInterrupt(native_pin, native_mS);

  /* Box the return value */
  mrb_value return_value = mrb_fixnum_value(result);

  return return_value;
}
Esempio n. 10
0
static void *interruptHandler (void *arg)
{
  int myPin ;

  (void)oliHiPri (55) ;  // Only effective if we run as root

  myPin   = pinPass ;
  pinPass = -1 ;

  for (;;)
    if (waitForInterrupt (myPin, -1) > 0) {
      // printf("Calling isr\n");
      isrFunctions [myPin] () ;
    }

  return NULL ;
}
Esempio n. 11
0
static void *waitForData0(void *arg)
{
	(void)arg;

	setHighPriority(10);
	while(1)
	{
	    if (waitForInterrupt (D0_PIN, -1) > 0)
	    {
			bitCount++;
			flagDone = 0;
			wiegand_counter = WIEGAND_WAIT_TIME;  
	    }
	}

	return NULL;
}
Esempio n. 12
0
void *interruptHandler (void *arg)
{
  int myPin ;

  (void)piHiPri (55) ;  // Only effective if we run as root

  myPin   = pinPass ;
  pinPass = -1 ;

  for (;;)
    if (waitForInterrupt (myPin, -1) > 0){
      pthread_mutex_lock (&pinMutex) ;
      isrFunctions [myPin] () ;
      pthread_mutex_unlock (&pinMutex) ;
    }

  return NULL ;
}
void initApplication(void)
{
    unsigned int address = currentVersion->baseAddress;
    setupPWM();

    for (unsigned int i = 0; i < NO_OF_CHANNELS; i++)
    {
        digitalWrite(outputPins[i], 0);
        pinMode(outputPins[i], OUTPUT);
        channels[i] = new Channel(i, address+16+i*256);
    }

    unsigned int initZeit = memMapper.getUInt8(P_InitZeit + address);
    Timeout startupDelay;
    if (initZeit)
    {
        startupDelay.start(initZeit);
        while (!startupDelay.expired())
        {
            waitForInterrupt();
        }
    }

/*  no yet used
    unsigned int telegrUnbegr = memMapper.getUInt8(PD_TelegrUnbegr + address);
    unsigned int telegrUebZeit = memMapper.getUInt16(P_TelegrUebZeit + address);
*/

    inBetrieb = memMapper.getUInt8(P_InBetrieb + address);
    inBetriebValue_0 = memMapper.getUInt8(P_InBetriebValue_0 + address);
    inBetriebZeit = memMapper.getUInt16(P_InBetriebZeit + address);

    if(inBetrieb != 255) {
    	inBetriebTimeout.start(1);
    }

    unsigned int einerFuerAlle = memMapper.getUInt8(t_EinerFuerAlle + address);

    msTimeout.start(1);
    timeoutTest.start(1);
}
Esempio n. 14
0
void CGpio::InterruptHandler()
{
	char c;
	int pin, fd, count, counter = 0, sched, priority;
	uint32_t diff = 1;
	bool bRead;
	struct timeval tvBegin, tvEnd, tvDiff;

	// Higher priority and real-time scheduling is only effective if we run as root
	GetSchedPriority(&sched, &priority);
	SetSchedPriority(SCHED_RR, (sched == SCHED_RR ? priority : 1), (sched == SCHED_RR));

	for(std::vector<CGpioPin>::iterator it = pins.begin(); it != pins.end(); ++it)
		if (it->GetPin() == pinPass)
		{
			if ((fd = it->GetReadValueFd()) == -1)
			{
				_log.Log(LOG_STATUS, "GPIO: Could not open file descriptor for GPIO %d", pinPass);
				pinPass = -1;
				return;
			}
			break;
		}

	pin = pinPass;
	pinPass = -1;

	if (ioctl (fd, FIONREAD, &count) != -1)
		for (int i = 0 ; i < count ; i++) // Clear any initial pending interrupt
			bRead = read(fd, &c, 1); // Catch value to suppress compiler unused warning

	_log.Log(LOG_STATUS, "GPIO: Interrupt handler for GPIO %d started (TID: %d)", pin, (pid_t)syscall(SYS_gettid));
	while (!m_stoprequested)
	{
		if (waitForInterrupt(fd, 2000) > 0)
		{
			if (counter > 100)
			{
				_log.Log(LOG_STATUS, "GPIO: Suppressing interruptstorm on GPIO %d, sleeping for 2 seconds..", pin);
				counter = -1;
				sleep_milliseconds(2000);
			}
			if (m_period > 0)
			{
				getclock(&tvEnd);
				if (timeval_subtract(&tvDiff, &tvEnd, &tvBegin)) {
					tvDiff.tv_sec = 0;
					tvDiff.tv_usec = 0;
				}
				diff = tvDiff.tv_usec + tvDiff.tv_sec * 1000000;
				getclock(&tvBegin);
			}
			if (diff > m_period * 1000 && counter != -1)
			{
				_log.Log(LOG_NORM, "GPIO: Processing interrupt for GPIO %d...", pin);
				if (m_debounce > 0)
					sleep_milliseconds(m_debounce); // Debounce reading
				UpdateSwitch(pin, GPIOReadFd(fd));
				_log.Log(LOG_NORM, "GPIO: Done processing interrupt for GPIO %d.", pin);

				if (counter > 0)
				{
					//_log.Log(LOG_STATUS, "GPIO: Suppressed %d interrupts on previous call for GPIO %d.", counter, pin);
					counter = 0;
				}
			}
			else
				counter++;
		}
		else
			if (fd != -1)
				close(fd);
	}
	_log.Log(LOG_STATUS, "GPIO: Interrupt handler for GPIO %d stopped", pin, (pid_t)syscall(SYS_gettid));
	return;
}
Esempio n. 15
0
void initApplication(void)
{
    unsigned int channels = currentVersion->noOfChannels;
    unsigned int longKeyTime = userEeprom.getUInt16(
            currentVersion->baseAddress + 2);
    unsigned int addressStartupDelay = currentVersion->baseAddress + 4 // debounce, longTime
            + channels * 46 + channels + (11 + channels) * 4 // logic config
            + 10;
    unsigned int busReturn = userEeprom.getUInt8(addressStartupDelay - 1) & 0x2; // bit offset is 6: means 2^(7-bit offset)
    memset(channelConfig, 0, sizeof(channelConfig));
    inputs.begin(channels, currentVersion->baseAddress);

    Timeout startupDelay;
    // delay in config is in seconds
    unsigned int delay = userEeprom.getUInt16(addressStartupDelay) * 1000;
    startupDelay.start(delay);
    if (delay)
    {
        while (!startupDelay.expired())
        {
            inputs.scan();
            for (int unsigned i = 0; i < currentVersion->noOfChannels; i++)
            {
                unsigned int value;
                inputs.checkInput(i, &value);
            }
            waitForInterrupt();
        }
    }


    unsigned int busReturnLogic = userEeprom.getUInt8(addressStartupDelay - 1) & 0x01;

    for (unsigned int i = 0; i < MAX_LOGIC; i++)
    {
        if (userEeprom.getUInt8(currentVersion->logicBaseAddress + i * (11 + channels))
                != 0xff)
        {
            logicConfig[i] = new Logic(currentVersion->logicBaseAddress, i,
                    channels, busReturnLogic);
        }
    }

    inputs.scan();
    for (unsigned int i = 0; i < channels; i++)
    {
        unsigned int value;
        int configBase = currentVersion->baseAddress + 4 + i * 46;
        word channelType = userEeprom.getUInt16(configBase);
        Channel * channel;
        inputs.checkInput(i, &value);
        //leds.setStatus(i, value);
        for (unsigned int n = 0; n < MAX_LOGIC; n++)
        {
            if (logicConfig[n])
            {
                logicConfig[n]->inputChanged(n, value);
            }
        }

        busReturn = userEeprom.getUInt8(configBase + 32) || userEeprom.getUInt8(addressStartupDelay - 1) & 0x02; // param sendValue || readToggleObject
        switch (channelType)
        {
        case 0: // channel is configured as switch
            channel = new Switch(i, longKeyTime, configBase, busReturn, value);
            break;
        case 256: // channel is configured as switch short/long
            channel = new Switch2Level(i, longKeyTime, configBase, busReturn,
                    value);
            break;
        case 1: // channel is configured as dimmer
            channel = new Dimmer(i, longKeyTime, configBase, busReturn, value);
            break;
        case 2: // channel is configured as jalo
            channel = new Jalo(i, longKeyTime, configBase, busReturn, value);
            break;
        case 3: // channel is configured as scene
            channel = new Scene(i, longKeyTime, configBase, busReturn, value);
            break;
        case 4: // channel is configured as counter
            channel = new Counter(i, longKeyTime, configBase, busReturn, value);
            break;
        case 511: // channel is configured as LED output
        	channel = new LedOutput(i, longKeyTime, configBase, busReturn, value);
            break;
        default:
            channel = 0;
        }
        channelConfig[i] = channel;
    }

}