Untitled

 avatar
unknown
plain_text
4 years ago
4.2 kB
14
Indexable
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Ticker.h>
#include <ArduinoJson.h>

#define SERVER_IP "SERVER"
const char *ssid =  "SSID";     // replace with your wifi ssid and wpa2 key
const char *pass =  "PASS";



int PINTIC = 5;

WiFiClient client;

Ticker blinker;

struct tm timeinfo;



#define LOG_PERIOD 20000    //период вывода CPM в миллисекундах, рекомендуется 15000-60000
#define MAX_PERIOD 60000    //маскимальный период мониторинга

unsigned long counts;             //переменная для записи количества импульсов с трубки
unsigned long cpm;                //переменная для CPM (количество распадов минуту)
unsigned int multiplier;          //множитель для подсчёта CPM
unsigned long previousMillis;     //переменная для записи времени

float mkzvHours = 0.0; // мкЗв/ч

void ICACHE_RAM_ATTR TicISR() {
  //Serial.println("Tick");
  counts++;
}

// #########################################################################
// Interrupt timer routine called every 250 ms
//
void onTimer() {
    cpm = counts * multiplier;                //CPM = количество импульсов * множитель
    mkzvHours = cpm / 151.0;                  //перевод CPM в мкЗв/час    
    counts = 0;                               //Сбросить счётчик импульсов
}

void setup() 
{
   Serial.begin(9600);
   delay(10);
           
   Serial.println("Connecting to ");
   Serial.println(ssid); 

   WiFi.begin(ssid, pass); 
   while (WiFi.status() != WL_CONNECTED) 
      {
        delay(500);
        Serial.print(".");
      }
  Serial.println("");
  Serial.print("Connected! IP address: ");
  Serial.println(WiFi.localIP());

  // Set time via NTP, as required for x.509 validation
  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  Serial.print("Waiting for NTP time sync: ");
  time_t now = time(nullptr);
  while (now < 8 * 3600 * 2) {
    delay(500);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println("");
  localtime_r(&now, &timeinfo);
  Serial.print("Current time: ");
  Serial.print(asctime(&timeinfo));


  counts = 0;                           //обнулить счётчик импульсов
  cpm = 0;                              //обнулить CPM
  multiplier = MAX_PERIOD / LOG_PERIOD; //расчёт множителя для перевода импульсов в CPM
      
  pinMode(PINTIC, INPUT);
  
  attachInterrupt(PINTIC, TicISR, FALLING);
  
  blinker.attach(LOG_PERIOD / 1000.0, onTimer);
}
 
void loop() 
{      
  // wait for WiFi connection
  if ((WiFi.status() == WL_CONNECTED)) {

    WiFiClient client;
    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    // configure traged server and url
    http.begin(client, "http://" SERVER_IP "/URL"); //HTTP
    http.addHeader("Content-Type", "application/json");

    Serial.print("[HTTP] POST...\n");

    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["geiger"] = mkzvHours;
    root["cpm"] = cpm;
    
    char JSONmessageBuffer[300];
    root.printTo( JSONmessageBuffer, sizeof(JSONmessageBuffer ) );
    Serial.println(JSONmessageBuffer);
    
    // start connection and send HTTP header and body
    int httpCode = http.POST(JSONmessageBuffer);

    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTP] POST... code: %d\n", httpCode);

      // file found at server
      if (httpCode == HTTP_CODE_OK) {
        const String& payload = http.getString();
        Serial.println(payload);
      }
    } else {
      Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();
  }
      
  delay(LOG_PERIOD);  // wait a while
}
Editor is loading...