GoTo Goat – A GPS goat tracker

As goats are naturally born masters of escaping, we soon realized that the electric fence only should be considered as the first line of defense. Usually, the most clever ones finds their way out, and then calls for the others to follow, and generally, their just heading out to a nearby pasture, where the grass is allegedly greener, or home to the barn. On a few occasions though, they have been spooked by wild boars, and ran off into the forest. When I was tracking them out on a small dirt road, and a neighbor called from his forestry tractor, about 3 km out, and asked if maybe my goats where out hiking, I realized that we have a need for a tracking device. The idea of the GoTo Goat device was born, a GPS-module, transmitting coordinates over the cell network.

wp-1474494088463.jpg
The goats where very happy to see me, and followed me home through the forest.

 

 

Features:

Real-time GPS location

Upload coordinates to a cloud service, or your own server over GPRS

Solar powered

Android locator app

Component list

Microcontroller: Arduino nano 6 euro

GPRS module: SIM800L 5 euro

GPS module: Ublox NEO-6M 7 euro

Power supply: Linocell 3X Solar Powerbank 8000 mAh 50 euro

Step-down regulator: AMS1117 adjustable (5V-3.7V) 1 euro

Sim card (Telia) free

Total cost: 19 euro for the components and 50 for the powerbank, but i bought the powerbank locally in Sweden, and there are much cheaper ones around on ebay. With a little more labour put into sourcing, the cost could probably drop to about 30 euro.

The SIM800L

s-l225

This is a very nice little module. Essentially a complete cell phone, except for user interface, speaker and mic. It’s controlled from the arduino by sending AT commands through serial communication. The SIM800L is supposed to be powered by a 3.7V Li cell, as in a cellphone, and that’s why the buck converter is needed in this setup to bring the current down from 5V.

The only functionality used here is the GPRS device for sending over HTTP, but using SMS or DMTF for controlling the unit are possibilities as well as calling the goat for an occasional chat.

 

 

The NEO-6M

u6

 

 

A neat GPS-module supported by the arduino TinyGPS library. Pretty fast on getting a fix, and supplying coordinates once a second.

 

 

 

The Nano

$_1

I choose an Arduino nano for prototyping, since it has it’s own FTDI, a reasonable size and a friendly number of pins. If the size, power consumption and prize needs to be further tweaked, I can’t see any reason not to use a mini pro though. The SIM800L is rated for max 3.7V to 4.1V so the internal voltage regulators will be useless.

 The SIM

Any sim card that supports GPRS will work, but it’s recommended to use one that not expires too soon after charging. As very little traffic volumes are transmitted, it would be a shame if the card needed to be refueled every 3 months or so. Instead, if you can find one that works for several years, and only using the throttled speed when paid data is depleted, that would be completely sufficient.

 

Connections

SIM800L pin NEO-&M pin AMS1117 pin Arduino pin Powerbank
Net – antenna Usb Port2
Vcc Vout
Rst D5
TX D8
RX D7
Gnd Gnd Gnd Gnd Port1 –
Vcc 5V
Rx D4
Tx D3
Vin Port1 +
31583617682_a1031ba862_o
SIM800 and nano in the center, NEO-6M to the right. Here, the SIM800 is powered by a 3.7V battery

Cloud API

I choose thingspeak.com as cloud service to store the coordinates. Mostly because I already use it for other sensors, so I’m already familiar with the API. Virtually any online API would be suitable, as long as you can send in values through a HTTP GET parameter.

Thingspeak will let you send in 3 000 000 updates / year with their free account, so that will limit you to 5.7 updates / minute. I’ll go for max 1/min, probably less. Since you are putting the API key in the arduino code, you don’t want to use a service that is likely to go off the market, or become “premium only”, like Xively did. To be sure that the service stays alive, you could host your own thingspeak platform on a raspberry pi or similar.

Code

The NEO-6M is very simple to interface from the Arduino. I used the kitchensink example from the TinyGPS library, and trimmed it down to the bare necessities.

The SIM800L is more complicated to interface, since you need 2-way communication to ensure that the commands have been successfully performed. I found some example code at Cassiopeia that was very helpful. Even if I do not use DMTF functionality as in the example, their approach for communicating with the SIM800L is very convenient.

As both the NEO-6M, the SIM800L and the arduino IDE Serial monitor are using serial communication for interfacing the arduino, there will be issues regarding which ports to use. I kept the hardware serial (Serial) for debugging purposes, and let only the computer interface with it. For the modules, I assigned two SoftwareSerial ports, sim800 on pin 7 and 8 and ss on pin 3 and 4. To keep the communication channels separated, the arduino is instructed on which one to listen, depending on where input is expected.


#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <avr/sleep.h>
#include <avr/wdt.h>
//Thingspeak channel
#define CHANNEL 199082 //Not used
//Thingspeak API write key
#define APIKEY "XXXXXXXXX"//Put your own write key here
//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8
#define RATE 10000 //GPS sampling rate
//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7
static const int RXPin = 3, TXPin = 4;
static const uint32_t GPSBaud = 9600;
const int sim_rst = 5;
int errors = 0;
//Create software serial object to communicate with SIM800
SoftwareSerial sim800(SIM800_TX_PIN,SIM800_RX_PIN);
SoftwareSerial ss(RXPin, TXPin);
TinyGPSPlus gps;
unsigned long last = 0UL;
// watchdog interrupt
ISR(WDT_vect)
{
wdt_disable(); // disable watchdog
}
void myWatchdogEnable(const byte interval)
{
MCUSR = 0; // reset various flags
WDTCSR |= 0b00011000; // see docs, set WDCE, WDE
WDTCSR = 0b01000000 | interval; // set WDIE, and appropriate delay

wdt_reset();
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_mode(); // now goes to Sleep and waits for the interrupt
}
void setup() {
//Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
Serial.begin(9600);
while(!Serial);

//Beging serial communication with Arduino and SIM800
sim800.begin(9600);
delay(1000);
ss.begin(GPSBaud);
delay(1000);
Serial.println("Setup Complete!");
last = millis()-RATE;
}

void loop() {
errors = 0;
// Dispatch incoming characters from GPS
ss.listen();
while (ss.available() > 0)
gps.encode(ss.read());
if (millis() - last > RATE)
{
if (gps.location.isValid())
{
static const double OFFICE_LAT = 56.000, OFFICE_LON = 14.000; //Hard coded reference coordinates if needed in the future
double distanceToOffice =
TinyGPSPlus::distanceBetween(
gps.location.lat(),
gps.location.lng(),
OFFICE_LAT,
OFFICE_LON);
Serial.println(distanceToOffice);
double courseToOffice =
TinyGPSPlus::courseTo(
gps.location.lat(),
gps.location.lng(),
OFFICE_LAT,
OFFICE_LON);
char tmpCourse[10];
char tmpDistance[10];
char tmpLat[10];
char tmpLng[10];
char tmpSpeed[10];
char params[200];
int batteryLevel;
//Convert GPS data to strings
dtostrf(gps.location.lat(),1,6, tmpLat);
dtostrf(gps.location.lng(),1,6, tmpLng);
dtostrf(distanceToOffice/1000, 1,6, tmpDistance);
dtostrf(courseToOffice,1,6, tmpCourse);
dtostrf(gps.speed.kmph(), 1,6, tmpSpeed);
sim800.listen();//Turn to sim800l channel
disconnectGPRS();//Sometimes, the sim800l gets stuck with GPRS activated, and trying to activate it again will naturally fail.
while(!wakeUpSim800());
if(simOK()){
batteryLevel= getBatteryLevel();
Serial.print("Battery level: ");
Serial.println(batteryLevel);
sprintf(params, "apikey=%s&field1=%s&field2=%s&field3=%s&field6=%d", APIKEY, tmpLat, tmpLng, tmpSpeed, batteryLevel);
Serial.println(params);
//Next three stages are sequential. Error handling means that if the sequence is not completed with less than 5 unsuccessful tries on all stages, there is something wrong, and the sequence is aborted.
while(!initGPRS()&&errors++<5);

while(!initHTTP()&&errors++<5);

while(!putDataToThingspeak(params)&&errors++<5);
errors = 0;
while(!disconnectGPRS()&&errors++<5);
while(!powerDownSim800());
delay(200);
Serial.println("Entering watchdog sleep");
delay(100);
myWatchdogEnable (0b100001); // 8 seconds
myWatchdogEnable (0b100001); // 8 seconds
myWatchdogEnable (0b100001); // 8 seconds
myWatchdogEnable (0b100001); // 8 seconds
myWatchdogEnable (0b100001); // 8 seconds
myWatchdogEnable (0b100001); // 8 seconds
myWatchdogEnable (0b100001); // 8 seconds
myWatchdogEnable (0b100001); // 8 seconds

Serial.println("Resuming operations");
}
ss.listen(); //Turn back to GPS channel
}

if (gps.charsProcessed() < 10)
Serial.println(F("WARNING: No GPS data. Check wiring."));

last = millis();

}
}
boolean wakeUpSim800(){
Serial.println(F("Checking for sim800 module..."));

digitalWrite(sim_rst, LOW); // hardware reset after sleep RST
delay(300);
digitalWrite(sim_rst, HIGH);

// time to startup 3 sec
for (int i = 0; i < 6; i++) {
digitalWrite(13, HIGH); // green LED blink after RESET
delay(250);
digitalWrite(13, LOW);
delay(250);
}

sim800.println("AT"); // check if sim800 module responds
delay(100);
if (sim800.find("OK")) {
Serial.println(F("sim800 module awake"));
return true;
}
else{
Serial.println(F("sim800 module not found"));
return false;
}

}
boolean simOK() { // SIM CHECK OK
Serial.println(F("Checking for SIM card.. "));

sim800.println("AT"); // check if sim800 module responds
delay(100);
if (sim800.find("OK")) {
Serial.println(F("sim800 module found"));

delay(100); // wait for sim800 to settle a bit
sim800.println("AT+CFUN=1"); // operation
if (sim800.find("OK"))
Serial.println(F("Function level 1"));
else
return false;
delay(2000);
sim800.println("AT+CSMINS?"); // check if SIM card inserted
delay(100);
if (sim800.find("CSMINS: 0,0")) {
Serial.println(F("no SIM card found, stop here"));
return false;
}
Serial.println(F("SIM card found")); // continue if SIM card found

Serial.println(F("Allow some time for SIM to register on the network.."));
Serial.println();
delay(1000);
return true;
}
else{
Serial.println(F("sim800 module not found, stop here"));
return false;
}
}

void simReply() { // SIM REPLY
delay(500);
while (sim800.available()) {
char c = sim800.read();
if (c != '\n') Serial.write(c); // replace new line with space
else Serial.print(" ");
delay(5);
}
Serial.println();
}

boolean initGPRS(){
boolean noError = true;
sim800.println("AT+CIPSHUT"); //Ensure GPRS PDP is down before init
simReply();
//delay(1000);
sim800.println("AT+CGATT=1");//Attach to GPRS service
simReply();

sim800.println("AT+SAPBR=3,1,CONTYPE,GPRS");//Set(3) bearer connected(1) to Contype GPRS
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+CGATT=1");//Attach to GPRS service
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+SAPBR=3,1,APN,online.telia.se");//Set(3) bearer connected(1) to APN
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+SAPBR=1,1");//Open connected bearer
if (sim800.find("ERROR"))
noError = false;
Serial.print("initGPRS finished with no errors = ");
Serial.println(noError);
return noError;

}

boolean initHTTP(){
boolean noError = true;
sim800.println("AT+HTTPTERM");
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+HTTPINIT");
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+HTTPPARA=CID,1");
if (sim800.find("ERROR"))
noError = false;
Serial.print("initHTTP finished with no errors = ");
Serial.println(noError);
return noError;
}
boolean putDataToThingspeak(char params[200]){
boolean noError = true;
char req[250];
sprintf(req, "AT+HTTPPARA=URL,api.thingspeak.com/update?%s", params);
Serial.println(req);
sim800.println(req);
if (sim800.find("ERROR"))
noError = false;
delay(1000);
sim800.println("AT+HTTPACTION = 0");
if (sim800.find("ERROR"))
noError = false;
Serial.print("putDataToThingspeak finished with no errors = ");
Serial.println(noError);
return noError;
}

boolean disconnectGPRS(){
boolean noError = true;
sim800.println("AT+CIPSHUT");
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+SAPBR=0,1");
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+CGATT=0");
if (sim800.find("ERROR"))
noError = false;
sim800.println("AT+CFUN=0");
if (sim800.find("ERROR"))
noError = false;
Serial.print("disconnectGPRS finished with no errors = ");
Serial.println(noError);
return noError;

}
int getBatteryLevel(){
sim800.listen();
sim800.println("AT+CBC"); // battery level
delay(500);
String s = sim800.readStringUntil(',');//Grab the value between the commas
String level = sim800.readStringUntil(',');

return(level.toInt());
}

boolean powerDownSim800(){
boolean noError = true;
sim800.println("AT+CPOWD=1");
if (sim800.find("ERROR"))
noError = false;

Serial.print("SIM800l power down = ");
Serial.println(noError);
return noError;

}

 

Here are the latitude results from thingspeak, for more, go to the GoTo goat section on the IoT page.

Android app

The Android app is still just an embryo, but it will find a goat… You can find it on Play: https://play.google.com/apps/testing/com.framtidabruk.gotogoats

You need to enter your own thingspeak.com Api key and channel ID in the settings before it becomes useful.

3766840962902790605-account_id=1

Arduino for beginners

As you might have noticed we love technology and finding innovative ways to use it around the farm. Nils has a lot of knowledge in programming as well as micro-computers such as Arduino and Raspberry Pi. Claire is an enthusiastic beginner, having participated in courses in Visual Basic, HTML/CSS and Python in the past. Her latest endeavour is to learn more about Arduino which according to the official website: “…is an open-source electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs – light on a sensor, a finger on a button, or a Twitter message – and turn it into an output – activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board. To do so you use the Arduino programming language (based on Wiring), and the Arduino Software (IDE), based on Processing.”

Happily, we found that there is a place called Blekinge uppfinnareverkstad dedicated to innovations and co-working in a near-by town called Svängsta, and they offer courses in Arduino for beginners -among other things. It is a really cool place, founded in the 80’s in an old factory and is run on a volunteer  basis. Worth a visit (or even membership – 500 SEK for a year) if you are interested in anything from welding to 3D printing.
IMG_20161103_190618The idea is to use Arduinos for some of the many things we want to monitor and automate at the farm – in the milking process, at the dairy – or even to make a goat locator for when the critters decide to break out of their pasture! We will keep you posted…

 

Defcon #24 and small scale farming

What did this years version of the annual hacker convention in Las Vegas have to tell about small scale farming? Nothing directly, being that kind of  happening where the participants and speakers seem to thrive in cellars and abandoned mines, rather than the open air. Indirectly, a lot.


The theme this year was Human vs Machines, and of course, the internet of things was among the most frequent topics. It’s always amusing to watch hackers exploit old gadgets that their manufacturers given a prolonged product cycle by connecting them to the internet, and pranking the neighbours by exposing their porn surfing habits through a vulnerable online toaster mostly raise the question: why did that guy buy a connected toaster?

So why should the small scale farmer be concerned about IoT security (except for the earlier mentioned reason)? The first link in the food supply chain is about to get more complex, as the demand for both locally produced and refined food grows. The specialized farmers that sells crop, meat or milk to industrialized facilities will have a hard time competing with producers that controls the complete value chain, from hay to cheese and steak, and understand to add ethical, esthetical and cultural value to their products.

There are two ways for the small scale farmer to accomplish a substancial increase in value, either by focusing on cultural and estethical factors, and become artisans, or by focusing on efficiency and interamplifying (is that a word?) processes. It’s with the interamplifying processes the internet of things makes its entrance. Automation, surveillance and statistics might not add the cultural value of a handmade cheese from Grannies recipe, but it ensures high food quality, and uniform products even in small batches, and that will allow you to make a larger variety of products, without being an master artisan in every field.

So the sensors and relays that will help you make the best food on the market, will they work for you, or for anyone that comes by digitally? Their information can be a great asset, as they provide the customer with unique data about their meal, but if you expose the controls, you also expose the possibility to replicate or sabotage your products. That’s the downside of shifting knowledge from human to machine.

In the great battle between man and machine, the machines are definitely winning. Knowledge is power, and we keep rely on the knowledge we stuff into machines, while we stress our brains back to the stoneage in our efforts to keep up with them. It’s when we taste the delicious cheese that where made with their help and without our efforts, that we realize who the real winner is. Just keep your networks segmented.

Diy wireless pH-meter

In cheese-making, the key to a tasty, and reproducable, cheese, is keeping track of the  exact pH and the temperature in the active culture. You can do this with manual tools, such as a kitchen thermometer and pH-strips, but the measurements will be crude, and depend on your constant presence. That leading to inconsistencies between batches,  and difficulties in tracking errors in the process.

Michel Lepage is cutting the curd. Photo taken at the craft cheese-making course we took at Eldrimner in 2014.
A digital pH-meter is expensive. You can find some from €100, but you wont get built-in temperature correction for less than €250, and wireless goes beyond €350. For continous readings and  the possibility to recalibrate your sensor yourself, instead of sending it to the manufacturer,  add a lot more… I havn’t yet found a device capable of tweeting its readings 😉

My diy pH-sensor is not exactly cheap either. It ticks in at about €150 in material costs. I’ve seen people look pensive when they see the casing, and subconsiously push it closer to the recycling, so a slightly pricier casing than the pet bottle might be an investment. Otherwise, the bill of materials looks like:

Sensor

  • Atlas pH meter kit $149 (EZO version)
  • Arduino mini pro 3.3v $1.90
  • NRF24L01 radio $1
  • DS18B20 waterproof temp sensor $1.63
  • Battery holder $3
  • 2xAA batteries
  • Cables

With todays exchange rates, it translates to around €150.
If you’re setting up a new sensor network, you need a radio gateway and a computer to run the controller software on too

  • Arduino nano $6
  • NRF24L01 radio $1
  • Cables
  • Old computer or raspberry pi $25-$50

      You can order everything from ebay or aliexpress through the Mysensors store, but the items listed there may not always be availible in singel packages. Anyway, you will need more of those radios.

      Shipping is usually free from China (who is paying that?), but the pH-kit comes from the US, so add a few euros for shipping and customs.

      Features:

      • Measures pH-level in fluids and semi-solid compounds.
      • Calculates the correct pH from the latest temperature reading.
      • Measures temperature
      • 30 seconds between samples.
      • Continous measuring, just leave the probe in the milk and watch the readings.
      • Wireless transfer of data to the raspberry pi based controller unit
      • Presents the readings as a datastream or in nice graphs in a web interface. Use your phone or tablet to monitor the process from anywhere.

          Prerequisites:

          Tools

          • FTDI USB programmer, to program the arduino  mini pro and perform calibration. If you use arduino nano instead, you can skip this, but the nano is more expensive and power consuming.
          • Soldering iron, lead, soldering paste.
          • Computer with arduino ide or codebender running.
          • Pliers, knives, screwdrivers and that kind of stuff.

          Skills

          • Basic soldering. The only soldering done in my prototype is on the on/off switch. For a sturdy and reliable device to use in a kitchen environment, I recommend soldering the connections rather than using Dupont cables.
          • Basic programming. You can clone my code from codebender and hope it will work out of the box, but since things changed quickly on the internets of things, you will probably need to change some code to adapt to new version etc. So some understanding of coding will be helpful.
          • Arduino/MCU experiences. I wouldn’t recommend to make this your first microcontroller or Mysensors project. Start out with a simple blinking light and then a temperature sensor to make sure you get the IDE and Mysensors API.
          • Raspberry pi/Linux experiences. You could use a Windows computer as controller and user interface server, but if you’re up to arduino hacking, you might as well use an embedded device right away.