Home › Forums › Mayfly Data Logger › Logging Mayfly with Decagon SDI-12 Sensor › Reply To: Logging Mayfly with Decagon SDI-12 Sensor
2017-04-03 at 11:03 PM
#2136
Now that your sensor is connected and has an address set, you can get data from it using code like this:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
SDI12 mySDI12(_dataPin); mySDI12.begin(); delay(500); // allow things to settle myCommand = ""; myCommand += _SDI12address; myCommand += "M!"; // SDI-12 measurement myCommand format [address]['M'][!] mySDI12.sendCommand(myCommand); Serial.println(myCommand); // For debugging delay(30); // wait for acknowlegement with format [address][ttt (3 char, seconds)][number of measurments available, 0-9] sdiResponse = ""; while (mySDI12.available()) // build response string { char c = mySDI12.read(); if ((c != '\n') && (c != '\r')) { sdiResponse += c; delay(5); } } mySDI12.flush(); // find out how long we have to wait (in seconds). unsigned int wait = 0; wait = sdiResponse.substring(1,4).toInt(); Serial.print(F("Waiting ")); // For debugging Serial.print(wait); // For debugging Serial.println(F(" seconds for measurement")); // For debugging // Set up the number of results to expect numMeasurements = sdiResponse.substring(4,5).toInt(); Serial.print(numMeasurements); // For debugging Serial.println(F(" results expected")); // For debugging unsigned long timerStart = millis(); while((millis() - timerStart) < (1000 * wait)) { if(mySDI12.available()) // sensor can interrupt us to let us know it is done early { Serial.println("Wait interrupted!"); // For debugging mySDI12.flush(); break; } } delay(30); mySDI12.flush(); Serial.println(F("Requesting data")); // For debugging myCommand = ""; myCommand += _SDI12address; myCommand += "D0!"; // SDI-12 command to get data [address][D][dataOption][!] mySDI12.sendCommand(myCommand); Serial.println(myCommand); // For debugging delay(30); Serial.println(F("Receiving data")); // For debugging mySDI12.read(); // ignore the repeated SDI12 address float sensorValues[numMeasurements] = {0}; // Create an array to receive data for (int i = 0; i < numMeasurements; i++) { float result = mySDI12.parseFloat(); sensorValues[i] += result; Serial.print(F("Result #")); // For debugging Serial.print(i); // For debugging Serial.print(F(": ")); // For debugging Serial.println(result); // For debugging } // Wait for and discard anything else mySDI12.flush(); |
Once you have an array of values from the sensor, you can save them to an SD card or anything you’d like.