Hello and thank you for your time,
I am having issues with sending data to my real-time Firebase database. When I do send the data, it constantly only returns a 10 value instead of my UID. This is my code
#include <WiFi.h>
#include <FirebaseESP32.h>
#include <SPI.h>
#include <MFRC522.h>
#define FIREBASE_HOST "https://matt-rfid-default-rtdb.asia-southeast1.firebasedatabase.app/" //Paste you Realtime database url here
#define FIREBASE_AUTH "AIzaSyBZ3dtXOSlsLBZ0PbytXflmJv2laqfqMD8" ///// <---- Paste your API key here
#define WIFI_SSID "Sharma Home"
#define WIFI_PASSWORD "0162229410p"
#define RST_PIN 4 // Configurable, see typical pin layout above
#define SS_PIN 5 // Configurable, see typical pin layout above
MFRC522 rfid(SS_PIN, RST_PIN);
FirebaseData firebaseData;
FirebaseJson json;
MFRC522::MIFARE_Key key;
void setup()
{
Serial.begin(115200);
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
Serial.println("Tap an RFID/NFC tag on the RFID-RC522 reader");
}
void loop()
{
//json.set("/one", Sdata);
if (rfid.PICC_IsNewCardPresent())
{ // new tag is available
if (rfid.PICC_ReadCardSerial())
{ // NUID has been readed
Serial.print("UID:");
for (int i = 0; i < rfid.uid.size; i++)
{
Firebase.updateNode(firebaseData,"/CARD ID NO:",json);
Serial.print(rfid.uid.uidByte[i], DEC);
//int sData = (rfid.uid.uidByte[i], DEC);
//json.set("/UID" + (rfid.uid.uidByte[i], DEC));
}
Serial.println();
rfid.PICC_HaltA(); // halt PICC
rfid.PCD_StopCrypto1(); // stop encryption on PCD
}
}
}
I want to receive the UID values in my database.
Related
I've been using the Thinger.io platform for some of my IoT projects (mostly ESP8266 modules) for quite a long time now. The way I implemented it is something similar to that:
#include <ThingerESP8266.h>
#include <ESP8266WIFI.h>
#define USERNAME "username"
#define DEVICE_ID "deviceid"
#define DEVICE_CREDENTIAL "devicecredential"
ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);
void connectToWifi() {
...
}
void setup() {
connectToWifi();
}
void loop() {
thing.handle();
}
and it just works. It is good to also mention that I've been using WiFi all the way.
Now I am trying to achieve the same by taking advantage of a controller called TTGO T-Call ESP32. It is GPRS enabled (using the TinyGsmClient.h) and I have inserted a SIM card inside of it which successfully connects to the internet. The issue is that I can not really establish a connection to the Thinger.io platform where my devices are hosted. This is what my code looks like (making a reference to this library example)
// Your GPRS credentials (leave empty, if not needed)
const char apn[] = ""; // APN (example: internet.vodafone.pt) use https://wiki.apnchanger.org
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password
// SIM card PIN (leave empty, if not defined)
const char simPIN[] = "";
// TTGO T-Call pins
#define MODEM_RST 5
#define MODEM_PWKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define I2C_SDA 21
#define I2C_SCL 22
// Set serial for debug console (to Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to SIM800 module)
#define SerialAT Serial1
// Configure TinyGSM library
#define TINY_GSM_MODEM_SIM800 // Modem is SIM800
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
// Define the serial console for debug prints, if needed
//#define DUMP_AT_COMMANDS
#include <Wire.h>
#include <TinyGsmClient.h>
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
// I2C for SIM800 (to keep it running when powered from battery)
TwoWire I2CPower = TwoWire(0);
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
#define uS_TO_S_FACTOR 1000000UL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 3600 /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */
#define IP5306_ADDR 0x75
#define IP5306_REG_SYS_CTL0 0x00
bool setPowerBoostKeepOn(int en){
I2CPower.beginTransmission(IP5306_ADDR);
I2CPower.write(IP5306_REG_SYS_CTL0);
if (en) {
I2CPower.write(0x37); // Set bit1: 1 enable 0 disable boost keep on
} else {
I2CPower.write(0x35); // 0x37 is default reg value
}
return I2CPower.endTransmission() == 0;
}
void connectToApn(){
SerialMon.println("Connecting to: internet.vivacom.bg ... ");
while(!modem.gprsConnect(apn, gprsUser, gprsPass))
delay(500);
SerialMon.println("Successfully connected to: internet.vivacom.bg");
}
// #include <ThingerCore32.h> => ArduinoJson.h: No such file or directory
// #include <ThingerESP8266.h> => ESP8266WiFi.h : No such file or directory
#define USERNAME ""
#define DEVICE_ID ""
#define DEVICE_CREDENTIAL ""
#include <ThingerESP32.h>
ThingerESP32 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);
//#include "arduino_secrets.h"
// Server details
const char server[] = "vsh.pp.ua";
const char resource[] = "/TinyGSM/logo.txt";
const int port = 80;
#include <ArduinoHttpClient.h>
HttpClient http(client, server, port);
void setup() {
// Set serial monitor debugging window baud rate to 115200
SerialMon.begin(115200);
// Start I2C communication
I2CPower.begin(I2C_SDA, I2C_SCL, 400000);
// Keep power when running from battery
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
// Configure the wake up source as timer wake up
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
// Connect to APN
connectToApn();
}
void loop() {
thing.handle();
SerialMon.println("In the loop ...");
delay(3000);
SerialMon.print(F("Performing HTTP GET request... "));
int err = http.get(resource);
if (err != 0) {
SerialMon.println(F("failed to connect"));
delay(10000);
return;
}
int status = http.responseStatusCode();
SerialMon.print(F("Response status code: "));
SerialMon.println(status);
if (!status) {
delay(10000);
return;
}
SerialMon.println(F("Response Headers:"));
while (http.headerAvailable()) {
String headerName = http.readHeaderName();
String headerValue = http.readHeaderValue();
SerialMon.println(" " + headerName + " : " + headerValue);
}
int length = http.contentLength();
if (length >= 0) {
SerialMon.print(F("Content length is: "));
SerialMon.println(length);
}
if (http.isResponseChunked()) {
SerialMon.println(F("The response is chunked"));
}
String body = http.responseBody();
SerialMon.println(F("Response:"));
SerialMon.println(body);
SerialMon.print(F("Body length is: "));
SerialMon.println(body.length());
// Put ESP32 into deep sleep mode (with timer wake up)
// esp_deep_sleep_start();
}
NOTE: The board I've picked from the Arduino IDE is called ESP32 Wrover Module
It would be better if you ask this question on the thinger community, the thinger.io https://community.thinger.io/ where the thinger devs or community will be listening.
I have some working code, see below, this works with SIM7000E, but it should work OK with SIM800 the code should work the same. I have noticed that you are not using the thinger library (ThingerTinyGSM.h) and this is probably why the device isn't connecting to thinger.
#define THINGER_SERIAL_DEBUG //This will provide debug messages of what thinger
code is trying to do
#define _DISABLE_TLS_ //TLS needs to be disabled if using ESP32 (not sure why, this is a known bug)
// Select your modem:
//#define TINY_GSM_MODEM_SIM800 //Note SimCom docs state that SIM7000e used same commands as SIM800
#define TINY_GSM_MODEM_SIM7000 //Note SimCom docs state that SIM7000e used same commands as SIM800
#define APN_NAME "..."
#define APN_USER "..."
#define APN_PSWD "..."
//Pins for connecting to SIM module using 2nd Serial connection
#define RXD1 16
#define TXD1 17
#include <TinyGsmClient.h>
#include <ThingerTinyGSM.h>
//Thinger credentials
#define USERNAME "...." //Thinger Account User Name
#define DEVICE_ID "...." //Thinger device IC
#define DEVICE_CREDENTIAL "...." //Thinger device credential (password)
ThingerTinyGSM thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL, Serial2);
/*******************************
**** SET-UP **** SET-UP ****
********************************/
void setup() {
// open serial for debugging
Serial.begin(115200);
Serial2.begin(115200, SERIAL_8N1, RXD1, TXD1);
delay(1000);
Serial.println(); Serial.println();
Serial.println("Starting Thinger GSM Test");
delay(1000);
// set APN, you can remove user and password from call if your apn does not require them
thing.setAPN(APN_NAME, APN_USER, APN_PSWD);
////// Thinger resource output example (i.e. reading a sensor value)
thing["Status"] >> [](pson & out) {
out["Timer(ms)"] = millis();
out["device"] = String(DEVICE_ID);
};
}
void loop() {
thing.handle();
}
This is the code which worked for me:
const char apn[] = ""; // APN (example: internet.vodafone.pt) use https://wiki.apnchanger.org
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password
// SIM card PIN (leave empty, if not defined)
const char simPIN[] = "";
// TTGO T-Call pins
#define MODEM_RST 5
#define MODEM_PWKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define I2C_SDA 21
#define I2C_SCL 22
// Set serial for debug console (to Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to SIM800 module)
#define SerialAT Serial1
// Configure TinyGSM library
#define TINY_GSM_MODEM_SIM800 // Modem is SIM800
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
#include <Wire.h>
#include <TinyGsmClient.h>
TinyGsm modem(SerialAT);
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
void connectToApn(){
SerialMon.println("Connecting to: internet.vivacom.bg ... ");
while(!modem.gprsConnect(apn, gprsUser, gprsPass))
delay(500);
SerialMon.println("Successfully connected to: internet.vivacom.bg");
}
#define USERNAME ""
#define DEVICE_ID ""
#define DEVICE_CREDENTIAL ""
#include <ThingerTinyGSM.h>
ThingerTinyGSM thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL, Serial1);
void setup() {
// Set serial monitor debugging window baud rate to 115200
SerialMon.begin(115200);
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
// Connect to APN
connectToApn();
}
void loop() {
thing.handle();
}
I am currently working in a project where I have to publish and possibly subscribe to MQTT topic over GSM network (I am using ESP8266 and Ai Thinker A6 GSM Module). So far I am able to publish message to the broker once using MQTT Example code from TinyGSM library,where they pass the GPRS client instance to Pubsub Client class, but when I add a code in loop to publish message continuously every n seconds. The message is published only once or twice and then freezes.
I doubt the mqttclient.loop() function in the void loop(). But, I am just wondering is there any other library which is completely tested, because the TinyGSM developer itself has mentioned this code is not tested in github.
The example code with mqtt publish in loop
// Select your modem:
#define TINY_GSM_MODEM_SIM800
// #define TINY_GSM_MODEM_SIM808
// #define TINY_GSM_MODEM_SIM868
// #define TINY_GSM_MODEM_SIM900
// #define TINY_GSM_MODEM_SIM7000
// #define TINY_GSM_MODEM_SIM5360
// #define TINY_GSM_MODEM_SIM7600
// #define TINY_GSM_MODEM_UBLOX
// #define TINY_GSM_MODEM_SARAR4
// #define TINY_GSM_MODEM_M95
// #define TINY_GSM_MODEM_BG96
// #define TINY_GSM_MODEM_A6
// #define TINY_GSM_MODEM_A7
// #define TINY_GSM_MODEM_M590
// #define TINY_GSM_MODEM_MC60
// #define TINY_GSM_MODEM_MC60E
// #define TINY_GSM_MODEM_ESP8266
// #define TINY_GSM_MODEM_XBEE
// #define TINY_GSM_MODEM_SEQUANS_MONARCH
// Set serial for debug console (to the Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to the module)
// Use Hardware Serial on Mega, Leonardo, Micro
#define SerialAT Serial1
// or Software Serial on Uno, Nano
//#include <SoftwareSerial.h>
//SoftwareSerial SerialAT(2, 3); // RX, TX
// See all AT commands, if wanted
// #define DUMP_AT_COMMANDS
// Define the serial console for debug prints, if needed
#define TINY_GSM_DEBUG SerialMon
// Range to attempt to autobaud
#define GSM_AUTOBAUD_MIN 9600
#define GSM_AUTOBAUD_MAX 115200
// Add a reception delay - may be needed for a fast processor at a slow baud rate
// #define TINY_GSM_YIELD() { delay(2); }
// Define how you're planning to connect to the internet
#define TINY_GSM_USE_GPRS true
#define TINY_GSM_USE_WIFI false
// set GSM PIN, if any
#define GSM_PIN ""
// Your GPRS credentials, if any
const char apn[] = "YourAPN";
const char gprsUser[] = "";
const char gprsPass[] = "";
// Your WiFi connection credentials, if applicable
const char wifiSSID[] = "YourSSID";
const char wifiPass[] = "YourWiFiPass";
// MQTT details
const char* broker = "broker.hivemq.com";
const char* topicLed = "GsmClientTest/led";
const char* topicInit = "GsmClientTest/init";
const char* topicLedStatus = "GsmClientTest/ledStatus";
#include <TinyGsmClient.h>
#include <PubSubClient.h>
// Just in case someone defined the wrong thing..
#if TINY_GSM_USE_GPRS && not defined TINY_GSM_MODEM_HAS_GPRS
#undef TINY_GSM_USE_GPRS
#undef TINY_GSM_USE_WIFI
#define TINY_GSM_USE_GPRS false
#define TINY_GSM_USE_WIFI true
#endif
#if TINY_GSM_USE_WIFI && not defined TINY_GSM_MODEM_HAS_WIFI
#undef TINY_GSM_USE_GPRS
#undef TINY_GSM_USE_WIFI
#define TINY_GSM_USE_GPRS true
#define TINY_GSM_USE_WIFI false
#endif
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
TinyGsmClient client(modem);
PubSubClient mqtt(client);
#define LED_PIN 13
int ledStatus = LOW;
uint32_t lastReconnectAttempt = 0;
void mqttCallback(char* topic, byte* payload, unsigned int len) {
SerialMon.print("Message arrived [");
SerialMon.print(topic);
SerialMon.print("]: ");
SerialMon.write(payload, len);
SerialMon.println();
// Only proceed if incoming message's topic matches
if (String(topic) == topicLed) {
ledStatus = !ledStatus;
digitalWrite(LED_PIN, ledStatus);
mqtt.publish(topicLedStatus, ledStatus ? "1" : "0");
}
}
boolean mqttConnect() {
SerialMon.print("Connecting to ");
SerialMon.print(broker);
// Connect to MQTT Broker
boolean status = mqtt.connect("GsmClientTest");
// Or, if you want to authenticate MQTT:
//boolean status = mqtt.connect("GsmClientName", "mqtt_user", "mqtt_pass");
if (status == false) {
SerialMon.println(" fail");
return false;
}
SerialMon.println(" success");
mqtt.publish(topicInit, "GsmClientTest started");
mqtt.subscribe(topicLed);
return mqtt.connected();
}
void setup() {
// Set console baud rate
SerialMon.begin(115200);
delay(10);
pinMode(LED_PIN, OUTPUT);
// !!!!!!!!!!!
// Set your reset, enable, power pins here
// !!!!!!!!!!!
SerialMon.println("Wait...");
// Set GSM module baud rate
// TinyGsmAutoBaud(SerialAT,GSM_AUTOBAUD_MIN,GSM_AUTOBAUD_MAX);
SerialAT.begin(9600);
delay(3000);
// Restart takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// modem.init();
String modemInfo = modem.getModemInfo();
SerialMon.print("Modem Info: ");
SerialMon.println(modemInfo);
#if TINY_GSM_USE_GPRS
// Unlock your SIM card with a PIN if needed
if ( GSM_PIN && modem.getSimStatus() != 3 ) {
modem.simUnlock(GSM_PIN);
}
#endif
#if TINY_GSM_USE_WIFI
// Wifi connection parameters must be set before waiting for the network
SerialMon.print(F("Setting SSID/password..."));
if (!modem.networkConnect(wifiSSID, wifiPass)) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" success");
#endif
#if TINY_GSM_USE_GPRS && defined TINY_GSM_MODEM_XBEE
// The XBee must run the gprsConnect function BEFORE waiting for network!
modem.gprsConnect(apn, gprsUser, gprsPass);
#endif
SerialMon.print("Waiting for network...");
if (!modem.waitForNetwork()) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" success");
if (modem.isNetworkConnected()) {
SerialMon.println("Network connected");
}
#if TINY_GSM_USE_GPRS
// GPRS connection parameters are usually set after network registration
SerialMon.print(F("Connecting to "));
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" success");
if (modem.isGprsConnected()) {
SerialMon.println("GPRS connected");
}
#endif
// MQTT Broker setup
mqtt.setServer(broker, 1883);
mqtt.setCallback(mqttCallback);
}
void loop() {
if (!mqtt.connected()) {
SerialMon.println("=== MQTT NOT CONNECTED ===");
// Reconnect every 10 seconds
uint32_t t = millis();
if (t - lastReconnectAttempt > 10000L) {
lastReconnectAttempt = t;
if (mqttConnect()) {
lastReconnectAttempt = 0;
}
}
delay(100);
return;
}
else
{
mqtt.publish("Topic/test","Hi");
delay(1000);
}
mqtt.loop();
}
I used aREST to access to my NODEMCU but it says "Attempting MQTT connection...failed, rc=-4 try again in 5 seconds" on serial monitor
My code:
// Control ESP8266 anywhere
// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include <aREST.h>
// Clients
WiFiClient espClient;
PubSubClient client(espClient);
// Create aREST instance
aREST rest = aREST(client);
// Unique ID to identify the device for cloud.arest.io
char* device_id = "aliziveh79";
// WiFi parameters
const char* ssid = "Samsung J7";
const char* password = "Movahed12341234";
// Functions
void callback(char* topic, byte* payload, unsigned int length);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Set callback
client.setCallback(callback);
// Give name and ID to device
rest.set_id(device_id);
rest.set_name("relay_anywhere");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Set output topic
char* out_topic = rest.get_topic();
}
void loop() {
// Connect to the cloud
rest.loop(client);
}
// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {
rest.handle_callback(client, topic, payload, length);
}
I used aREST to access to my NODEMCU but it says Attempting MQTT connection...failed, rc=-4 try again in 5 seconds" on serial monitor
Return code -4 is a timeout trying to connect to the broker
// Possible values for client.state()
#define MQTT_CONNECTION_TIMEOUT -4
#define MQTT_CONNECTION_LOST -3
#define MQTT_CONNECT_FAILED -2
#define MQTT_DISCONNECTED -1
#define MQTT_CONNECTED 0
#define MQTT_CONNECT_BAD_PROTOCOL 1
#define MQTT_CONNECT_BAD_CLIENT_ID 2
#define MQTT_CONNECT_UNAVAILABLE 3
#define MQTT_CONNECT_BAD_CREDENTIALS 4
#define MQTT_CONNECT_UNAUTHORIZED 5
This most likely means the address for your broker is wrong (but I don't see where you are specifying that in the code you have provided)
When you connect the client, you have to change the name of the Device:
if (client.connect("CHANGE_THIS_IT_HAS_TO_BE_DIFFERENT_FOR_EACH_DEVICE"))
I use the MAC Address to change it dynamically
I followed a basic example for the RFID module on an ARDUINO UNO REV3 and it works great. But when I try to connect it to the new ARDUINO UNO WiFi REV2 it won't work. The code compiles, but when I scan the NFC badge, nothing is being printed to the console. The NFC module communicates via SPI protocol. Is the SPI connection different on the new Arduino Uno WiFi REV2?
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
/* Set your new UID here! */
#define NEW_UID {0xDE, 0xAD, 0xBE, 0xEF}
MFRC522::MIFARE_Key key;
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Warning: this example overwrites the UID of your UID changeable card, use with care!"));
// Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
}
void loop() {
// Look for new cards, and select one if present
if ( ! mfrc522.PICC_IsNewCardPresent() || ! mfrc522.PICC_ReadCardSerial() ) {
delay(50);
return;
}
// Now a card is selected. The UID and SAK is in mfrc522.uid.
// Dump UID
Serial.print(F("Card UID:"));
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.println();
// Set new UID
byte newUid[] = NEW_UID;
if ( mfrc522.MIFARE_SetUid(newUid, (byte)4, true) ) {
Serial.println(F("Wrote new UID to card."));
}
// Halt PICC and re-select it so DumpToSerial doesn't get confused
mfrc522.PICC_HaltA();
if ( ! mfrc522.PICC_IsNewCardPresent() || ! mfrc522.PICC_ReadCardSerial() ) {
return;
}
// Dump the new memory contents
Serial.println(F("New UID and contents:"));
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
delay(2000);
}
I have a sketch working with an Arduino Uno and an Ethernet Shield - and it's working fine. Now I've gotten my hands on some Arduino Uno WiFi, and I want to port the sketch from ethernet to wifi - but I've run into a wall now. Most of the guide/FAQ/help I can find is for a WiFi Shield, and not a WiFi Arduino, so I'm stuck here.
Below is my (original Ethernet) code. I can post my somewhat modified Wifi code, but I can't even compile it without errors.
// Hartmann fugtighedsmåler v 0.1
// Lavet af Jan Andreasen
// Skriver til DB på FDKTO517
#include <Ethernet.h>
#include <SPI.h>
#include <DHT.h>
#define DHTPIN 2 // Siger sig selv
#define DHTTYPE DHT11 // Typen af sensor.
float h = 0;
float t = 0;
byte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02}; // Macadresse på kortet
IPAddress server(10,16,9,229); // Server adressen på SQL'en
EthernetClient client;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
Ethernet.begin(mac);
dht.begin();
}
void loop() {
readTempHum();
delay(300000); // Loop timer i millis - 5 minutter
}
void get_request(float t, float h) {
Serial.println("Connecting to Client...");
if (client.connect(server, 10080)) {
Serial.println("--> connection ok\n");
client.print("GET /test.php?");
// Placering af PHP script til upload til DB
client.print("t="); // Temp
client.print(t);
client.print("&h="); // Fugtighed
client.print(h);
client.println(" HTTP/1.1");
client.print( "Host: " );
client.println(server);
client.println("Connection: close");
client.println();
client.println();
client.stop();
Serial.println("--> finished transmission\n");
} else {
Serial.println("--> connection failed\n");
}
}
void readTempHum() {
h = dht.readHumidity();
t = dht.readTemperature();
{
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%\t");
Serial.print("Temperature:");
Serial.print(t);
Serial.println("*C");
get_request(t,h);
}
}
I've also posted this on the Arduino Forum. I'm sorry if you see my double-post, and I'll post the solution to my problem here as well.
New sketch:
#include <Wire.h>
#include <UnoWiFiDevEd.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
float h = 0;
float t = 0;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
const char* connector = "rest";
const char* server = "10.16.9.229";
const char* method = "GET";
const char* resource = "/test.php?t=";
Serial.begin(9600);
Ciao.begin();
dht.begin();
pinMode(2, INPUT);
delay(10000);
}
void loop() {
readTempHum();
// doRequest(connector, server, resource, method);
delay(300000);
}
void doRequest(const char* conn, const char* server, const char* command, const char* method, float t, float h){
CiaoData data = Ciao.write(conn, server, command, method);
}
void readTempHum() {
h = dht.readHumidity();
t = dht.readTemperature();
const char* connector = "rest";
const char* server = "10.16.9.229";
const char* method = "GET";
const char* resource = "/test.php?t=";
{
doRequest(connector, server, resource, method,t,h);
}
}
Now, I've ran into a new problem. The value from the sensor (t and h) are supposed to be output in the HTTP/GET command like this:
test.php?t=1&h=2
But I can't seem to make that work. If I try to define the resource as this
const char* resource = "/test.php?t="+t+"&h="+h;
I get an error (obviously), but if I try to declare it as a string, I the same error again.
Error:
HumidSQL3_Wifi_master:24: error: invalid operands of types 'const char [13]' and 'float' to binary 'operator+'
const char* resource = "/test.php?t="+t+"&h="+h;
Now, I hope that some of you could help me out a bit here :/
If it is the Arduino.org Arduino UNO WiFi Developer Edition, then use WiFi Link with UNO WiFi Serial1 library
Okay - so I made it work. I had to start from scratch, and with the help from Juraj (I'll accept your answer as well) it works now.
Below are the final sketch ("final", as the DHT11 sensor only were for testing purpose, as a proof-of-concept)
// Hartmann fugtighedsmåler v 0.2.2
// Lavet af Jan Andreasen
// Skriver til DB på FDKTO517
// WiFi udgave, testversion
#include <Wire.h>
#include <UnoWiFiDevEd.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
#define CONNECTOR "rest"
#define SERVER_ADDR "10.16.9.229"
float h = 0;
float t = 0;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Ciao.begin();
dht.begin();
pinMode(2, INPUT); // I'm not sure if this is required, just saw it now
delay(10000); // A 10 second delay from start to initialization
}
void loop() {
readTempHum();
delay(300000); // A 5 minute delay between measurements
}
void readTempHum() {
h = dht.readHumidity(); // Reads the humidity from sensor
t = dht.readTemperature(); // Reads the temperature from sensor
String uri = "/test.php?t="; // URL to the PHP-file
uri += t; // Insert the T-value
uri +="&h=";
uri += h; // Insert the H-value
CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, uri); // Make a basic HTTP request to the specified server using REST and the URL specified above
}
Maybe not the prettiest code you've seen, however, it works now.