void AnalogSampler::measure()
{
    double v = analogRead(_pin) / 1024.0;
    addMeasurement(v);
}
void AirSensor::ReadDifferentialPressure(AirDC *out,int sensor)
{
    switch (sensor)
    {
    case 1 :
    {
        //Sensor one is I2C HLCA12X5
        //http://www.first-sensor.com/cms/upload/datasheets/DS_Standard-HCLA_E_11629.pdf
        //Basic software for HLCA12X5 from Sensortechnics/First
        // Pressure  - Sensor output hex/dec
        //12.5  mBar 1250 Pa - 6CCCx /27852d
        //-12.5 mBar 1250 Pa - 0666x /1638d
        // 0    mBar    0 Pa - 3999x/14745
        //(27852-1638)/2500=10.4856 per Pascal
        int   reading ;//The reading from pressure sensor[Pa]
        float rawdata; //Reading with offset
        Wire.beginTransmission(120); //Initialize correct I2C device number
        Wire.requestFrom(120, 2);
        if(2 <= Wire.available())   //When the two requested bytes are available proceed to data handling
        {
            reading = Wire.read();  //16 Bit reading, 1 byte per time
            reading = reading << 8;
            reading |= Wire.read();
            rawdata=(reading-1638)/10.4856-1250;
        }
        //Update measurement values
        out->_qc=rawdata; //pa
        out->_uqc=10.0;//pa
    }
    break;
    case 2 :
    {
        /*
        Differential Pressure sensor LDES205U by FirstSensor/SensorThecnics
        This sensor uses SPI

        Circuit:
        LDES250U   <-->  ArduinoUno
        MOSI: pin 7      MOSI: pin 11                    GREEN
        MISO: pin 8      MISO: pin 12   //MSB first      RED
        SCLK: pin 6      SCK : pin 13                    YELLOW
        /CS:  pin 9      SS  : pin 10   //Asserted low   BROWN
        Power connections to LDES250U

        pin 2 +5V   RED
        pin 3 GND  BLACK

        DATASHEET
        http://www.first-sensor.com/cms/upload/datasheets/DS_Standard-LDE_E_11815.pdf
        */
        float sensorgain=0.00833333; // Pa/Count
        const byte POLL=0x2D;
        const byte REGISTER=0x14;
        const byte GETMEASURE=0x98;
        int value,result;
        int cs = 10;
        float rawpressure;
//Get the reading
        digitalWrite(cs, LOW);
        SPI.transfer(POLL);
        digitalWrite(cs, HIGH);
        digitalWrite(cs, LOW);
        SPI.transfer(REGISTER);
        digitalWrite(cs, HIGH);
        digitalWrite(cs, LOW);
        SPI.transfer(GETMEASURE);
        digitalWrite(cs, HIGH);
        digitalWrite(cs, LOW);
        byte hb = SPI.transfer(0x00);
        byte lb = SPI.transfer(0x00);
        digitalWrite(cs, HIGH);
        result=word(hb,lb);
        rawpressure=result*sensorgain;
        out->_qc=rawpressure; //pa
        out->_uqc=5.0;//pa
    }
    break; //Sensor two is SPI
    case 3 :
    {
        //MPXV7002 Sensor
        //Wire the Arduino Uno and MPXV7002 (That sensor is mounted on HobbyKing Pitot Board) in this way
        //MPXV7002    <->   Arduino Uno
        //GND                     GND
        //VDD                      5V
        //SIGNAL                   A0
        float offsetv=0;
        int analogPin=0; //Wired on input A0
        int raw;
        float Vread,Pread;
        raw = analogRead(analogPin);
        Vread=5.0/1023.0*(raw);
        Pread=(Vread-2.5-offsetv)*1000;
        #if (DEBUG==1)
        Pread=469.9651;
        #endif
        out->_qc=Pread; //pa
        out->_uqc=50.0;//pa
    }
    break;
    }
}
Example #3
0
void loop()
{
  uint8_t new_status;
  uint8_t tmp;
  uint8_t tmp_pitch_bit;

  //
  // the loop updates the sound parameters
  //
  // since we don't want all the parameters updated when playing,
  // some parameters are updated only on silence and on sustain,
  // and others are updated only on silence
  //

  // envelopes are updated only on silence and sustain
  if ((g_env_stage != 0) && (g_env_stage != 2)) {
    g_env_lengths[0] = analogRead(ATTACK_CTRL) * 16;
    g_env_lengths[1] = analogRead(RELEASE_CTRL) * 16;
    g_env_type = 
      (digitalRead(LOWPASS_PIN) == LOW) ? 1 :
      ((digitalRead(FREQ_PIN) == LOW) ? 2 : 0);
  }

  // vibrato and resonance are always welcome
  tmp = (uint8_t)(analogRead(VIBRATO_CTRL) / 4);
  g_vib_strength = (tmp > 20) ? tmp : 0;
  tmp = analogRead(RESONANCE_CTRL) / 4;
  g_lpf_resonance = (tmp > 20) ? tmp : 0;

  // so are tremolo and distortion
  g_trem_status = digitalRead(TREM_PIN)==LOW ? 1 : 0;
  g_dist_status = digitalRead(DIST_PIN)==LOW ? 1 : 0;

  //
  // pitch buttons
  //

  new_status = get_button_status();

  // is the current pitch released?
  if ((g_env_stage < 2) && ((g_current_pitch_bit & new_status) == 0)) {
    g_env_stage = 2;
  }

  // are all buttons released?
  if (new_status == 0) {
    g_current_pitch_bit = 0x00;
  }
  // or is a different pitch selected?
  else if (new_status != g_button_status) {
    tmp_pitch_bit = g_current_pitch_bit;

    // if a new button is pressed - select it
    if (new_status & (~g_button_status)) {
      tmp_pitch_bit = new_status & (~g_button_status);
    }
    // or if the current pitch is released - select another
    else if ((new_status & (~g_current_pitch_bit)) == 0) {
      tmp_pitch_bit = new_status;
    }

    // select only one pitch
    tmp_pitch_bit &= (~(tmp_pitch_bit-1));

    // if it's really a different pitch, play it
    if (tmp_pitch_bit != g_current_pitch_bit) {
      g_current_pitch_bit = tmp_pitch_bit;

      // change the pitch with interrupts disabled
      cli();
      g_base_freq = get_base_freq(g_current_pitch_bit);
      reset_sample();
      g_env_stage = 0;
      sei();
    }
  }

  g_button_status = new_status;
}
void moveYto(byte sspeed, uint16_t target){
	volatile ServoChannel &ser = servos[INNER_SERVOY];

	if(pcb_type == 2 ){		// servos + magicled
		//Serial.print("-SERVO speed ");
		//Serial.print(String(sspeed));
		//Serial.print(" target:");
		//Serial.println(String(target));
		if(!servo_lib[INNER_SERVOY].attached()){            //  turn on even if the same target pos
			servo_lib[INNER_SERVOY].attach(ser.pin);
		}
		if( ser.target_pos  == target && ser.last_pos == target ){      // the same pos
			servo_lib[INNER_SERVOY].attach(ser.pin);
			servo_lib[INNER_SERVOY].writeMicroseconds(ser.last_pos);
			ser.moving		= DRIVER_DIR_STOP;
			y_repeat		= 0;
			send_servoYisReady();
			enableYZ();
		}else{
			if( target < ser.last_pos ){    // jedz w dol
				ser.delta_pos = -sspeed;
				ser.last_distance = ser.last_pos - target;
				ser.moving	= DRIVER_DIR_BACKWARD;
				y_repeat		= 0;
			}else if( target > ser.last_pos ){    // jedz w gore
				ser.delta_pos = sspeed;
				ser.last_distance = target - ser.last_pos;
				ser.moving	= DRIVER_DIR_FORWARD;
				y_repeat		= 0;
			}
			if(!enabled6){
				enableYZ();
				delay(150);		// wait for stabilization of servo
				servo_lib[INNER_SERVOY].writeMicroseconds(ser.last_pos);
		//		delay(500);
			}
			servos[INNER_SERVOY].target_pos    = target;
			prescaler					= SERVO_PRESCALER;
		}
	}else if(pcb_type == 3 ){		// actuators + magicled
		ser.last_pos = analogRead(PIN_B3_IN_Y);

		if( target < ser.last_pos ){    // jedz w dol
		//	ser.last_distance	= ser.last_pos - target;
			ser.moving			= DRIVER_DIR_BACKWARD;
			y_repeat			= 0;
		}else if( target > ser.last_pos ){    // jedz w gore
		//	ser.last_distance	= target - ser.last_pos;
			ser.moving			= DRIVER_DIR_FORWARD;
			y_repeat			= 0;
		}else if( target == ser.last_pos ){   				   // current pos
			if( ser.last_pos == target ){
				ser.moving		= DRIVER_DIR_STOP;
				send_servoYisReady();
			}
		}
		if( ser.moving	!= DRIVER_DIR_STOP ){
			ser.target_pos	= target;
			if( ser.moving		== DRIVER_DIR_BACKWARD ){

				if(YZ_INPUT_ON_DISABLE){
					pinMode(PIN_B3_OUT_Y1, OUTPUT );
					pinMode(PIN_B3_OUT_Y2, OUTPUT );
				}
				
				digitalWrite(PIN_B3_OUT_Y1, LOW);
				//digitalWrite(PIN_B3_OUT_Y2, HIGH);
				analogWrite( PIN_B3_OUT_Y2, sspeed );		// enable on HIGH, 255 = max speed
			}else{											// DRIVER_DIR_FORWARD
				digitalWrite(PIN_B3_OUT_Y1, HIGH);
				//digitalWrite(PIN_B3_OUT_Y2, LOW);
				analogWrite( PIN_B3_OUT_Y2, 255 - sspeed );			// enable on LOW so PWM is upside down, 0 = max speed
			}
		}
	}/*
	Serial.print("-moveYto: ");
	Serial.print(String(target));
	Serial.print(" lastpos: ");
	Serial.print(String(ser.last_pos));
	Serial.print(" moving: ");
	Serial.println(String(ser.moving));*/
}
Example #5
0
int accelLib::readX()
{
   return analogRead(_xpin);
}
Example #6
0
int get_shock_data(){
  return analogRead(0);
}
Example #7
0
double Vehicle::getVoltageSupply(void)
{
	return ((double)analogRead(A0) * config->voltageDividerConstant) + config->voltageDividerCalibrateOffset;
}
Example #8
0
/**
 * Welchen Wert hat der LDR?
 */
unsigned int LDR::value() {
  unsigned int val = analogRead(_pin);
  if(val != _lastValue) {
    _lastValue = val;

//Autoscale defines the min and max value to determine the boundaries of the Brightness
#ifdef LDR_AUTOSCALE
    if(val < _min) {
      _min = val;
    }
    if(val > _max) {
      _max = val;
    }
#else
    val = constrain(val, _min, _max); 
#endif
    unsigned int mapVal = map(val, _min, _max, 100, 0);
    
    DEBUG_PRINT(F(" _min: "));
    DEBUG_PRINT(_min);
    DEBUG_PRINT(F(" _max: "));
    DEBUG_PRINT(_max);
    DEBUG_PRINT(F(" ldr: "));
    DEBUG_PRINT(val);
    DEBUG_PRINT(F(" mapValue: "));
    DEBUG_PRINTLN(mapVal);
    DEBUG_FLUSH();
    // glaetten
    
    if (_BufferFull != true) 
    {
      // buffer is not yet full
      if (_meanpointer == 0) 
      {
        _outputValue == mapVal;
        _TotalMeanValues == mapVal;
      }
       else
       {
         // store value in buffer position
         _meanvalues[_meanpointer] = mapVal;
         // calculate running average
         _TotalMeanValues == _TotalMeanValues + mapVal;  
         _outputValue = (unsigned int)(_TotalMeanValues)/(_meanpointer+1);
       }
     } //endif _meanpointer == 0
    else
    {
      // buffer is full
      // First remove the 'old' value from the buffer and substract this from the TotalMeanValues
      _TotalMeanValues == _TotalMeanValues - _meanvalues[_meanpointer];
      // now add MapVal
      _TotalMeanValues == (_TotalMeanValues + mapVal);
      // store new value in buffer position
      _meanvalues[_meanpointer] = mapVal;
      // Calculate average
      _outputValue = (unsigned int)(_TotalMeanValues)/LDR_MEAN_COUNT;
    }
    
    _meanpointer++; // increase meanpointer
    
    if(_meanpointer == LDR_MEAN_COUNT) 
    {
      _meanpointer = 0; // reset meanpointer if array index length is exceeded
      _BufferFull = true; // This only happens once because _Bufferfull is only false at initialisation. When the whole buffer is filled with data, the buffer becomes a circular buffer
    }
    
  return _outputValue;
}
}
void loop(){
  Serial.println(analogRead(A0));
  delay(1000);

}
// Return motor 2 current value in milliamps.
unsigned int DualVNH5019MotorShield::getM2CurrentMilliamps()
{
  // 5V / 1024 ADC counts / 144 mV per A = 34 mA per count
  return analogRead(_CS2) * 34;
}
Example #11
0
/**
 * ATTR::read
 * Reads the value from the pin and sets it to the pin private property
 * @return ATTR *
 */
AATR *AATR::read() {
  readValue = analogRead(pin);

  return this;
}
Example #12
0
float MQ135::getResistance() {
  int val = analogRead(_pin);
  return (1023./(float)val)*RLOAD;
}
/**
 * Process Events. This should be called in the loop()
 *
 */
void JoystickShield::processEvents() {
    int x_direction = 0;
    int y_direction = 0;

    // read from Joystick pins
    int x_position = analogRead(pin_analog_x);
    int y_position = analogRead(pin_analog_y);

    // determine Joystick direction
    if (x_position > x_threshold_high) {
        x_direction = 1;
    } else if (x_position < x_threshold_low) {
        x_direction = -1;
    }

    if (y_position > y_threshold_high) {
        y_direction = 1;
    } else if (y_position < y_threshold_low) {
        y_direction = -1;
    }

    if (x_direction == -1) {
        if (y_direction == -1) {
            currentStatus = LEFT_DOWN;
        } else if (y_direction == 0) {
            currentStatus = LEFT;
        } else {
            currentStatus = LEFT_UP;
        }
    } else if (x_direction == 0) {
        if (y_direction == -1) {
            currentStatus = DOWN;
        } else if (y_direction == 0) {
            currentStatus = CENTER;
        } else {
            currentStatus = UP;
        }
    } else {
        if (y_direction == -1) {
            currentStatus = RIGHT_DOWN;
        } else if (y_direction == 0) {
            currentStatus = RIGHT;
        } else {
            currentStatus = RIGHT_UP;
        }
    }

    // Determine which buttons were pressed
    if (digitalRead(pin_joystick_button) == LOW) {
        currentButton = JOYSTICK_BUTTON;
    }

    if (digitalRead(pin_up_button) == LOW) {
        currentButton = UP_BUTTON;
    }

    if (digitalRead(pin_right_button) == LOW) {
        currentButton = RIGHT_BUTTON;
    }

    if (digitalRead(pin_down_button) == LOW) {
        currentButton = DOWN_BUTTON;
    }

    if (digitalRead(pin_left_button) == LOW) {
        currentButton = LEFT_BUTTON;
    }

}
//
// Read as many sensors as are configured
//
// One function saves code space on small micros such
// as the Atmega328.
//
bool
LightHouseHardware::readSensors(LightHouseSensors* sensors)
{
     uint16_t tmp;

    // Power on if required
    if (m_sensors.sensorPower != (-1)) {
        digitalWrite(m_sensors.sensorPower, 1);
        delay(10); // wait for settling
    }

    // m_sensors contains the configured pin numbers.

    // sensors* is the output for the current readings.

    //
    // To test sensor hardware send the following Dweet:
    //
    //                        lite bat  slr  mois temp
    // GETSTATE_REPLY=SENSORS:0000.0000.0000.0000.0000
    // dweet GETSTATE=SENSORS
    //

    //
    // MenloSensor2 returns with 1.2v NiCD battery almost dead
    // and solar cell facing down/blocked.
    //
    // lite bat  slr  mois temp
    // 03B1.015B.016C.0120.0000
    //
    //

    if (m_sensors.lightIntensity != (-1)) {

        //
        //
        // MenloSensor1
        //
        // light:
        //
        // 10 bit A/D. Brighter light is a lower reading.
        //
        // Light is 0x27B (635) dark 0x01B (27) light
        //
        // So we subtract from the A/D range (0-1023) to
        // get a value that increases with light intensity.
        //
        tmp = analogRead(m_sensors.lightIntensity);

        sensors->lightIntensity = 1023 - tmp;
    }
    else {
        sensors->lightIntensity = 0;
    }

    if (m_sensors.battery != (-1)) {

        //
        // MenloSensor1
        //
        // battery:
        //
        // currently read 0x1B3 (435) on a fairly full Alkaline battery
        //
        // (435/1023) == 0.4252 ratio of a 3.3v reference == 1.403 volts
        //
        sensors->battery = analogRead(m_sensors.battery);
    }
    else {
        sensors->battery = 0;
    }

    if (m_sensors.solar != (-1)) {

        //
        // MenloSensor1
        //
        // solar:
        //
        // currently read 0x1B5 (437) on a disconnected solar cell and
        // a fairly full Alkaline battery installed.
        //
        // Even though there is a blocking diode we could be reading
        // back leakage since there is no load.
        //
        sensors->solar = analogRead(m_sensors.solar);
    }
    else {
        sensors->solar = 0;
    }

    if (m_sensors.moisture != (-1)) {

        //
        // MenloSensor1
        //
        // moisture:
        //
        // Currently read 0x015C () while disconnected (open ended)
        //
        sensors->moisture = analogRead(m_sensors.moisture);
    }
    else {
        sensors->moisture = 0;
    }

    if (m_sensors.temperature != (-1)) {

#if USE_DS18S20

        //
        // This sensor has the following issues:
        //
        // Cost: About $3.50
        // Slow: Must be awake for 1-2 seconds bouncing its signal
        //       and waiting to get a reading. Hurts battery life when
        //       could be sleeping.
        //
        // Weird signals: It's use has dropped the Nordic Radio/SPI offline
        // requiring re-initialization, and signal coupling has caused other
        // problems. It must always be on the power rail, though it goes into
        // it own low power sleep. Can't put it on sensor power pin.
        //
        // Code Size Cost: 2114 bytes for OS_DS18S20 library + OneWire support library.
        //            vs. a single analogRead() of a < $1.00 TMP36.
        //
        // 30,094 enabled
        // 27,980 disabled
        // -------
        //  2114 bytes
        //

        //
        // Currently a Dallas DS18B20 One Wire Temperature Sensor
        //
        sensors->temperature = m_temperatureSensor.GetTemperature();
#else
        //
        // A TMP36 is an analog sensor which is cheaper (< $1.00)
        // and does not burn xxx bytes of code space.
        //
        // sensors->temperature = analogRead(m_sensors.temperature);
        sensors->temperature = 0;
#endif
    }
    else {
        sensors->temperature = 0;
    }

    // Power off if required
    if (m_sensors.sensorPower != (-1)) {
        digitalWrite(m_sensors.sensorPower, 0);
    }

    //
    // Record any running meteorological sensor data that has
    // been received over NMEA 0183 from a co-resident weather station.
    //
    sensors->windspeed = m_windspeed;
    sensors->winddirection = m_winddirection;

    //
    // The WeatherStation temperature reading overrides any
    // base lighthouse one.
    //
    sensors->temperature = m_temperature;

    sensors->barometer = m_barometer;
    sensors->humidity = m_humidity;
    sensors->rainfall = m_rain;

    if (m_sensors.lightIntensity == (-1)) {

        //
        // No support for light intensity from the LightHouse
        // hardware so use the received NMEA 0183 value.
        //
        sensors->lightIntensity = m_nmeaLight;
    }
    else {

        //
        // The light sensor on the SparkFun Weathershield is underneath
        // the lantern house where it gets no light. So we can't use
        // the value from the NMEA 0183 stream from the WeatherStation.
        //
        // In this case the lighthouse hardware has a sensor into the
        // lantern house so we will use that value which was read previously.
        //
        // sensors->lightIntensity = m_nmeaLight;
    }

    sensors->battery = m_battery;
    sensors->solar = m_solar;

    return true;
}
Example #15
0
int cdsModule::read(int range)
{
    pinMode(pin_number, INPUT_ANALOG);
	int temp = map(analogRead(pin_number), 0, 4095, 0, range-1);
	return temp;
}
Example #16
0
int main() {
  // SETUP
  init();
  Serial.begin(9600);
  tft.initR(INITR_BLACKTAB);  // initialize screen
  
  // Setting the joystick button and LEDs
  pinMode(JOYSTICK_BUTTON, INPUT);
  digitalWrite(JOYSTICK_BUTTON, HIGH);
  
  // Initialize the SD card
  Serial.print("Initializing SD card...");
  if (!SD.begin(SD_CS)) {
    Serial.println("failed!");
    while(true) {} // something is wrong
  } 
  else {Serial.println("OK!");}
  
  // More initialization
  Serial.print("Initializing Raw SD card...");
  if (!card.init(SPI_HALF_SPEED, SD_CS)) {
    Serial.println("failed!");
    while(true) {} // something is wrong
  } 
  else {Serial.println("OK!");}
  
  // Create states for different modes
  // C1 for Mode 1 - MENU screen
  // C2 for Mode 2 - Snake Game
  // C3 for Mode 3 - GAME OVER screen
  // C4 for Mode 4 - Choose level
  // C5 for Mode 5 - PAUSE screen
  typedef enum {C1 = 1, C2, C3, C4, C5, ERR} State;
  State state = C1;
  int select, snakelength;
  
  while (state!=ERR) {
    if  (state == C1) {
      /// ====== MODE 1 - MENU ====== ///
      Serial.println("Currently in Mode 1");
      snakelength = 1;
      init_vert = analogRead(JOYSTICK_VERT); 
      init_horiz = analogRead(JOYSTICK_HORIZ);
      
      // preparations for the game - to not overlap with the pause menu
      q = q_create(720);
      i = 64; // x component
      j = 80; // y component
      q_add(q,i,j); // load into the queue
      random_x = food_x(); // load x coordinate of food piece
      random_y = food_y(); // load y coordinate of food piece
      pausedirection = 0; // set paused direction to 0
      // reset grid to 0
      for (int a = 0; a < 24; a++) {
        for (int b = 0; b < 30; b++) {
        grid[a][b] = 0;
        }
      }
      
      // display main menu
      snake();
      tft.setTextSize(2);
      
      while(true) {
        // alternate highlighting of START
        unsigned long time = millis()%1000;
        int a = time%1000;
        if ((a<17)) {
        tft.setCursor(34, 83);
        tft.fillRoundRect(30,80,65,20,5,WHITE);
        tft.setTextColor(RED);
        tft.print("START");
        }
        else if ((a>500) && (a<520)) {
        tft.setCursor(34, 83);
        tft.fillRoundRect(30,80,65,20,5,RED);
        tft.setTextColor(WHITE);
        tft.print("START");
        }
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          break;
        }
      }
      state = C4; 
    }
    
    else if (state == C2) {
      /// ====== MODE 2 - SNAKE GAME ====== ///
      Serial.println("Currently in Mode 2");
      delay(50);
      soundsetup(); //setting up sound pin
      // print the background
      tft.fillScreen(DARKRED);
      tft.fillRect(4,5,120,150,DARKGRN);
      
      // print the snake
      int x,y;
      x = q_frontx(q);
      y = q_fronty(q);
      tft.fillRect(x,y,5,5, WHITE);
      
      //Bringing the food in, outside while loop first.
      tft.fillRect(random_x, random_y, 5, 5, YELLOW);
      
      // do auto calibration
      int px, py;
      int lastmove;
      
      // read beginning direction chosen by user
      if (pausedirection == 0) {
        direction = read_direction();
      }
      else {
        direction = pausedirection;
      }
      lastmove = direction;
      
      while (true) {
        
        // to direct movement 
        // (without going in reverse direction of previous movement)
        
        // up
        if (direction == 1) {
          if (lastmove == 2) {
            direction = 2;
            j = j-5;
          }
          else {
            j = j+5;
        }
        q_add(q,i,j);
        }
        // down
        else if (direction == 2) {
          if (lastmove == 1) {
            direction = 1;
            j = j+5;
          }
          else {
            j = j-5;
          }
        q_add(q,i,j);
        }
        // right
        else if (direction == 3) {
          if (lastmove == 4) {
            direction = 4;
            i = i-5;
          }
          else {
            i = i+5;
          }
        q_add(q,i,j);
        }
        // left
        else if (direction == 4) {
          if (lastmove == 3) {
            direction = 3;
            i = i+5;
          }
          else {
            i = i-5;
          }
        q_add(q,i,j);
        }
        
        // if the direction is changed, store the new direction & last move
        int new_direc = read_direction();
        if ((new_direc != direction) && (new_direc != 0)) {
          lastmove = direction;
          direction = new_direc;
        }
        
        // if the snake hits a piece of food, the food vanishes and gets replaced 
        if ((i == random_x) && (j == random_y)) {
          // snake grows by 4 squares, except for the first time
          // this allows for it to end up as a max of 720 in the queue
          if (snakelength == 1) {
            q_add(q,i,j);
            q_add(q,i,j);
            q_add(q,i,j);
            snakelength += 3;
          }
          else {
            q_add(q,i,j);
            q_add(q,i,j);
            q_add(q,i,j);
            q_add(q,i,j);
            snakelength += 4;
          }
      if (snakelength < 720) {
        random_x = food_x();
        random_y = food_y();
      
        // if the snake is already there, find a new spot for the food
        while (grid[random_x/5][random_y/5-1] == 1) {
          random_x = food_x();
          random_y = food_y();
        }
        // print the new food
        tft.fillRect(random_x, random_y, 5, 5, YELLOW);
          }
        }
        
        // if the snake runs over itself
        if ((snakelength > 1) && (grid[i/5][j/5-1] == 1)) {
          delay(450); // pause when snake runs into itself
          int m = 0;
          soundLoop();
          while(m < 6000) {
            int rand_x = dissolve_x();
            int rand_y = dissolve_y();
            tft.fillRect(rand_x, rand_y, 5, 5, BLACK);
            m++;
          }
          state = C3;
          break;
        }
        
        px = q_frontx(q);
        py = q_fronty(q);
        // reprint the snake if there is movement
        if ((i != px) || (j != py)) {
          tft.fillRect(i,j,5,5, WHITE);
          grid[i/5][j/5-1] = 1;          // snake body is in grid
          tft.fillRect(px,py,5,5,DARKGRN);
          grid[px/5][py/5-1] = 0;        // snake body is no longer in grid
          q_remove(q);                   // take away from the queue
          delay(speed);                  // controls the speed of the snake
        }
       
        // if any of the borders are hit
        if ((i < 4)||(j < 5)||(i > 119)||(j > 150)) {
          delay(450); // pause when border is hit
          // dissolve the screen
          int m = 0;
          soundLoop();
          while(m < 6000) {
            int rand_x = dissolve_x();
            int rand_y = dissolve_y();
            tft.fillRect(rand_x, rand_y, 5, 5, BLACK);
            m++;
          }
          //~ delay(250);
          state = C3; 
          break;
        }
        
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          state = C5;
          break;
        }
      }
    }
    
    else if (state == C3) {
      /// ====== MODE 3 - GAME OVER ====== ///
      Serial.println("Currently in Mode 3");
      q_destroy(q); // clear the queue
      tft.fillScreen(BLACK);
      tft.fillRoundRect(5,20,118,25,5,RED);
      tft.setCursor(10, 25); 
      tft.setTextColor(BLACK);
      tft.setTextSize(2);
      tft.setTextWrap(true);
      tft.print("GAME OVER");
      tft.print("\n"); 
      
      tft.setCursor(10, 55);
      tft.setTextColor(RED);
      tft.setTextSize(1.5);
      if (snakelength >= 720) {
        snakelength = 720;
        tft.print("YOU WON! CONGRATZ");
      }
      else {
        tft.print("      Oh no!         You hit something!");
      }
      
      tft.setCursor(10, 80);
      tft.setTextColor(WHITE);
      tft.setTextSize(1);
      tft.print("Length of Snake:");
      tft.print(snakelength);
      tft.setCursor(10, 100);
      tft.print("Press the joystick   to return to main    menu");
      
      // Read the Joystick - HIGH if not pressed, LOW otherwise
      while (true) {
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          break;
        }
      }
      state = C1;
    }
    
    else if (state == C4) {
      /// ====== MODE 4 - CHOOSE LEVEL ====== ///
      Serial.println("Currently in Mode 4");
      // printing
      // snake display
      snake();
      // difficulty levels
      tft.setTextSize(2);  
      tft.setTextColor(WHITE);
      easy(RED);
      tft.setTextColor(RED);
      medium(WHITE);
      hard(WHITE);
      
      int selection = 1;
      int oldselection;
      while(true) {
        // read direction from the user for updating selection
        oldselection = selection;
        vertical = analogRead(JOYSTICK_VERT);      // will be 0-1023
        delay(100);
        
        // scroll down
        if (vertical > init_vert + 200) {
        selection++;
          if (selection > 3) {
            selection = 0;
          }
        } 
        // scroll up
        else if (vertical < init_vert - 200) {
          selection--;
          if (selection < 0) {
            selection = 3;
          }
        }
        
        if (selection != oldselection) {
          update(selection);
        }
        
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          Serial.print("made selection: ");
          Serial.println(selection);
          if (selection == 1) {speed = 225;}
          else if (selection == 2) {speed = 150;}
          else if (selection == 3) {speed = 75;}
          break;
        }
      }
      state = C2;
    }
    
    else if (state == C5) {
      /// ====== MODE 5 - PAUSE MENU ====== ///
      Serial.println("Currently in Mode 5");
      pausedirection = direction;
      
      // printing snake and pause
      snake();
      tft.setTextSize(2);
      tft.setCursor(34, 73); 
      tft.fillRoundRect(30,70,65,20,5,WHITE);
      tft.setTextColor(RED);
      tft.print("Pause");
      
      while(true) {
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          break;
        }
      }
      // reset grid to 0
      for (int a = 0; a < 24; a++) {
        for (int b = 0; b < 30; b++) {
        grid[a][b] = 0;
        }
      }
      state = C2; 
    }
    //if not any of this:
    else { 
      Serial.println("There has been an error");
      state = ERR; 
    }
  }
    
  Serial.end();
  return 0;
}
Example #17
0
int microphoneModule::readAnalog(void){
	pinMode(pin_number, INPUT_ANALOG);
	int analogValue = analogRead(pin_number);
	pinMode(pin_number, INPUT);
	return analogValue;
}
Point TouchScreen::getPoint(void) 
{
    int x, y, z = 1;
    int samples[NUMSAMPLES];
#if TSDEBUG
    int xx[2] = {0, 0};
    int yy[2] = {0, 0};
#endif
    uint8_t i, valid;

    uint8_t xp_port = digitalPinToPort(_xp);
    unsigned char yp_port = digitalPinToPort(_yp);
    unsigned char xm_port = digitalPinToPort(_xm);
    unsigned char ym_port = digitalPinToPort(_ym);

    unsigned char xp_pin = digitalPinToBitMask(_xp);
    unsigned char yp_pin = digitalPinToBitMask(_yp);
    unsigned char xm_pin = digitalPinToBitMask(_xm);
    unsigned char ym_pin = digitalPinToBitMask(_ym);
    valid = 1;
    pinMode(_yp, INPUT);
    pinMode(_ym, INPUT);

    *portOutputRegister(yp_port) &= ~yp_pin;
    *portOutputRegister(ym_port) &= ~ym_pin;

    pinMode(_xp, OUTPUT);
    pinMode(_xm, OUTPUT);

    *portOutputRegister(xp_port) |= xp_pin;
    *portOutputRegister(xm_port) &= ~xm_pin;

    for (i=0; i<NUMSAMPLES; i++)
    {
#if AVERAGE
        samples[i] = avr_analog(_yp);
#else
        samples[i] = analogRead(_yp);
#endif

#if TSDEBUG
        xx[i] = samples[i];
#endif
    }

#if !COMP
    if (samples[0] != samples[1]) { valid = 0; }
#else
    int icomp = samples[0]>samples[1]?samples[0]-samples[1]:samples[1] - samples[0];
    if(icomp > COMP)valid = 0;
#endif

    x = (samples[0] + samples[1]);

    pinMode(_xp, INPUT);
    pinMode(_xm, INPUT);
    *portOutputRegister(xp_port) &= ~xp_pin;

    pinMode(_yp, OUTPUT);
    *portOutputRegister(yp_port) |= yp_pin;
    pinMode(_ym, OUTPUT);

    for (i=0; i<NUMSAMPLES; i++) {
#if AVERAGE
        samples[i] = avr_analog(_xm);
#else
        samples[i] = analogRead(_xm);
#endif
#if TSDEBUG
        yy[i] = samples[i];
#endif
    }

#if !COMP
    if (samples[0] != samples[1]) { valid = 0; }
#else
    icomp = samples[0]>samples[1]?samples[0]-samples[1]:samples[1] - samples[0];
    if(icomp>COMP)valid = 0;
#endif
    y = (samples[0]+samples[0]);

    pinMode(_xp, OUTPUT);
    *portOutputRegister(xp_port) &= ~xp_pin;            // Set X+ to ground
    *portOutputRegister(ym_port) |=  ym_pin;            // Set Y- to VCC
    *portOutputRegister(yp_port) &= ~yp_pin;            // Hi-Z X- and Y+
    pinMode(_yp, INPUT);

    int z1          = analogRead(_xm);
    int z2          = analogRead(_yp);
    float rtouch    = 0;

    rtouch  = z2;
    rtouch /= z1;
    rtouch -= 1;
    rtouch *= (2046-x)/2;
    rtouch *= RXPLATE;
    rtouch /= 1024;
    z = rtouch;
    if (! valid) {
        z = 0;
    }

#if TSDEBUG
    if(z > __PRESURE){
        Serial.print("x1 = "); Serial.print(xx[0]);
        Serial.print("\tx2 = ");Serial.print(xx[1]);
        Serial.print("\ty2 = ");Serial.print(yy[0]);
        Serial.print("\ty2 = ");Serial.println(yy[1]);
    }
#endif

    return Point(x, y, z);
}
Example #19
0
// Main arduino loop.
void loop() {
    short      v;
    byte       t;
    int        p;
    rov_servo *s;
    if (!is_waiting && Serial.available() > 32) {
        Serial.write(OP_SHOULDWAIT);
        is_waiting = true;
        return;
    } else if (is_waiting && Serial.available() < 16) {
        Serial.write(OP_SHOULDSTART);
        is_waiting = false;
        return;
    } else if (Serial.available() > 0) {
        switch(Serial.read()) {
        case OP_SERVO_WRITE:
            while(!Serial.available());
            p = Serial.read();
            while(!Serial.available());
            v = Serial.read();
            if (s = lookup_servo(p)) { // Find the servo object on this pin.
                s->s.write(v);
            }
            break;
        case OP_DIGITAL_ON:
            while (!Serial.available());
            digitalWrite(Serial.read(),HIGH);
            break;
        case OP_DIGITAL_OFF:
            while (!Serial.available());
            digitalWrite(Serial.read(),LOW);
            break;
        case OP_DIGITAL_READ:
            while(!Serial.available());
            v = (digitalRead(Serial.read()) == HIGH) ? 1 : 0;
            Serial.write((uint8_t*) &v,2);
            break;
        case OP_ANALOG_WRITE:
            while (!Serial.available());
            p = Serial.read();
            while (!Serial.available());
            v = Serial.read();
            analogWrite(p,v);
            break;
        case OP_ANALOG_READ:
            while (!Serial.available());
            v = analogRead(Serial.read());
            Serial.write((uint8_t*) &v,2);
            break;
        case OP_SET_PINSTATE:
            while (!Serial.available());
            t = Serial.read();
            p = t & 0x3f;  // Get the pin number.
            if (s = lookup_servo(p)) { // Detach any servos on this pin.
                s->s.detach();
                s->p = -1;
            }
            t = (t & 0xc0) >> 6;
            if (t == ROV_SERVO) {
                for (v = 0; v < SERVOC; v++) {
                    if (servov[v].p == -1) { // Find a free servo.
                        s = &servov[v];
                        s->p = p;
                        s->s.attach(p,1000,2000);
                        s->s.write(90);
                        break;
                    }
                }
            } else if (t == INPUT_PULLUP) {
                pinMode(p,INPUT_PULLUP);
            } else {
                pinMode(p,(t) ? OUTPUT : INPUT);
            }
            break;
        }
    }
}
Example #20
0
void loop()
{
  // read the potentiometer position
  colorVal = analogRead(potPin);
  powerVal = map(analogRead(pwrPotPin), 0, 1023, 0, 510);
  
  Serial.println(powerVal, DEC);
  
  buttonState = digitalRead(switchPin);  // read input value and store it in val

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {                // check if the button is pressed
      switch(lightMode) {
        case 0:
        lightMode = 1;
        break;
        case 1:
        lightMode = 2;
        break;
        case 2:
        lightMode = 3;
        break;
        case 3:
        lightMode = 0;
        break;
      }
    }
    lastButtonState = buttonState;
  }

  if (lightMode == 0) {      // turn light off
    analogWrite(ledRed, 0);
    analogWrite(ledGreen, 0);
    analogWrite(ledBlue, 0); 
  }
  if (lightMode == 1) {        // set fixed color
    setColor();
    setPower();

    writeLED();
  }

  if (lightMode == 2) {     // pulse fixed color
    if (millis() - previousMillis > interval) {
      // save the last time you blinked the LED 
      previousMillis = millis();
      setColor();
      
      /*
      if (pulseState > powerVal) {
        pulseState = powerVal;
      }
      */
      
      if (pulseDir == 0) {
        pulseState--;
        
        if (pulseState == 0) {
          pulseDir = 1;
        }
      } else {
        pulseState++;
        
        if (pulseState >= 255) {
          pulseDir = 0;
        }
      }
      
      redPwr = map(redPwr, 0, 255, 0, pulseState);
      bluePwr = map(bluePwr, 0, 255, 0, pulseState);
      greenPwr = map(greenPwr, 0, 255, 0, pulseState);
      
      
      writeLED();
    }
  }

  if (lightMode == 3) {  // randomsize colorNew and step colorPwr to it
    if (millis() - previousMillis > interval) {
      // save the last time you blinked the LED 
      previousMillis = millis();
      
      if (redPwr > redNew) {
        redPwr--;
      } 
      if (redPwr < redNew) {
        redPwr++;
      }
      if (greenPwr > greenNew) {
        greenPwr--;
      } 
      if (greenPwr < greenNew) {
        greenPwr++;
      }
      if (bluePwr > blueNew) {
        bluePwr--;
      } 
      if (bluePwr < blueNew) {
        bluePwr++;
      }

      // If all Pwr match New get new colors

      if (redPwr == redNew) {
        if (greenPwr == greenNew) {
          if (bluePwr == blueNew) {
            redNew = random(254);
            greenNew = random(254);
            blueNew = random(254);
          }
        }
      }
      
      writeLED();
    }
  }
}
Example #21
0
void step_servoY() {       		    // synchroniczne
	volatile ServoChannel &ser = servos[INNER_SERVOY];
	if( pcb_type == 2 ){			// servos + magicled
		if( ser.pos_changed == true ){  // mam byc gdzie indziej
		//	Serial.print("-pos= " + String(servos[index].last_pos ));
		//	Serial.print("\t tar= " + String(servos[index].target_pos) );
		//	Serial.println("\t d= " + String(delta) );
			servo_lib[INNER_SERVOY].writeMicroseconds(ser.last_pos);
			ser.pos_changed = false;
			if(ser.last_pos == ser.target_pos){		// on target pos
				ser.moving= DRIVER_DIR_STOP;
				send_servoYisReady();
			}
		}
	}else if(pcb_type == 3 ){		// actuators + magicled
		if( ser.moving != DRIVER_DIR_STOP ){
			ser.last_pos = analogRead(PIN_B3_IN_Y);
			if( ser.last_pos == y_last_val || abs(ser.last_pos - y_last_val) <= 3){
			/*
				if( y_repeat %30 == 1 ){
					Serial.print("-");
					Serial.print(ser.last_pos);
					Serial.print("-");
					Serial.println(y_repeat);
				}*/
				y_repeat++;
				if( y_repeat == 700 ){
					Serial.print("RRYSTOPS,");
					Serial.println(ser.last_pos);
					Serial.flush();
					stopY( false );
					sendYpos();
					y_repeat = 0;
				}
			}else{
			/*
				if(y_repeat>60){
					Serial.print("-reset-");
					Serial.print(ser.last_pos);
					Serial.print("-");
					Serial.println(y_repeat);
				}*/
				y_repeat	=0;
				y_last_val	= ser.last_pos;
			}
			
			if( ser.moving == DRIVER_DIR_FORWARD ){
				if( ser.last_pos >= Y_MAX_VAL ){			// stop
					stopY( false );
					sendYpos();
		//			Serial.println("-step, STOP Z max");
				}else if( ser.last_pos >= ser.target_pos ){
					stopY( false );
					sendYpos();
				}
			}else if( ser.moving == DRIVER_DIR_BACKWARD ){
				if(  ser.last_pos <= Y_MIN_VAL ){			// stop
		//			Serial.println("-step, STOP Z min");
					stopY( false );
					sendYpos();
				}else if( ser.last_pos <= ser.target_pos ){
					stopY( false );
					sendYpos();
				}
			}
		}
	}
}
Example #22
0
	//function to get data from sensor and queue results for transfer to ST Cloud 
	void PS_Illuminance::getData()
	{
		int m_nSensorValue=map(analogRead(m_nAnalogInputPin), SENSOR_LOW, SENSOR_HIGH, MAPPED_LOW, MAPPED_HIGH);
		
		Everything::sendSmartString(getName() + " " + String(m_nSensorValue));
	}
Example #23
0
void loop() {
	// try to get client
	EthernetClient client = server.available();
	String getStr;
	
	if (client) {
		digitalWrite(greLed,HIGH);
		boolean currentLineIsBlank = true;
		boolean indice = false;
		while (client.connected()) {
			if (client.available()) {	// client data available to read
				char c = client.read();	// read 1 byte (character) from client
				// filter GET request
				// GET /index.html HTTP/1.1
				if (c == 'G') {
					c = client.read();
					if (c == 'E') {
						c = client.read();
						if (c == 'T') {
							Serial.print("GET=");
							c = client.read(); // space
							while (true) {
								c = client.read();
								if (c == ' ') {
									break;
								}
								//Serial.println(c);
								getRequest[getIndi] = c;
								getIndi++;
							}
							Serial.print(getRequest);
							Serial.println("@");
						}
					}
				}
				if (c == '\n' && currentLineIsBlank) {
					// convert to string and clear char array
					String getStr(getRequest);
					Clear();

					// if check
					// first page
					if (getStr == "/" || getStr == "/index.html") {
						indice = true;
					}

					// ajax GET info
					else if (getStr.startsWith("/Set?")) {
						indice = true;
						int getRequestStart = getStr.indexOf('?' );
						int getRequestFirst = getStr.indexOf('=' );
						int getRequestFinal = getStr.indexOf('/',2);
						int getRequestDuall = getStr.indexOf('&' );	// 2 GET
						if (getRequestDuall>0) {	// /index.html?X=20&Y=30
							int getRequestSecon = getStr.indexOf('=', getRequestFirst+1);
							String inputFirst_1 = getStr.substring(getRequestStart+1, getRequestFirst);	// X
							String valueFirst_1 = getStr.substring(getRequestFirst+1, getRequestDuall);	// 20
							String inputFirst_2 = getStr.substring(getRequestDuall+1, getRequestSecon);	// Y
							String valueFirst_2 = getStr.substring(getRequestSecon+1, getRequestFinal);	// 30
							if (inputFirst_1 == "X") {
								Update('X',valueFirst_1.toInt());
								Update('Y',valueFirst_2.toInt());
							}
							// reverse
							else if (inputFirst_1 == "Y") {
								Update('Y',valueFirst_1.toInt());
								Update('X',valueFirst_2.toInt());
							}
						}
						else {						// /index.html?Y=50 or X=50
							String inputFirst = getStr.substring(getRequestStart+1, getRequestFirst);	// Y
							String valueFirst = getStr.substring(getRequestFirst+1, getRequestFinal);	// 50
							if (inputFirst == "X") {
								Update('X',valueFirst.toInt());
							}
							else if (inputFirst == "Y") {
								Update('Y',valueFirst.toInt());
							}
						}
					}

					//ajax SAVE info
					else if (getStr.startsWith("/Save/")) {
						digitalWrite(redLed,HIGH);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						Serial.println("SAVE");
						Serial.println("");
						SD.remove(LOG);
						dataFile = SD.open(LOG, FILE_WRITE);
						if(dataFile) {				// X=123-Y=45-
							dataFile.print("X=");
							dataFile.print(X);
							dataFile.print("-Y=");
							dataFile.print(Y);
							dataFile.print("-");
							dataFile.close();
						}
						digitalWrite(redLed,LOW);
					}

					//ajax RESET info
					else if (getStr.startsWith("/Reset/")) {
						digitalWrite(redLed,HIGH);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						Serial.println("RESET");
						Serial.println("");
						delay(1);
						servoX.detach();
						servoY.detach();
						digitalWrite(redLed,LOW);
						digitalWrite(resetPin, LOW);
					}
					// ajax SET info
					else if (getStr.startsWith("/Coordinate/")) {
						digitalWrite(redLed,HIGH);
						GetValue();
						double temp = analogRead(thermRes);
						int phot = analogRead(photoRes);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						client.println();
						// JSON
						client.print("{\"coordinate\":{\"X\":");
						client.print(X);
						client.print(",\"Y\":");
						client.print(Y);
						client.print("},\"temp\":");
						client.print(GetTemp(temp),1);
						client.print(",\"light\":");
						client.print(phot);
						client.print(",\"network\":\"");
						client.print(Ethernet.localIP());
						client.print("\",\"file\":[");
						for (int i=0; i<HTTP_FILE; i++) {
							File dFile = SD.open(GET[i]);
							if (dFile) {
								if(i>0) {
									client.print(",");
								}
								client.print("{");
								client.print("\"name\":\"");
								client.print(GET[i]);
								client.print("\",\"size\":");
								client.print(dFile.size());
								client.print("}");
							}
						}
						client.println("]}");
						digitalWrite(redLed,LOW);
					}

					// print other file
					else {
						for(int i=1; i<HTTP_FILE; i++) {
							if (getStr == TYP[0][i]) {
								webFile = SD.open(GET[i]);
								if (webFile) {
									client.println("HTTP/1.1 200 OK");
									client.println(TYP[1][i]);
									if(TYP[2][i] == "1") {
										client.println("Content-Encoding: gzip");
									}
									client.print("Content-Length: ");
									client.println(webFile.size());
									client.println("Cache-Control: max-age=302400, public");
									client.println("Connection: close");
									client.println();
								}
								break;
							}
						}
					}
					// endif check

					// print index.html
					if (indice) {
						webFile = SD.open(GET[0]);
						if (webFile) {
							client.println("HTTP/1.1 200 OK");
							client.println(TYP[1][0]);
							client.print("Content-Length: ");
							client.println(webFile.size());
							client.println("Connection: close");
							client.println();
						}
					}
					// read file and write into web client
					if (webFile) {
						while(webFile.available()) {
							client.write(webFile.read());
						}
						webFile.close();
					}
					
					break;
				}

				if (c == '\n') {
					// last character on line of received text. Starting new line with next character read
					currentLineIsBlank = true;
				} 
				else if (c != '\r') {
					// you've gotten a character on the current line
					currentLineIsBlank = false;
				}
			}
		}
		//delay(1);		// give the web browser time to receive the data
		client.stop();	// close the connection
		digitalWrite(greLed,LOW);
	}
}
Example #24
0
void Bras::read_pression()
{
    pression =  (analogRead(pin_pression) / 1024.  + 0.095)/9;
    pression_on = pression < 0.8;
}
Example #25
0
int accelLib::readY()
{
   return analogRead(_ypin);
}
Example #26
0
float temperatureModule::read(void){
	pinMode(pin_number, INPUT_ANALOG);
	float temp = (((float)analogRead(pin_number) * 3300 / 4096)-400) / 19.5;
	return temp;
}
/// getDistanceRaw(): Returns the distance as a raw value: ADC output: 0 -> 1023
int AnalogDistanceSensor::getDistanceRaw()
{
  return (analogRead(_distancePin));
}
Example #28
0
int hallModule::read(void){
	pinMode(pin_number, INPUT_ANALOG);
	int temp = 23 + (((analogRead(pin_number) * 3300 / 4096) - 1691) / 1.3);
	return temp;
}
Example #29
0
void Device::loop(){
 
 // temperature sensor
#ifdef temperature
  float umidade = dht.readHumidity(); 
  
  // Lê o valor da temperatura em Celsius (leitura padrão).
  float temperatura = dht.readTemperature();

  // Calcula o índice de calor em graus Celsius (Fahrenheit = false).
  float indiceCalor = dht.computeHeatIndex(temperatura, umidade, false);

  #ifdef LCD	
	ardulcd.loop(umidade,temperatura,indiceCalor);	
  #endif
  
  root["temperature"] = temperatura;  
  root["humidity"] = umidade;  
  root["heatIndex"] = indiceCalor; 
#endif

// luminosity sensor
#ifdef luminosity
   int readValue = analogRead(sensorPort); 
   root["luminosity"] = readValue;
  
  #ifdef LCD
	ardulcd.loop(readValue);
  #endif
#endif

// presence sensor
#ifdef presence
	//Lendo o valor do sensor PIR. Este sensor pode assumir 2 valores
	//1 quando detecta algum movimento e 0 quando não detecta.
   if (detected){
		ligarAlarme();
	}
	
	valorSensorPIR = digitalRead(pinSensorPIR);  	
	 
	//Verificando se ocorreu detecção de movimentos
	if (valorSensorPIR == 1) {	  			  
	  root["value'"] = "Tem alguem";
	  #ifdef LCD
		ardulcd.loop("Tem alguem");
	  #endif
	  detected = true;
	} else {
		desligarAlarme();
		root["value'"] = "Nao tem ninguem";
		#ifdef LCD
			ardulcd.loop("Nao tem ninguem");
		#endif
		detected = false;
	} 
	
#endif

// gas sensor
#ifdef gas
	int valor_analogico = 0;
	valor_analogico = analogRead(sensorPort);  
	root["GasLevel"] = valor_analogico;
	// Verifica o nível da concentração de gás.
  	if (valor_analogico > nivel_sem_gas){    
    	root["Info"] = "Gas detected.";   
		#ifdef LCD
			ardulcd.loop("Gas detected", valor_analogico);
		#endif
  	}else{
    	root["Info"] = "Gas not detected"; 
		#ifdef LCD
			ardulcd.loop("Gas not detected", valor_analogico);
		#endif
  	}
#endif

#ifdef agua
  	if( digitalRead(sensorPort) == HIGH) {      
      	sensorData = 1;
		
		root["value"] = "Water detected";  
		#ifdef LCD
			ardulcd.loop("Water detected");
		#endif
   	}else{
      	sensorData = 0;
		
		root["value"] = "Water undetected"; 
		#ifdef LCD
			ardulcd.loop("Water undetected");
		#endif
   	}
	
    if (sensorData == 1){    
    	
 	}else{
    	
 	}

#endif

#ifdef USB
   root.printTo(Serial);
#endif
   
}
Example #30
0
uint16_t GasSensor::loopAction(char temp, char humidity)
{
  // Quality calculation after MAP_RESET_TIME
  uint32_t start_millis = millis();
  if (start_millis>lmillis)
  {
    mapresettime=mapresettime-((start_millis-lmillis)/1000);      
    if (mapresettime<=0)
    {
      // reset counter
      mapresettime = MAP_RESET_TIME;
    
     // htmap_max -> htmap_avg calucation
     for (uint8_t hum=0; hum<HT_MAP_COUNT_HUM; hum++)
     {
       for (uint8_t temp=0; temp<HT_MAP_COUNT_TEMP; temp++)
       {
         if (htmap_max[hum][temp]<65535)
         {
           htmap_avg[hum][temp]=(uint16_t)(((unsigned long)htmap_avg[hum][temp]*(MAP_RESET_AVG_COUNT-1)+(unsigned long)htmap_max[hum][temp])/MAP_RESET_AVG_COUNT);
           htmap_max[hum][temp]=65535;
         }
       }
     }
    }
  }
  lmillis=start_millis;
  
  // Pin protection
#ifdef ARDUINO
  if (pinhigh)
  {
     if (!digitalRead(pin))
     {
      pinhigh=false;
     }
       else
     {
        return 65535;
     }
  }
#endif

  // Read value
  int tmp=analogRead(pin);

  // Pin protection II Value near maximum (1.2V)?
  if (tmp>65000)
  {
      pinhigh=true;
  }
  
  // Burn in time?
  if ( (lval==0) && (millis()<SENSOR_GAS_PREHEAT_TIME))
  {
    ltmp = temp;
    lhum = humidity;
    return tmp;
  }
 
  // Calculation
  char hpos = (humidity-HT_MAP_MIN_HUM)/HT_MAP_DIV_HUM;
  if (hpos<0) hpos==0;
  if (hpos>=HT_MAP_COUNT_HUM) hpos=HT_MAP_COUNT_HUM-1;
  char tpos = (temp-HT_MAP_MIN_TEMP)/HT_MAP_DIV_TEMP;
  if (tpos<0) tpos=0;
  if (tpos>=HT_MAP_COUNT_TEMP) tpos=HT_MAP_COUNT_TEMP-1;
  
  // Write htmap
  lval = tmp;
  sethtmap(temp,humidity,tmp);
  
  // Rule check to avoid jumps in table, check actual cell against neighbours
  int maxval = htmap_avg[hpos][tpos];
  if ( (hpos>0) && (tpos>0) &&  (hpos<HT_MAP_COUNT_HUM-1) && (tpos<HT_MAP_COUNT_TEMP-1))
  {
    // hpos-1 must be less
    if (htmap_avg[hpos-1][tpos]>maxval) htmap_avg[hpos-1][tpos]=maxval;
    // tpos-1 must be less
    if (htmap_avg[hpos][tpos-1]>maxval) htmap_avg[hpos][tpos-1]=maxval;
    // hpos-1,tpos-1 must be less
    if (htmap_avg[hpos-1][tpos-1]>maxval) htmap_avg[hpos-1][tpos-1]=maxval;    
    // hpos+1 must be greater
    if (htmap_avg[hpos+1][tpos]<maxval) htmap_avg[hpos][tpos-1]=maxval;
    // tpos +1 must be greater
    if (htmap_avg[hpos][tpos+1]<maxval) htmap_avg[hpos][tpos+1]=maxval;
    // hpos+1,tpos +1 must be greater
    if (htmap_avg[hpos+1][tpos+1]<maxval) htmap_avg[hpos+1][tpos+1]=maxval;
    // hpos-1,tpos +1 must be greater
    if (htmap_avg[hpos-1][tpos+1]<maxval) htmap_avg[hpos-1][tpos+1]=maxval;
    // hpos+1,tpos-1 must be less
    if (htmap_avg[hpos+1][tpos-1]>maxval) htmap_avg[hpos+1][tpos-1]=maxval;
  }
  
  // maxval: bilinear interpolation
  // avoid quality jumping when temp/hum
  if ( (htmap_avg[hpos][tpos+1]<65535) && (htmap_avg[hpos+1][tpos]<65535) && (htmap_avg[hpos+1][tpos+1]<65535) && (hpos<HT_MAP_COUNT_HUM-2) && (tpos<HT_MAP_COUNT_TEMP-2))
  {
      char modulo_temp = (temp-HT_MAP_MIN_TEMP)%HT_MAP_DIV_TEMP;
      char modulo_hum  = (humidity-HT_MAP_MIN_HUM)%HT_MAP_DIV_HUM;
      
      uint16_t temp1 = interpolation(htmap_avg[hpos][tpos],htmap_avg[hpos][tpos+1], modulo_temp, HT_MAP_DIV_TEMP);
      uint16_t temp2 = interpolation(htmap_avg[hpos+1][tpos],htmap_avg[hpos+1][tpos+1], modulo_temp, HT_MAP_DIV_TEMP);
      
      maxval = interpolation(temp1,temp2, modulo_hum, HT_MAP_DIV_HUM);
  }

  //  quality = ( (float)maxval/(float)lval)*100;
  float f1 = lval-maxval;
  if (f1<0) f1=0;
  float f2 = (maxval*SENSOR_VARIANCE)-maxval;
  if (f2<0) f2=1;
  quality = 100-((f1*100)/f2);
  
  ltmp = temp;
  lhum = humidity;
  
  // Store quality history
  quality_history[quality_history_pos]=quality;
  quality_history_pos++;
  if (quality_history_pos>=QUALITY_HISTORY) quality_history_pos=0;
  
  return lval;
}