Visualizzazione post con etichetta Interrupt. Mostra tutti i post
Visualizzazione post con etichetta Interrupt. Mostra tutti i post

martedì 19 marzo 2019

Arduino MKR1010 ed allarme ricorsivo con RTCZero e risparmio energetico

Aggiornamento: questo post e' molto simile al precedente

Lo scopo di questo script e' generare ogni 10 secondi un allarme che risvegli dall standby la MKR1010 per effettuare una operazione e poi la riaddormenti in staandy


Una volta in Sleep Mode in consumo e' inferiore a 10 mA ovvero e' sotto la soglia di misura del mio strumento

Con questa configurazione il consumo e' di circa 14 mA

Attenzione : quando viene lanciato il programma il processore va in standby e viene disabilitata la porta USB. Per effettuare un nuovo upload si deve premere il tasto di reset per due volte in modo veloce
--------------------------------------------------------------------------
#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 = 17;

/* Change these values to set the current initial date */
const byte day = 17;
const byte month = 11;
const byte year = 15;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  rtc.begin();

  rtc.setTime(hours, minutes, seconds);
  rtc.setDate(day, month, year);

  rtc.setAlarmTime(17, 00, 10);
  // Abilita l'allarme quando i secondi sono uguali alla soglia
  rtc.enableAlarm(rtc.MATCH_SS);
  rtc.attachInterrupt(alarmMatch);

  rtc.standbyMode();
}

void loop()
{
  rtc.standbyMode();    // Sleep until next alarm match
}

void alarmMatch()

  // INVERTE LO STATO DEL LED
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  // Setta il nuovo allarme 10 secondi nel futuro
  rtc.setAlarmSeconds((rtc.getSeconds() + 10) % 60);
}

martedì 5 febbraio 2019

Arduino MKR1400

E' arrivata sulla scrivania la concorrente diretta della Particle Electron (e molto probabilmente la vincitrice), la Arduino MKR1400 una MKR1000 con in aggiunta un modulo GSM

La scheda funziona con le microSIM e non con le nanoSIM (come la Electron) e supporta senza nessun problema Things Mobile



Una prima cosa strana: la scheda mi e' arrivata senza antenna nonostante sullo store ne viene segnalata la presenza. Ho utilizzato quella della Electron

Ho avuto problemi di connessione con la porta seriale. In caso di necessita' di reset della scheda si deve premere due volte in modo ravvicinato il tasto di reset

Il connettore della LiPo e' di tipo JST-PH
Per controllare il livello della batteria si puo' usare questo sketch
----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(ADC_BATTERY);
  float voltage = sensorValue * (4.3 / 1023.0);
  Serial.print(voltage);
  Serial.println("V");
}
----------------------------------------------------------------------------

Per inviare SMS il codice piu' semplice e' il seguente.
Negli sketch deve essere sempre inserita la parte in giallo di configurazione della seriale
Alla SIM e' stato rimosso il pincode per cui non e' necessario configuralo nello sketch

----------------------------------------------------------------------------
#include <MKRGSM.h>


GSM gsmAccess;
GSM_SMS sms;

void setup() {
 Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  
bool connected = false;

  while (!connected) {
    if (gsmAccess.begin() == GSM_READY) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
}

void loop() {
  delay(1000);
  sms.beginSMS("+393471xxxxxxx");
  sms.print("Prova MKR14000");
  sms.endSMS(); 
  Serial.println("Inviato");
  delay(60000);
}
--------------------------------------------------------

Nel momento di provare ad usare la MKR1400 in accoppiata con un ADXL345 sono entrato in una serie di problemi apparentemente senza uscita perche' ogni volta che cercavo di configurare il canale I2C la scheda perdeva la configurazione della porta seriale su USB e non eseguiva nessuno sketch

Dopo un'oretta di prove a caso ho messo un delay di 5 secondi all'inizio della funzione di setup()  e l'accelerometro ha iniziato a funzionare in modo corretto

MKR1400 e ADXL345



----------------------------------------------------------
/
#include <MKRGSM.h>

GSM gsmAccess;
GSM_SMS sms;

#include <SparkFun_ADXL345.h>         // SparkFun ADXL345 Library

ADXL345 adxl = ADXL345();             // USE FOR I2C COMMUNICATION
int interruptPin = 2;                 // Setup pin 2 to be the interrupt pin (for most Arduino Boards)

void setup(){
  
  Serial.begin(9600);  
  while (!Serial)
  {}; 
  delay(5000);
  Serial.println("SMS Messages Sender");

  
  // Start the serial terminal
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();
  
  adxl.powerOn();                     // Power on the ADXL345

  adxl.setRangeSetting(16);           // Give the range settings
                                      // Accepted values are 2g, 4g, 8g or 16g
                                      // Higher Values = Wider Measurement Range
                                      // Lower Values = Greater Sensitivity

  adxl.setSpiBit(0);                  // Configure the device to be in 4 wire SPI mode when set to '0' or 3 wire SPI mode when set to 1
                                      // Default: Set to 1
                                      // SPI pins on the ATMega328: 11, 12 and 13 as reference in SPI Library 
   
  adxl.setActivityXYZ(1, 0, 0);       // Set to activate movement detection in the axes "adxl.setActivityXYZ(X, Y, Z);" (1 == ON, 0 == OFF)
  adxl.setActivityThreshold(75);      // 62.5mg per increment   // Set activity   // Inactivity thresholds (0-255)

  adxl.setInactivityXYZ(1, 0, 0);     // Set to detect inactivity in all the axes "adxl.setInactivityXYZ(X, Y, Z);" (1 == ON, 0 == OFF)
  adxl.setInactivityThreshold(75);    // 62.5mg per increment   // Set inactivity // Inactivity thresholds (0-255)
  adxl.setTimeInactivity(10);         // How many seconds of no activity is inactive?

  adxl.setTapDetectionOnXYZ(0, 0, 1); // Detect taps in the directions turned ON "adxl.setTapDetectionOnX(X, Y, Z);" (1 == ON, 0 == OFF)

  // Set values for what is considered a TAP and what is a DOUBLE TAP (0-255)
  adxl.setTapThreshold(50);           // 62.5 mg per increment
  adxl.setTapDuration(15);            // 625 μs per increment
  adxl.setDoubleTapLatency(80);       // 1.25 ms per increment
  adxl.setDoubleTapWindow(200);       // 1.25 ms per increment

  // Set values for what is considered FREE FALL (0-255)
  adxl.setFreeFallThreshold(7);       // (5 - 9) recommended - 62.5mg per increment
  adxl.setFreeFallDuration(30);       // (20 - 70) recommended - 5ms per increment

  // Setting all interupts to take place on INT1 pin
  //adxl.setImportantInterruptMapping(1, 1, 1, 1, 1);     // Sets "adxl.setEveryInterruptMapping(single tap, double tap, free fall, activity, inactivity);" 
                                                        // Accepts only 1 or 2 values for pins INT1 and INT2. This chooses the pin on the ADXL345 to use for Interrupts.
                                                        // This library may have a problem using INT2 pin. Default to INT1 pin.
  
  // Turn on Interrupts for each mode (1 == ON, 0 == OFF)
  adxl.InactivityINT(1);
  adxl.ActivityINT(1);
  adxl.FreeFallINT(1);
  adxl.doubleTapINT(1);
  adxl.singleTapINT(1);
  
attachInterrupt(digitalPinToInterrupt(interruptPin), ADXL_ISR, RISING);   // Attach Interrupt

}

/****************** MAIN CODE ******************/
/*     Accelerometer Readings and Interrupt    */
void loop(){
  
  // Accelerometer Readings
  int x,y,z;   
  adxl.readAccel(&x, &y, &z);         // Read the accelerometer values and store them in variables declared above x,y,z

  // Output Results to Serial
  /* UNCOMMENT TO VIEW X Y Z ACCELEROMETER VALUES 
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z); */
  
  ADXL_ISR();
  // You may also choose to avoid using interrupts and simply run the functions within ADXL_ISR(); 
  //  and place it within the loop instead.  
  // This may come in handy when it doesn't matter when the action occurs. 

}

/********************* ISR *********************/
/* Look for Interrupts and Triggered Action    */
void ADXL_ISR() {
  
  // getInterruptSource clears all triggered actions after returning value
  // Do not call again until you need to recheck for triggered actions
  byte interrupts = adxl.getInterruptSource();
  
  // Free Fall Detection
  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
    Serial.println("*** FREE FALL ***");

    //add code here to do when free fall is sensed
  } 
  
  // Inactivity
  if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
    Serial.println("*** INACTIVITY ***");
     //add code here to do when inactivity is sensed
  }
  
  // Activity
  if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
    Serial.println("*** ACTIVITY ***"); 
     //add code here to do when activity is sensed
  }
  
  // Double Tap Detection
  if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
    Serial.println("*** DOUBLE TAP ***");
     //add code here to do when a 2X tap is sensed
  }
  
  // Tap Detection
  if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
    Serial.println("*** TAP ***");
            bool connected = false;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (!connected) {
    if (gsmAccess.begin() == GSM_READY) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }
    Serial.println("Luca mi ha toccato");

   delay(1000);
  sms.beginSMS("+3934710xxxxxx");
  sms.print("Luca mi ha toccato");
  sms.endSMS(); 
  Serial.println("Inviato");
  delay(60000);


  } 
}



giovedì 31 gennaio 2019

ESP32 Vroom Sleep + Interrupt

Esempio di Esp32 su scheda Esp-Vroom-32 con modalita' di risveglio da Sleep mode mediante un interrupt fisico (in questo caso un contatto sul pin 33)

Per aggiungere la scheda alla IDE di Arduino si deve aggiungere questo link alle additional boards
https://dl.espressif.com/dl/package_esp32_index.json





Queste sono le impostazioni per programmare la scheda nella IDE





tra gli esempi si trova questo codice che imposta la modalita' deeep sleep e risveglio da pin 33
il consumo di corrente e' inferiore a 0.01A (questo e' il limite inferiore del mio misuratore di corrente USB)

=======================================================

/*
Deep Sleep with External Wake Up
=====================================
This code displays how to use deep sleep with
an external trigger as a wake up source and how
to store data in RTC memory to use it over reboots

This code is under Public Domain License.

Hardware Connections
======================
Push Button to GPIO 33 pulled down with a 10K Ohm
resistor

NOTE:
======
Only RTC IO can be used as a source for external wake
source. They are pins: 0,2,4,12-15,25-27,32-39.

Author:
Pranav Cherukupalli <cherukupallip@gmail.com>
*/

#define BUTTON_PIN_BITMASK 0x200000000 // 2^33 in hex

RTC_DATA_ATTR int bootCount = 0;

/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;

  wakeup_reason = esp_sleep_get_wakeup_cause();

  switch(wakeup_reason)
  {
    case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
    case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
    case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
    case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
    case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
    default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
  }
}

void setup(){
  Serial.begin(115200);
  delay(1000); //Take some time to open up the Serial Monitor

  //Increment boot number and print it every reboot
  ++bootCount;
  Serial.println("Boot number: " + String(bootCount));

  //Print the wakeup reason for ESP32
  print_wakeup_reason();

  esp_sleep_enable_ext0_wakeup(GPIO_NUM_33,1); //1 = High, 0 = Low

  //If you were to use ext1, you would use it like
  //esp_sleep_enable_ext1_wakeup(BUTTON_PIN_BITMASK,ESP_EXT1_WAKEUP_ANY_HIGH);

  //Go to sleep now
  Serial.println("Going to sleep now");
  esp_deep_sleep_start();
}

void loop(){
  }

mercoledì 30 gennaio 2019

SMS + DeepSleep + Interrupt in Particle Electron

Prendendo spunto dal post precedente in questo caso l'SMS e' inviato da una Particle Electron generato da un interrupt su pin D2 (in questo caso pero' mandando il pin a GND) partendo pero' da una condizione di Deep Sleep

===============================================================
#include "application.h"
#include "cellular_hal.h"
STARTUP(cellular_credentials_set("TM", "", "", NULL));

const char* phNum = "+39347107xxxx";
const char* msg = "Interrupt fired";
int  ret;


void setup()
{
 pinMode(D7, OUTPUT);
 pinMode(D2, INPUT_PULLDOWN);    // sets pin as input
}

void loop()
    {
    digitalWrite(D7, HIGH);

    System.sleep(D2,FALLING);
    Cellular.on();
    Cellular.connect();
    delay(20000);
    if (Cellular.ready() == true)
    {
      ret = Cellular.command("AT+CMGF=1\r\n");
      ret = Cellular.command("AT+CMGS=\"%s%s\",129\r\n",(phNum[0] != '+') ? "+" : "", phNum); //
      ret = Cellular.command("%s\x1a", msg);
      digitalWrite(D7, LOW);
      delay(5000);

    }

}

Invio SMS da Particle Electron da interrupt

Come gestire gli interrupt fisici su Particle Electron ed inviare SMS
Al contratio di Arduino Uno sulla Electron ci sono molteplici pin che possono essere settati per ricevere un interrupt. In questo caso e' stato scelto il D2


Per atttivare l'interrupt viene mandata una corrente di 3.3V sul Pin D2 e viene settata una variabile volatile in modo che possa essere intercettata anche fuori dall'interrupt nella funzione loop. La gestione di invio inoltre non puo' essere gestita all'interno della funzione di interrupt

per la compilazione

particle compile electron interrupt.ino --saveTo interrupt.bin
particle flash --usb  interrupt.bin 

Nel video si osserva la procedura

----------------------------------------------------------------
#include "application.h"
#include "cellular_hal.h"
STARTUP(cellular_credentials_set("TM", "", "", NULL));

const char* phNum = "+3934710xxxxx";
const char* msg = "Interrupt fired";
int  ret;
volatile bool invio;

void  IN4_ISR() {
      invio = true;
}

void setup()
{
  invio = false;
 pinMode(D7, OUTPUT);
 pinMode(D2, INPUT_PULLDOWN);    // sets pin as input
 attachInterrupt(D2, IN4_ISR, FALLING);  //RISING, FALLING, CHANGE
}

void loop()
    {
      if (invio)
      {
        digitalWrite(D7, HIGH);
        ret = Cellular.command("AT+CMGF=1\r\n");
        ret = Cellular.command("AT+CMGS=\"%s%s\",129\r\n",(phNum[0] != '+') ? "+" : "", phNum); //
        ret = Cellular.command("%s\x1a", msg);
        invio = false;
        delay(500);
        digitalWrite(D7, LOW);
      }

}

Geologi

  E so anche espatriare senza praticamente toccare strada asfaltata