aml_sensorbox_tmpNoise.ino 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. /*
  2. * AML TMP+NOISE
  3. *
  4. * VERSION: 1.11
  5. *
  6. *
  7. * The Sensorbox measures Temperature and Noise-Level and sends this information with the GPS-position to a webservice.
  8. *
  9. * ************************************************
  10. * GENERAL INFO AND COMPONENTS
  11. *
  12. * Measuring Battery: https://learn.adafruit.com/adafruit-feather-32u4-fona/power-management
  13. * Gettin Noise: http://arduinolearning.com/code/arduino-and-max4466-electret-module-example.php
  14. * Getting GSM Location: https://www.instructables.com/id/How-to-make-a-Mobile-Cellular-Location-Logger-with/
  15. *
  16. * Tiny GPS++ Library: http://arduiniana.org/libraries/tinygpsplus/
  17. *
  18. *
  19. * Battery saving:
  20. *
  21. * GPS Board: - Use EN Pin to turn of the board when not needed (https://learn.adafruit.com/adafruit-ultimate-gps/overview)
  22. * - EN soll laut der Quelle auf GND gesetzt werden. Es dauert dann aber länger bis wieder ein Fix gefunden wurde.
  23. *
  24. *
  25. * Feather FONA: - Cut the key trac on the bottom of the board (https://learn.adafruit.com/adafruit-feather-32u4-fona/power-management)
  26. * - If you want to depower the cell module, cut the KEY trace on the bottom of the board, wire KEY to an unused pad,
  27. * and toggle the pin low for 100ms to completely turn on/off the module.
  28. * - https://arduino.stackexchange.com/questions/54001/adafruit-feather-32u4-fona-key-pin
  29. * cut the trace and wire it to a micro controller pin
  30. * - Key - this is by default tied to ground, cut the trace on the bottom and wire to a microcontroller pin to manually turn the module on and off.
  31. * (Pulse low for a few seconds to change from on to off) This is the only way to truly disable the cellular module.
  32. *
  33. *************************************************
  34. * TODOS & BUGS:
  35. * - Die Ladeanzeige über die LED funktioniert nicht immer korrekt. Besonders gelbes Blinken (Aufladen) ist davon betroffen.
  36. * - GPS fix ist noch valide obwohl die Box offline ist. Wenn der Akku aus ist, sollte ein NO-FIX gesendet werden.
  37. *
  38. ************************************************
  39. *
  40. * IMPORTANT INFO:
  41. * - Be sure to use the correct Token and device number before uplading the code
  42. * - For A1 Sim-Cards the APN needs to be set in initFONA(). Uncomment the line if other SIM-Card is used or set the correct APN
  43. *
  44. *
  45. *
  46. *
  47. ************************************************
  48. *
  49. */
  50. #include <Adafruit_NeoPixel.h>
  51. #include "Adafruit_FONA.h"
  52. #include <SoftwareSerial.h>
  53. #include <TinyGPS++.h>
  54. #include <AES.h>
  55. #define LEDPIN 13
  56. #define ANALOG_TEMP_PIN A0
  57. #define ANALOG_NOISE_PIN A1
  58. #define KEYPIN 12
  59. #define GPSENABLE 11
  60. #define FONA_RX 9
  61. #define FONA_TX 8
  62. #define FONA_RST 4
  63. #define FONA_RI 7
  64. #define aref_voltage 3.3
  65. Adafruit_NeoPixel pixel(1, LEDPIN, NEO_GRB + NEO_KHZ800);
  66. //GSM
  67. SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
  68. SoftwareSerial *fonaSerial = &fonaSS;
  69. Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
  70. uint8_t type;
  71. //This is: Box 5
  72. char URL[] = "http://aml.media.tuwien.ac.at:11312/api/sensordata/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlhdCI6MTYwMDg0NjY2NH0.d5xvkTVDcHJl-K6KkohIWcUC5XcYNRZ_wzSLMvqAyvw";
  73. //char URL2[] = "http://www.mobillab.wien/sensorbox/write/";
  74. char URL3[] = "http://aml.media.tuwien.ac.at:11312/api/sensorstatus/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlhdCI6MTYwMDg0NjY2NH0.d5xvkTVDcHJl-K6KkohIWcUC5XcYNRZ_wzSLMvqAyvw";
  75. unsigned long ATtimeOut = 10000; // How long we will give an AT command to complete
  76. boolean initFONAagain = false;
  77. //Limits
  78. int offlineMv = 3520; //Lowest Millivolts before box shuts down
  79. int onlineMv = 3570; //Millivolts to go online again
  80. //GPS
  81. static const uint32_t GPSBaud = 9600;
  82. TinyGPSPlus gps;
  83. boolean encodeGPSAgain = false;
  84. //Timing
  85. unsigned long currentMillis = 0;
  86. unsigned long singleBlinkDuration = 500; //Duration for 1 Blink
  87. unsigned long lastSingleBlinkStart = 0;
  88. unsigned long blinkSequenceDuration = 4200; //Duration for an blink sequence (not sure if needed)
  89. unsigned long lastBlinkSequenceStart = 0;
  90. unsigned long blinkPauseDuration = 200; //Duration for blink pause
  91. unsigned long lastBlinkPauseStart = 0;
  92. unsigned long blinkInterval = 10000; //Interval to blink
  93. unsigned long checkBatInterval = 15000; //Interval for Checking the Battery -> long interval: every 10 Minutes (if everthing is ok) 600000; short interval: every 15 seconds (150000)
  94. unsigned long lastBatCheck = 0;
  95. unsigned long sendToWebInterval = 1200000; //20 min = 1200000; 5min = 300000; //Interval for sending data to webservice
  96. unsigned long lastSendToWeb = 0;
  97. unsigned long pullLowDuration = 2000; //3 seconds for pulling KEYPIN low to turn off/on Fona
  98. unsigned long GPSUpdateInterval = 21600000; // 6hrs
  99. unsigned long lastGPSupdate = 0;
  100. unsigned long GPSUpdateTimeout = 180000; //Time for trying to find a fix! If over, then no fix found (indoor).
  101. unsigned long noiseSameplingInterval = 2000; //Start sampling
  102. unsigned long lastNoiseSampling = 0;
  103. //Temp
  104. byte tempPin = A0;
  105. float temperature;
  106. //Noise
  107. const int sampleWindow = 500; // Sample window width in mS (50 mS = 20Hz)
  108. unsigned int sample;
  109. int noiseAVG = 0;
  110. const int numReadings = 20; // change for higher smoothing
  111. int readings[numReadings]; // the readings from the analog input
  112. int readIndex = 0; // the index of the current reading
  113. int total = 0; // the running total
  114. double boxDB = 115;
  115. //Status Flags
  116. byte statusInfo[] = {
  117. 1, //Value = 1 - status everything ok (white)
  118. 0, //Value = 1 - no Position (blue)
  119. 0, //Value = 1 - no connection to server (GSM) (pink)
  120. 0, //Value = 1 - low battery (red)
  121. 0, //Value = 1 - is charging (yellow)
  122. 0, //Value = 1 - battery fully charged (green)
  123. };
  124. uint16_t lastBatteryLevel = 0;
  125. uint16_t lastMilliVolts = 0;
  126. boolean lastMessageSent = true;
  127. //encryption
  128. //AES aes;
  129. //byte *key = (unsigned char*)"0123491889010123";
  130. void setup() {
  131. //while (!Serial);
  132. Serial.begin(115200);
  133. Serial1.begin(GPSBaud);
  134. //Init LED and turn on pixel
  135. pixel.begin();
  136. pixel.setBrightness(30);
  137. pixel.setPixelColor(0, pixel.Color(255, 255, 255)); //light up while startup
  138. pixel.show();
  139. analogReference(EXTERNAL); //sets analog reference voltage to AREF pin
  140. // initialize the readings for Noise to 0:
  141. for (int thisReading = 0; thisReading < numReadings; thisReading++) {
  142. readings[thisReading] = 0;
  143. }
  144. //Pins to turn on and off gsm and gps
  145. pinMode(KEYPIN, OUTPUT);
  146. digitalWrite(KEYPIN, HIGH);
  147. pinMode(GPSENABLE, OUTPUT);
  148. digitalWrite(GPSENABLE, LOW);
  149. encodeGPSAgain = true;
  150. delay(900000); //15minutes to charge the battery before anything else is done 900000
  151. //Turn off pixel
  152. pixel.setPixelColor(0, pixel.Color(0, 0, 0));
  153. pixel.show();
  154. }
  155. void loop() {
  156. if (!lastMessageSent) { //Turn off everything thats not needed
  157. blinkStatus();
  158. if (encodeGPSAgain) encodeGPS(); //Encoding again if no valid or updated signal found; no rekursion here
  159. /*if(initFONAagain) { //NOT NEEDED?????
  160. initFONA(); //Init FONA again if FONA was off while first attempt
  161. Serial.println("INFO: Init Fona again before noise sampling; Line 211");
  162. }*/
  163. //Sampling Noise in a specific interval.
  164. currentMillis = millis();
  165. if (currentMillis - lastNoiseSampling >= noiseSameplingInterval) {
  166. lastNoiseSampling = currentMillis;
  167. noiseAVG = getNoise();
  168. //Serial.println("Info: Noise: " + String(noiseAVG) + "dB");
  169. }
  170. //Getting GPS data in a specific interval.
  171. currentMillis = millis();
  172. if (currentMillis - lastGPSupdate >= GPSUpdateInterval) {
  173. //Serial.println("Checking GPS");
  174. lastGPSupdate = currentMillis;
  175. encodeGPS();
  176. }
  177. }
  178. //Send to Web in a specific interval
  179. currentMillis = millis();
  180. if ((currentMillis - lastSendToWeb >= sendToWebInterval)) {
  181. //Serial.println("foo");
  182. lastSendToWeb = currentMillis;
  183. switchFONA();
  184. //Serial.println(" INFO: Switching FONA (in begin of sendtoweb); Line 239");
  185. initFONA();
  186. if (initFONAagain) {
  187. initFONA();
  188. //Serial.println(" Init FONA again (in begin of sendtoweb); Line 243");
  189. }
  190. //Send to Webservice, if battery is good enough and GPS was once valid
  191. //INFO: Checking for valid GPS Signal only makes sense for static use on one place.
  192. // For dynamic use with changing places the check should use gps.location.isUpdated()
  193. if (gps.location.isValid() && (lastMilliVolts >= offlineMv) && !lastMessageSent) {
  194. lastMilliVolts = getBatteryVoltage();
  195. lastBatteryLevel = getBatteryLevel();
  196. //delay(10000);
  197. //Serial.println("INFO: Sending Data!");
  198. sendToWebService(getGeoJSONDataString(), URL);
  199. //delay(10000);
  200. //Serial.println("INFO: Sending Status!");
  201. sendToWebService("{\"battery\": " + String(getBatteryLevel()) + ", \"millivolt\": " + String(getBatteryVoltage()) + ", \"gps_fix\": 1, \"online\": 1}", URL3);
  202. } else { //Check Battery
  203. lastMilliVolts = getBatteryVoltage();
  204. lastBatteryLevel = getBatteryLevel();
  205. }
  206. //SERVICE MESSAGES
  207. //Power too low, but last message not yet sent -> send last message; BUT make sure, that mV is plausible -> >500
  208. byte gpsFix = 1;
  209. if (statusInfo[1] == 1) { //Statusinfo is 1 in case of error -> no gps
  210. gpsFix = 0;
  211. }
  212. if ((lastMilliVolts < offlineMv) && (lastMilliVolts > 500) && !lastMessageSent) {
  213. //Serial.println("INFO: Sending last message to DATAHUB");
  214. //Tell the server that there is no GPS Fix (although there might still be one).
  215. //TODO: Clear the tinyGPS object (so that there is actually no fix)
  216. sendToWebService("{\"battery\": " + String(getBatteryLevel()) + ", \"millivolt\": " + getBatteryVoltage() + ", \"gps_fix\": 0" + ", \"online\": 0}", URL3);
  217. lastMessageSent = true; //set to false; needed if battery is charging and sensor is sending again
  218. } else if ((lastMilliVolts > onlineMv) && lastMessageSent) { //Power sufficient again (after charging) -> back to work msg (just a service msg) (3520mV to avoid pending between last msg and back to work msg)
  219. //Serial.println("INFO: Sending Back to Work message to DATAHUB");
  220. sendToWebService("{\"battery\": " + String(getBatteryLevel()) + ", \"millivolt\": " + getBatteryVoltage() + ", \"gps_fix\": " + gpsFix + ", \"online\": 1}", URL3);
  221. lastMessageSent = false; //set to false; needed if battery is charging and sensor is sending again
  222. }
  223. //Try to get a valid GPS location
  224. if (!gps.location.isValid() && (lastMilliVolts >= onlineMv) && !lastMessageSent) {
  225. //Serial.println("INFO: Sending NO GPS Message to DATAHUB");
  226. sendToWebService("{\"battery\": " + String(getBatteryLevel()) + ", \"millivolt\": " + getBatteryVoltage() + ", \"gps_fix\": 0" + ", \"online\": 1}", URL3);
  227. GPSUpdateInterval = sendToWebInterval;
  228. }
  229. switchFONA();
  230. //Serial.println("INFO: Switching FONA after sending; Line 300");
  231. }
  232. }
  233. void initFONA() {
  234. //Serial.println("INFO: Starting FONA init");
  235. fonaSerial->begin(4800);
  236. if (!fona.begin(*fonaSerial)) {
  237. //Serial.println(F("INIT - Couldn't find FONA"));
  238. switchFONA(); //In case Phona is turned off (happens wenn battery runs completely out and is charged up again.
  239. //Serial.println("INFO: Switching FONA in initFONA; Line 314");
  240. initFONAagain = true; //after switching ON try to init again
  241. //Serial.println("ERROR: init FONA again; FONA not found");
  242. statusInfo[2] = 1;
  243. // Try to turn it on
  244. //turnOn();
  245. if (!fona.begin(*fonaSerial)) {
  246. while (1)
  247. ;
  248. }
  249. } else {
  250. statusInfo[2] = 0;
  251. initFONAagain = false;
  252. }
  253. type = fona.type();
  254. // Set APN (needed for A1 Sim cards) -> Uncomment if other SIM-Cards are in use
  255. fona.setGPRSNetworkSettings(F("A1.net"), F("ppp@a1plus.at"), F("ppp"));
  256. // turn GPRS on
  257. delay(10000);
  258. if (!fona.enableGPRS(true)) {
  259. //Serial.println(F("INIT - Failed to turn on GPRS"));
  260. statusInfo[2] = 1;
  261. //Serial.println("ERROR: init FONA again; no GPRS");
  262. initFONAagain = true; //Try to init FONA again in the next loop
  263. } else {
  264. statusInfo[2] = 0;
  265. initFONAagain = false;
  266. }
  267. /* NOT WORKING: Sending timestamp couses HTTP POST ERROR
  268. // enable NTP time sync
  269. fona.enableNTPTimeSync(true, F("pool.ntp.org"));
  270. //Serial.println(F("INFO: Failed to enable NTP time sync"));
  271. */
  272. //turnOnOffFona();
  273. }
  274. void switchFONA() {
  275. //Switching FONA on and off through pulling the KEYPIN LOW for a while
  276. //Each pull to LOW switches the FONA, either on or off (depending on the current state)
  277. //Serial.println("INFO: Switching FONA");
  278. unsigned long startMillis = millis();
  279. while (millis() - startMillis < pullLowDuration) {
  280. digitalWrite(KEYPIN, LOW);
  281. }
  282. digitalWrite(KEYPIN, HIGH);
  283. }
  284. void sendToWebService(String message, char URL[]) {
  285. //Serial.println("INFO - Start sending to Webservice");
  286. uint16_t statuscode;
  287. int16_t length;
  288. //String datastring = getGeoJSON();
  289. //String datastring = getSimpleDataString(); //For readable output on Server
  290. String datastring = message;
  291. //******with encryption start******
  292. /*
  293. byte *key = (unsigned char*)"0123491889010123"; //needs to be randomized!!!!
  294. unsigned long long int my_iv = 36712162; //needs to be randomized!!!!
  295. byte plain[datastring.length()];
  296. datastring.getBytes(plain, datastring.length());
  297. int plainLength = sizeof(plain)-1; // don't count the trailing /0 of the string !
  298. int padedLength = plainLength + N_BLOCK - plainLength % N_BLOCK;
  299. aes.iv_inc();
  300. byte iv [N_BLOCK] ;
  301. byte plain_p[padedLength];
  302. byte cipher [padedLength] ;
  303. aes.set_IV(my_iv);
  304. aes.get_IV(iv);
  305. aes.do_aes_encrypt(plain,plainLength,cipher,key,128,iv);
  306. flushSerial();
  307. bool success = true;
  308. if (!fona.HTTP_POST_start(URL, F("text/plain"), (uint8_t *) plain, strlen(plain), &statuscode, (uint16_t *)&length)) {
  309. //Serial.println("HTTP POST FAILED!");
  310. statusInfo[2] = 1;
  311. } else {
  312. statusInfo[2] = 0;
  313. }
  314. */
  315. //******with encryption end******
  316. //******without encryption start******
  317. unsigned int len = datastring.length() + 1;
  318. char data[len];
  319. datastring.toCharArray(data, len);
  320. flushSerial();
  321. //char myData[] = "{\"simple\":\"json\"}";
  322. bool success = true;
  323. String test = "fona";
  324. unsigned int lenToken = test.length() + 1;
  325. char tokenData[lenToken];
  326. test.toCharArray(tokenData, lenToken);
  327. if (!fona.HTTP_POST_start(URL, F("text/plain"), (uint8_t *)data, strlen(data), &statuscode, (uint16_t *)&length)) {
  328. statusInfo[2] = 1; //HTTP Post failed
  329. //Serial.println("ERROR: HTTP post failed");
  330. //pixel.setPixelColor(0, pixel.Color(255 ,255, 255)); //white, just for testing
  331. //pixel.show();
  332. } else {
  333. statusInfo[2] = 0;
  334. }
  335. //******without encryption end******
  336. fona.HTTP_POST_end();
  337. //Serial.println("INFO - End sending to Webservice");
  338. }
  339. String getGeoJSONDataString() {
  340. /* GeoJSON should look like this:
  341. {
  342. "type": "Feature",
  343. "geometry": {
  344. "type": "Point",
  345. "coordinates": [100.0, 0.0]
  346. },
  347. "properties": {
  348. "Temperature": [24.5, "°C"],
  349. "Noise": [100.0, "dB"],
  350. "timestamp": "123456723495",
  351. }
  352. }
  353. */
  354. String json = "{\"type\":\"Feature\",\"geometry\":{\"type\": \"Point\", \"coordinates\":[" + floatToString(gps.location.lng()) + ", " + floatToString(gps.location.lat()) + "]}, \"properties\": {\"Temperature\":[" + String(getTemperature()) + ", \"°C\"], \"Noise\":[" + String(noiseAVG) + ", \"dB\"], \"timestamp\":\"" + getTimeString() + "\"}}";
  355. return json;
  356. }
  357. String getTimeString() {
  358. /* NOT WORKING: Sending timestamp couses HTTP POST ERROR
  359. *
  360. *
  361. // read the time
  362. char timeBuffer[23];
  363. fona.getTime(timeBuffer, 23); // make sure replybuffer is at least 23 bytes!
  364. //Format timebuffer: YY/MM/DD,HH:MM+00
  365. //Serial.println("INFO: Time: " + String(timeBuffer));
  366. String timestamp = timeBuffer;
  367. */
  368. return "";
  369. }
  370. /* JUST USED FOR TESTING
  371. String getSimpleDataString() {
  372. return ("GPS: " + floatToString(gps.location.lng()) + ", " + floatToString(gps.location.lat()) +
  373. "; Temperature: " + String(getTemperature()) + " C; Noise: " + String(noiseAVG) + " DB; Battery: " + String(getBatteryLevel()) + " %; Voltage: " + String(getBatteryVoltage()) +" mV; " + boxID);
  374. }
  375. */
  376. String floatToString(float val) {
  377. int i;
  378. char buff[10];
  379. String valueString = "";
  380. dtostrf(val, 4, 6, buff); //4 is mininum width, 6 is precision
  381. valueString += buff;
  382. return valueString;
  383. }
  384. //////////// Get Sensor Data ///////////////////
  385. void encodeGPS() {
  386. //Serial.println("INFO: Turning on GPS module");
  387. digitalWrite(GPSENABLE, HIGH);
  388. unsigned long start = millis();
  389. // For one second we parse GPS data and report some key values
  390. for (start; millis() - start < 1000;) {
  391. while (Serial1.available()) {
  392. char c = Serial1.read();
  393. //Serial.write(c); // uncomment this line if you want to see the GPS data flowing
  394. gps.encode(c); // Did a new valid sentence come in?
  395. }
  396. }
  397. //Serial.println();
  398. // DEBUGGING: Re-encoding for a certain time
  399. if (millis() - lastGPSupdate <= GPSUpdateTimeout) {
  400. //if we haven't seen lots of data in 5 seconds, something's wrong.
  401. if (start > 5000 && gps.charsProcessed() < 10) {
  402. //Serial.println("ERROR: Not getting any GPS data! Encoding again");
  403. encodeGPSAgain = true;
  404. //TODO: Turning Module OFF here?
  405. } else if (!gps.location.isValid()) { //also add timer for circumstances when there is definately no signal to find
  406. //Serial.println("ERROR: GPS Data not valid! Encoding again");
  407. encodeGPSAgain = true;
  408. GPSUpdateInterval = sendToWebInterval; //SendToWebinterval is usually shorter.
  409. } else if (!gps.location.isUpdated()) {
  410. //Serial.println("ERROR: GPS Data not updated! Encoding again");
  411. encodeGPSAgain = true;
  412. } else {
  413. //Serial.println("INFO: GPS: " + floatToString(gps.location.lat()) + ", " + floatToString(gps.location.lng()));
  414. //Serial.println("INFO: Turning off GPS-Module");
  415. digitalWrite(GPSENABLE, LOW); //turn gps module off
  416. encodeGPSAgain = false;
  417. GPSUpdateInterval = 21600000;
  418. statusInfo[1] = 0;
  419. }
  420. } else {
  421. //Serial.println("ERROR: Timeout - No GPS-Data");
  422. statusInfo[1] = 1;
  423. //TODO: Send Error Message to Server
  424. digitalWrite(GPSENABLE, LOW); //turn gps module off
  425. encodeGPSAgain = false;
  426. GPSUpdateInterval = sendToWebInterval;
  427. }
  428. }
  429. float getTemperature() {
  430. int pinReading = analogRead(ANALOG_TEMP_PIN);
  431. float voltage = pinReading * aref_voltage;
  432. voltage /= 1024.0;
  433. float temp = (voltage - 0.5) * 100;
  434. //Serial.println("Temperature: " + String(temp));
  435. //(((analogRead(ANALOG_TEMP_PIN) * 3.3)/1024.0) - 0.5) * 100;
  436. return temp;
  437. }
  438. //source: http://arduinolearning.com/code/arduino-and-max4466-electret-module-example.php
  439. float getNoiseReading() {
  440. unsigned long startMillis = millis(); // Start of sample window
  441. unsigned int peakToPeak = 0; // peak-to-peak level
  442. unsigned int signalMax = 0;
  443. unsigned int signalMin = 1024;
  444. while (millis() - startMillis < sampleWindow) {
  445. sample = analogRead(ANALOG_NOISE_PIN);
  446. if (sample < 1024) { // toss out spurious readings
  447. if (sample > signalMax) {
  448. signalMax = sample; // save just the max levels
  449. } else if (sample < signalMin) {
  450. signalMin = sample; // save just the min levels
  451. }
  452. }
  453. }
  454. peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
  455. return peakToPeak; //* 3.3) / 1024; // convert to volts
  456. }
  457. int getNoise() {
  458. // subtract the last reading:
  459. total = total - readings[readIndex];
  460. double noiseReading = getNoiseReading();
  461. // read from the sensor:
  462. // https://forum.arduino.cc/index.php?topic=318908.0
  463. // 80 = db on SPL-Meter, 120 = Noise from Noise Sensor at 80 db on the SPL-Meter
  464. //How to calibrate:
  465. //take the SPL-Meter and the Sensorbox
  466. //uncomment this:
  467. //Serial.println("Noise:");
  468. //Serial.println(noiseReading);
  469. //Serial.println("");
  470. //uncomment the seria println before the return
  471. //play a sound to reach 80 db on the SPL Meter
  472. // change boxDB on top to Value which is showing for the Sensorbox
  473. readings[readIndex] = (20 * log(noiseReading / boxDB) + 80);
  474. // add the reading to the total:
  475. total = total + readings[readIndex];
  476. // advance to the next position in the array:
  477. readIndex = readIndex + 1;
  478. // if we're at the end of the array...
  479. if (readIndex >= numReadings) {
  480. // ...wrap around to the beginning:
  481. readIndex = 0;
  482. }
  483. // calculate the average:
  484. //for calibration of Noise
  485. //Serial.println(total / numReadings);
  486. return (total / numReadings);
  487. // send it to the computer as ASCII digits
  488. }
  489. uint16_t getBatteryLevel() {
  490. uint16_t vbat;
  491. fona.getBattPercent(&vbat);
  492. lastBatteryLevel = vbat;
  493. //Serial.println("Battery Level: " + String(vbat));
  494. return vbat;
  495. }
  496. uint16_t getBatteryVoltage() {
  497. uint16_t vbat;
  498. //uint16_t batStat; //NOT WORKING
  499. fona.getBattVoltage(&vbat);
  500. //ATTENTION: This function doesn NOT work with public FONA Library.!!!!
  501. //Status: 0 = not charging; 1 = charging; 2 = finished charging
  502. //More Info in SIM800 Series AT Command Manual
  503. //NOT WORKING: getBattStatus always returns 0
  504. //fona.getBattStatus(&batStat);
  505. //Serial.println("Battery Status: " + String(batStat));
  506. //Serial.println("MilliVolts: " + String(vbat));
  507. //Clear false readings with too high (unrealistic) values
  508. if (vbat > 4700) vbat = 0;
  509. //Battery low
  510. if (vbat <= 3600 && vbat != 0) statusInfo[3] = 1;
  511. else statusInfo[3] = 0;
  512. //Battery charging
  513. if (vbat > lastMilliVolts && vbat != 0) statusInfo[4] = 1;
  514. else statusInfo[4] = 0;
  515. //Battery fully charged
  516. if (vbat > 4170 && vbat != 0) {
  517. statusInfo[5] = 1;
  518. statusInfo[4] = 0;
  519. } else {
  520. statusInfo[5] = 0;
  521. }
  522. return vbat;
  523. }
  524. //////////// Helpers & Output ///////////////////
  525. void blinkStatus() {
  526. //get number of statusInfo
  527. boolean blinkSequenceActive = false;
  528. currentMillis = millis();
  529. if (currentMillis - lastBlinkSequenceStart >= blinkInterval) { //start blinking
  530. blinkSequenceActive = true;
  531. lastBlinkSequenceStart = currentMillis;
  532. }
  533. if (blinkSequenceActive) { //do the blink sequence
  534. lastSingleBlinkStart = currentMillis;
  535. for (int i = 0; i < sizeof(statusInfo);) {
  536. switch (i) {
  537. case 0:
  538. pixel.setPixelColor(0, pixel.Color(255, 255, 255)); //white -> status blink
  539. break;
  540. case 1:
  541. pixel.setPixelColor(0, pixel.Color(0, 200, 255)); //blue -> no GPS
  542. break;
  543. case 2:
  544. pixel.setPixelColor(0, pixel.Color(255, 0, 255)); //pink -> no GSM
  545. break;
  546. case 3:
  547. pixel.setPixelColor(0, pixel.Color(255, 0, 0)); //red -> low Battery
  548. break;
  549. case 4:
  550. pixel.setPixelColor(0, pixel.Color(255, 188, 0)); //orange -> bat charging
  551. break;
  552. case 5:
  553. pixel.setPixelColor(0, pixel.Color(0, 255, 0)); //green -> bat fully charged
  554. break;
  555. }
  556. if (statusInfo[i] != 0) pixel.show();
  557. currentMillis = millis();
  558. if (currentMillis - lastSingleBlinkStart >= singleBlinkDuration) {
  559. i++; //increase counter to get to the next info
  560. lastSingleBlinkStart = currentMillis;
  561. pixel.setPixelColor(0, pixel.Color(0, 0, 0)); //green -> bat fully charged
  562. pixel.show();
  563. }
  564. }
  565. }
  566. if (currentMillis - lastBlinkSequenceStart >= blinkSequenceDuration) { //turn off again
  567. pixel.setPixelColor(0, pixel.Color(0, 0, 0));
  568. pixel.show();
  569. blinkSequenceActive = false;
  570. }
  571. }
  572. /*
  573. void printSensorData(){
  574. Serial.println("SensorData:");
  575. Serial.print("\nTemperature: "); Serial.println(getTemperature());
  576. Serial.print("\nNoise: "); Serial.println(getNoise());
  577. Serial.print("\nBattery: "); Serial.print(getBatteryLevel()); Serial.println(" %");
  578. Serial.print("\nLocation: "); Serial.print(gps.location.lat(), 6); Serial.print(", "); Serial.println(gps.location.lng(), 6);
  579. Serial.println("---------------------------------------");
  580. }
  581. String sensorDataToString() {
  582. String data = "Sensordata: Temperature: " + String(getTemperature()) + " Noise: " + String(getNoise()) + " Battery: " + String(getBatteryLevel()) + "% Location: " + String(gps.location.lat()) + ", " + String(gps.location.lng());
  583. return data;
  584. }
  585. */
  586. void flushSerial() {
  587. while (Serial.available()) {
  588. Serial.read();
  589. }
  590. }