Showing posts with label MKR1000. Show all posts
Showing posts with label MKR1000. Show all posts

Saturday, June 30, 2018

Speeding up the ADC on Arduino SAMD21 Boards (Zero, Mkr, etc) P1

In this video we look at how to get higher ADC speeds out of Arduino boards that are based off of the SAMD21 microcontroller.



Windows file paths from video:
  • files that define register data structures: C:\Users\yourname\AppData\Local\Arduino15\packages\arduino\hardware\samd\1.6.18\bootloaders\sofia\Bootloader_D21_Sofia_V2.1\src\ASF\sam0\utils\cmsis\samd21\include\component
  • wire.c file path: C:\Users\yourname\AppData\Local\Arduino15\packages\arduino\hardware\samd\1.6.18\cores\arduino

//*******************Arduino example code from video*************************
/*This code is from a tutorial on the ForceTronics YouTube Channel that talks about speeding up the sample rate on Arduino boards 
 * that use the SAMD21 microcontroller like the Arduino Zero or MKR series. This code is free and clear for other to use and modify 
 * at their own risk. 
 */
#include <SPI.h>
#include <SD.h>

const int16_t dSize = 1024; //used to set number of samples
const byte chipSelect = 38; //used for SPI chip select pin
const byte gClk = 3; //used to define which generic clock we will use for ADC
const byte intPri = 0; //used to set interrupt priority for ADC
const int cDiv = 1; //divide factor for generic clock
const float period = 3.3334; //period of 300k sample rate
String wFile = "ADC_DATA"; //used as file name to store wind and GPS data
volatile int aDCVal[dSize]; //array to hold ADC samples
volatile int count = 0; //tracks how many samples we have collected
bool done = false; //tracks when done writing data to SD card

void setup() {
  portSetup(); //setup the ports or pin to make ADC measurement
  genericClockSetup(gClk,cDiv); //setup generic clock and routed it to ADC
  aDCSetup(); //this function set up registers for ADC, input argument sets ADC reference
  setUpInterrupt(intPri); //sets up interrupt for ADC and argument assigns priority
  aDCSWTrigger(); //trigger ADC to start free run mode
}

void loop() {
  
  if(count==(dSize-1) and !done) { //if done reading and they have not been written to SD card yet
    removeDCOffset(aDCVal, dSize, 8); //this function removes DC offset if you are measuring an AC signal
    SD.begin(chipSelect); //start SD card library
    File myFile = SD.open((wFile + ".csv"), FILE_WRITE); //open file to write data to CSV file
    if (myFile) {
      float sTime = 0;
      for (int y = 0; y < dSize; y++) {
        myFile.print(sTime,5); //write each reading to SD card as string
        myFile.print(",");
        myFile.println(String(aDCVal[y])+","); //write each reading to SD card as string
        sTime = sTime + period; //update signal period info
      }
    }
    myFile.close(); //close file
    done = true; //we are done 
  }
}

//function for configuring ports or pins, note that this will not use the same pin numbering scheme as Arduino
void portSetup() {
  // Input pin for ADC Arduino A0/PA02
  REG_PORT_DIRCLR1 = PORT_PA02;

  // Enable multiplexing on PA02_AIN0 PA03/ADC_VREFA
  PORT->Group[0].PINCFG[2].bit.PMUXEN = 1;
  PORT->Group[0].PINCFG[3].bit.PMUXEN = 1;
  PORT->Group[0].PMUX[1].reg = PORT_PMUX_PMUXE_B | PORT_PMUX_PMUXO_B;
}

//this function sets up the generic clock that will be used for the ADC unit
//by default it uses the 48M system clock, input arguments set divide factor for generic clock and choose which generic clock
//Note unless you understand how the clock system works use clock 3. clocks 5 and up can brick the microcontroller based on how Arduino configures things
void genericClockSetup(int clk, int dFactor) {
  // Enable the APBC clock for the ADC
  REG_PM_APBCMASK |= PM_APBCMASK_ADC;
  
  //This allows you to setup a div factor for the selected clock certain clocks allow certain division factors: Generic clock generators 3 - 8 8 division factor bits - DIV[7:0]
  GCLK->GENDIV.reg |= GCLK_GENDIV_ID(clk)| GCLK_GENDIV_DIV(dFactor);
  while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);  

  //configure the generator of the generic clock with 48MHz clock
  GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_DFLL48M | GCLK_GENCTRL_ID(clk); // GCLK_GENCTRL_DIVSEL don't need this, it makes divide based on power of two
  while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);
  
  //enable clock, set gen clock number, and ID to where the clock goes (30 is ADC)
  GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(clk) | GCLK_CLKCTRL_ID(30);
  while (GCLK->STATUS.bit.SYNCBUSY);
}

/*
ADC_CTRLB_PRESCALER_DIV4_Val    0x0u  
ADC_CTRLB_PRESCALER_DIV8_Val    0x1u   
ADC_CTRLB_PRESCALER_DIV16_Val   0x2u   
ADC_CTRLB_PRESCALER_DIV32_Val   0x3u   
ADC_CTRLB_PRESCALER_DIV64_Val   0x4u   
ADC_CTRLB_PRESCALER_DIV128_Val  0x5u   
ADC_CTRLB_PRESCALER_DIV256_Val  0x6u   
ADC_CTRLB_PRESCALER_DIV512_Val  0x7u   
--> 8 bit ADC measurement takes 5 clock cycles, 10 bit ADC measurement takes 6 clock cycles
--> Using 48MHz system clock with division factor of 1
--> Using ADC division factor of 32
--> Sample rate = 48M / (5 x 32) = 300 KSPS
This function sets up the ADC, including setting resolution and ADC sample rate
*/
void aDCSetup() {
  // Select reference
  REG_ADC_REFCTRL = ADC_REFCTRL_REFSEL_INTVCC1; //set vref for ADC to VCC

  // Average control 1 sample, no right-shift
  REG_ADC_AVGCTRL |= ADC_AVGCTRL_SAMPLENUM_1;

  // Sampling time, no extra sampling half clock-cycles
  REG_ADC_SAMPCTRL = ADC_SAMPCTRL_SAMPLEN(0);
  
  // Input control and input scan
  REG_ADC_INPUTCTRL |= ADC_INPUTCTRL_GAIN_1X | ADC_INPUTCTRL_MUXNEG_GND | ADC_INPUTCTRL_MUXPOS_PIN0;
  // Wait for synchronization
  while (REG_ADC_STATUS & ADC_STATUS_SYNCBUSY);

  ADC->CTRLB.reg |= ADC_CTRLB_RESSEL_8BIT | ADC_CTRLB_PRESCALER_DIV32 | ADC_CTRLB_FREERUN; //This is where you set the divide factor, note that the divide call has no effect until you change Arduino wire.c
  //Wait for synchronization
  while (REG_ADC_STATUS & ADC_STATUS_SYNCBUSY);

  ADC->WINCTRL.reg = ADC_WINCTRL_WINMODE_DISABLE; // Disable window monitor mode
  while(ADC->STATUS.bit.SYNCBUSY);

  ADC->EVCTRL.reg |= ADC_EVCTRL_STARTEI; //start ADC when event occurs
  while (ADC->STATUS.bit.SYNCBUSY);

  ADC->CTRLA.reg |= ADC_CTRLA_ENABLE; //set ADC to run in standby
  while (ADC->STATUS.bit.SYNCBUSY);
}

//This function sets up an ADC interrupt that is triggered 
//when an ADC value is out of range of the window
//input argument is priority of interrupt (0 is highest priority)
void setUpInterrupt(byte priority) {
  
  ADC->INTENSET.reg |= ADC_INTENSET_RESRDY; // enable ADC ready interrupt
  while (ADC->STATUS.bit.SYNCBUSY);

  NVIC_EnableIRQ(ADC_IRQn); // enable ADC interrupts
  NVIC_SetPriority(ADC_IRQn, priority); //set priority of the interrupt
}

//software trigger to start ADC in free run
//in future could use this to set various ADC triggers
void aDCSWTrigger() {
  ADC->SWTRIG.reg |= ADC_SWTRIG_START;
}

//This ISR is called each time ADC makes a reading
void ADC_Handler() {
    if(count<1023) {
      aDCVal[count] = REG_ADC_RESULT;
      count++;
    }
    ADC->INTFLAG.reg = ADC_INTENSET_RESRDY; //Need to reset interrupt
}

//This function takes out DC offset of AC signal, it assumes that the offset brings signal to zero volts
//input arguments: array with measured points and bits of measurement
void removeDCOffset(volatile int aDC[], int aSize, int bits) {
  int aSteps = pow(2,bits)/2; //get number of levels in ADC measurement and cut it in half
  for(int i=0; i<aSize; i++) {
    aDC[i] = aDC[i] - aSteps; //take out offset
  }
}

Thursday, August 10, 2017

Getting Started with Arduino and the ThingSpeak Cloud

In this video we look at how to use Arduino with the ThingSpeak IoT, cloud, and analytics platform. In the video we look at two use cases of ThingSpeak. For the first use case we log wireless sensor data to the cloud and perform post processing on the data using MATLAB. In the second use case we monitor a room with a wireless motion detector setup and have ThingSpeak send out a Tweet if any movement is detected in the room.



//*****************Arduino code from video**********************************
/*
This sketch was created for a video tutorial on the ForceTronics YouTube that shows how to use Arduino with the ThingSpeak cloud
This code is public domain and free for anybody to use or modify at their own risk

Note this code was leveraged from:
 Arduino --> ThingSpeak Channel via MKR1000 Wi-Fi
 Created: May 7, 2016 by Hans Scharler (http://www.nothans.com)
*/
   
#include <SPI.h>
#include <WiFi101.h> //This sketch should work with any Arduino or shield that can use the WiFi101 library

char ssid[] = "YourNetwork"; //  your network SSID (name)
char pass[] = "YourPassword"; // your network password

int status = WL_IDLE_STATUS;

// Initialize the Wifi clients
WiFiClient tClient; //this one is used to post temperature data
WiFiClient mClient; //this one is used to post motion detection data

// ThingSpeak Settings
char server[] = "api.thingspeak.com";
String writeAPIKey = "YourWriteKey";

//Timing variables for tracking temperature posting
unsigned long tempLastConnectionTime = 0; // track the last connection time
const unsigned long tempPostingInterval = 295000L; // post temp ADC value just under every 5 min

//Timing and logic variables for tracking temperature posting
unsigned long mLastConnectionTime = 0; // track the last connection time
const unsigned long mPostingInterval = 30000L; //checks to see if motion was detected every 30 sec
bool mReset = true; //tracks if motion detection has been reset

void setup() {
  pinMode(2,INPUT); //digital pin used to read output of motion detector
  pinMode(6,OUTPUT); //LED pin used to know when data is sent to cloud
  
  // attempt to connect to Wifi network
  while ( status != WL_CONNECTED) {
    // Connect to WPA/WPA2 Wi-Fi network
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection
    delay(10000);
  }
}

void loop() {
  //timer to know when it is time to post temp data to cloud
  if (millis() - tempLastConnectionTime > tempPostingInterval) {
    digitalWrite(6,HIGH); //Use the LED to see if Arduino gets heldup posting data to the cloud
    tempHttpRequest(); //function that formats data strings and posts data to ThingSpeak cloud
    digitalWrite(6,LOW);
  }

  if (millis() - mLastConnectionTime > mPostingInterval) {
    digitalWrite(6,HIGH); //Use the LED to see if Arduino gets heldup posting data to the cloud
    if(digitalRead(2) && mReset) { //if motion was detected post it
      mReset = false; //motion detected so reset variable
      mHttpRequest(); //if true motion was detected so post to cloud
    }
    else mReset = true; //reset logic tracker
    
    digitalWrite(6,LOW);
  }

}

//Posts temp data to thingspeak cloud
void tempHttpRequest() {
  // read analog pin 0 with temp sensor connected
  int sensorValue = analogRead(0);

  // create data string to send to ThingSpeak
 String data = String("field1=" + String(sensorValue, DEC)); 

  // POST data to ThingSpeak
  if (tClient.connect(server, 80)) {
    tClient.println("POST /update HTTP/1.1");
    tClient.println("Host: api.thingspeak.com");
    tClient.println("Connection: close");
    tClient.println("User-Agent: ArduinoWiFi/1.1");
    tClient.println("X-THINGSPEAKAPIKEY: "+writeAPIKey);
    tClient.println("Content-Type: application/x-www-form-urlencoded");
    tClient.print("Content-Length: ");
    tClient.print(data.length());
    tClient.print("\n\n");
    tClient.print(data);
     // close any connection before sending a new request
    tClient.stop();
    // note the last connection time
    tempLastConnectionTime = millis();
  }
}

//posts motion detection data to thingspeak cloud
void mHttpRequest() {

  // create data string to send to ThingSpeak, we always send a one here to indicate motion detected
 String data = String("field2=" + String(1,DEC)); 

  // POST data to ThingSpeak
  if (mClient.connect(server, 80)) {
    mClient.println("POST /update HTTP/1.1");
    mClient.println("Host: api.thingspeak.com");
    mClient.println("Connection: close");
    mClient.println("User-Agent: ArduinoWiFi/1.1");
    mClient.println("X-THINGSPEAKAPIKEY: "+writeAPIKey);
    mClient.println("Content-Type: application/x-www-form-urlencoded");
    mClient.print("Content-Length: ");
    mClient.print(data.length());
    mClient.print("\n\n");
    mClient.print(data);
     // close any connection before sending a new request
    mClient.stop();
    // note the last connection time
    mLastConnectionTime = millis();
  }
}

%*************************MATLAB code from video***************************
% Channel ID to read raw ADC temp data from
readChannelID = chanID;
% Temperature Field ID
TemperatureFieldID = 1;

% Channel Read API Key 
readAPIKey = 'YourReadKey';

% Channel ID to write temp data to:
writeChannelID = [chanID];
% API key for write channel:
writeAPIKey = 'YourWriteKey';

%Read raw ADC temp data
aDC = thingSpeakRead(readChannelID, 'Fields', TemperatureFieldID, 'ReadKey', readAPIKey);

%Convert raw 10 bit ADC data to voltage
volt = aDC*(3.3/1023);

%Using analog temp sensor TMP36
%calculate temp in C, .75 volts is 25 C. 10mV per degree
 if volt < .75 
     temp = 25 - ((.75-volt)/.01); %if below 25 C
 elseif volt == .75 
         temp = 25;
 else 
     temp = 25 + ((volt -.75)/.01);  %if above 25
 end

% Convert to Fahrenheit
tempF = (9/5*temp) + 32;

%This writes temp value to below console for debugging
display(tempF);

%write temp F value to channel
thingSpeakWrite(writeChannelID, 'Fields',1,'Values',tempF, 'Writekey', writeAPIKey);

Tuesday, May 30, 2017

Home Automation with Arduino and the Amazon Echo Part 4

In the final conclusion of this four part series on using the Amazon Echo and Arduino for home automation we look at the Arduino hardware setup for monitoring the current consumption of a washer machine and reports its state to the cloud.




You can access code from GitHub: https://github.com/ForceTronics/Arduino_Echo_Home_Automation


Friday, May 26, 2017

Home Automation with the Arduino and the Amazon Echo Part 3

In part 3 instead of controlling a household device with the Echo, Arduino, and the cloud like we did in parts 1 and 2, we are monitoring an appliance (washer) so the data is flowing in the opposite direction.



You can access the code on github:  https://github.com/ForceTronics/Arduino_Echo_Home_Automation



Wednesday, November 23, 2016

Creating a Sensor Network that Connects to the Cloud Part 3

In this three part series we look at how to create a wireless sensor mesh network that stores data on the cloud using the Arduino platform. In part three we look at how to access the sensor data from the cloud with a PC or Android device.


GitHub link to access code from the series: https://github.com/ForceTronics/nRF24L01-Sensor-Network-that-Connects-to-the-Cloud/

Thursday, November 3, 2016

Creating a Sensor Network that Connects to the Cloud Part 2

In this three part series we look at how to create a wireless sensor mesh network that stores data on the cloud using the Arduino platform. In part two we look at how to add time stamps to our sensor data and track the battery state of our nodes.



GitHub: https://github.com/ForceTronics/nRF24L01-Sensor-Network-that-Connects-to-the-Cloud/tree/master

Wednesday, October 26, 2016

Creating a Sensor Network that Connects to the Cloud Part 1

In this three part series we look at how to create a wireless sensor mesh network that stores data on the cloud using the Arduino platform. In part one we will look at the architecture of the network and how to get started sending sensor data to the cloud. 


Link to GitHub library and sketch code from video https://github.com/ForceTronics/nRF24L01-Sensor-Network-that-Connects-to-the-Cloud


Friday, October 14, 2016

Utilizing Advanced ADC Capabilities on Arduino’s with the SAMD21 (Zero, MKR1000, etc) Part 1

We are all familiar with the Arduino "analogRead()" function, but there is a lot more to the SAMD21 ADC then just taking simple readings. In this video series we look at some of the more advanced ADC capabilities of the SAMD21 and how to use them. In part 1 we look at how to use the window monitoring capability of the ADC.



//*******************Arduino code from the video*********************
//This sketch is from a tutorial on the ForceTronics YouTube Channel called 
//Utilizing Advanced ADC Capabilities on Arduino’s with the SAMD21 (Zero, MKR1000, etc)
//This code is public domain and free to anyone to use or modify at your own risk

//declare const for window mode settings
const byte DISABLE = 0;
const byte MODE1 = 1;
const byte MODE2 = 2;
const byte MODE3 = 3;
const byte MODE4 = 4;

void setup() {
  //call this function to start the ADC in window and define the window parameters
  ADCWindowBegin(MODE1, 512, 750); //Do not use the Arduino analog functions until you call ADCWindowEnd()
  Serial.begin(57600);
}

void loop() {
  delay(1500);
  Serial.println(readADC()); //the "readADC()" function can be used to get ADC readings while in Window mode
  Serial.println();
}

//This is the interrupt service routine (ISR) that is called 
//if an ADC measurement falls out of the range of the window 
void ADC_Handler() {
    digitalWrite(LED_BUILTIN, HIGH); //turn LED off
    ADC->INTFLAG.reg = ADC_INTFLAG_WINMON; //Need to reset interrupt
}

//this function sets up the ADC window mode with interrupt
void ADCWindowBegin(byte mode, int upper, int lower) {
  setMeasPin(); //function sets up ADC pin A0 as input
  setGenClock(); //setup ADC clock, using internal 8MHz clock
  setUPADC(); //configure ADC
  setADCWindow(mode, upper, lower); //setup ADC window mode 
  setUpInterrupt(0); //setup window mode interrupt with highest priority
  enableADC(1); //enable ADC 
}

void ADCWindowEnd() {
  NVIC_DisableIRQ(ADC_IRQn); //turn off interrupt
  enableADC(0); //disable ADC 
}

//setup measurement pin, using Arduino ADC pin A3
void setMeasPin() {
  // Input pin for ADC Arduino A3/PA04
  REG_PORT_DIRCLR1 = PORT_PA04;

  // Enable multiplexing on PA04
  PORT->Group[0].PINCFG[4].bit.PMUXEN = 1;
  PORT->Group[0].PMUX[1].reg = PORT_PMUX_PMUXE_B | PORT_PMUX_PMUXO_B;
}

//Function sets up generic clock for ADC
//Uses built-in 8MHz clock
void setGenClock() {
   // Enable the APBC clock for the ADC
  REG_PM_APBCMASK |= PM_APBCMASK_ADC;

  configOSC8M(); //this function sets up the internal 8MHz clock that we will use for the ADC
  
  // Setup clock GCLK3 for no div factor
   GCLK->GENDIV.reg |= GCLK_GENDIV_ID(3)| GCLK_GENDIV_DIV(1);
   while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);  

  //configure the generator of the generic clock, which is 8MHz clock
  GCLK->GENCTRL.reg |= GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSC8M | GCLK_GENCTRL_ID(3) | GCLK_GENCTRL_DIVSEL;
  while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY);
  
  //enable clock, set gen clock number, and ID to where the clock goes (30 is ADC)
  GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(3) | GCLK_CLKCTRL_ID(30);
  while (GCLK->STATUS.bit.SYNCBUSY);
}

//Function that does general settings for ADC
//sets it for a single sample
//Uses internal voltage reference
//sets gain factor to 1/2
void setUPADC() {
  // Select reference, internal VCC/2
  ADC->REFCTRL.reg |= ADC_REFCTRL_REFSEL_INTVCC1; // VDDANA/2, combine with gain DIV2 for full VCC range

  // Average control 1 sample, no right-shift
  ADC->AVGCTRL.reg |= ADC_AVGCTRL_ADJRES(0) | ADC_AVGCTRL_SAMPLENUM_1;

  // Sampling time, no extra sampling half clock-cycles
  REG_ADC_SAMPCTRL |= ADC_SAMPCTRL_SAMPLEN(0);

  // Input control: set gain to div by two so ADC has measurement range of VCC, no diff measurement so set neg to gnd, pos input set to pin 0 or A0
  ADC->INPUTCTRL.reg |= ADC_INPUTCTRL_GAIN_DIV2 | ADC_INPUTCTRL_MUXNEG_GND | ADC_INPUTCTRL_MUXPOS_PIN4;
  while (REG_ADC_STATUS & ADC_STATUS_SYNCBUSY);

  // PS16, 8 MHz, ADC_CLK = 500 kHz, ADC sampling rate, single eded, 12 bit, free running, DIV2 gain, 7 ADC_CLKs, 14 usec
  ADC->CTRLB.reg |= ADC_CTRLB_PRESCALER_DIV16 | ADC_CTRLB_RESSEL_10BIT | ADC_CTRLB_FREERUN; // Run ADC continously, 7 ADC_CLKs, 14 usec
  while (REG_ADC_STATUS & ADC_STATUS_SYNCBUSY);
}

//This function is used to setup the ADC windowing mode
//inputs are the mode, upper window value, and lower window value
//
void setADCWindow(byte mode, int upper, int lower) {
  ADC->WINCTRL.reg = mode; //set window mode
  while (ADC->STATUS.bit.SYNCBUSY);

   ADC->WINUT.reg = upper; //set upper threshold
   while (ADC->STATUS.bit.SYNCBUSY);

   ADC->WINLT.reg = lower; //set lower threshold
   while (ADC->STATUS.bit.SYNCBUSY);
}

//This function sets up an ADC interrupt that is triggered 
//when an ADC value is out of range of the window
//input argument is priority of interrupt (0 is highest priority)
void setUpInterrupt(byte priority) {
  
  ADC->INTENSET.reg |= ADC_INTENSET_WINMON; // enable ADC window monitor interrupt
   while (ADC->STATUS.bit.SYNCBUSY);

   NVIC_EnableIRQ(ADC_IRQn); // enable ADC interrupts
   NVIC_SetPriority(ADC_IRQn, priority); //set priority of the interrupt
}

//function allows you to enable or disable ADC
void enableADC(bool en) {
  if(en) ADC->CTRLA.reg = 2; //2 is binary 010 which is register bit to enable ADC
  else ADC->CTRLA.reg = 0; //0 disables ADC
}

//This function will return the latest ADC reading made during free run window mode
//must first start the ADC before calling this function
unsigned int readADC() {
  // Free running, wait for conversion to complete
  while (!(REG_ADC_INTFLAG & ADC_INTFLAG_RESRDY));
  // Wait for synchronization before reading RESULT
  while (REG_ADC_STATUS & ADC_STATUS_SYNCBUSY);
  
  return REG_ADC_RESULT;
}

//function enables the 8MHz clock used for the ADC
void configOSC8M() 
{
  SYSCTRL->OSC8M.reg |= SYSCTRL_OSC8M_ENABLE;
}


Saturday, September 24, 2016

Reducing Power Consumption on Arduino Zero, MKR1000, or any SAMD21 Arduino Part 1

In this multiple part series we look at how to reduce power consumption for battery powered designs that utilize Arduino's with the Atmel SAMD21 MCU (Zero, MKR1000, etc). In part one we look at how to put the SAMD21 to sleep and wake it up with either the real time clock (RTC) or an external event on an input pin.



//***************Arduino Sketch from the video*********************.
//This code was used for a tutorial on the ForceTronics YouTube channel. It shows how to save power
//by putting Arduino's based on the SAMD21 MCU (MKR1000, Zero, etc) to sleep and how to wake them
//This code is public domain for anybody to use or modify

//#include "RTCZero.h"
#include <RTCZero.h>

/* Create an rtc object */
RTCZero rtc;

/* Change these values to set the current initial time */
const byte seconds = 0;
const byte minutes = 00;
const byte hours = 00;

/* Change these values to set the current initial date */
const byte day = 24;
const byte month = 9;
const byte year = 16;

void setup() 
{
  delay(5000); //delay so we can see normal current draw
   pinMode(LED_BUILTIN, OUTPUT); //set LED pin to output
  digitalWrite(LED_BUILTIN, LOW); //turn LED off

  rtc.begin(); //Start RTC library, this is where the clock source is initialized

  rtc.setTime(hours, minutes, seconds); //set time
  rtc.setDate(day, month, year); //set date

  rtc.setAlarmTime(00, 00, 10); //set alarm time to go off in 10 seconds
  
  //following two lines enable alarm, comment both out if you want to do external interrupt
  rtc.enableAlarm(rtc.MATCH_HHMMSS); //set alarm
  rtc.attachInterrupt(ISR); //creates an interrupt that wakes the SAMD21 which is triggered by a FTC alarm
  //comment out the below line if you are using RTC alarm for interrupt
 // extInterrupt(A1); //creates an interrupt source on external pin
  
  //puts SAMD21 to sleep
  rtc.standbyMode(); //library call
  //samSleep(); //function to show how call works
}

void loop() 
{
  //do nothing in main loop
}

//interrupt service routine (ISR), called when interrupt is triggered 
//executes after MCU wakes up
void ISR()
{
  digitalWrite(LED_BUILTIN, HIGH);
}


//function that sets up external interrupt
void extInterrupt(int interruptPin) {
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(interruptPin, ISR, LOW);
}

//function to show how to put the 
void samSleep()
{
  // Set the sleep mode to standby
  SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
  // SAMD sleep
  __WFI();
}

//**********************Changed "begin" function from RTCZero Library**************
void RTCZero::begin(bool resetTime)
{
  uint16_t tmp_reg = 0;
  
  PM->APBAMASK.reg |= PM_APBAMASK_RTC; // turn on digital interface clock
  //config32kOSC();

  // If the RTC is in clock mode and the reset was
  // not due to POR or BOD, preserve the clock time
  // POR causes a reset anyway, BOD behaviour is?
  bool validTime = false;
  RTC_MODE2_CLOCK_Type oldTime;

  if ((!resetTime) && (PM->RCAUSE.reg & (PM_RCAUSE_SYST | PM_RCAUSE_WDT | PM_RCAUSE_EXT))) {
    if (RTC->MODE2.CTRL.reg & RTC_MODE2_CTRL_MODE_CLOCK) {

      validTime = true;
      oldTime.reg = RTC->MODE2.CLOCK.reg;
    }
  }
  // Setup clock GCLK2 with OSC32K divided by 32
  GCLK->GENDIV.reg = GCLK_GENDIV_ID(2)|GCLK_GENDIV_DIV(4);
  while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY)
    ;                                                         /*XOSC32K*/
  GCLK->GENCTRL.reg = (GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_DIVSEL );
  while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY)
    ;
  GCLK->CLKCTRL.reg = (uint32_t)((GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2 | (RTC_GCLK_ID << GCLK_CLKCTRL_ID_Pos)));
  while (GCLK->STATUS.bit.SYNCBUSY)
    ;

  RTCdisable();

  RTCreset();

  tmp_reg |= RTC_MODE2_CTRL_MODE_CLOCK; // set clock operating mode
  tmp_reg |= RTC_MODE2_CTRL_PRESCALER_DIV1024; // set prescaler to 1024 for MODE2
  tmp_reg &= ~RTC_MODE2_CTRL_MATCHCLR; // disable clear on match
  
  //According to the datasheet RTC_MODE2_CTRL_CLKREP = 0 for 24h
  tmp_reg &= ~RTC_MODE2_CTRL_CLKREP; // 24h time representation

  RTC->MODE2.READREQ.reg &= ~RTC_READREQ_RCONT; // disable continuously mode

  RTC->MODE2.CTRL.reg = tmp_reg;
  while (RTCisSyncing())
    ;

  NVIC_EnableIRQ(RTC_IRQn); // enable RTC interrupt 
  NVIC_SetPriority(RTC_IRQn, 0x00);

  RTC->MODE2.INTENSET.reg |= RTC_MODE2_INTENSET_ALARM0; // enable alarm interrupt
  RTC->MODE2.Mode2Alarm[0].MASK.bit.SEL = MATCH_OFF; // default alarm match is off (disabled)
  
  while (RTCisSyncing())
    ;

  RTCenable();
  RTCresetRemove();

  // If desired and valid, restore the time value
  if ((!resetTime) && (validTime)) {
    RTC->MODE2.CLOCK.reg = oldTime.reg;
    while (RTCisSyncing())
      ;
  }

  _configured = true;
}

Monday, September 5, 2016

Combining Arduino, Android, and the Cloud Part 3

In this 3 part series we look at how to create an Android app to monitor and control multiple WiFi enabled Arduinos using the cloud. In part 3 the finale we will look at how to send control data to the cloud using an Android App to control the Arduino WiFi nodes. To download the Android App .aia file to load into MIT App Inventor II use the following link: https://dl.dropboxusercontent.com/u/26591541/CloudHomeAutoEx2.aia


//Arduino MKR1000 Code****************************************************
/*
 This sketch was created for a tutorial called Combining Arduino, Android, and the Cloud Part 3 
 That was presented on the ForceTronics YouTube Channel. This code is public domain for anybody to 
 use or modify at your own risk

 Note that this code was leveraged from the Arduino WiFi101 examples and from a Sparkfun example 
 on using their cloud service Phant
 */


#include <SPI.h>
#include <WiFi101.h>

char ssid[] = "YourNetwork"; //  your network SSID (name)
char pass[] = "YourPassword";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)
bool pData = false;  //used to toggle between posting data and getting data

int status = WL_IDLE_STATUS;

//define some constant variables for pins and node number
const int LED_PIN = 6; // Thing's onboard, green LED
const int ANALOG_PIN = A0; // The only analog pin on the Thing
const int NODE_NUM = 2; //node identifier
const char parseKey[] = "stamp";

//define areas for phant cloud address and security keys
const char PhantHost[] = "data.sparkfun.com";
const char pPublicKey[] = "PublicKeyForPosting";
const char pPrivateKey[] = "PrivateKeyForPosting";
const char gPublicKey[] = "PublicKeyForGetting";
const char gPrivateKey[] = "PublicKeyForGetting";
//The following variables are from Phant library created by Sparkfun.
String _pub;
String _prv;
String _host;
String _params;
static const char HEADER_POST_URL1[] PROGMEM = "POST /input/";
static const char HEADER_POST_URL2[] PROGMEM = ".txt HTTP/1.1\n";
static const char HEADER_PHANT_PRV_KEY[] PROGMEM = "Phant-Private-Key: ";
static const char HEADER_CONNECTION_CLOSE[] PROGMEM = "Connection: close\n";
static const char HEADER_CONTENT_TYPE[] PROGMEM = "Content-Type: application/x-www-form-urlencoded\n";
static const char HEADER_CONTENT_LENGTH[] PROGMEM = "Content-Length: ";

//timing for posting to the phant cloud
const unsigned long postRate = 15000;
unsigned long lastPost = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT); //setup LED pin
  digitalWrite(LED_PIN, LOW); //Turn off LED
  Serial.begin(9600);
  while (!Serial) { //Note the code will not cont unless you open serial monitor
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus(); //Print info about the WiFi network that you are connected to
}

void loop() {
  //Delay for set time then post and get data from Phant cloud
  if (lastPost + postRate <= millis())
  {
    if(pData) {
      if (postToPhant()) lastPost = millis();
      else lastPost = millis(); //Even if we fail delay whole cycle before we try again   
    } 
    else {
      if (getFromPhant()) lastPost = millis();
      else lastPost = millis(); //Even if we fail delay whole cycle before we try again 
    }
  }
}

//function that handles posting and getting data from phant cloud
int getFromPhant()

 //Set phant data
 phant(PhantHost, gPublicKey, gPrivateKey);
  
  WiFiClient client; //Create client object to communicate with the phant server

  if (!client.connect(PhantHost, 80)) { //Attempt to connect to phant server using port 80
    // If we fail to connect, return 0.
    return 0;
  }

  //Get data from phant cloud
    client.print(phantGet()); 
    client.println();
    Serial.println("sent get request.....");
   int cTrack = 0; //variable that tracks count to spell stamp
   bool match = false; //tracks when we have a match with "stamp" and we can then get control data
   int pCount = 0; //variable used to track whe we have control data
   while(1) { //loop until we get data and server closes connection
    if (client.available()) { //if data is available from phant server
      char c = client.read(); //read a bite of data from server
      if(!match) { //if true than we have not found the word "stamp" so keep looking
        if(c == parseKey[cTrack]) //check if we have a character match with word "stamp"
        {
          if(cTrack == (sizeof(parseKey)-2)) match = true; //if true it means we found a match for "stamp" in data from phant cloud
          cTrack++; //iterate this count if a character match was found
        }
        else { //if true means no character match so reset count
          cTrack = 0;
        }
      }
      else { //if true it means we found a match to "stamp" and we are ready to get control data
        
        if(pCount == 3) { //if true we are at the point in the data to read control data for node oen
          Serial.print(c);
          int dControl = c - '0'; //convert char data to an int by subtract an ASCII zero
          if(dControl == 1 | dControl == 0) digitalWrite(LED_PIN, dControl); //make sure data is a one or zer and set LED pin with it
        }
        pCount++; //iterate the parse counter
      }
    }

    // if the server's disconnected, stop the client:
    if (!client.connected()) {
      Serial.println();
      Serial.println("disconnecting.");
      client.stop(); //stop client, if you don't have this you will create too many clients and server won't let you connect anymore
      break; //This is how we get out of the loop
    }
   }
  pData = true; //set to true so we post data to cloud next loop
  return 1; // Return success
}

//function used to post data to phant cloud
int postToPhant()
{
  // Declare an object from the Phant library - phant
  phant(PhantHost, pPublicKey, pPrivateKey);
  //These calls build the web communication strings with Phant
  phantAdd("adcdata", analogRead(ANALOG_PIN)); //specify field and data used in that field
  phantAdd("wifinode", NODE_NUM);
  
  WiFiClient client; //Create client object to communicate with the phant server

  if (!client.connect(PhantHost, 80)) { //Attempt to connect to phant server using port 80
    // If we fail to connect, return 0.
    pData = false; //set to false so we get data from cloud next loop
    return 0;
  }

  //Send post to phant server
  client.print(phantPost()); 
  
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    String line = client.readStringUntil('\r');
    //Do something with data
  }
  client.stop();
  pData = false; //set to false so we get data from cloud next loop
  return 1; // Return success
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  Serial.println();
}


//This is from phant library, initializes variables
void phant(String host, String publicKey, String privateKey) {
  _host = host;
  _pub = publicKey;
  _prv = privateKey;
  _params = "";
}

//From phant library, builds string of field and data
void phantAdd(String field, int data) {

  _params += "&" + field + "=" + String(data);

}

//From phant library, builds string to get data from Phant cloud
String phantGet() {
  String result = "GET /output/" + _pub + ".csv?page=1 HTTP/1.1\n";
  result += "Host: " + _host + "\n";
  result += "Connection: close\n";

  return result;

}

//From phant library, builds the string used to post data to phant over web services
String phantPost() {

  String params = _params.substring(1);
  String result;
  //String result = "POST /input/" + _pub + ".txt HTTP/1.1\n";
  for (int i=0; i<strlen(HEADER_POST_URL1); i++)
  {
    result += (char)pgm_read_byte_near(HEADER_POST_URL1 + i);
  }
  result += _pub;
  for (int i=0; i<strlen(HEADER_POST_URL2); i++)
  {
    result += (char)pgm_read_byte_near(HEADER_POST_URL2 + i);
  }
  result += "Host: " + _host + "\n";
  //result += "Phant-Private-Key: " + _prv + "\n";
  for (int i=0; i<strlen(HEADER_PHANT_PRV_KEY); i++)
  {
    result += (char)pgm_read_byte_near(HEADER_PHANT_PRV_KEY + i);
  }
  result += _prv + '\n';
  //result += "Connection: close\n";
  for (int i=0; i<strlen(HEADER_CONNECTION_CLOSE); i++)
  {
    result += (char)pgm_read_byte_near(HEADER_CONNECTION_CLOSE + i);
  }
  //result += "Content-Type: application/x-www-form-urlencoded\n";
  for (int i=0; i<strlen(HEADER_CONTENT_TYPE); i++)
  {
    result += (char)pgm_read_byte_near(HEADER_CONTENT_TYPE + i);
  }  
  //result += "Content-Length: " + String(params.length()) + "\n\n";
  for (int i=0; i<strlen(HEADER_CONTENT_LENGTH); i++)
  {
    result += (char)pgm_read_byte_near(HEADER_CONTENT_LENGTH + i);
  } 
  result += String(params.length()) + "\n\n";
  result += params;

  _params = "";
  return result;
}

//This function convers the ADC level integer value into float voltage value.
//The inputs are the measured ADC value and the ADC reference voltage level
//The formula used was obtained from the data sheet: (ADC value / 1024) x ref voltage
float convertToVolt(float refVal, int aVAL) {
  return (((float)aVAL/1024)*refVal);
}

//this function calculates temp in F from TMP36 temp sensor
//see TMP36 datasheet to understand algorithm used
float calculateTempF(float v1) { 
 float temp = 0;
 //calculate temp in C, .75 volts is 25 C. 10mV per degree
 if (v1 < .75) { temp = 25 - ((.75-v1)/.01); } //if below 25 C
 else if (v1 == .75) {temp = 25; }
 else { temp = 25 + ((v1 -.75)/.01); } //if above 25
 //convert to F
 temp =((temp*9)/5) + 32;
 return temp;
}

//Arduino ESP8266 Code****************************************************
/*
 This sketch was created for a tutorial called Combining Arduino, Android, and the Cloud Part 3 
 That was presented on the ForceTronics YouTube Channel. This code is public domain for anybody to 
 use or modify at your own risk

 Note that this code was leveraged from a Sparkfun example 
 on using their cloud service Phant
 */

// Include the ESP8266 WiFi library. (Works a lot like the
// Arduino WiFi library.)
#include <ESP8266WiFi.h>
// Include the SparkFun Phant library.
#include <Phant.h>

//Set your network name and password
const char WiFiSSID[] = "YourNetwork";
const char WiFiPSK[] = "YourPassword";

//define constants for pin control and node number
const int LED_PIN = 5; // Thing's onboard, green LED
const int ANALOG_PIN = A0; // The only analog pin on the Thing
const int NODE_NUM = 1; //node identifier
const char parseKey[] = "stamp";
bool pData = false;  //used to toggle between posting data and getting data

//declare phant address and security keys
const char PhantHost[] = "data.sparkfun.com";
const char pPublicKey[] = "PublicKeyForPosting";
const char pPrivateKey[] = "PrivateKeyForPosting";
const char gPublicKey[] = "PublicKeyForGetting";
const char gPrivateKey[] = "PublicKeyForGetting";

//specify the rate that you post data to cloud
const unsigned long postRate = 15000;
unsigned long lastPost = 0;

void setup() 
{
  initHardware(); //setup arduino hardware
  connectWiFi(); //Connect your WiFi network
  digitalWrite(LED_PIN, HIGH);
}

void loop() 
{ //loop until it is time to post data to phant cloud
  if (lastPost + postRate <= millis())
  {
    if(pData) {
      if (postToPhant()) lastPost = millis();
      else lastPost = millis(); //Even if we fail delay whole cycle before we try again   
    } 
    else {
      if (getFromPhant()) lastPost = millis();
      else lastPost = millis(); //Even if we fail delay whole cycle before we try again 
    }
  }
}

//function used to connect to WiFi network
void connectWiFi()
{
  byte ledStatus = LOW;
  // Set WiFi mode to station (as opposed to AP or AP_STA)
  WiFi.mode(WIFI_STA);
  // WiFI.begin([ssid], [passkey]) initiates a WiFI connection
  // to the stated [ssid], using the [passkey] as a WPA, WPA2,
  // or WEP passphrase.
  WiFi.begin(WiFiSSID, WiFiPSK);
  
  // Use the WiFi.status() function to check if the ESP8266
  // is connected to a WiFi network.
  while (WiFi.status() != WL_CONNECTED)
  {
    // Blink the LED
    digitalWrite(LED_PIN, ledStatus); // Write LED high/low
    ledStatus = (ledStatus == HIGH) ? LOW : HIGH;
    
    // Delays allow the ESP8266 to perform critical tasks
    // defined outside of the sketch. These tasks include
    // setting up, and maintaining, a WiFi connection.
    delay(100);
    // Potentially infinite loops are generally dangerous.
    // Add delays -- allowing the processor to perform other
    // tasks -- wherever possible.
  }
}

//function that sets up some initial hardware states
void initHardware()
{
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
}

//function that handles posting and getting data from phant cloud
int getFromPhant()

 //Set phant data
 Phant phant(PhantHost, gPublicKey, gPrivateKey);
  
  WiFiClient client; //Create client object to communicate with the phant server

  if (!client.connect(PhantHost, 80)) { //Attempt to connect to phant server using port 80
    // If we fail to connect, return 0.
    return 0;
  }

  //Get data from phant cloud
    client.print(phant.get()); 
    client.println();
   int cTrack = 0; //variable that tracks count to spell stamp
   bool match = false; //tracks when we have a match with "stamp" and we can then get control data
   int pCount = 0; //variable used to track whe we have control data
   while(1) { //loop until we get data and server closes connection
    if (client.available()) { //if data is available from phant server
      char c = client.read(); //read a bite of data from server
      if(!match) { //if true than we have not found the word "stamp" so keep looking
        if(c == parseKey[cTrack]) //check if we have a character match with word "stamp"
        {
          if(cTrack == (sizeof(parseKey)-2)) match = true; //if true it means we found a match for "stamp" in data from phant cloud
          cTrack++; //iterate this count if a character match was found
        }
        else { //if true means no character match so reset count
          cTrack = 0;
        }
      }
      else { //if true it means we found a match to "stamp" and we are ready to get control data
        
        if(pCount == 1) { //if true we are at the point in the data to read control data for node oen
          int dControl = c - '0'; //convert char data to an int by subtract an ASCII zero
          if(dControl == 1 | dControl == 0) digitalWrite(LED_PIN, dControl); //make sure data is a one or zer and set LED pin with it
        }
        pCount++; //iterate the parse counter
      }
    }

    // if the server's disconnected, stop the client:
    if (!client.connected()) {
      client.stop(); //stop client, if you don't have this you will create too many clients and server won't let you connect anymore
      break; //This is how we get out of the loop
    }
   }
  pData = true; //set to true so we post data to cloud next loop
  return 1; // Return success
}

//this function takes data and posts it to the cloud
int postToPhant()

  // Declare an object from the Phant library - phant
  Phant phant(PhantHost, pPublicKey, pPrivateKey);
  //These functions build data and field string that will be sent to phant cloud
  phant.add("adcdata", analogRead(ANALOG_PIN));
  phant.add("wifinode", NODE_NUM);
  
  // Now connect to data.sparkfun.com, and post our data:
  WiFiClient client; //declare client object that will post the data
  const int httpPort = 80; //specify port to post through
  
  if (!client.connect(PhantHost, httpPort)) //attempt to connect to phant
  {
    // If we fail to connect, return 0.
    return 0;
  }
 //Send post to phant
  client.print(phant.post());
  
  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    //Serial.print(line); // Trying to avoid using serial
  }
  pData = false; //set to false so we get data from cloud next loop
  return 1; // Return success
}
  

Saturday, August 27, 2016

Combining Arduino, Android, and the Cloud Part 2

In this 3 part series we look at how to create an Android app to monitor and control multiple WiFi enabled Arduinos using the cloud. In part 2 we will look at how to grab the Arduino data from the cloud using a custom Android App.




To download the Android App .aia file to load into MIT App Inventor II use the following link: https://dl.dropboxusercontent.com/u/26591541/CloudHomeAutoEx.aia