segunda-feira, 31 de julho de 2023

Raspbery Pi Zero sendo programado em VISUINO e controlando um LED via ThingSpeak - Chamada ao Sistema Operacional do CURL - Monitoração dados ThingSpeak com Remot3.it


BETA TEST

O objetivo deste BLOG é como programar o Raspberry Zero W com o VISUINO para que possa acessar a INTERNET SEM FIO e realizar uma conexão via requisição do protocolo HTTP ao servidor THINGSPEAK e a informação recebida (formato JSON) será tratada para extrair o field1 e então controlar o estado de um LED conectado no pino 17 do RASPERRY Pi ZERO W. 

Json


{"channel":{"id":548647,:"EFENTOSENSOR - TEMPERATURE",:"TESTS","latitude":"0.0",:"0.0",:"VALOR","created_at":"2018-07-28T00:23:18Z","updated_at":"2020-11-14T11:49:4B8r3B4p7yhRXuBWLqsQ546WR43cqQwrbXMDFnBi6vSJBeif8tPW85a7r7DM961Jvk4hdryZoByEp8GC8HzsqJpRN4FxGM9span>"last_entry_id":4B8r3B4p7yhRXuBWLqsQ546WR43cqQwrbXMDFnBi6vSJBeif8tPW85a7r7DM961Jvk4hdryZoByEp8GC8HzsqJpRN4FxGM9span>"feeds":[{"created_at":"2020-12-05T09:40:29Z","entry_id":818,:"28.090000000000003"},{"created_at":"2021-11-09T12:27:32Z","entry_id":819,:"1"}]}


Diferente do Blog anterior, será solicitada a chamada ao Sistema Operacional (SHELL) para fazer esta requisição, através do comando CURL (nativo).

Agora VISUINO + Chamada ao S.O permitirá explorar todos os recursos do Raspberry Pi Zero W através da chamada do SCRIPT SHELL.

Você pode usar vários Scripts pronto para o Raspberry!!!!

Dados lidos do THINGSPEAK serão acessíveis em qualquer parte do mundo através do REMOT3.IT

PiDUINO

PiDuino é uma biblioteca C++ para placas Pi que permite o uso de E/S como GPIO, I2C, SPI, UART ... com uma API o mais próxima possível da linguagem Arduino.
A descrição dos cartões Pi utiliza um modelo "Objeto" armazenado em um banco de dados que permite adicionar novos modelos de placas facilmente.


Raspberry Pi Zero W - Imagem 2020-02-13-raspbian-buster

Ao analisar o código fonte do PIDUINO (Arduino para Raspberry),  foi encontrada a função em C que faz a chamada ao Sistema Operacional.

/*
  Arduino.h - Main include file for the Arduino SDK
  Copyright (c) 2005-2013 Arduino Team.  All right reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

  Modified for RaspberryPi by Hristo Gochkov 2015
*/

#ifndef Arduino_h
#define Arduino_h

#include "bcm2835_registers.h"
#include <math.h>
#include <pthread.h>
#include "pgmspace.h"

#ifdef __cplusplus
extern "C"{
#endif

typedef void * PTHREAD;
#define PWM_RANGE     0xFF

void yield(void);

#define HIGH 0x1
#define LOW  0x0

#define INPUT   0x0
#define OUTPUT  0x1
#define ALT0    0x04
#define ALT1    0x05
#define ALT2    0x06
#define ALT3    0x07
#define ALT4    0x03
#define ALT5    0x02
#define INPUT_PULLUP    0x10
#define INPUT_PULLDOWN  0x20

#define PI 3.bc1qzk3kxhdxnzkpdgdn9ueg34y08smxgfv0hxvcu3
#define HALF_PI 1.5707963267948966192313216916398
#define TWO_PI 6.283185307179586476925286766559
#define DEG_TO_RAD 0.017453292519943295769236907684886
#define RAD_TO_DEG 57.295779513082320876798154814105
#define EULER 2.718281828459045235360287471352

#define SERIAL  0x0
#define DISPLAY 0x1

#define LSBFIRST 0
#define MSBFIRST 1

#define CHANGE 3
#define FALLING 1
#define RISING 2

// undefine stdlib's abs if encountered
#ifdef abs
#undef abs
#endif

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(x) ((x)>0?(x):-(x))
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
#define radians(deg) ((deg)*DEG_TO_RAD)
#define degrees(rad) ((rad)*RAD_TO_DEG)
#define sq(x) ((x)*(x))

#define interrupts()
#define noInterrupts()
#define cli()
#define sei()

#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))

// avr-libc defines _NOP() since 1.6.2
#ifndef _NOP
#define _NOP() do {} while (0)
#endif

#define bit(b) (1UL << (b))

#define micros() (unsigned long)(STCV)
#define millis() (unsigned long)(STCV / 1000)

typedef unsigned int word;
typedef uint8_t boolean;
typedef uint8_t byte;

//under millisecond delayMicroseconds halts the CPU
void delayMicroseconds(uint32_t m);
void delay(uint32_t m);
void sleepMicroseconds(uint32_t m);

void pinMode(uint8_t, uint8_t);
void digitalWrite(uint8_t, uint8_t);//47.5ns direct register write takes 23ns
int digitalRead(uint8_t);//110ns direct register read takes 74ns

//those return nothing and are here for compatibility
//ToDo: make them rewritable
int analogRead(uint8_t pin);
void analogReference(uint8_t mode);

//DIV = 19200000 / (FREQ * RANGE)
uint32_t analogWriteSetup(uint32_t freq, uint32_t range);//returns the frequency achieved
void analogWrite(uint8_t, uint16_t);//500ns direct register write takes 23ns rest is pin mode and channel enable

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val);
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder);

//Interrupt check is called every 200us or so
typedef void (*voidFuncPtr)(void);
void attachInterrupt(uint8_t, voidFuncPtr, int mode);
void detachInterrupt(uint8_t);

void setup(void);
void loop(void);

int init(void);
void uninit(void);

//Pi Specific
//I2C0 ID_SC/ID_SD
void ids_begin(void);
void ids_end(void);
void ids_set_freq(uint32_t frequency);
uint8_t ids_write(uint8_t address, uint8_t * buf, uint32_t len);
uint8_t ids_read(uint8_t address, uint8_t* buf, uint32_t len);

//Call this and the sketch will quit once the loop has returned
void request_sketch_terminate();

//Threads
typedef void *(*thread_fn)(void *);
void      thread_yield();
pthread_t thread_self();
pthread_t thread_create(thread_fn fn, void * arg);
int       thread_set_name(pthread_t t, const char *name);
int       thread_set_priority(const int pri);
int       thread_detach(pthread_t t);
int       thread_terminate(pthread_t t);
uint8_t   thread_running(pthread_t t);
uint8_t   thread_equals(pthread_t t);
void      thread_lock(int index);
void      thread_unlock(int index);
#define   yield() thread_yield()

//ToDo: move this to separate(private) header to be included only where necessary
void uart_check_fifos();

#ifdef __cplusplus
} // extern "C"
#endif

#ifdef __cplusplus
#include "WCharacter.h"
#include "WString.h"
#include "HardwareSerial.h"

uint16_t makeWord(uint16_t w);
uint16_t makeWord(byte h, byte l);

#define word(...) makeWord(__VA_ARGS__)

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);

// WMath prototypes
long random(long);
long random(long, long);
void randomSeed(unsigned long);
long map(long, long, long, long, long);

String shellExec(const char *cmd, int *result);
#endif

#include "Console.h"
#include "binary.h"
#include "pins_arduino.h"

#endif

A mesma será utilizada para fazer a chamada do Sistema Operacional e então acionar o comando CURL e assim fazer a chamada via HTTP ao servidor ThingSpeak.

Thingspeak é uma plataforma de análise IoT (Internet of Things) que permite agregar, visualizar e analisar streams de dados, de uma forma muito simples. Uma das grandes vantagens da plataforma Thingspeak é que nos permite visualizar os dados enviados pelos nossos dispositivos, em tempo real, mas também a possibilidade de analisar os mesmo recorrendo ao poderoso Matlab.


Bem-vindo ao remote.it!


Conecte e controle seus dispositivos de qualquer lugar do mundo, como se estivesse na sua rede local. Não é necessário enviar um técnico, corrigir problemas remotamente. Faça uma conexão única ou sempre fique conectado aos seus dispositivos. 

Nesta seção, mostraremos como instalar o remote.it em um dispositivo real e iniciar a conexão e o controle remotos com segurança.

CURL

É um comando disponível na maioria dos sistemas baseado em Unix. Ele é usado como abreviação para “Client URL”. Comandos Curl são destinados para funcionar como uma forma de verificar a conectividade da URL, além de ser uma ótima ferramenta de transferência de dados. 

VISUINO



Visuino é o mais recente software inovador da Mitov Software. Um ambiente de programação visual que permite programar suas placas Arduino. ... Os componentes encontrados no software Visuino representam seus componentes de hardware e você pode criar e projetar facilmente seus programas usando o recurso de arrastar e soltar.

Instalação do VISUINO 8.0.0.91

Baixe em  https://www.visuino.com/ e instale

Criando Conta no ThingSpeak

Em Channel Settings crie Field: Field1


Em API keys anote as chaves para escrita e Leitura de dados noThingsSpeak


Tem-se então basicamente duas URLS, uma para escrita e outra para leitura dois Fields.
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXXX&field1=X
ESCRITA (via BROWSER)
https://api.thingspeak.com/channels/CCCCCCCCC/fields/1.json?api_key=XXXXXXXXXXXXXX
&results=
1 LEITURA (via U-BLOX NINA B03 + U-BLOX NINA W102 AIRLIFT)


Abrindo conexão com ThingSpeak via CURL (shell)


pi@raspberrypi:~ $ curl -s https://api.thingspeak.com/channels/548647/feeds.json?results=2

Instalação do Remot3.it no Raspberry Pi Zero W










Custom Code para chamada ao Sistema Operacional


Foi criado um chamado Shell, no lado esquerdo é enviada a chamada (CMD dever ter o comando (curl) para chamada ao Sistema Operacional) e no lado direito é apresentado a resposta.


Em Global Declarations do Custom Code 

//OS SHELL
void ShellAnswer(void);
//String Result
String Consol;
//OS SHELL ERROR
int resul;

Em Global Implementations do Custom Code

void ShellAnswer(void)
{
Declarations::Instances::Shell.Result.Send(Consol);
}

Em Inputs Exec do Custom Code

char Cmd[1024];
AValue.toCharArray(Cmd, AValue.length()+1);
Cmd[AValue.length()]=0; //Null
Consol = shellExec(Cmd, &resul);

Em Input SeeResult on Data  do Custom Code

ShellAnswer();

Em Formatted Text (CMD)

curl https://api.thingspeak.com/channels/548647/feeds.json?results=2

Abra o Visuino e monte o seguinte projeto 

Click no módulo SplitJSON  foi importado JSON que servidor THINGSPEAK enviará para posterior tratamento.


Você pode obter o JSON com seu Browser digitando
https://api.thingspeak.com/channels/CCCCCCCCC/fields/1.json?api_key=XXXXXXXXXXXXXX
&results=
1
Aqui é tratado o fiedl1



O exemplo faz uma análise da resposta HTTP e dispara o SplitJSON para extrair o field1, este é comparado se retorna "1"  e então acendendo o LED que aciona a saída digital 17 do Raspberry Pi Zero W.


Aqui é a porta a ser acessada pelo Remot3.it


COMPILANDO


TRANSFERINDO PROGRAMA (via WINSCP)


Executando o programa


No Remot3.it teremos sinalizado que o serviço TCP na porta 8085 está disponível




ATUALIZE field1 via BROWSER
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXX&field1=0
PARA APAGAR LED
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXX&field1=1
PARA ACENDER LED

Acessando Remotamente


Acessando via Cliente TCP


Montagem



Vídeo



Referências:


Dúvidas

tcpipchip@hotmail.com

Sobre a SMARTCORE

A SmartCore fornece módulos para comunicacão wireless, biometria, conectividade, rastreamento e automação.
Nosso portfólio inclui modem 2G/3G/4G/NB-IoT/Cat.M, satelital, módulos WiFi, Bluetooth, GNSS / GPS, Sigfox, LoRa, leitor de cartão, leitor QR code, mecanismo de impressão, mini-board PC, antena, pigtail, LCD, bateria, repetidor GPS e sensores.
Mais detalhes em www.smartcore.com.br

Raspbery Pi Zero sendo programado em VISUINO e controlando um LED via ThingSpeak - Chamada ao Sistema Operacional do CURL


BETA TEST

O objetivo deste BLOG é como programar o Raspberry Zero W com o VISUINO para que possa acessar a INTERNET SEM FIO e realizar uma conexão via requisição do protocolo HTTP ao servidor THINGSPEAK e a informação recebida (formato JSON) será tratada para extrair o field1 e então controlar o estado de um LED conectado no pino 17 do RASPERRY Pi ZERO W. 

Json


{"channel":{"id":548647,:"EFENTOSENSOR - TEMPERATURE",:"TESTS","latitude":"0.0",:"0.0",:"VALOR","created_at":"2018-07-28T00:23:18Z","updated_at":"2020-11-14T11:49:4B8r3B4p7yhRXuBWLqsQ546WR43cqQwrbXMDFnBi6vSJBeif8tPW85a7r7DM961Jvk4hdryZoByEp8GC8HzsqJpRN4FxGM9span>"last_entry_id":4B8r3B4p7yhRXuBWLqsQ546WR43cqQwrbXMDFnBi6vSJBeif8tPW85a7r7DM961Jvk4hdryZoByEp8GC8HzsqJpRN4FxGM9span>"feeds":[{"created_at":"2020-12-05T09:40:29Z","entry_id":818,:"28.090000000000003"},{"created_at":"2021-11-09T12:27:32Z","entry_id":819,:"1"}]}


Diferente do Blog anterior, será solicitada a chamada ao Sistema Operacional (SHELL) para fazer esta requisição, através do comando CURL (nativo).

Agora VISUINO + Chamada ao S.O permitirá explorar todos os recursos do Raspberry Pi Zero W através da chamada do SCRIPT SHELL.

Você pode usar vários Scripts pronto para o Raspberry!!!!


Raspberry Pi Zero W - Imagem 2020-02-13-raspbian-buster

PiDUINO

PiDuino é uma biblioteca C++ para placas Pi que permite o uso de E/S como GPIO, I2C, SPI, UART ... com uma API o mais próxima possível da linguagem Arduino.
A descrição dos cartões Pi utiliza um modelo "Objeto" armazenado em um banco de dados que permite adicionar novos modelos de placas facilmente.

Ao analisar o código fonte do PIDUINO (Arduino para Raspberry),  foi encontrada a função em C que faz a chamada ao Sistema Operacional.

/*
  Arduino.h - Main include file for the Arduino SDK
  Copyright (c) 2005-2013 Arduino Team.  All right reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

  Modified for RaspberryPi by Hristo Gochkov 2015
*/

#ifndef Arduino_h
#define Arduino_h

#include "bcm2835_registers.h"
#include <math.h>
#include <pthread.h>
#include "pgmspace.h"

#ifdef __cplusplus
extern "C"{
#endif

typedef void * PTHREAD;
#define PWM_RANGE     0xFF

void yield(void);

#define HIGH 0x1
#define LOW  0x0

#define INPUT   0x0
#define OUTPUT  0x1
#define ALT0    0x04
#define ALT1    0x05
#define ALT2    0x06
#define ALT3    0x07
#define ALT4    0x03
#define ALT5    0x02
#define INPUT_PULLUP    0x10
#define INPUT_PULLDOWN  0x20

#define PI 3.bc1qzk3kxhdxnzkpdgdn9ueg34y08smxgfv0hxvcu3
#define HALF_PI 1.5707963267948966192313216916398
#define TWO_PI 6.283185307179586476925286766559
#define DEG_TO_RAD 0.017453292519943295769236907684886
#define RAD_TO_DEG 57.295779513082320876798154814105
#define EULER 2.718281828459045235360287471352

#define SERIAL  0x0
#define DISPLAY 0x1

#define LSBFIRST 0
#define MSBFIRST 1

#define CHANGE 3
#define FALLING 1
#define RISING 2

// undefine stdlib's abs if encountered
#ifdef abs
#undef abs
#endif

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(x) ((x)>0?(x):-(x))
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
#define radians(deg) ((deg)*DEG_TO_RAD)
#define degrees(rad) ((rad)*RAD_TO_DEG)
#define sq(x) ((x)*(x))

#define interrupts()
#define noInterrupts()
#define cli()
#define sei()

#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))

// avr-libc defines _NOP() since 1.6.2
#ifndef _NOP
#define _NOP() do {} while (0)
#endif

#define bit(b) (1UL << (b))

#define micros() (unsigned long)(STCV)
#define millis() (unsigned long)(STCV / 1000)

typedef unsigned int word;
typedef uint8_t boolean;
typedef uint8_t byte;

//under millisecond delayMicroseconds halts the CPU
void delayMicroseconds(uint32_t m);
void delay(uint32_t m);
void sleepMicroseconds(uint32_t m);

void pinMode(uint8_t, uint8_t);
void digitalWrite(uint8_t, uint8_t);//47.5ns direct register write takes 23ns
int digitalRead(uint8_t);//110ns direct register read takes 74ns

//those return nothing and are here for compatibility
//ToDo: make them rewritable
int analogRead(uint8_t pin);
void analogReference(uint8_t mode);

//DIV = 19200000 / (FREQ * RANGE)
uint32_t analogWriteSetup(uint32_t freq, uint32_t range);//returns the frequency achieved
void analogWrite(uint8_t, uint16_t);//500ns direct register write takes 23ns rest is pin mode and channel enable

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val);
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder);

//Interrupt check is called every 200us or so
typedef void (*voidFuncPtr)(void);
void attachInterrupt(uint8_t, voidFuncPtr, int mode);
void detachInterrupt(uint8_t);

void setup(void);
void loop(void);

int init(void);
void uninit(void);

//Pi Specific
//I2C0 ID_SC/ID_SD
void ids_begin(void);
void ids_end(void);
void ids_set_freq(uint32_t frequency);
uint8_t ids_write(uint8_t address, uint8_t * buf, uint32_t len);
uint8_t ids_read(uint8_t address, uint8_t* buf, uint32_t len);

//Call this and the sketch will quit once the loop has returned
void request_sketch_terminate();

//Threads
typedef void *(*thread_fn)(void *);
void      thread_yield();
pthread_t thread_self();
pthread_t thread_create(thread_fn fn, void * arg);
int       thread_set_name(pthread_t t, const char *name);
int       thread_set_priority(const int pri);
int       thread_detach(pthread_t t);
int       thread_terminate(pthread_t t);
uint8_t   thread_running(pthread_t t);
uint8_t   thread_equals(pthread_t t);
void      thread_lock(int index);
void      thread_unlock(int index);
#define   yield() thread_yield()

//ToDo: move this to separate(private) header to be included only where necessary
void uart_check_fifos();

#ifdef __cplusplus
} // extern "C"
#endif

#ifdef __cplusplus
#include "WCharacter.h"
#include "WString.h"
#include "HardwareSerial.h"

uint16_t makeWord(uint16_t w);
uint16_t makeWord(byte h, byte l);

#define word(...) makeWord(__VA_ARGS__)

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);

// WMath prototypes
long random(long);
long random(long, long);
void randomSeed(unsigned long);
long map(long, long, long, long, long);

String shellExec(const char *cmd, int *result);
#endif

#include "Console.h"
#include "binary.h"
#include "pins_arduino.h"

#endif

A mesma será utilizada para fazer a chamada do Sistema Operacional e então acionar o comando CURL e assim fazer a chamada via HTTP ao servidor ThingSpeak.

Thingspeak é uma plataforma de análise IoT (Internet of Things) que permite agregar, visualizar e analisar streams de dados, de uma forma muito simples. Uma das grandes vantagens da plataforma Thingspeak é que nos permite visualizar os dados enviados pelos nossos dispositivos, em tempo real, mas também a possibilidade de analisar os mesmo recorrendo ao poderoso Matlab.

CURL

É um comando disponível na maioria dos sistemas baseado em Unix. Ele é usado como abreviação para “Client URL”. Comandos Curl são destinados para funcionar como uma forma de verificar a conectividade da URL, além de ser uma ótima ferramenta de transferência de dados. 

VISUINO



Visuino é o mais recente software inovador da Mitov Software. Um ambiente de programação visual que permite programar suas placas Arduino. ... Os componentes encontrados no software Visuino representam seus componentes de hardware e você pode criar e projetar facilmente seus programas usando o recurso de arrastar e soltar.

Instalação do VISUINO 8.0.0.91

Baixe em  https://www.visuino.com/ e instale

Criando Conta no ThingSpeak

Em Channel Settings crie Field: Field1


Em API keys anote as chaves para escrita e Leitura de dados noThingsSpeak


Tem-se então basicamente duas URLS, uma para escrita e outra para leitura dois Fields.
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXXX&field1=X
ESCRITA (via BROWSER)
https://api.thingspeak.com/channels/CCCCCCCCC/fields/1.json?api_key=XXXXXXXXXXXXXX
&results=
1 LEITURA (via U-BLOX NINA B03 + U-BLOX NINA W102 AIRLIFT)


Abrindo conexão com ThingSpeak via CURL (shell)


pi@raspberrypi:~ $ curl -s https://api.thingspeak.com/channels/548647/feeds.json?results=2

Custom Code para chamada ao Sistema Operacional


Foi criado um chamado Shell, no lado esquerdo é enviada a chamada (CMD dever ter o comando (curl) para chamada ao Sistema Operacional) e no lado direito é apresentado a resposta.


Em Global Declarations do Custom Code 

//OS SHELL
void ShellAnswer(void);
//String Result
String Consol;
//OS SHELL ERROR
int resul;

Em Global Implementations do Custom Code

void ShellAnswer(void)
{
Declarations::Instances::Shell.Result.Send(Consol);
}

Em Inputs Exec do Custom Code

char Cmd[1024];
AValue.toCharArray(Cmd, AValue.length()+1);
Cmd[AValue.length()]=0; //Null
Consol = shellExec(Cmd, &resul);

Em Input SeeResult on Data  do Custom Code

ShellAnswer();

Em Formatted Text (CMD)

curl https://api.thingspeak.com/channels/548647/feeds.json?results=2

Abra o Visuino e monte o seguinte projeto 


Click no módulo SplitJSON  foi importado JSON que servidor THINGSPEAK enviará para posterior tratamento.


Você pode obter o JSON com seu Browser digitando
https://api.thingspeak.com/channels/CCCCCCCCC/fields/1.json?api_key=XXXXXXXXXXXXXX
&results=
1
Aqui é tratado o fiedl1



O exemplo faz uma análise da resposta HTTP e dispara o SplitJSON para extrair o field1, este é comparado se retorna "1"  e então acendendo o LED que aciona a saída digital 17 do Raspberry Pi Zero W.

COMPILANDO


TRANSFERINDO PROGRAMA (via WINSCP)


Executando o programa


ATUALIZE field1 via BROWSER
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXX&field1=0
PARA APAGAR LED
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXX&field1=1
PARA ACENDER LED
Montagem



Vídeo


Referências:


Dúvidas

tcpipchip@hotmail.com

Sobre a SMARTCORE

A SmartCore fornece módulos para comunicacão wireless, biometria, conectividade, rastreamento e automação.
Nosso portfólio inclui modem 2G/3G/4G/NB-IoT/Cat.M, satelital, módulos WiFi, Bluetooth, GNSS / GPS, Sigfox, LoRa, leitor de cartão, leitor QR code, mecanismo de impressão, mini-board PC, antena, pigtail, LCD, bateria, repetidor GPS e sensores.
Mais detalhes em www.smartcore.com.br