Advertisement
Guest User

Untitled

a guest
Jun 24th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 7.63 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. // if testing over 1000 cpm turn off debugging or the serial buffer will overload
  5. boolean debugmode = true;
  6.  
  7. const char* ssid = "";
  8. const char* password = "";
  9. const char* mqtt_server = "";
  10. const int interruptPin = D2; // ~D2 // connected to + LED
  11.  
  12. int totalHitCount = 0;
  13. int currentHitCount = 0;
  14. int lastMinCount = 0;
  15. double startMillis;
  16. double seconds;
  17. double minutes;
  18. double CPM = 0.0;
  19. double uSv = 0.0;
  20. double lastcSv = 0.0;
  21. int currentTimeSlot = 0;
  22. int eventsArray[60];
  23. int WiFiStrength = 0;
  24. int minHolder = 0;
  25. int minuteHits = 0;
  26. char msg[512];
  27.  
  28. boolean WiFiConnected = true;
  29.  
  30. const unsigned long REFRESH_INTERVAL = 10000; // ms
  31. double lastRefreshTime = 0;
  32.  
  33. const unsigned long LAST_MINUTE_COUNT_INTERVAL = 60000; // ms
  34. double lastMinuteCountTime = 0;
  35.  
  36. const unsigned long EVERY_SECOND_INTERVAL = 1000; // ms
  37. double everySecondCountTime = 0;
  38.  
  39. WiFiServer server(80);
  40. WiFiClient espClient;
  41. PubSubClient client(espClient);
  42.  
  43. //////////////////////////////////////////////////////////////////////////////////////
  44. // this function executes everytime there is hit to the Geiger counter             ///
  45. //////////////////////////////////////////////////////////////////////////////////////
  46. void pinChanged()
  47. {
  48.   detachInterrupt(interruptPin);
  49.   seconds = (millis() - startMillis) / 1000;
  50.   minutes = seconds / 60;
  51.   totalHitCount++;
  52.   currentHitCount++;
  53.   minuteHits++;
  54.  
  55.   // increase the event count by 1 for the current time slot
  56.   eventsArray[currentTimeSlot]++;
  57.  
  58.   // sum up all the event counts in our eventsArray to get a running sum
  59.   CPM = 0;
  60.   for (int i = 0; i < 60; i++) {
  61.     CPM += eventsArray[i];
  62.   }
  63.   uSv = CPM * 0.0057;
  64.  
  65.   if (debugmode) {
  66.     //  Good for debugging
  67.     Serial.print(" Total hit Count: "); Serial.println(totalHitCount);
  68.     Serial.print(" Current hit Count: "); Serial.println(currentHitCount);
  69.     Serial.print(" Last minute count: "); Serial.println(lastMinCount);
  70.     Serial.print(" Time seconds: "); Serial.println(seconds);
  71.     Serial.print(" Time minutes: "); Serial.println(minutes);
  72.     Serial.print(" CPM: "); Serial.println(CPM);
  73.     Serial.print(" uSv/hr: "); Serial.println(uSv);
  74.     Serial.print(" Slot: "); Serial.println((millis() / 1000) % 60);
  75.     Serial.println(" ");
  76.   }
  77.  
  78.   attachInterrupt(interruptPin, pinChanged, RISING);
  79. }
  80.  
  81. void sendStats(int totalHitCounter, int upseconds, int upminutes, double cpm, double sv) {
  82.   sprintf(msg, "{\"totalHitCounter\": %d, \"upseconds\": %d, \"upminutes\": %d, \"cpm\": %0.2f, \"sv\": %0.2f}", (int)totalHitCounter, (int)(upseconds), (int)upminutes, (double)cpm, (double)sv);
  83.   Serial.print("Publish message: ");
  84.   Serial.println(msg);
  85.   client.publish("home/sensors/geiger/input", msg);
  86. }
  87.  
  88. //////////////////////////////////////////////////////////////////
  89. // function used to reset variables: used for data clearing    ///
  90. // session reset                                               ///
  91. //////////////////////////////////////////////////////////////////
  92.  
  93. void resetVariables()
  94. {
  95.   //reset varialbles
  96.   totalHitCount = 0;
  97.   startMillis = millis();
  98.   seconds = 0.0;
  99.   minutes = 0.0;
  100.   CPM = 0.0;
  101.   uSv = 0.0;
  102.   minHolder = 0;
  103.   minuteHits = 0;
  104.   lastcSv = 0;
  105.   //
  106. }
  107.  
  108. void reconnect() {
  109.   // Loop until we're reconnected
  110.   while (!client.connected()) {
  111.     Serial.print("Attempting MQTT connection...");
  112.     // Create a random client ID
  113.     String clientId = "ESP8266Client-";
  114.     clientId += String(random(0xffff), HEX);
  115.     // Attempt to connect
  116.     if (client.connect(clientId.c_str())) {
  117.       Serial.println("connected");
  118.       // Once connected, publish an announcement...
  119.       client.publish("home/sensors/geiger/input", "geiger meter connected");
  120.       // ... and resubscribe
  121.       client.subscribe("home/sensors/geiger/output");
  122.     } else {
  123.       Serial.print("failed, rc=");
  124.       Serial.print(client.state());
  125.       Serial.println(" try again in 5 seconds");
  126.       // Wait 5 seconds before retrying
  127.       delay(1000);
  128.     }
  129.   }
  130. }
  131.  
  132. void callback(char* topic, byte* payload, int length) {
  133.   Serial.print("Message arrived [");
  134.   Serial.print(topic);
  135.   Serial.print("] ");
  136.   for (int i = 0; i < length; i++) {
  137.     Serial.print((char)payload[i]);
  138.   }
  139.   Serial.println();
  140. }
  141.  
  142. //////////////////////////////////
  143. //    main setup function      ///
  144. //////////////////////////////////
  145.  
  146. void setup() {
  147.  
  148.   pinMode(interruptPin, INPUT);
  149.   startMillis = millis();
  150.   attachInterrupt(interruptPin, pinChanged, RISING); // start counting Geiger hits
  151.  
  152.   if (debugmode)
  153.   {
  154.     Serial.begin(115200);
  155.     delay(10);
  156.   }
  157.  
  158.   // Connect to WiFi network
  159.   if (debugmode)
  160.   {
  161.     Serial.println();
  162.     Serial.println();
  163.     Serial.print("Connecting to ");
  164.     Serial.println(ssid);
  165.   }
  166.  
  167.   WiFi.begin(ssid, password);
  168.  
  169.   // Set the ip address of the webserver
  170.   // WiFi.config(WebServerIP, Gatway, Subnet)
  171.   // or comment out the line below and DHCP will be used to obtain an IP address
  172.   // which will be displayed via the serial console
  173.  
  174.   //WiFi.config(IPAddress(192, 168, 1, 220), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0));
  175.  
  176.   // connect to WiFi router
  177.   int waitCount = 0;
  178.   while (WiFi.status() != WL_CONNECTED) {
  179.     delay(500);
  180.     if (debugmode)
  181.       Serial.print(".");
  182.  
  183.     waitCount++;
  184.  
  185.     if (waitCount > 30)
  186.     {
  187.       WiFiConnected = false;
  188.       break;
  189.     }
  190.   }
  191.  
  192.   if (WiFiConnected) {
  193.     if (debugmode) {
  194.       Serial.println("");
  195.       Serial.println("WiFi connected");
  196.     }
  197.     // Start the server
  198.     server.begin();
  199.  
  200.     if (debugmode) {
  201.       Serial.println("Server started");
  202.       // Print the IP address
  203.       Serial.print("Use this URL to connect: ");
  204.       Serial.print("http://");
  205.       Serial.print(WiFi.localIP());
  206.       Serial.println("/");
  207.     }
  208.  
  209.   } else {
  210.     if (debugmode)
  211.       Serial.println("WiFi NOT connected");
  212.   }
  213.   client.setServer(mqtt_server, 1883);
  214.   client.setCallback(callback);
  215.  
  216.   // clean up eventsArray
  217.   for (int i = 0; i < 60; i++) {
  218.     eventsArray[i] = 0;
  219.   }
  220. }
  221.  
  222. ////////////////////////////////////
  223. //       main loop function      ///
  224. ////////////////////////////////////
  225.  
  226. void loop() {
  227.  
  228.   if (!client.connected()) {
  229.     reconnect();
  230.   }
  231.   client.loop();
  232.  
  233.   if((millis() - lastRefreshTime) > REFRESH_INTERVAL) {
  234.     lastRefreshTime = millis();
  235.     sendStats(totalHitCount, seconds, minutes, CPM, uSv);
  236.   }
  237.  
  238.   // hold the event count value every minune
  239.   if((millis() - lastMinuteCountTime) > LAST_MINUTE_COUNT_INTERVAL) {
  240.     lastMinuteCountTime = millis();
  241.     lastMinCount = currentHitCount;
  242.     currentHitCount = 0;
  243.   }
  244.  
  245.   // run every second
  246.   if((millis() - everySecondCountTime) > EVERY_SECOND_INTERVAL) {
  247.     everySecondCountTime = millis();
  248.     currentTimeSlot = (int)(everySecondCountTime / 1000) % 60;
  249.     eventsArray[currentTimeSlot] = 0;
  250.     /*
  251.     for (int i = 0; i < 60; i++) {
  252.       Serial.print(eventsArray[i]); Serial.print(", ");
  253.     }
  254.     Serial.println();
  255.     */
  256.   }
  257.  
  258.   // check to for any web server requests. ie - browser requesting a page from the webserver
  259.   WiFiClient client = server.available();
  260.   if (!client) {
  261.     return;
  262.   }
  263.  
  264.   // Wait until the client sends some data
  265.   WiFiStrength = WiFi.RSSI();
  266.   if (debugmode) {
  267.     Serial.println("new client");
  268.   }
  269.  
  270.   /*
  271.   double analogValue = analogRead(A0); // read the analog signal
  272.  
  273.   // convert the analog signal to voltage
  274.   // the ESP2866 A0 reads between 0 and ~3 volts, producing a corresponding value
  275.   // between 0 and 1024. The equation below will convert the value to a voltage value.
  276.  
  277.   double analogVolts = (analogValue * 3.12) / 1024;
  278.   */
  279. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement