Exemple #1
0
void main()
{
	LED = 0;
	delay_ms(5);
  uart_init();
	interrupts();
  OUTPUT = 0;
	wdt_enable(D_WDT_SCALE_4);//¿ªÃŹ·¶¨Ê±142.2ms 11.0592MHz
	while(1)
  {
		if((start_check == false) && (INPUT == 0))
		{
      send_string("start check\r\n");
      start_check = true;
			time_counter = 0;
			key_match_count = 0;
    }
		
		if((power_state == POWER_OFF) && (start_check == true))
		{
		  time_counter ++;
			if(INPUT == 0)
			{
			  key_match_count ++;
			}
			if(time_counter > 100)
			{
				start_check = false;
			  time_counter = 0;
				if(key_match_count > 75)
				{
					send_string("power on\r\n");
					OUTPUT = 1;
					delay_ms(100);
					LED = 1;
				}
				key_match_count = 0;
				while(!INPUT)
				{
          wdt_reset();
					power_state = POWER_ON;
				  send_string("wait 1!\r\n"); 
				}
			}
		}
    if((power_state == POWER_ON) && (start_check == true))
		{
		  time_counter ++;
			if(INPUT == 0)
			{
			  key_match_count ++;
			}
			if(time_counter > 100)
			{
				start_check = false;
			  time_counter = 0;
				if(key_match_count > 60)
				{
          send_string("power off\r\n");
          power_state = POWER_OFF;
          LED = 0;
					OUTPUT = 0;
				}
				key_match_count = 0;
				while(!INPUT)
				{
          wdt_reset();
				  send_string("wait 2!\r\n"); 
				}
			}
		}
		delay1ms();
		wdt_reset();
  }
}
int RHT03::errorExit(int code)
{
    interrupts();
    return code;
}
Exemple #3
0
void setupGeigerCounter() {
  attachInterrupt(INT1, incrementCount, RISING);
  interrupts();
}
Exemple #4
0
void retryClose(){
  noInterrupts();
  while(!txSelX(6,200)){}
  interrupts();
}
Exemple #5
0
  TTUI::TTUI():LiquidCrystal_SR_LCD3(11, 10, 12 ,2) 
#else
  TTUI::TTUI():LiquidCrystal(A3,4,5, 6, 7, 8, 9) 
#endif
  {
	
	pTTUI = this;	//the ptr points to this object
	trapActive_ = false; 
  }

  /***********************************************************
   * 
   * begin
   * 
   ***********************************************************/
  void TTUI::setup(Trigger& laser, Trigger& sound, Trigger& light,Trigger& timeLapse, Trigger& aux)
  {

	#ifdef SERIAL_DEBUG
		Serial.begin(9600);
	#endif
	
	#ifndef SERIAL_DEBUG
	  // USB Serial port configure as input, disable pullup
	  pinMode (0, INPUT);
	  pinMode (1, INPUT);
	  digitalWrite(0, LOW);
	  digitalWrite(1, LOW);
	#endif

	 analogReference(INTERNAL);
	
	//set triggers into array
	triggers[0] = &laser;
	triggers[1] = &sound;
	triggers[2] = &light;
	triggers[3] = &timeLapse;
	triggers[4] = &aux;
	
	triggers[0]->restoreSystem(); //restore system menu settings from trigger 0. Could work with any trigger though
	boolean focusSetting = triggers[0]->getFocus();
	boolean shutterSetting = triggers[0]->getShutter();
	boolean IRSetting = triggers[0]->getIRShutter();
	
	for(uint8_t i=0;i<NUM_OF_SENSORS;++i)
	{
		triggers[i]->setIndex(i);
		triggers[i]->restoreState();
		triggers[i]->focusOn(focusSetting);
		triggers[i]->shutterOn(shutterSetting);
		triggers[i]->IRShutterOn(IRSetting);
		
	}
	systemMenu = NUM_OF_SENSORS; //system Menu is always the last menu, even if you add more sensors
	
	incSystemOption = 0; //the current system option menu state
	trapActive_ = false;
	startBttnHold = false; 	
	currentTrigger = 0;

	//configure start button
	pinMode(START_BUTTON, INPUT);       // Start Button
    digitalWrite(START_BUTTON, HIGH);   // turn on pullup resistor for Start button
	#ifdef TT_SHIELD
	    PCintPort::attachInterrupt(START_BUTTON,startDownHandler,FALLING);  
	#else
		attachInterrupt(0,startDownHandler,FALLING); //trigger ISR function on start button press.
	#endif
	
	//Shutter and Focus pins set to output
	pinMode(FOCUS_TRIGGER_PIN, OUTPUT);
    pinMode(SHUTTER_TRIGGER_PIN, OUTPUT);
    digitalWrite(FOCUS_TRIGGER_PIN, HIGH); // is off
    digitalWrite(SHUTTER_TRIGGER_PIN, HIGH); // is off
	
	//set UI Power
	 #ifndef TT_SHIELD //if TT is normal not Shield
	 	DDRB |= (1<<PORTB7);   //pinMode(KEY_PAD_LEDS, OUTPUT);      // LED on UI
		DDRB |= (1<<PORTB6);   //pinMode(POWER_UI,OUTPUT);
	 #endif	
	 state_UIPower = false; 
	 uiPowerOn(); //turn on power at startup
	 previousMillis_UIPower = 0; 
	
	 #ifdef TT_SHIELD
	 	touch.begin();
	 #else
     	touch.begin(KEY_CHANGE);  //init touch UI with key change interrupt
	 #endif //TT_SHIELD endif

	activeMenu == START_MESSAGE;
	
	//this class inherits from LCD, so call lcd functions as part of this class
 	#ifndef TT_SHIELD //if TT is normal not Shield
		//LCD Stuff
		TCCR1B = TCCR1B & 0b11111000 | 0x01; //-- sets the pwm base

		pinMode (10, OUTPUT); // lcd contrast output 

		if(batteryPower() == true)
		{
			long lcdContrast = analogRead(A1);
			lcdContrast = 175 - ((lcdContrast * 5)  / 32);
			analogWrite (10, lcdContrast);

		}
		else
		{
			byte lcdContrast = 25; 
			analogWrite (10, lcdContrast);

		}
	#endif // END TT if
    
    begin(8, 2);
  	// Print a message to the LCD.
  	print("TrigTrap");
	setCursor(0,1);
	print("v");
	print(FIRMWARE_VERSION);

    #ifdef SERIAL_DEBUG
	Serial.print("TT v");
	Serial.println(FIRMWARE_VERSION);
    #endif

	 interrupts(); //make sure interrupts are on
  }
boolean DHT::read(void) {
  uint8_t laststate = HIGH;
  uint8_t counter = 0;
  uint8_t j = 0, i;
  unsigned long currenttime;

  // pull the pin high and wait 250 milliseconds
  digitalWrite(_pin, HIGH);
  delay(250);

  currenttime = millis();
  if (currenttime < _lastreadtime) {
    // ie there was a rollover
    _lastreadtime = 0;
  }
  if (!firstreading && ((currenttime - _lastreadtime) < 2000)) {
    return true; // return last correct measurement
    //delay(2000 - (currenttime - _lastreadtime));
  }
  firstreading = false;
  /*
    Serial.print("Currtime: "); Serial.print(currenttime);
    Serial.print(" Lasttime: "); Serial.print(_lastreadtime);
  */
  _lastreadtime = millis();

  data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  
  // now pull it low for ~20 milliseconds
  pinMode(_pin, OUTPUT);
  digitalWrite(_pin, LOW);
  delay(20);
  noInterrupts();
  digitalWrite(_pin, HIGH);
  delayMicroseconds(40);
  pinMode(_pin, INPUT);

  // read in timings
  for ( i=0; i< MAXTIMINGS; i++) {
    counter = 0;
    while (digitalRead(_pin) == laststate) {
      counter++;
      delayMicroseconds(3);
      if (counter == 255) {
        break;
      }
    }
    laststate = digitalRead(_pin);

    if (counter == 255) break;

    // ignore first 3 transitions
    if ((i >= 4) && (i%2 == 0)) {
      // shove each bit into the storage bytes
      data[j/8] <<= 1;
      if (counter > 6)
        data[j/8] |= 1;
      j++;
    }

  }

 interrupts();
  
  /*
  Serial.println(j, DEC);
  Serial.print(data[0], HEX); Serial.print(", ");
  Serial.print(data[1], HEX); Serial.print(", ");
  Serial.print(data[2], HEX); Serial.print(", ");
  Serial.print(data[3], HEX); Serial.print(", ");
  Serial.print(data[4], HEX); Serial.print(" =? ");
  Serial.println(data[0] + data[1] + data[2] + data[3], HEX);
  */

  // check we read 40 bits and that the checksum matches
  if ((j >= 40) && 
      (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
    return true;
  }
  

  return false;

}
Exemple #7
0
// Enable interrupts
void sei(void) { interrupts(); }
int MultiReadCircBuffer::write(const uint8_t* src, int srcLen,
			       bool& overwritten)
{
  boolean intEn = interruptsEnabled();
  int len = srcLen; // The length to copy

  if (blockSize)
    len -= (len % blockSize); // Round down len to a multiple of the blockSize

  // The length to return. Normally the same as the number of bytes
  // copied, except when len > bufferLen.
  int rlen = len; 
  
  // Assume overwritten is false (always the case when allowOverwrite
  // is false)
  overwritten = false;

  if (allowOverwrite) { 
    if (len > bufferLen) {
      // Pretend to write all data but only actually write the last
      // capacity bytes. This case always 'overwrites' data.
      overwritten = true;
      len = bufferLen;
      src += (srcLen - len);
    }
    if (useInterrupts)
      noInterrupts();
  }
  else {
    // Reduce len to smallest size that can be written without
    // overwriting any data. This section must run with interrupts
    // off.
    if (useInterrupts)
      noInterrupts();
    for (int i = 0; i < numReaders; ++i) {
      int n = bufferLen - getSize(i);
      if (n < len)
	rlen = len = n;
    }
    if (useInterrupts && intEn)
      interrupts();
  }
  
  // Copy up until the end of the buffer (or sooner)
  int bbw = getBytesBeforeWrap(writePtr);
  int len1 = (len < bbw ? len : bbw);
  memcpy(writePtr, src, len1);
  if (len1 == bbw)
    writePtr = buffer; // Must wrap pointer
  else
    writePtr += len1;

  // Copy the remainder from the start of the buffer
  if (len > bbw) {
    int len2 = len - bbw;
    memcpy(writePtr, src + len1, len2);
    writePtr = buffer + len2;
  }

  // Update sizes and readPtrs
  if (useInterrupts)
    noInterrupts(); // no interrupts even for allowOverwrite == false
  for (int i = 0; i < numReaders; ++i)
    if ((sizes[i] += len) > bufferLen) {
      overwritten = true;
      readPtrs[i] = writePtr;
      sizes[i] = bufferLen;
    }
  
  // Restore interrupt status
  if (useInterrupts && intEn)
    interrupts();
  return rlen;
}
Exemple #9
0
void MeteoTemp::doStep3()
{
	int i, j = 0, counter = 0;
	uint8_t laststate = HIGH;
	data[0] = data[1] = data[2] = data[3] = data[4] = 0;

#ifdef DEBUG
	unsigned long begin = micros();
#endif
	noInterrupts();
	digitalWrite(_pin, HIGH);
	delayMicroseconds(40);
	pinMode(_pin, INPUT);

	// read in timings
	for ( i=0; i< MAXTIMINGS; i++) {
		counter = 0;
		while (digitalRead(_pin) == laststate) {
			counter++;
			delayMicroseconds(1);
			if (counter == 255) {
				break;
			}
		}
		laststate = digitalRead(_pin);

		if (counter == 255) break;

		// ignore first 3 transitions
		if ((i >= 4) && (i%2 == 0)) {
			// shove each bit into the storage bytes
			data[j/8] <<= 1;
			if (counter > _count)
				data[j/8] |= 1;
			j++;
		}

	}

	interrupts();

	bool isOk = (j >= 40) &&
			(data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF));
	hasData = isOk;
	if (isOk) {
		mainLogic.temperatureUpdated();
	}
	status.needUpdate();
#ifdef DEBUG
	unsigned long duration = micros() - begin;
	Serial.print(F("DHT="));
	Serial.print(isOk);
	Serial.print(F(" took:"));
	Serial.println(duration);

	Serial.print(lastTemperature());
	Serial.print(F("° "));
	Serial.print(lastHumidity());
	Serial.println(F("%"));
#endif
	prepareStep1(false);
}
uint8_t atsha204Class::swi_receive_bytes(uint8_t count, uint8_t *buffer)
{
    uint8_t status = SWI_FUNCTION_RETCODE_SUCCESS;
    uint8_t i;
    uint8_t bit_mask;
    uint8_t pulse_count;
#ifdef IS_AVR
    uint8_t timeout_count;
#else
    uint32_t timeout_count;
#endif

    // Disable interrupts while receiving.
    noInterrupts(); //swi_disable_interrupts();

    // Configure signal pin as input.
    SET_DEVICE_PORT_TO_INPUT();
    //*device_port_DDR &= ~pinBitmask;

    // Receive bits and store in buffer.
    for (i = 0; i < count; i++)
    {
        for (bit_mask = 1; bit_mask > 0; bit_mask <<= 1)
        {
            pulse_count = 0;

            // Make sure that the variable below is big enough.
            // Change it to uint16_t if 255 is too small, but be aware that
            // the loop resolution decreases on an 8-bit controller in that case.
            timeout_count = START_PULSE_TIME_OUT;

            // Detect start bit.
            while (--timeout_count > 0)
            {
                // Wait for falling edge.
                if ((*device_port_IN & pinBitmask) == 0)
                    break;
            }

            if (timeout_count == 0)
            {
                status = SWI_FUNCTION_RETCODE_TIMEOUT;
                break;
            }

            do
            {
                // Wait for rising edge.
                if ((*device_port_IN & pinBitmask) != 0)
                {
                    // For an Atmel microcontroller this might be faster than "pulse_count++".
                    pulse_count = 1;
                    break;
                }
            } while (--timeout_count > 0);

            if (pulse_count == 0)
            {
                status = SWI_FUNCTION_RETCODE_TIMEOUT;
                break;
            }

            // Trying to measure the time of start bit and calculating the timeout
            // for zero bit detection is not accurate enough for an 8 MHz 8-bit CPU.
            // So let's just wait the maximum time for the falling edge of a zero bit
            // to arrive after we have detected the rising edge of the start bit.
            timeout_count = ZERO_PULSE_TIME_OUT;

            // Detect possible edge indicating zero bit.
            do
            {
                if ((*device_port_IN & pinBitmask) == 0)
                {
                    // For an Atmel microcontroller this might be faster than "pulse_count++".
                    pulse_count = 2;
                    break;
                }
            } while (--timeout_count > 0);

            // Wait for rising edge of zero pulse before returning. Otherwise we might interpret
            // its rising edge as the next start pulse.
            if (pulse_count == 2)
            {
                do
                {
                    if ((*device_port_IN & pinBitmask) != 0)
                        break;
                } while (timeout_count-- > 0);
            }

            // Update byte at current buffer index.
            else
                buffer[i] |= bit_mask;  // received "one" bit
        }

        if (status != SWI_FUNCTION_RETCODE_SUCCESS)
            break;
    }
    interrupts(); //swi_enable_interrupts();

    if (status == SWI_FUNCTION_RETCODE_TIMEOUT)
    {
        if (i > 0)
            // Indicate that we timed out after having received at least one byte.
            status = SWI_FUNCTION_RETCODE_RX_FAIL;
    }
    return status;
}
Exemple #11
0
/**
 * @par Function
 *   depower
 * @par Description
 *   Stop forcing power onto the bus. You only need to do this if
 *   you used the 'power' flag to write() or used a write_bit() call
 *   and aren't about to do another read or write. You would rather
 *   not leave this powered if you don't have to, just in case
 *   someone shorts your bus.
 * @par Output
 *   None 
 * return
 *   None
 * @par Others
 *   None
 */
void LOOL_OneWire::depower(void)
{
  noInterrupts();
  MeDIRECT_MODE_INPUT(baseReg, bitmask);
  interrupts();
}
Exemple #12
0
/*
 * The anemometer turns up to 60rps at 140knots - so min 16ms/16000us per turn
 * Mostly much lower :-)
 */
void Wind::calcWindSpeedAndDir() {
//grab data
// an interrupt could fire in here
	noInterrupts();
	unsigned long wsMicrosLast = windSpeedMicrosLastTmp;
	unsigned long wsMicros = windSpeedMicrosTmp;
	unsigned long wdMicrosLast = windDirMicrosLast;
	unsigned long wdMicros = windDirMicros;
	interrupts();

	/*Serial.print("wsMicros,");
		Serial.print(wsMicros);
		Serial.print(",wdMicros,");
		Serial.print(wdMicros);
		Serial.print(",wsMicrosLast,");
		Serial.print(wsMicrosLast);
		Serial.print(",wdMicrosLast,");
		Serial.println(wdMicrosLast);*/
//micros resets every 50 min,
// avoid 0, bad data, rollover and too fast (bounce? <25ms)
	if (wsMicrosLast >= wsMicros || wsMicros - wsMicrosLast < MICROS_DEBOUNCE) {
		//Serial.println("DEBUG:wsMicrosLast >= wsMicros || wsMicros - wsMicrosLast < MICROS_DEBOUNCE");
		return;
	}
	if (wdMicrosLast >= wdMicros || wdMicros - wdMicrosLast < MICROS_DEBOUNCE) {
		//Serial.println("DEBUG:wdMicrosLast >= wdMicros || wdMicros - wdMicrosLast < MICROS_DEBOUNCE");
		return;
	}
	//wd after ws, both above 0
	if(wdMicros==0 || wdMicrosLast==0 || wsMicros==0 || wsMicrosLast==0 || wdMicrosLast<=wsMicrosLast || wdMicros < wsMicros){
		//Serial.println("DEBUG:wdMicros==0 || wdMicrosLast==0 || wsMicros==0 || wsMicrosLast==0 || wdMicrosLast<=wsMicrosLast || wdMicros < wsMicros");
		return;
	}
//speed in micros, both speed and dir should agree
	//smooth it?
	windSpeedDur = ((wsMicros - wsMicrosLast)+(wdMicros-wdMicrosLast))/2;

//direction
//FROM ULTIMETER:
//AT 130 KNTS ABOUT 46US PER DEGREE OF ROTATION
	// avoid 0, bad data, rollover and too fast (bounce? <25ms)

	//average
	windDirDur = ((wdMicrosLast - wsMicrosLast)+(wdMicros-wsMicros))/2;
	unsigned long windDirDurTmp =0l;
	if (windDirDur > 0 && windDirDur<windSpeedDur) {

		//convert to degrees, this is deg clockwise from arbitrary 'north'
		windDirDurTmp = (windDirDur * 360ul) / windSpeedDur;
		//correct the dir to clockwise
		if(windDirDurTmp>=0 && windDirDurTmp <360){
			dirList.addValue(windDirDurTmp);
		}

	}
	/*Serial.print("wsMicros,");
	Serial.print(wsMicros);
	Serial.print(",wdMicros,");
	Serial.print(wdMicros);
	Serial.print(",wsMicrosLast,");
	Serial.print(wsMicrosLast);
	Serial.print(",wdMicrosLast,");
	Serial.print(wdMicrosLast);
	Serial.print(",windDirDurTmp,");
	Serial.println(windDirDurTmp);*/

}
Exemple #13
0
String cinterrupts()
{
  interrupts();
  return "";
}
Exemple #14
0
void MSFTime::init(byte ledPin)
{
  mLedPin = ledPin;


  mOffStartMillis = 0;
  mOnStartMillis = 0;
  mPrevOffStartMillis = 0;
  mPrevOnStartMillis = 0;
  mOnWidth = 0;
  mFixMillis = 0;
  mIsReading = false;
  mBitIndex = 0;
  mGoodPulses = 0;

  for( int i = 0; i < 7; i ++ )
  {
    mABits[i] = 0;
    mBBits[i] = 0;
  }


  if( ledPin != 255 )
    pinMode(mLedPin, OUTPUT);


  sMSF = this;

  #ifdef USE_AVR_INTERRUPTS
    // see
    // http://www.me.ucsb.edu/~me170c/Code/How_to_Enable_Interrupts_on_ANY_pin.pdf
    // for a good descripton of the AVR pin interrupt malarkey
    // Switching this stuff to a different pin requires reading the table there quite carefully
    // You will need to change the block below, and also the ISR(PCINT?_vect) line below.
    // I chose digital 8 as my input because it is one of the few pins that the LOLShield does not use.

    // for analogue pin 0:
    mInputPin = 14;
    pinMode(mInputPin, INPUT);

    PCICR |= (1<<PCIE1);
    PCMSK1 |= (1<<PCINT8);
    MCUCR = (1<<ISC01) | (1<<ISC00);
    /*
    // for digital pin 7:
    mInputPin = 7;
    pinMode(mInputPin, INPUT);

    PCICR |= (1<<PCIE2);
    PCMSK2 |= (1<<PCINT23);
    MCUCR = (1<<ISC01) | (1<<ISC00);
  */
    // enable interrupts
    interrupts();
  #else
    mInputPin = 2;
    pinMode(mInputPin, INPUT);
    interruptIndex = 0; // the Arduino interrupt for pin 2
    attachInterrupt(interruptIndex, sStateChange, CHANGE);

  #endif
}
Exemple #15
0
ui_state_t UserInterface::getInput(void)
{
    uint32_t switch_depressed = 0;

    noInterrupts();

    if (getState() != _last_ui_state)
    {
        stateInit();
        _last_ui_state = _ui_state;
        _sleep = millis();
    }
    else if (s_switch_state != SWITCH_STATE__NONE)
    {
        _switch_state = s_switch_state;
        if (s_switch_state != SWITCH_STATE__DEPRESSED)
            s_switch_state = SWITCH_STATE__NONE;
        switch_depressed = millis() - s_switch_depressed;
        s_encoder_turn = 0;
    }
    else if (s_encoder_turn != 0)
    {
        _encoder_turn = s_encoder_turn;
        s_encoder_turn = 0;
        s_switch_state = SWITCH_STATE__NONE;
    }
    else if (s_brightness != _brightness)
    {
        _brightness = s_brightness;
    }

    interrupts();

    if (_switch_state == SWITCH_STATE__DEPRESSED)
    {
        if (switch_depressed >= RESET_TIME)
        {
            static int display_blink = 0;
            static uint32_t blink_last = 0;

            timerStop();

            if ((switch_depressed - blink_last) > 300)
            {
                blink_last = switch_depressed;

                display_blink ^= 1;

                if (display_blink)
                    Display::dashes();
                else
                    Display::blank();
            }
        }

        return UI_STATE__PASS;
    }

    if (sleep())
        return UI_STATE__PASS;

    return _ui_state;
}
Exemple #16
0
PacketBuffer * FaceQueue::removeInboundBG() {
  noInterrupts();             // Ditto
  PacketBuffer * ret = inbound.remove();
  interrupts();
  return ret;
}
Exemple #17
0
void DS2433::duty(OneWireHub * const hub)
{
    constexpr uint8_t ALTERNATE_01 { 0b10101010 };

    static uint16_t reg_TA { 0 }; // contains TA1, TA2 (Target Address)
    static uint8_t  reg_ES { 31 };  // E/S register

    uint8_t  data, cmd;
    uint16_t crc { 0 };

    if (hub->recv(&cmd,1,crc))  return;

    switch (cmd)
    {
        case 0x0F:      // WRITE SCRATCHPAD COMMAND

            if (hub->recv(reinterpret_cast<uint8_t *>(&reg_TA),2,crc)) return;
            reg_TA &= MEM_MASK; // make sure to stay in boundary
            reg_ES = uint8_t(reg_TA) & PAGE_MASK; // register-offset

            // receive up to 8 bytes of data
            for (; reg_ES < PAGE_SIZE; ++reg_ES)
            {
                if (hub->recv(&scratchpad[reg_ES], 1, crc))
                {
                    if (hub->getError() == Error::AWAIT_TIMESLOT_TIMEOUT_HIGH) reg_ES |= REG_ES_PF_MASK;
                    break;
                }
            }
            reg_ES--;
            reg_ES &= PAGE_MASK;

            if (hub->getError() == Error::NO_ERROR)  // try to send crc if wanted
            {
                crc = ~crc; // normally crc16 is sent ~inverted
                hub->send(reinterpret_cast<uint8_t *>(&crc), 2);
            }
            break;

        case 0x55:      // COPY SCRATCHPAD

            if (hub->recv(&data)) return; // TA1
            if (data != reinterpret_cast<uint8_t *>(&reg_TA)[0]) return;
            if (hub->recv(&data)) return;  // TA2
            if (data != reinterpret_cast<uint8_t *>(&reg_TA)[1]) return;
            if (hub->recv(&data)) return;  // ES
            if (data != reg_ES) return;

            if ((reg_ES & REG_ES_PF_MASK) != 0)                  break; // stop if error occured earlier

            reg_ES |= REG_ES_AA_MASK; // compare was successful

            {    // Write Scratchpad to memory, writing takes about 5ms
                const uint8_t start  = uint8_t(reg_TA) & PAGE_MASK;
                const uint8_t length = (reg_ES & PAGE_MASK)+ uint8_t(1) - start;
                writeMemory(&scratchpad[start], length, reg_TA);
            }

            noInterrupts();

            do
            {
                hub->clearError();
                hub->sendBit(true); // send passive 1s
            }
            while   (hub->getError() == Error::AWAIT_TIMESLOT_TIMEOUT_HIGH); // wait for timeslots

            interrupts();

            while (!hub->send(&ALTERNATE_01)); // send alternating 1 & 0 after copy is complete
            break;

        case 0xAA:      // READ SCRATCHPAD COMMAND

            if (hub->send(reinterpret_cast<uint8_t *>(&reg_TA),2))  return;
            if (hub->send(&reg_ES,1)) return;

            {   // send Scratchpad content
                const uint8_t start  = uint8_t(reg_TA) & PAGE_MASK;
                const uint8_t length = PAGE_SIZE - start;
                if (hub->send(&scratchpad[start],length))   return;
            }
            return; // datasheed says we should send all 1s, till reset (1s are passive... so nothing to do here)

        case 0xF0:      // READ MEMORY

            if (hub->recv(reinterpret_cast<uint8_t *>(&reg_TA),2)) return;

            for (uint16_t i = reg_TA; i < MEM_SIZE; i+=PAGE_SIZE) // model of the 32byte scratchpad
            {
                if (hub->send(&memory[i],PAGE_SIZE)) return;
            }
            return; // datasheed says we should send all 1s, till reset (1s are passive... so nothing to do here)

        default:

            hub->raiseSlaveError(cmd);
    }
}
Exemple #18
0
void FaceQueue::insertOutboundBG(PacketBuffer * pb) {
  noInterrupts();             // Brute force for now
  outbound.insert(pb);
  interrupts();
}
void loop()
{
  // create local variables to hold a local copies of the channel inputs
  // these are declared static so that thier values will be retained 
  // between calls to loop.
  static uint16_t unThrottleIn;
  static uint16_t unSteeringIn;
  static uint16_t unAuxIn;
  // local copy of update flags
  static uint8_t bUpdateFlags;

  // check shared update flags to see if any channels have a new signal
  if(bUpdateFlagsShared)
  {
    noInterrupts(); // turn interrupts off quickly while we take local copies of the shared variables

    // take a local copy of which channels were updated in case we need to use this in the rest of loop
    bUpdateFlags = bUpdateFlagsShared;
    
    // in the current code, the shared values are always populated
    // so we could copy them without testing the flags
    // however in the future this could change, so lets
    // only copy when the flags tell us we can.
    
    if(bUpdateFlags & THROTTLE_FLAG)
    {
      unThrottleIn = unThrottleInShared;
    }
    
    if(bUpdateFlags & STEERING_FLAG)
    {
      unSteeringIn = unSteeringInShared;
    }
    
    if(bUpdateFlags & AUX_FLAG)
    {
      unAuxIn = unAuxInShared;
    }
     
    // clear shared copy of updated flags as we have already taken the updates
    // we still have a local copy if we need to use it in bUpdateFlags
    bUpdateFlagsShared = 0;
    
    interrupts(); // we have local copies of the inputs, so now we can turn interrupts back on
    // as soon as interrupts are back on, we can no longer use the shared copies, the interrupt
    // service routines own these and could update them at any time. During the update, the 
    // shared copies may contain junk. Luckily we have our local copies to work with :-)
  }
  
  // do any processing from here onwards
  // only use the local values unAuxIn, unThrottleIn and unSteeringIn, the shared
  // variables unAuxInShared, unThrottleInShared, unSteeringInShared are always owned by 
  // the interrupt routines and should not be used in loop
  
  // the following code provides simple pass through 
  // this is a good initial test, the Arduino will pass through
  // receiver input as if the Arduino is not there.
  // This should be used to confirm the circuit and power
  // before attempting any custom processing in a project.
  
  // we are checking to see if the channel value has changed, this is indicated  
  // by the flags. For the simple pass through we don't really need this check,
  // but for a more complex project where a new signal requires significant processing
  // this allows us to only calculate new values when we have new inputs, rather than
  // on every cycle.
  if(bUpdateFlags & THROTTLE_FLAG)
  {
    if(servoThrottle.readMicroseconds() != unThrottleIn)
    {
      servoThrottle.writeMicroseconds(unThrottleIn);
    }
  }
  
  if(bUpdateFlags & STEERING_FLAG)
  {
    if(servoSteering.readMicroseconds() != unSteeringIn)
    {
      servoSteering.writeMicroseconds(unSteeringIn);
    }
  }
  
  if(bUpdateFlags & AUX_FLAG)
  {
    if(servoAux.readMicroseconds() != unAuxIn)
    {
      servoAux.writeMicroseconds(unAuxIn);
    }
  }
  
  bUpdateFlags = 0;
}
Exemple #20
0
bool AccessPointClass::config(String ssid, String password, AUTH_MODE mode, bool hidden /* = false*/, int channel /* = 7*/, int beaconInterval /* = 200*/)
{
	softap_config config = {0};
	if (mode == AUTH_WEP) return false; // Not supported!

	if (mode == AUTH_OPEN)
		password = "";

	bool enabled = isEnabled();
	enable(true);
	wifi_softap_dhcps_stop();
	wifi_softap_get_config(&config);
	config.channel = channel;
	config.ssid_hidden = hidden;
	memset(config.ssid, 0, sizeof(config.ssid));
	memset(config.password, 0, sizeof(config.password));
	strcpy((char*)config.ssid, ssid.c_str());
	strcpy((char*)config.password, password.c_str());
	config.ssid_len = ssid.length();
	config.authmode = mode;
	config.max_connection = 4; // max 4
	config.beacon_interval = beaconInterval;

// RTOS TODO Check Systemready procedure including sotsp setup

	noInterrupts();
	if (!wifi_softap_set_config(&config))
	{
		interrupts();
		wifi_softap_dhcps_start();
		enable(enabled);
		debugf("Can't set AP configuration!");
		return false;
	}
	interrupts();
	debugf("AP configuration was updated");


/*
	if (System.isReady())
	{
		noInterrupts();
		if (!wifi_softap_set_config(&config))
		{
			interrupts();
			wifi_softap_dhcps_start();
			enable(enabled);
			debugf("Can't set AP configuration!");
			return false;
		}
		interrupts();
		debugf("AP configuration was updated");
	}
	else
	{
		debugf("Set AP configuration in background");
		if (runConfig != NULL)
			delete runConfig;
		runConfig = new softap_config();
		memcpy(runConfig, &config, sizeof(softap_config));
	}
	*/

	wifi_softap_dhcps_start();
	enable(enabled);

	return true;
}
Exemple #21
0
void Timeout::start(){
  noInterrupts();
    setPrescaler(prescaler);
  interrupts();
}
Exemple #22
0
void LEDs::Mode(tOrientation Orientation)
{
  noInterrupts();
  m_iOrientation = Orientation;
  interrupts();
}
uint16_t Adafruit_VS1053::decodeTime() {
  noInterrupts(); //cli();
  uint16_t t = sciRead(VS1053_REG_DECODETIME);
  interrupts(); //sei();
  return t;
}
Exemple #24
0
void Watchdog::begin(timeouts timeout)
{
  byte wdtcsr_byte = 0;
  switch (timeout)
  {
    case TIMEOUT_16MS:
      wdtcsr_byte = (0<<WDP3) | (0<<WDP2) | (0<<WDP1) | (0<<WDP0);
      break;
    case TIMEOUT_32MS:
      wdtcsr_byte = (0<<WDP3) | (0<<WDP2) | (0<<WDP1) | (1<<WDP0);
      break;
    case TIMEOUT_64MS:
      wdtcsr_byte = (0<<WDP3) | (0<<WDP2) | (1<<WDP1) | (0<<WDP0);
      break;
    case TIMEOUT_125MS:
      wdtcsr_byte = (0<<WDP3) | (0<<WDP2) | (1<<WDP1) | (1<<WDP0);
      break;
    case TIMEOUT_250MS:
      wdtcsr_byte = (0<<WDP3) | (1<<WDP2) | (0<<WDP1) | (0<<WDP0);
      break;
    case TIMEOUT_500MS:
      wdtcsr_byte = (0<<WDP3) | (1<<WDP2) | (0<<WDP1) | (1<<WDP0);
      break;
    case TIMEOUT_1000MS:
      wdtcsr_byte = (0<<WDP3) | (1<<WDP2) | (1<<WDP1) | (0<<WDP0);
      break;
    case TIMEOUT_2000MS:
      wdtcsr_byte = (0<<WDP3) | (1<<WDP2) | (1<<WDP1) | (1<<WDP0);
      break;
    case TIMEOUT_4000MS:
      wdtcsr_byte = (1<<WDP3) | (0<<WDP2) | (0<<WDP1) | (0<<WDP0);
      break;
    case TIMEOUT_8000MS:
      wdtcsr_byte = (1<<WDP3) | (0<<WDP2) | (0<<WDP1) | (1<<WDP0);
      break;
  }

  // Set Watchdog settings
  if (system_reset_)
  {
    wdtcsr_byte |= (1<<WDE);
  }
  if (isr_enabled_)
  {
    wdtcsr_byte |= (1<<WDIE);
  }

  // disable interrupts
  noInterrupts();

  // reset watchdog timer
  wdt_reset();

  // Clear WDRF in MCUSR
  MCUSR &= ~(1<<WDRF);

  // Enter Watchdog Configuration mode:
  // Write logical one to WDCE and WDE
  // Keep old prescaler setting to prevent unintentional time-out
  WDTCSR |= (1<<WDCE) | (1<<WDE);

  WDTCSR = wdtcsr_byte;

  interrupts();
}
mrb_value mrb_arduino_interrupts(mrb_state *mrb, mrb_value self){
  interrupts();
  return mrb_nil_value();
}
// This function uses bit manibulation for higher speed & smaller code
uint8_t LSM303C::SPI_ReadByte(CHIP_t chip, uint8_t data)
{
  debug_print("Reading register 0x");
  debug_printlns(data, HEX);
  uint8_t counter;

  // Set the read/write bit (bit 7) to do a read
  data |= _BV(7);

  // Set data pin to output
  bitSet(DIR_REG, DATABIT);
 
  noInterrupts();

  // Select the chip & deselect the other
  switch (chip)
  {
  case MAG:
    bitClear(CSPORT_MAG, CSBIT_MAG);
    bitSet(CSPORT_XL, CSBIT_XL);
    break;
  case ACC:
    bitClear(CSPORT_XL, CSBIT_XL);
    bitSet(CSPORT_MAG, CSBIT_MAG);
    break;
  }

  // Shift out 8-bit address
  for(counter = 8; counter; counter--)
  {
    bitWrite(DATAPORTO, DATABIT, data & 0x80);
    // Data is setup, so drop clock edge
    bitClear(CLKPORT, CLKBIT);
    bitSet(CLKPORT, CLKBIT);
    // Shift off sent bit
    data <<= 1;
  }
  
  // Switch data pin to input (0 = INPUT)
  bitClear(DIR_REG, DATABIT);

  // Shift in register data from address
  for(counter = 8; counter; counter--)
  {
    // Shift data to the left.  Remains 0 after first shift
    data <<= 1;

    bitClear(CLKPORT, CLKBIT);
    // Sample on rising egde
    bitSet(CLKPORT, CLKBIT);
    if (bitRead(DATAPORTI, DATABIT))
    {
      data |= 0x01;
    }
  }

  // Unselect chip
  switch (chip)
  {
  case MAG:
    bitSet(CSPORT_MAG, CSBIT_MAG);
    break;
  case ACC:
    bitSet(CSPORT_XL, CSBIT_XL);
    break;
  }

  interrupts();

  return(data);
}
int RHT03::update()
{
    unsigned long marks[41] = {0};
    unsigned long stops[40] = {0};
    unsigned int highTime, lowTime;
    byte dataBytes[5] = {0};
    
    noInterrupts();
    
    // Begin state: input HIGH
    pinMode(_dataPin, INPUT_PULLUP);
    delay(100);
    // Start signal: host sets data low, waits 1 ms, then pulls back up, wait 20-40us
    pinMode(_dataPin, OUTPUT);
    digitalWrite(_dataPin, LOW);
    delay(2); // Wait 1 ms minimum
    pinMode(_dataPin, INPUT_PULLUP);
    delayMicroseconds(20);
    // Sensor should pull data pin low 80us, then pull back up
    if (! waitForRHT(LOW, 1000) )
        return errorExit(0);
    if (! waitForRHT(HIGH, 1000) )
        return errorExit(0);
    
    // Sensor transmits 40 bytes (16 rh, 16 temp, 8 checksum)
    // Each byte starts with a ~50us LOW then a HIGH pulse. The duration of the
    // HIGH pulse determines the value of the bit.
    // LOW: 26-28us (<LOW duration)
    // HIGH: 70us (>LOW duration)
    for (int i=0; i<40; i++)
    {
        if (! waitForRHT(LOW, 1000) )
            return errorExit(-i);
        marks[i] = micros();
        if (! waitForRHT(HIGH, 1000) )
            return errorExit(-i);
        stops[i] = micros();
    }
    if (! waitForRHT(LOW, 1000) )
        return errorExit(-41);
    marks[40] = micros();
    
    interrupts();
    
    for (int i=0; i<40; i++)
    {
        lowTime = stops[i] - marks[i];
        highTime = marks[i + 1] - stops[i];
        if (highTime > lowTime)
        {
            dataBytes[i/8] |= (1<<(7 - i%8));
        }
    }
    
    if (checksum(dataBytes[CHECKSUM], dataBytes, 4))
    {
        _humidity = ((uint16_t) dataBytes[HUMIDITY_H] << 8) | dataBytes[HUMIDITY_L];
        if(_humidity & 0x8000) {
            int _humidity_temporary = -_humidity & 0x7FFF;
            _humidity = _humidity_temporary;
        }
        _temperature = ((uint16_t) dataBytes[TEMP_H] << 8) | dataBytes[TEMP_L];
        if(_temperature & 0x8000) {
            int _temperature_temporary = -_temperature & 0x7FFF;
            _temperature = _temperature_temporary;
        }
        return 1;
    }
    else
    {
        return -43;
    }
}
// This function uses bit manibulation for higher speed & smaller code
status_t LSM303C::SPI_WriteByte(CHIP_t chip, uint8_t reg, uint8_t data)
{
  debug_print("Writing 0x");
  debug_prints(data, HEX);
  debug_prints(" to register 0x");
  debug_printlns(reg, HEX);

  uint8_t counter;
  uint16_t twoBytes;

  // Clear the read/write bit (bit 7) to do a write
  reg &= ~_BV(7);
  twoBytes = reg << 8 | data;

  // Set data pin to output
  bitSet(DIR_REG, DATABIT);
 
  noInterrupts();

  // Select the chip & deselect the other
  switch (chip)
  {
  case MAG:
    bitClear(CSPORT_MAG, CSBIT_MAG);
    bitSet(CSPORT_XL, CSBIT_XL);
    break;
  case ACC:
    bitClear(CSPORT_XL, CSBIT_XL);
    bitSet(CSPORT_MAG, CSBIT_MAG);
    break;
  }

  // Shift out 8-bit address & 8-bit data
  for(counter = 16; counter; counter--)
  {
    bitWrite(DATAPORTO, DATABIT, twoBytes & 0x8000);
    
    // Data is setup, so drop clock edge
    bitClear(CLKPORT, CLKBIT);
    bitSet(CLKPORT, CLKBIT);
    // Shift off sent bit
    twoBytes <<= 1;
  }
  
  // Unselect chip
  switch (chip)
  {
  case MAG:
    bitSet(CSPORT_MAG, CSBIT_MAG);
    break;
  case ACC:
    bitSet(CSPORT_XL, CSBIT_XL);
    break;
  }
 
  interrupts();

  // Set data pin to input
  bitClear(DIR_REG, DATABIT);

  // Is there a way to verify true success?
  return IMU_SUCCESS;
}
Exemple #29
0
void getGeigerCounterData(Datum *datum) {
  noInterrupts();
  datum->counts = counts;
  counts = 0;
  interrupts();
}
boolean DHTSensor::loop(void)
{
    uint8_t data[6];
    uint8_t laststate = HIGH;
    uint8_t counter = 0;
    uint8_t j = 0, i;
    unsigned long currentMillis = millis();

    if ((unsigned long)(currentMillis - _lastreadtime) < DELAY_BETWEEN_READ) {
        return true; // return last correct measurement
    }

    _lastreadtime = currentMillis;
    // pull the pin high and wait 250 milliseconds
    digitalWrite(_pin, HIGH);
    delay(250);

    data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  
    // now pull it low for ~20 milliseconds
    pinMode(_pin, OUTPUT);
    digitalWrite(_pin, LOW);
    delay(20);

    noInterrupts();
    digitalWrite(_pin, HIGH);
    delayMicroseconds(40);
    pinMode(_pin, INPUT);

    // read in timings
    for ( i=0; i< MAXTIMINGS; i++) {
        counter = 0;
        while (digitalRead(_pin) == laststate) {
            counter++;
            delayMicroseconds(1);
            if (counter == 255) {
                break;
            }
        }
        laststate = digitalRead(_pin);

        if (counter == 255) break;

        // ignore first 3 transitions
        if ((i >= 4) && (i%2 == 0)) {
            // shove each bit into the storage bytes
            data[j/8] <<= 1;
            if (counter > 6)
            data[j/8] |= 1;
            j++;
        }
    }
    interrupts();


    /*
    Serial.println(j, DEC);
    Serial.print(data[0], HEX); Serial.print(", ");
    Serial.print(data[1], HEX); Serial.print(", ");
    Serial.print(data[2], HEX); Serial.print(", ");
    Serial.print(data[3], HEX); Serial.print(", ");
    Serial.print(data[4], HEX); Serial.print(" =? ");
    Serial.println(data[0] + data[1] + data[2] + data[3], HEX);
    */

    // check we read 40 bits and that the checksum matches
    if ((j >= 40) &&  (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
        switch (_type) {
            case DHTSensorType_11:
                _humidity = data[0];
                break;
            case DHTSensorType_22:
            case DHTSensorType_21:
            case DHTSensorType_AM2301:
                _humidity = data[0];
                _humidity *= 256;
                _humidity += data[1];
                _humidity /= 10;
                break;
        }
        switch (_type) {
            case DHTSensorType_11:
                _temperature = data[2];
                break;
            case DHTSensorType_22:
            case DHTSensorType_21:
            case DHTSensorType_AM2301:
                _temperature = data[2] & 0x7F;
                _temperature *= 256;
                _temperature += data[3];
                _temperature /= 10;
                if (data[2] & 0x80)
                _temperature *= -1;
                break;
        }
        return true;
    }
  
    return false;
}