Facebook
From ka, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 86
  1. //#define CAYENNE_DEBUG
  2. #define CAYENNE_PRINT Serial  // Comment this out to disable prints and save space
  3. #include <CayenneMQTTEthernet.h>
  4.  
  5. // Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
  6. char username[] = "";
  7. char password[] = "";
  8. char clientID[] = "";
  9.  
  10. #define PRESISTOR_VIRTUAL_CHANNEL 0
  11.  
  12. #define DISTANCE_VIRTUAL_CHANNEL 1
  13.  
  14. // Defines pins numbers for the HC-SR04 connections.
  15. const int trigPin = 9;
  16. const int echoPin = 10;
  17. const int pResistor = A0;
  18.  
  19. long duration;
  20. int distanceCm;
  21. int value;
  22. void setup() {
  23.  
  24. pinMode(trigPin, OUTPUT);
  25. pinMode(echoPin, INPUT);
  26. Serial.begin(9600);
  27. pinMode(pResistor, INPUT);// Set pResistor - A0 pin as an input (optional)
  28.  
  29.  Cayenne.begin(username, password, clientID);
  30.  
  31. }
  32.  
  33. void loop() {
  34.  // Cayenne.loop();
  35. value = analogRead(pResistor);
  36.     Serial.println(value);
  37.  
  38.  
  39. digitalWrite(trigPin, LOW);
  40. delayMicroseconds(2);
  41. digitalWrite(trigPin, HIGH);
  42. delayMicroseconds(10);
  43. digitalWrite(trigPin, LOW);
  44. duration = pulseIn(echoPin, HIGH);
  45. distanceCm= duration*0.034/2;
  46.  
  47.       Serial.println(distanceCm);// if distance less than 0.5 meter and more than 0 (0 or less means over range)
  48.  
  49. delay(100);
  50.  
  51.  
  52. if( (distanceCm < 68)&&(distanceCm > 10) && (value < 180))
  53.  {
  54.   Cayenne.virtualWrite(DISTANCE_VIRTUAL_CHANNEL, distanceCm, "prox", "cm");
  55.   Cayenne.virtualWrite(PRESISTOR_VIRTUAL_CHANNEL,value);
  56. }
  57.  
  58. }
  59.  
  60.  
  61. CAYENNE_OUT(PRESISTOR_VIRTUAL_CHANNEL)
  62. {
  63.    
  64.    value = analogRead(pResistor);
  65.    Serial.println(value);
  66.    
  67.  
  68. Cayenne.virtualWrite(PRESISTOR_VIRTUAL_CHANNEL,value);
  69. }
  70.  
  71. // This function is called at intervals to send HC-SR04 sensor data to Cayenne.
  72. CAYENNE_OUT(DISTANCE_VIRTUAL_CHANNEL)
  73. {
  74.  digitalWrite(trigPin, LOW);
  75. delayMicroseconds(2);
  76. digitalWrite(trigPin, HIGH);
  77. delayMicroseconds(10);
  78. digitalWrite(trigPin, LOW);
  79. duration = pulseIn(echoPin, HIGH);
  80. distanceCm= duration*0.034/2;
  81.  
  82. Serial.println(distanceCm);// if distance less than 0.5 meter and more than 0 (0 or less means over range)
  83.  
  84. delay(100);
  85.   // Send the distance value to Cayenne on proximity widget in centimeter.
  86.   Cayenne.virtualWrite(DISTANCE_VIRTUAL_CHANNEL, distanceCm, "prox", "cm");
  87. }
captcha