1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- /* Functions for various sensor types */
- float Vref = 0; //read your Vcc voltage,typical voltage should be 5000mV(5.0V)
- float microsecondsToCm(long microseconds)
- {
- // The speed of sound is 340 m/s or 29 microseconds per cm.
- // The ping travels out and back, so to find the distance of the
- // object we take half of the distance travelled.
- return microseconds / 29 / 2;
- }
- long Ping(int pin) {
- long duration, range;
- // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
- // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
- pinMode(pin, OUTPUT);
- digitalWrite(pin, LOW);
- delayMicroseconds(2);
- digitalWrite(pin, HIGH);
- delayMicroseconds(5);
- digitalWrite(pin, LOW);
- // The same pin is used to read the signal from the PING))): a HIGH
- // pulse whose duration is the time (in microseconds) from the sending
- // of the ping to the reception of its echo off of an object.
- pinMode(pin, INPUT);
- duration = pulseIn(pin, HIGH);
- // convert the time into meters
- range = microsecondsToCm(duration);
- return (range);
- }
- /*read reference voltage*/
- long readVref()
- {
- long result;
- #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__) || defined (__AVR_ATmega328P__)
- ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
- #elif defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB1286__)
- ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
- ADCSRB &= ~_BV(MUX5); // Without this the function always returns -1 on the ATmega2560 http://openenergymonitor.org/emon/node/2253#comment-11432
- #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
- ADMUX = _BV(MUX5) | _BV(MUX0);
- #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
- ADMUX = _BV(MUX3) | _BV(MUX2);
- #endif
- #if defined(__AVR__)
- delay(2); // Wait for Vref to settle
- ADCSRA |= _BV(ADSC); // Convert
- while (bit_is_set(ADCSRA, ADSC));
- result = ADCL;
- result |= ADCH << 8;
- result = 1126400L / result; //1100mV*1024 ADC steps http://openenergymonitor.org/emon/node/1186
- return result;
- #elif defined(__arm__)
- return (3300); //Arduino Due
- #else
- return (3300); //Guess that other un-supported architectures will be running a 3.3V!
- #endif
- }
- void initCurrentSensor()
- {
- Vref = readVref(); //read the reference votage(default:VCC)
- }
|