ESP32: Add micro sd card reader on 2nd SPI bus - arduino

I am trying to create a music box for my son, but i am having some trouble getting the SD card to work.
The idea is that when we scan a RFID tag we should get the corresponding mp3 file from the SD card.
I am using:
a ESP32 DOIT DEVKIT V1
RFID reader is a RFID-RC522
Micro SD card reader has no brand or model number on it. It just says "Micro sd card adapter" on the back and has 6 pins: cs, sck, mosi, miso, vcc, gnd
My problem is that both the RFID reader and the Micro SD Card reader should use SPI.
With the following code the RFID Card is working well. I just have no idea on how to add the SD Card reader (i have tried using the same pins as the rfid reader and also the HSPI pins, but without success!)
Any help is much appreciated!
#include <SPI.h>
#include <MFRC522.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
#include "web_index.h"
// Constants
const char *ssid = "****";
const char *password = "****";
const int dns_port = 53;
const int http_port = 80;
const int ws_port = 1337;
// Globals
AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(1337);
char msg_buf[10];
// Tag reader variables
#define RFID_RC522_RST_PIN 27
#define RFID_RC522_SDA_PIN 5
MFRC522 mfrc522(RFID_RC522_SDA_PIN, RFID_RC522_RST_PIN);
bool rfid_tag_present_prev = false;
bool rfid_tag_present = false;
int _rfid_error_counter = 0;
bool _tag_found = false;
// Volume Variables
int VOLUME = 15;
int VOLUME_NORMAL_MAX = 30;
int VOLUME_LIMIT_MAX = 15;
int VOLUME_MAX = VOLUME_NORMAL_MAX;
int VOLUME_MIN = 0;
int VOLUME_CHANGE_AMOUNT = 1;
bool VOLUME_IS_LIMITED = false;
// Player variables
bool IS_PLAYING = false;
String TRACK_NAME = "-";
String ARTIST_NAME = "-";
// Button variables
const int BUTTON_VOL_DOWN_PIN = 34;
bool BUTTON_VOL_DOWN_STATE = HIGH;
bool BUTTON_VOL_DOWN_PREV_STATE = HIGH;
const int BUTTON_VOL_UP_PIN = 35;
bool BUTTON_VOL_UP_STATE = HIGH;
bool BUTTON_VOL_UP_PREV_STATE = HIGH;
const int BUTTON_STOP_PIN = 32;
bool BUTTON_STOP_STATE = HIGH;
bool BUTTON_STOP_PREV_STATE = HIGH;
const int BUTTON_NEXT_PIN = 33;
bool BUTTON_NEXT_STATE = HIGH;
bool BUTTON_NEXT_PREV_STATE = HIGH;
// Tag IDs
String TAG_TEST = "93 44 5C 92";
String TAG_BACH = "9C CD 69 0F";
/***********************************************************
Functions
*/
void volumeDecrease() {
if (VOLUME > VOLUME_MIN) {
VOLUME = VOLUME - VOLUME_CHANGE_AMOUNT;
broadcastUpdate();
}
}
void volumeIncrease() {
if (VOLUME < VOLUME_MAX) {
VOLUME = VOLUME + VOLUME_CHANGE_AMOUNT;
broadcastUpdate();
} else {
VOLUME = VOLUME_MAX;
broadcastUpdate();
}
}
void updateVolumeLimitState(bool state) {
VOLUME_IS_LIMITED = state;
broadcastUpdate();
}
void broadcastUpdate() {
DynamicJsonDocument doc(1024);
doc["volume"] = VOLUME;
doc["volume_min"] = VOLUME_MIN;
doc["volume_max"] = VOLUME_MAX;
doc["volume_is_limited"] = VOLUME_IS_LIMITED;
doc["is_playing"] = IS_PLAYING;
doc["track_name"] = TRACK_NAME;
doc["artist_name"] = ARTIST_NAME;
char json_string[1024];
serializeJson(doc, json_string);
webSocket.broadcastTXT(json_string);
}
void handleWsTextMessage(uint8_t client_num, uint8_t * payload) {
if ( strcmp((char *)payload, "getValues") == 0 ) {
broadcastUpdate();
} else if ( strcmp((char *)payload, "volume_down_button_click") == 0 ) {
volumeDecrease();
} else if ( strcmp((char *)payload, "volume_up_button_click") == 0 ) {
volumeIncrease();
} else if ( strcmp((char *)payload, "volume_limit_checkbox_on") == 0 ) {
updateVolumeLimitState(true);
} else if ( strcmp((char *)payload, "volume_limit_checkbox_off") == 0 ) {
updateVolumeLimitState(false);
} else { // Message not recognized
Serial.println("[%u] Message not recognized");
}
}
// Callback: receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num, WStype_t type, uint8_t * payload, size_t length) {
// Figure out the type of WebSocket event
switch (type) {
// Client has disconnected
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", client_num);
break;
// New client has connected
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(client_num);
Serial.printf("[%u] Connection from ", client_num);
Serial.println(ip.toString());
}
break;
// Handle text messages from client
case WStype_TEXT:
// Print out raw message
Serial.printf("[%u] Received text: %s\n", client_num, payload);
handleWsTextMessage(client_num, payload);
break;
// For everything else: do nothing
case WStype_BIN:
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
default:
break;
}
}
// Callback: send homepage
void onIndexRequest(AsyncWebServerRequest *request) {
const char* dataType = "text/html";
IPAddress remote_ip = request->client()->remoteIP();
Serial.println("[" + remote_ip.toString() +
"] HTTP GET request of " + request->url());
// request->send(SPIFFS, "/index.html", "text/html");
AsyncWebServerResponse *response = request->beginResponse_P(200, dataType, index_html_gz, index_html_gz_len);
response->addHeader("Content-Encoding", "gzip");
request->send(response);
}
// Callback: send 404 if requested file does not exist
void onPageNotFound(AsyncWebServerRequest *request) {
IPAddress remote_ip = request->client()->remoteIP();
Serial.println("[" + remote_ip.toString() +
"] HTTP GET request of " + request->url());
request->send(404, "text/plain", "Not found");
}
/***********************************************************
Main
*/
void handleButtons() {
// VOLUME DOWN BUTTON
bool buttonVolDownState = digitalRead(BUTTON_VOL_DOWN_PIN);
if (buttonVolDownState == LOW && BUTTON_VOL_DOWN_PREV_STATE == HIGH) {
Serial.println("button down pressed");
volumeDecrease();
BUTTON_VOL_DOWN_PREV_STATE = LOW;
} else if (buttonVolDownState == HIGH && BUTTON_VOL_DOWN_PREV_STATE == LOW) {
BUTTON_VOL_DOWN_PREV_STATE = HIGH;
}
// VOLUME UP BUTTON
bool buttonVolUpState = digitalRead(BUTTON_VOL_UP_PIN);
if (buttonVolUpState == LOW && BUTTON_VOL_UP_PREV_STATE == HIGH) {
Serial.println("button up pressed");
volumeIncrease();
BUTTON_VOL_UP_PREV_STATE = LOW;
} else if (buttonVolUpState == HIGH && BUTTON_VOL_UP_PREV_STATE == LOW) {
BUTTON_VOL_UP_PREV_STATE = HIGH;
}
// STOP BUTTON
bool buttonStopState = digitalRead(BUTTON_STOP_PIN);
if (buttonStopState == LOW && BUTTON_STOP_PREV_STATE == HIGH) {
Serial.println("button stop pressed");
volumeIncrease();
BUTTON_STOP_PREV_STATE = LOW;
} else if (buttonStopState == HIGH && BUTTON_STOP_PREV_STATE == LOW) {
BUTTON_STOP_PREV_STATE = HIGH;
}
// NEXT BUTTON
bool buttonNextState = digitalRead(BUTTON_NEXT_PIN);
if (buttonNextState == LOW && BUTTON_NEXT_PREV_STATE == HIGH) {
Serial.println("button next pressed");
volumeIncrease();
BUTTON_NEXT_PREV_STATE = LOW;
} else if (buttonNextState == HIGH && BUTTON_NEXT_PREV_STATE == LOW) {
BUTTON_NEXT_PREV_STATE = HIGH;
}
}
String getTagUid() {
String content = "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++) {
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
content.toUpperCase();
String tag_uid = content.substring(1);
Serial.println("Getting tag uid");
Serial.println(content.substring(1));
return content.substring(1);
}
void checkTagValidity(String tag_uid) {
if (tag_uid == TAG_TEST) {
Serial.println("BLUE TAG");
ARTIST_NAME = "Blue Tag";
TRACK_NAME = "Super Track name";
IS_PLAYING = true;
broadcastUpdate();
} else if (tag_uid == TAG_BACH) {
Serial.println("BACH");
} else {
Serial.println("UNKNOWN CARD: ");
Serial.print(tag_uid);
}
}
void setup() {
// Init buttons
pinMode(BUTTON_VOL_DOWN_PIN, INPUT_PULLUP);
pinMode(BUTTON_VOL_UP_PIN, INPUT_PULLUP);
pinMode(BUTTON_STOP_PIN, INPUT_PULLUP);
pinMode(BUTTON_NEXT_PIN, INPUT_PULLUP);
// Start Serial port
Serial.begin(115200);
// Init SPI bus (for the tag reader)
SPI.begin();
// Init the tag reader
mfrc522.PCD_Init();
// Start access point
WiFi.softAP(ssid, password);
// Print our IP address
Serial.println();
Serial.println("AP running");
Serial.print("My IP address: ");
Serial.println(WiFi.softAPIP());
// On HTTP request for root, provide index.html file
server.on("/", HTTP_GET, onIndexRequest);
// 404 page
server.onNotFound(onPageNotFound);
// Start web server
server.begin();
// Start WebSocket server and assign callback
webSocket.begin();
webSocket.onEvent(onWebSocketEvent);
}
void loop() {
// Check for button clicks
handleButtons();
// Look for and handle WebSocket data
webSocket.loop();
rfid_tag_present_prev = rfid_tag_present;
_rfid_error_counter += 1;
if (_rfid_error_counter > 2) {
_tag_found = false;
}
// Detect Tag without looking for collisions
byte bufferATQA[2];
byte bufferSize = sizeof(bufferATQA);
// Reset baud rates
mfrc522.PCD_WriteRegister(mfrc522.TxModeReg, 0x00);
mfrc522.PCD_WriteRegister(mfrc522.RxModeReg, 0x00);
// Reset ModWidthReg
mfrc522.PCD_WriteRegister(mfrc522.ModWidthReg, 0x26);
MFRC522::StatusCode result = mfrc522.PICC_RequestA(bufferATQA, &bufferSize);
if (result == mfrc522.STATUS_OK) {
if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
return;
}
_rfid_error_counter = 0;
_tag_found = true;
}
rfid_tag_present = _tag_found;
// rising edge
if (rfid_tag_present && !rfid_tag_present_prev) {
Serial.println("Tag found");
// Get tag uid
String tag_uid = getTagUid();
// Check if valid tag
checkTagValidity(tag_uid);
}
// falling edge
if (!rfid_tag_present && rfid_tag_present_prev) {
Serial.println("Tag gone");
ARTIST_NAME = "-";
TRACK_NAME = "-";
IS_PLAYING = false;
broadcastUpdate();
}
}

Thanks to the comments from #romkey and #RamyHx i got it to work using the same SPI pins.
My problem was that i was using the same pin for the CS of both devices. Once i change it to different CS pins for the rfid and sd card reader it started working.
For the RFID i have used the pin D2, and for the sd card reader i have used the pin D5.
For the rfid i have change #define RFID_RC522_SDA_PIN 5 into #define RFID_RC522_SDA_PIN 2.
For the sd card i have used the code here, which assumes we are using the default pins (with CS connected to pin D5).

Related

Arduino MEGA, LCD and SSR is frozen after 24 hours

I'm going to tell you my problem with arduino.
I am making an access rfdi system to enable a water pump, the procedure is as follows: I bring the rfid keyring closer to the reader, I make a sql query to the server and if it returns the data, I enable the pump and later register that user is served water.
Everything works fine for 18-24 hours, after that time the screen freezes and the arduino doesn't respond in any way or run the program. To get it to work again I have to restart it.
Maybe I thought it was a memory problem, but I don't know. On build I have Sketch (18%) and memory (22%).
I don't know where the problem is.
#include <U8glib.h>
#include <SPI.h>
#include <EthernetENC.h>
#include <Wiegand.h> //PROTOCOLO P/ RFDI
#include <ArduinoJson.h>
U8GLIB_ST7920_128X64_1X u8g(6, 5, 4 ,7); //LCD Enable, RW, RS, RESET
#define FALSE 0
#define TRUE 1
long int rawToken;
char c;
char pageAdd[64];
char user[64];
int totalCount = 0;
String ID = "";
String readString = "";
String clientegraba = "";
String terrenograba = "";
bool inicio = true;
bool errorbit = false;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// CONFIG IP ARDUINO
IPAddress ip(192,168,0,210);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);
// IP Y PUERTO SERVIDOR
IPAddress server(192,168,0,104);
char serverName[] = "192.168.0.104";
int serverPort = 80;
EthernetClient client;
WIEGAND wg;
void setup() {
Serial.begin(9600);
pinMode(34,OUTPUT); //OUT PUMP
digitalWrite(34,LOW);
welcome(); //PANTALLA BIENVENIDA
//GATE A
wg.D0PinA =2;
wg.D1PinA =3;
//GATE B
wg.D0PinB =18;
wg.D1PinB =19;
//GATE C
wg.D0PinC =20;
wg.D1PinC =21;
// Reader enable
wg.begin(TRUE, FALSE, FALSE); // wg.begin(GateA , GateB, GateC)
// disable SD SPI
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
// Start ethernet
Serial.println(F("Iniciando ethernet..."));
Ethernet.begin(mac, ip, gateway, gateway, subnet);
Serial.println(Ethernet.localIP());
delay(2000);
Serial.println(F("Listo"));
ingresellave();
}
void loop()
{
if(wg.available()){
errorbit = false;
espere(); //WAITING SCREEN
ID = String(wg.getCode()); //OBTIENE ID DE TARJETA
String data = "/test.php?cliente=" + ID; //CONCAT ID
sprintf(pageAdd,data.c_str(),totalCount);
Serial.println(pageAdd);
if(!getPage(server,serverPort,pageAdd)){
Serial.print(F("Falla "));
}else{
Serial.print(F("Paso "));
}
totalCount++;
Serial.println(totalCount,DEC);
}
if(ID != ""){
if(clientegraba != ""){
grabacarga(clientegraba,terrenograba);
}else{
if(errorbit == false){
noexiste();
delay(3000);
ID = "";
ingresellave();
}
}
}
delay(200);
}
byte getPage(IPAddress ipBuf,int thisPort, char *page)
{
int inChar;
char outBuf[128];
Serial.print(F("Conectando..."));
if(client.connect(ipBuf,thisPort) == 1){
Serial.println(F("Conectado"));
sprintf(outBuf,"GET %s HTTP/1.1",page);
client.println(outBuf);
sprintf(outBuf,"Host: %s",serverName);
client.println(outBuf);
client.println(F("Connection: close\r\n"));
}else{
error();
errorbit = true;
Serial.println(F("Error en servidor"));
return 0;
}
// connectLoop controls the hardware fail timeout
int connectLoop = 0;
boolean reader = false;
while(client.connected())
{
while(client.available())
{
String line = client.readStringUntil('\n');
if(reader){
StaticJsonBuffer<200> jsonBuffer;
JsonObject& datos = jsonBuffer.parseObject(line);
String apellido = datos["name"];
String cliente = datos["cliente"];
clientegraba = cliente;
long total = datos["total"];
long libres = datos["libres"];
String terreno = datos["terreno"];
terrenograba = terreno;
String costo = datos["costo"];
float price = costo.toFloat();
usuario(apellido,total,libres,price);
Serial.println("User: " + apellido);
Serial.println("Cliente: " + cliente);
Serial.println("Tarjeta: " + ID);
Serial.println("Terreno: " + terreno);
Serial.println("Costo: " + String(costo));
Serial.println("Total: " + String(total));
Serial.println("Libres: " + String(libres));
if(apellido != ""){
digitalWrite(34,HIGH); //PUMP START
delay(1000);
digitalWrite(34,LOW); //PUMP STOP
}
}
if(line == "\r") {
reader = true;
break;
}
// set connectLoop to zero if a packet arrives
connectLoop = 0;
}
connectLoop++;
// if more than 10000 milliseconds since the last packet
if(connectLoop > 10000)
{
// then close the connection from this end.
Serial.println();
Serial.println(F("Timeout"));
client.stop();
}
// this is a delay for the connectLoop timing
delay(1);
}
Serial.println();
Serial.println(F("Desconectando."));
// close client end
client.stop();
delay(100);
return 1;
}
void grabacarga(String cliente, String terreno){
String data = "/graba.php?cliente=" + cliente + "&tarjeta=" + ID + "&terreno='" + terreno + "'";
sprintf(pageAdd,data.c_str(),totalCount);
Serial.println(pageAdd);
if(!getPage(server,serverPort,pageAdd)) Serial.print(F("Falla "));
else Serial.print(F("Paso "));
totalCount++;
Serial.println(totalCount,DEC);
ID = "";
terrenograba = "";
clientegraba = "";
inicio = true;
delay(9000);
ingresellave();
}
void welcome() {
u8g.setRot180();
u8g.setFont(u8g_font_unifont);
u8g.firstPage();
do {
u8g.drawStr(18,22,"SISTEMA");
u8g.drawStr(15,50,"ACCESO RFID");
} while( u8g.nextPage() );
}
void ingresellave() {
u8g.setFont(u8g_font_unifont);
u8g.firstPage();
do {
u8g.drawStr(0,10,"COLOQUE EL BIDON");
u8g.drawStr(2,35,"Y LUEGO INGRESE");
u8g.drawStr(25,60,"UNA LLAVE");
} while( u8g.nextPage() );
}
void error() {
u8g.setFont(u8g_font_unifont);
u8g.firstPage();
do {
u8g.drawStr(40,10,"ERROR");
u8g.drawStr(33,35,"INTENTE");
u8g.drawStr(22,60,"NUEVAMENTE");
} while( u8g.nextPage() );
}
void espere() {
u8g.setFont(u8g_font_unifont);
u8g.firstPage();
do {
u8g.drawStr(25,35,"ESPERE...");
} while( u8g.nextPage() );
}
void usuario(String user, long total, long libres, float costo) {
u8g.firstPage();
do {
u8g.setFont(u8g_font_6x10);
u8g.drawStr(0,10,user.c_str());
String carga = "Carga:" + String(total) + "/" + String(libres);
u8g.setFont(u8g_font_unifont);
u8g.drawStr(15,33,carga.c_str());
if(total > libres){
long precio = total - libres;
float costototal = precio * costo;
Serial.println(costototal);
String valor = "Costo:$" + String(costototal);
u8g.drawStr(0,60,valor.c_str());
}
} while( u8g.nextPage() );
}
void noexiste(){
u8g.setFont(u8g_font_unifont);
u8g.firstPage();
do {
u8g.drawStr(34,22,"USUARIO");
u8g.drawStr(12,50,"NO REGISTRADO");
} while( u8g.nextPage() );
}
The system power is from a 12V 4.5A source and the Arduino Mega along with the screen(LCD12864A) are powered from the 5V pin through an external LM2596 regulator.
The screen data pins are connected to pins 4,5,6 and 7, the rfid reader to pins 2 and 3 and the water pump output is pin 34 which has a 2222a pnp transistor connected with a 1K base resistor, emitter to ground and collector to an SSR-24DA solid state relay.
Thank you.
After reading your comment mentioning wiegand malfunction, and the fact that it only malfunctioned after several hours of running well, I would try and see if it's overheating somehow, or try and reduce EMI by using EMI filter on the power supply and shielding the circuit board with aluminium box or the like.
Water pump can cause high EMI and voltage spike in the mains upon turning on or off.

Sending data over ESP_NOW

I'm a total noob and just starting out with PlatformIO and Arduino/ESP32. I also want to say thanks in advance to any help I can get.
Plan:
I have 2 ESP32's talking over ESP_NOW, I just can't verify the data being sent in order to progress with my project. Basically, I have a Nextion display that sends specific info to an ESP32 (tested and working) and that ESP32 is then to send that information via ESP_NOW to the other ESP32 which will translate it into serial data to send to an Arduino Due and perform some tasks.
Problem:
The issue I have is that when I test, I see the data I think I am transmitting, but when I try to Serial.print said info, I get "0 0 0 0". I'm not sure that I am sending OR receiving the data properly. All I know is that when I press the button on the Nextion, I get a response on the ESP32 that is not connected.
Code:
#include <Arduino.h>
#include <esp_now.h>
#include <WiFi.h>
// Example to receive data with a start marker and length byte
// For ease of testing this uses upper-case characters A and B
// for the request and response types
// and Z for the start marker
// this version saves all the bytes after the start marker
// if the TYPE byte is wrong it aborts
const byte numBytes = 32;
byte receivedBytes[numBytes];
const byte typeBytePosition = 6; // Position after the start byte
const byte requestType = 0x65;
const byte requestLength = 7;
boolean newData = false;
int LED = 21;
// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
// Define variables to store Nextion readings to be sent
byte NexEventID;
byte NexPageID;
byte NexObjectID;
byte NexStatusID;
// Define variables to store incoming readings// Define variables to store incoming readings
byte incomingEventID;
byte incomingPageID;
byte incomingObjectID;
byte incomingStatusID;
// Variable to store if sending data was successful
String success;
typedef struct struct_message
{
byte EventID;
byte PageID;
byte ObjectID;
byte StatusID;
} struct_message;
// Create a struct_message called NextionInfo to hold Nextion settings
struct_message NextionInfo;
// Create a struct_message called IncomingInfo to hold incoming info
struct_message IncomingInfo;
// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
if (status == 0)
{
success = "Delivery Success :)";
}
else
{
success = "Delivery Fail :(";
}
}
// Callback when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len)
{
struct_message *IncomingInfo = (struct_message *)incomingData;
Serial.println(WiFi.macAddress());
// memcpy(&IncomingInfo, incomingData, sizeof(IncomingInfo));
Serial.print("Bytes received: ");
Serial.println(len);
// incomingEventID = IncomingInfo.EventID;
Serial.print((byte)IncomingInfo->EventID, HEX);
Serial.print(' ');
// incomingPageID = IncomingInfo.PageID;
Serial.print((byte)IncomingInfo->PageID, HEX);
Serial.print(' ');
// incomingObjectID = IncomingInfo.ObjectID;
Serial.print((byte)IncomingInfo->ObjectID, HEX);
Serial.print(' ');
// incomingStatusID = IncomingInfo.StatusID;
Serial.println((byte)IncomingInfo->StatusID, HEX);
}
void emptyBuffer()
{
for (byte n = 0; n < numBytes; n++)
{
receivedBytes[n] = 0;
}
}
void recvBytesWithStartMarker()
{
static boolean recvInProgress = false;
static int ndx = -1;
static byte numBytesReceived = 0;
static byte mesgLen = 0;
const byte startMarker = 0x65;
byte rc;
while (Serial2.available() > 0 && newData == false)
{
rc = Serial2.read();
receivedBytes[numBytesReceived] = rc;
numBytesReceived++;
if (numBytesReceived > 33)
{
Serial.println("Error Rx : RESET !!");
Serial.println();
emptyBuffer();
numBytesReceived = 0;
newData = false;
}
if (recvInProgress == true)
{
if (numBytesReceived == typeBytePosition)
{
ndx = 0; // enable saving of data (anticipate good data)
if (rc == requestType)
{
mesgLen = requestLength;
}
else
{
recvInProgress = false; // abort - invalid request type
ndx = -1;
}
}
if (ndx >= 0)
{
ndx++;
}
if (numBytesReceived >= (mesgLen + typeBytePosition))
{ // got the whole message
recvInProgress = false;
newData = true;
}
}
else if (rc == startMarker)
{
emptyBuffer();
recvInProgress = true;
numBytesReceived = 0;
ndx = -1; // prevent counting valid bytes for the moment
}
}
}
// void getNexInfo()
// {
// NexEventID = receivedBytes[0];
// NexPageID = receivedBytes[1];
// NexObjectID = receivedBytes[2];
// NexStatusID = receivedBytes[3];
// // Serial.print(NexEventID&&NexPageID&&NexObjectID&&NexStatusID);
// }
void showNewData()
{
if (newData == true)
{
Serial.println(WiFi.macAddress());
Serial.print(requestType, HEX);
Serial.print(' ');
for (byte n = 0; n < typeBytePosition; n++) // n < numBytes
{
if (n == 0)
{
NexEventID = receivedBytes[n];
}
else if (n == 1)
{
NexPageID = receivedBytes[n];
}
else if (n == 2)
{
NexObjectID = receivedBytes[n];
}
else if (n == 3)
{
NexStatusID = receivedBytes[n];
}
Serial.print(receivedBytes[n], HEX);
Serial.print(' ');
}
//Serial.print(getNexInfo(),HEX);
Serial.println();
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&NextionInfo, sizeof(NextionInfo));
if (result == ESP_OK)
{
Serial.println("Sent with success");
}
else
{
Serial.println("Error sending the data");
}
newData = false;
}
}
void sendNewData()
{
// Set values to send
NextionInfo.EventID = NexEventID;
NextionInfo.PageID = NexPageID;
NextionInfo.ObjectID = NexObjectID;
NextionInfo.StatusID = NexStatusID;
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&NextionInfo, sizeof(NextionInfo));
if (result == ESP_OK)
{
Serial.println("Sent with success");
}
else
{
Serial.println("Error sending the data");
}
}
void setup()
{
pinMode(LED, OUTPUT);
Serial.begin(250000);
Serial2.begin(115200);
while (!Serial)
{
;
}
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK)
{
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK)
{
Serial.println("Failed to add peer");
return;
}
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
//Setup has completed
Serial.println("<ESP32 is ready>");
}
void loop()
{
recvBytesWithStartMarker();
showNewData();
}
Most of this has come from various tutorials across the web including YouTube and RandomNerdTutorials. I am by no means a master programmer, but I am trying to learn.
Here are the results I get from the serial monitors:
ESP32 1:
�<ESP32 is ready>
AC:67:B2:36:AA:A8
65 1 2 1 FF FF FF
Sent with success
Last Packet Send Status: Delivery Success
ESP32 2:
AC:67:B2:35:19:D8
Bytes received: 4
0 0 0 0
Note that I am only sending 4 bytes of info (65 1 2 1), so it seems to match up (I'm not sending FF FF FF)...
Thanks again for any help!!
I was able to resolve my issue. Below is the code that displayed the same information that was sent from the host and received by the slave ESP32.
#include <Arduino.h>
#include <esp_now.h>
#include <WiFi.h>
// Example to receive data with a start marker and length byte
// For ease of testing this uses upper-case characters A and B
// for the request and response types
// and Z for the start marker
// this version saves all the bytes after the start marker
// if the TYPE byte is wrong it aborts
const byte numBytes = 32;
byte receivedBytes[numBytes];
const byte typeBytePosition = 6; // Position after the start byte
const byte requestType = 0x65;
const byte requestLength = 7;
boolean newData = false;
int LED = 2;
// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
// Variable to store if sending data was successful
String success;
struct __attribute__((packed)) dataPacket
{
byte EventID;
byte PageID;
byte ObjectID;
byte StatusID;
} packet, *packetPtr;
const dataPacket onLoc1R = {0x65, 0x01, 0x01, 0x01};
const dataPacket offLoc1R = {0x065, 0x01, 0x01, 0x00};
const dataPacket onLoc1L = {0x65, 0x01, 0x02, 0x01};
const dataPacket offLoc1L = {0x65, 0x01, 0x02, 0x00};
// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
void emptyBuffer()
{
for (byte n = 0; n < numBytes; n++)
{
receivedBytes[n] = 0;
}
}
void recvBytesWithStartMarker()
{
static boolean recvInProgress = false;
static int ndx = -1;
static byte numBytesReceived = 0;
static byte mesgLen = 0;
const byte startMarker = 0x65;
byte rc;
while (Serial2.available() > 0 && newData == false)
{
rc = Serial2.read();
receivedBytes[numBytesReceived] = rc;
numBytesReceived++;
if (numBytesReceived > 33)
{
Serial.println("Error Rx : RESET !!");
Serial.println();
emptyBuffer();
numBytesReceived = 0;
newData = false;
}
if (recvInProgress == true)
{
if (numBytesReceived == typeBytePosition)
{
ndx = 0; // enable saving of data (anticipate good data)
if (rc == requestType)
{
mesgLen = requestLength;
}
else
{
recvInProgress = false; // abort - invalid request type
ndx = -1;
}
}
if (ndx >= 0)
{
ndx++;
}
if (numBytesReceived >= (mesgLen + typeBytePosition))
{ // got the whole message
recvInProgress = false;
newData = true;
}
}
else if (rc == startMarker)
{
emptyBuffer();
recvInProgress = true;
numBytesReceived = 0;
ndx = -1; // prevent counting valid bytes for the moment
}
}
}
void showNewData()
{
if (newData == true)
{
Serial.println(WiFi.macAddress());
Serial.print(requestType, HEX);
packet.EventID = requestType;
Serial.print(' ');
for (byte n = 0; n < typeBytePosition; n++) // n < numBytes
{
if (n == 0)
{
packet.PageID = receivedBytes[n];
}
else if (n == 1)
{
packet.ObjectID = receivedBytes[n];
}
else if (n == 2)
{
packet.StatusID = receivedBytes[n];
}
Serial.print(receivedBytes[n], HEX);
Serial.print(' ');
}
Serial.println();
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &packet, sizeof(packet));
if (result == ESP_OK)
{
Serial.println("Sent with success");
}
else
{
Serial.println("Error sending the data");
}
newData = false;
}
}
// Callback when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *data, int len)
{
Serial.println(WiFi.macAddress());
memcpy(&packet, data, sizeof(packet));
Serial.printf("%x %x %x %x\n",(byte) packet.EventID,(byte) packet.PageID,(byte) packet.ObjectID,(byte) packet.StatusID);
Serial.println();
}
void sendNewData()
{
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &packet, sizeof(packet));
if (result == ESP_OK)
{
Serial.println("Sent with success");
}
else
{
Serial.println("Error sending the data");
}
}
void setup()
{
pinMode(LED, OUTPUT);
Serial.begin(250000);
Serial2.begin(115200);
while (!Serial)
{
;
}
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK)
{
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK)
{
Serial.println("Failed to add peer");
return;
}
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
//Setup has completed
Serial.println("<ESP32 is ready>");
}
void loop()
{
recvBytesWithStartMarker();
showNewData();
}

Arduino TTL jpeg Serial Camera and esp8266 wifi Wi-Fi module

I'm writing a code to take pictures if the distance is more than a certain distance after measuring the distance.
And send the distance data to Thingspeak, Store the photos on the SD card.
However, the program keeps stopping in the middle.
Serial moniter capture
Distance measurement and Thingspeak server data transfer / camera shooting were developed separately.
The two source codes worked normally independently.
But when the two codes are combined, there is an error.
Parts for Use : Arduino Uno, esp8266 wifi module, TTL Serial JPEG Camera with NTSC Video, 2Y0A21 Infrared Distance Sensor, Micro SD card adapter
#include <SoftwareSerial.h>
#include <stdlib.h>
#include <Adafruit_VC0706.h>
#include <SPI.h>
#include <SD.h>
#define DEBUG true
#define chipSelect 10
const int distancePin = 0;
String apiKey = "39R00EYW0BTKK5JJ";
SoftwareSerial esp8266(2, 3); //TX/RX
#if ARDUINO >= 100
SoftwareSerial cameraconnection = SoftwareSerial(4, 5); //TX/RX
#else
NewSoftSerial cameraconnection = NewSoftSerial(4, 5);
#endif
Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);
int defaultDistance = 0;
int temp = 0;
void ThingspeakSendData(String alarmData);
void Snapshots();
void setup() {
#if !defined(SOFTWARE_SPI)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
if (chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
#else
if (chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
#endif
#endif
Serial.begin(9600);
Serial.println("VC0706 Camera snapshot test");//the program keeps stopping in the middle.
if (cam.begin()) {
Serial.println("Camera Found:");
}
else {
Serial.println("No camera found?");
return;
}
char *reply = cam.getVersion();
if (reply == 0) {
Serial.print("Failed to get version");
}
else {
Serial.println("-----------------");
Serial.print(reply);
Serial.println("-----------------");
}
cam.setImageSize(VC0706_640x480);
uint8_t imgsize = cam.getImageSize();
Serial.print("Image size: ");
if (imgsize == VC0706_640x480) Serial.println("640x480");
if (imgsize == VC0706_320x240) Serial.println("320x240");
if (imgsize == VC0706_160x120) Serial.println("160x120");
esp8266.begin(9600);
sendData("AT+RST\r\n", 2000, DEBUG); //reset module
sendData("AT+CWMODE=1\r\n", 1000, DEBUG); //dual mode로 설정
sendData("AT+CWJAP=\"0sangsiljangnim\",\"123456788\"\r\n", 5000, DEBUG);
// 2Y0A21
analogReference(DEFAULT);
pinMode(distancePin, INPUT);
// distancePin 2Y0A21
int raw = analogRead(distancePin);
int volt = map(raw, 0, 1023, 0, 5000);
int distance = (21.61 / (volt - 0.1696)) * 1000;
defaultDistance = distance;
Serial.println("Default : " + defaultDistance);
}
void loop() {
// distancePin 2Y0A21
int raw = analogRead(distancePin);
int volt = map(raw, 0, 1023, 0, 5000);
int distance = (21.61 / (volt - 0.1696)) * 1000;
Serial.println(distance);
if (distance < defaultDistance)
{
String alarmData = "1";
esp8266.listen();
ThingspeakSendData(alarmData);
cameraconnection.listen();
Snapshots();
}
else if (distance == defaultDistance)
{
String alarmData = "0";
esp8266.listen();
ThingspeakSendData(alarmData);
}
delay(3000);
}
void ThingspeakSendData(String alarmData) {
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "184.106.153.149";
cmd += "\",80";
esp8266.println(cmd);
if (esp8266.find("Error")) {
Serial.println("AT+CIPSTART error");
return;
}
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr += "&field1=";
getStr += String(alarmData);
getStr += "\r\n\r\n";
// Send Data
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
esp8266.println(cmd);
if (esp8266.find(">")) {
esp8266.print(getStr);
}
else {
esp8266.println("AT+CIPCLOSE");
// alert uesp8266
Serial.println("AT+CIPCLOSE");
}
}
String sendData(String command, const int timeout, boolean debug) {
String response = "";
esp8266.print(command);
long int time = millis();
while ((time + timeout) > millis()) {
while (esp8266.available()) {
char c = esp8266.read();
response += c;
}
}
if (debug) {
Serial.print(response);
}
return response;
}
void Snapshots() {
Serial.println("Snap in 3 secs...");
delay(3000);
if (!cam.takePicture())
Serial.println("Failed to snap!");
else
Serial.println("Picture taken!");
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
return;
}
char filename[13];
strcpy(filename, "IMAGE00.JPG");
for (int i = 0; i < 100; i++) {
filename[5] = '0' + i / 10;
filename[6] = '0' + i % 10;
if (!SD.exists(filename)) {
break;
}
}
File imgFile = SD.open(filename, FILE_WRITE);
uint16_t jpglen = cam.frameLength();
Serial.print("Storing ");
Serial.print(jpglen, DEC);
Serial.print(" byte image.");
int32_t time = millis();
pinMode(8, OUTPUT);
byte wCount = 0;
while (jpglen > 0) {
uint8_t *buffer;
uint8_t bytesToRead = min(32, jpglen);
buffer = cam.readPicture(bytesToRead);
imgFile.write(buffer, bytesToRead);
if (++wCount >= 64) {
Serial.print('.');
wCount = 0;
}
jpglen -= bytesToRead;
}
imgFile.close();
time = millis() - time;
Serial.println("done!");
Serial.print(time); Serial.println(" ms elapsed");
}

Arduino: If/Else issues

Situation: I have a webpage that has two buttons on it. One sends to the PubNub channel a JSON string of {"lightRight":"1"} and one sends {"lightRight":"0"}, regardless of what I do in the Arduino Sketch I cannot make it into the "on" portion of the void light function.
I know from the serial output of the arduino that I am receiving communication from the web page. If I flip my boolean values to off then I am able to get the "LED HIGH" output but then no longer can I get the "led low".
The code I am trying to adapt can be found here.
https://gist.github.com/ianjennings/ada8fb1a91a486a0c73e
It is very possible I have hacked out to much code from the examples that is why I am including it, but running the stock code I cannot seem to get this to work.
I am not a developer, so I am very sorry if I do not call things as their proper terms. I will learn from correction.
#include <PubNub.h>
#include <SPI.h>
#include <EthernetV2_0.h>
#include <string.h>
#include <Servo.h>
byte mac[] = { MAC was here };
byte gateway[] = { Gate was here };
byte subnet[] = { Sub was here };
IPAddress ip(IP was here);
char pubkey[] = "Key was here";
char subkey[] = "Key was here";
char channel[] = "Channel was here";
int lightRight = 5;
int lightRoom = 6;
int lightGarage = 7;
int i;
EthernetClient *client;
#define W5200_CS 3
#define SDCARD_CS 4
void setup()
{
pinMode(SDCARD_CS,OUTPUT);
digitalWrite(SDCARD_CS,HIGH);
Serial.begin(9600);
Serial.println("Serial set up");
while (!Ethernet.begin(mac)) {
Serial.println("Ethernet setup error");
blink(1000, 999999);
delay(1000);
}
Serial.println("Ethernet set up");
PubNub.begin(pubkey, subkey);
Serial.println("PubNub set up");
pinMode(lightRight, OUTPUT);
pinMode(lightRoom, OUTPUT);
pinMode(lightGarage, OUTPUT);
// blink(100, 5);
reset();
}
//void flash(int ledPin)
//{
// for (int i = 0; i < 3; i++) {
// Serial.println("flash");
// digitalWrite(ledPin, HIGH);
// delay(100);
// digitalWrite(ledPin, LOW);
// delay(100);
// }
//}
void loop()
{
Ethernet.maintain();
PubSubClient *client;
Serial.println("waiting for a message (subscribe)");
client = PubNub.subscribe(channel);
if (!client) {
Serial.println("subscription error");
return;
}
String messages[10];
boolean inside_command = false;
int num_commands = 0;
String message = "";
char c;
while (client->wait_for_data()) {
c = client->read();
if(inside_command && c != '"') {
messages[num_commands] += c;
}
if(c == '"') {
if(inside_command) {
num_commands = num_commands + 1;
inside_command = false;
} else {
inside_command = true;
}
}
message += c;
}
client->stop();
for (i = 0; i < num_commands; i++){
int colonIndex = messages[i].indexOf(':');
String subject = messages[i].substring(0, colonIndex);
String valueString = messages[i].substring(colonIndex + 1, messages[i].length());
boolean value = false;
if(valueString == "1") {
value = true;
}
if(subject == "lightRight") {
light(lightRight, value);
}
if(subject == "lightRoom") {
light(lightRoom, value);
}
if(subject == "lightGarage") {
light(lightGarage, value);
}
if(subject == "blink") {
blink(100, valueString.toInt());
}
Serial.println(subject);
Serial.println(value);
}
Serial.print(message);
Serial.println();
delay(2000);
}
void light(int ledPin, boolean on) {
if(on) {
digitalWrite(ledPin, HIGH);
Serial.println("LED HIGH");
} else {
digitalWrite(ledPin, LOW);
Serial.println("led low");
}
}
void reset() {
Serial.println("Void reset");
light(lightRight, false);
light(lightRoom, false);
light(lightGarage, false);
}
void on() {
Serial.println("Void on");
light(lightRight, true);
light(lightRoom, true);
light(lightGarage, true);
}
void off() {
Serial.println("Void off");
light(lightRight, false);
light(lightRoom, false);
light(lightGarage, false);
}
void blink(int delayn, int count) {
for (int j=0; j <= count; j++){
on();
delay(delayn);
off();
delay(delayn);
}
}
That example expects the PubNub publish to be "lightRight:1" and not {"lightRight": "1"}.

if equals not matched but should be. Aduino IDE Serial

I'm trying to get a raspberry pi communicating with an arduino over serial, hardware all is setup and there are some comms ok.
Problem I have is the arguments passed are not matched with a if, else if expression but really should be going off what is returned.
SerialCommand library handles what commands trigger what functions. We're only interested in sayHello() for this example. RaspberryPi sends "HELLO HELLO", which should receive "YES HELLO" but I always get "NO HELLO" suggesting no match on the arg HELLO. Obviously what argument was received is echoed back regardless and I receive back what should have matched, HELLO so I'm stumped at this stage, any suggestions?
EDIT: THanks to Thanushan Balakrishnan comment in his answer below, replacing
if(arg == "HELLO")
with the below fixes the problem.
if(strcmp("HELLO", arg) == 0)
_
// Demo Code for SerialCommand Library
// Steven Cogswell
// May 2011
// temp & Humidity
#include <DHT22.h>
#define DHT22_PIN 12
// Setup a DHT22 instance
DHT22 myDHT22(DHT22_PIN);
// tank water level
int sensorValue = 0;
int constrainedValue = 0;
int tankLevel = 0;
#define TANK_SENSOR 0
#define TANK_EMPTY 0
#define TANK_FULL 1023
/*RelayBrd */
//Pin connected to latch pin (ST_CP) of 74HC595
const int latchPin = 4;
//Pin connected to clock pin (SH_CP) of 74HC595
const int clockPin = 3;
////Pin connected to Data in (DS) of 74HC595
const int dataPin = 2;
boolean thisState = LOW;
#include <SerialCommand.h>
#define arduinoLED 13 // Arduino LED on board
SerialCommand sCmd; // The demo SerialCommand object
void setup() {
pinMode(arduinoLED, OUTPUT); // Configure the onboard LED for output
digitalWrite(arduinoLED, LOW); // default to LED off
//mySerial.begin(9600);
//mySerial.println("Ready");
Serial.begin(115200);
// Setup callbacks for SerialCommand commands
sCmd.addCommand("ON", LED_on); // Turns LED on
sCmd.addCommand("OFF", LED_off); // Turns LED off
sCmd.addCommand("getenv", getEnv);
sCmd.addCommand("relaybrd", relayBrd);
sCmd.addCommand("gettanklevel", getTankLevel);
sCmd.addCommand("setlouver", setLouver);
sCmd.addCommand("HELLO", sayHello); // Echos the string argument back
sCmd.addCommand("P", processCommand); // Converts two arguments to integers and echos them back
sCmd.setDefaultHandler(unrecognized); // Handler for command that isn't matched (says "What?")
Serial.println("Ready");
}
void loop() {
sCmd.readSerial(); // We don't do much, just process serial commands
// if (mySerial.available())
// Serial.write(mySerial.read());
// if (Serial.available())
// mySerial.write(Serial.read());
}
void relayBrd(){
char *arg;
char *arg1;
arg = sCmd.next();
arg1 = sCmd.next();
if (arg != NULL) {
//int num = atol(arg);
if (arg1 != NULL) {
int state = atol(arg1);
if (arg == "fan") {
//do something when var equals 1
registerWrite(1, state);
}else if(arg == "water"){
//do something when var equals 2
registerWrite(2, state);
}else if(arg == "mister"){
//do something when var equals 2
registerWrite(3, state);
}else if(arg == "heater"){
//do something when var equals 2
registerWrite(4, state);
}else{
// if nothing else matches, do the default
Serial.print("ERR got:");Serial.print(arg);Serial.println(":");
}
}else{
Serial.println("ERR Relay state missing 1/0");
}
}else{
Serial.println("ERR Relay argument missing fan/water/heater/mister");
}
}
// This method sends bits to the shift register:
void registerWrite(int whichPin, int whichState) {
Serial.print("Relay ");Serial.print(whichPin);Serial.print(" set to ");Serial.println(whichState);
// the bits you want to send
byte bitsToSend = 0;
// turn off the output so the pins don't light up
// while you're shifting bits:
digitalWrite(latchPin, LOW);
// turn on the next highest bit in bitsToSend:
bitWrite(bitsToSend, whichPin, whichState);
// shift the bits out:
shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);
// turn on the output so the LEDs can light up:
digitalWrite(latchPin, HIGH);
}
void getEnv(){
Serial.println("26 degC");
DHT22_ERROR_t errorCode;
Serial.print("Requesting data...");
errorCode = myDHT22.readData();
switch(errorCode)
{
case DHT_ERROR_NONE:
Serial.print("Got Data ");
Serial.print(myDHT22.getTemperatureC());
Serial.print("C ");
Serial.print(myDHT22.getHumidity());
Serial.println("%");
break;
default:
Serial.print("ERR DHT22 ");
Serial.println(errorCode);
}
}
void getTankLevel(){
Serial.println("78% water level");
sensorValue = analogRead( TANK_SENSOR );
constrainedValue = constrain( sensorValue, TANK_EMPTY, TANK_FULL );
tankLevel = map( constrainedValue, TANK_EMPTY, TANK_FULL, 0, 100 );
}
void setLouver() {
char *arg;
arg = sCmd.next();
if (arg != NULL) {
if(arg == "OPEN"){
Serial.println("Louver OPEN");
}else if(arg == "CLOSE"){
Serial.println("Louver CLOSED");
}else{
Serial.print(arg);Serial.println(" not known");
}
}else{
Serial.println("Louver command missing OPEN/CLOSE");
}
}
void LED_on() {
Serial.println("LED on");
digitalWrite(arduinoLED, HIGH);
}
void LED_off() {
Serial.println("LED off");
digitalWrite(arduinoLED, LOW);
}
void sayHello() {
char *arg;
arg = sCmd.next(); // Get the next argument from the SerialCommand object buffer
if (arg != NULL) { // As long as it existed, take it
if (arg == "HELLO") { // As long as it existed, take it
Serial.print("YES ");
Serial.println(arg);
}else{
Serial.print("NO ");
Serial.println(arg);
}
}
else {
Serial.println("Hello Pi");
}
}
void processCommand() {
int aNumber;
char *arg;
Serial.println("We're in processCommand");
arg = sCmd.next();
if (arg != NULL) {
aNumber = atoi(arg); // Converts a char string to an integer
Serial.print("First argument was: ");
Serial.println(aNumber);
}
else {
Serial.println("No arguments");
}
arg = sCmd.next();
if (arg != NULL) {
aNumber = atol(arg);
Serial.print("Second argument was: ");
Serial.println(aNumber);
}
else {
Serial.println("No second argument");
}
}
// This gets set as the default handler, and gets called when no other command matches.
void unrecognized(const char *command) {
Serial.println("What?");
}
In the following function arg is a pointer. So arg has the address of the memory which holds "HELLO". so you should check *arg == "HELLO"
void sayHello()
{
char *arg;
arg = sCmd.next(); // Get the next argument from the SerialCommand object buffer
if (arg != NULL) { // As long as it existed, take it
if (strcmp("HELLO\n", arg) == 0) { <-------------------------- HERE
Serial.print("YES ");
Serial.println(arg);
}else{
Serial.print("NO ");
Serial.println(arg);
}
}
else {
Serial.println("Hello Pi");
}
}

Resources