sensors.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Functions for various sensor types */
  2. float Vref = 0; //read your Vcc voltage,typical voltage should be 5000mV(5.0V)
  3. float microsecondsToCm(long microseconds)
  4. {
  5. // The speed of sound is 340 m/s or 29 microseconds per cm.
  6. // The ping travels out and back, so to find the distance of the
  7. // object we take half of the distance travelled.
  8. return microseconds / 29 / 2;
  9. }
  10. long Ping(int pin) {
  11. long duration, range;
  12. // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  13. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  14. pinMode(pin, OUTPUT);
  15. digitalWrite(pin, LOW);
  16. delayMicroseconds(2);
  17. digitalWrite(pin, HIGH);
  18. delayMicroseconds(5);
  19. digitalWrite(pin, LOW);
  20. // The same pin is used to read the signal from the PING))): a HIGH
  21. // pulse whose duration is the time (in microseconds) from the sending
  22. // of the ping to the reception of its echo off of an object.
  23. pinMode(pin, INPUT);
  24. duration = pulseIn(pin, HIGH);
  25. // convert the time into meters
  26. range = microsecondsToCm(duration);
  27. return (range);
  28. }
  29. /*read reference voltage*/
  30. long readVref()
  31. {
  32. long result;
  33. #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__) || defined (__AVR_ATmega328P__)
  34. ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  35. #elif defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB1286__)
  36. ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  37. ADCSRB &= ~_BV(MUX5); // Without this the function always returns -1 on the ATmega2560 http://openenergymonitor.org/emon/node/2253#comment-11432
  38. #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
  39. ADMUX = _BV(MUX5) | _BV(MUX0);
  40. #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
  41. ADMUX = _BV(MUX3) | _BV(MUX2);
  42. #endif
  43. #if defined(__AVR__)
  44. delay(2); // Wait for Vref to settle
  45. ADCSRA |= _BV(ADSC); // Convert
  46. while (bit_is_set(ADCSRA, ADSC));
  47. result = ADCL;
  48. result |= ADCH << 8;
  49. result = 1126400L / result; //1100mV*1024 ADC steps http://openenergymonitor.org/emon/node/1186
  50. return result;
  51. #elif defined(__arm__)
  52. return (3300); //Arduino Due
  53. #else
  54. return (3300); //Guess that other un-supported architectures will be running a 3.3V!
  55. #endif
  56. }
  57. void initCurrentSensor()
  58. {
  59. Vref = readVref(); //read the reference votage(default:VCC)
  60. }