text:
How to send JSON on a http POST request using an ESP8266?
I'm working on a project aimed on sending alerts via SMS. I signed up for a SMS service that works via HTTP requests (REST standard). I need, then, to send data as JSON, so that their server processes the data and sends the SMS message to a list of recipients.
I am working with an ESP8266 board. I have tried some code, but I couldn't do the JSON part properly, given I have little knowledge on HTTP requests and HTTP libraries for Arduino. I managed to test things using python code (with which I am much more familiar).
In short, I have this piece of code in python that works quite perfectly:
payload = {'sender': '558499999999','content': 'Just a message', 'groupName': 'Recipients_list'}
request = requests.post('https://cheap.sms.sending.guys/sendcontactmessage',
                         data=json.dumps(payload),
                         headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'})

I tried to write something that does the same thing on a ESP8266, but it is not working and I can't figure the correct way to do it. The code I tried was the following:
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "my_ssid";
const char* password = "my_password";

void setup() {
  Serial.begin(115200);

  //TESTING JSON CREATION
  Serial.println("Starting JSON");
  StaticJsonBuffer<69> jsonBuffer;
  char json[] = "{\"sender\":\"558499999999\",\"content\":\"Just a message\",\"groupName\":\"Recipients_list\"}";
  JsonObject& root = jsonBuffer.parseObject(json);
  if(!root.success()) {
    Serial.println("parseObject() failed");
  } else {
    Serial.println("JSON OK");
  }

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("Connecting... ");
  }

  //TESTING POST
  //headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'}
  String sms_service_URL = "https://cheap.sms.sending.guys/sendcontactmessage";

  Serial.println("TESTING POST");
  //Declare an object of class HTTPClient
  HTTPClient http;

  if (WiFi.status() == WL_CONNECTED) {
    //Specify request destination
    http.begin(sms_service_URL);
    http.addHeader("Content-Type", "application/json");
    http.addHeader("auth-key", "My_authentication_key");

    String data;
    root.printTo(data);
    //Send the request
    int httpCode = http.POST(data);

    //Check the returning code
    if (httpCode > 0) {
      //Get the request response payload
      String payload = http.getString();
      //Print the response payload
      Serial.println(payload);
    }
    //Close connection
    http.end();
    Serial.println(httpCode);
  }
}

void loop() {

}

I am aware that the arduino code is pretty lame. I was just in a trial-failure process, lol.
I'd appreciate any suggestions

What is the problem? What output do you get? Also, why do you first create a JSON string, then parse that string into an JSON object tree, and then convert it back into a string (which should be identical to the first string)? You can just skip those last two steps.

I'm not sure if I have understood your requirements right, but generally JSON is just text and so the actual transmission should ve trivial. It's up to the devices at either end how to handle this data


text:
Unable to upload code to the Arduino Nano
I tried to to upload a hex file I generated for the Arduino Nano using avrdude but I keep getting the error:
avrdude: stk500_2_ReceiveMessage(): timeout

First the arduino board stops doing whatever it is programmed to do, in this case powering a vibration motor .
Then this error keeps showing up in delays of around 10 seconds.
That error is then followed by
avrdude: ser_recv(): read error: The I/O operation has been aborted because of either a thread exit or an application re
quest.

which appears to be caused by me pulling out the USB cable after waiting a while.
Thanks

I suggest you disconnect the motor while you are uploading. The power it is using, or the electrical noise it is generating, may intefere with the uploading process.

thanks for your help, I was just able to upload the hex using Xloader software.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
File download from SD card hangs up my ESP-12E
I'm using ESP8266 Arduino for compiling and uploading my code to NodeMCU 1.0 (ESP-12E Module).
Flash Size: 4M (3M SPIFFS)
CPU frequency: 80 MHz
Upload Speed: 115200
I'm using portable arduino-1.6.9-windows extracted in my D: drive. I'm using the latest ESP8266 Arduino image brought by git command.
I've written this basic code to download 'datalog.txt' file (stored in the root of my SD card).
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

const char *ssid = "tiny-esp";
const char *password = "password";

ESP8266WebServer server(80);

String home = "
Hello! from ESP8266!
"
                "
<button>Download</button>";

void handleRoot() {
    server.send(200, "text/html", home);
}

void handleDownload() {

    File dataFile = SD.open("datalog.txt");
    int fsizeDisk = dataFile.size();
    Serial.print("fsizeDisk: ");
    Serial.println(fsizeDisk);

    size_t fsizeSent = server.streamFile(dataFile,"text/plain");

    Serial.print("fsizeSent: ");
    Serial.println(fsizeSent);

    dataFile.close();
}

void setup() {
    delay(500);
    Serial.begin(115200);
    Serial.println();

    WiFi.softAP(ssid, password);

    IPAddress apip = WiFi.softAPIP();
    Serial.print("Please visit: \n");
    Serial.println(apip);

    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
        Serial.println("\nCard failed, or not present");
        // don't do anything more:
        return;
    }
    Serial.println("\nCard Initialized.");

    server.on("/", handleRoot);
    server.on("/down", handleDownload);
    server.begin();
    Serial.println("HTTP server started");
}

void loop() {
    server.handleClient();
}

But, when I press the 'Download' button, the ESP hangs, dumps some errors and then restarts as displayed below (from my Serial Monitor):
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600

Panic D:\arduino-1.6.9-windows\arduino-1.6.9\hardware\esp8266com\esp8266\cores\esp8266\core_esp8266_main.cpp:98 __yield

ctx: sys
sp: 3ffffc80 end: 3fffffb0 offset: 01b0

>>>stack>>>
3ffffe30:  3ffefdf4 000003b9 000003b9 4010020c
3ffffe40:  00000000 3ffe9645 00000001 4020815d
3ffffe50:  3ffefdf4 00000481 3fff0d50 402077e5
3ffffe60:  3fff337c 00000b68 00000000 40207823
3ffffe70:  3fff3a74 3fff1480 3fff3a74 3fff1474
3ffffe80:  3fff337c 00000b68 3fff307c 40202a57
3ffffe90:  3fff3a74 00000b68 3fff2cfc 40202c07
3ffffea0:  00000000 3ffe9704 3fff337c 3fff1474
3ffffeb0:  3fff337c 3fff147c 3fff2cfc 40202d34
3ffffec0:  3ffeead0 0883f900 3fff1478 40202d54
3ffffed0:  3fff337c 3fff147c 3fff1478 4022670d
3ffffee0:  00000000 0104a8c0 00000010 00000000
3ffffef0:  00000000 00000010 3ffefe40 40221001
3fffff00:  40210000 00000000 0000007d 3fff151c
3fffff10:  3ffebae4 3fff1520 3fff3434 40224b39
3fffff20:  3fff1370 3fff1fac 3fff1fac 4021547e
3fffff30:  40215972 3ffed310 3ffebabc 3fff1fac
3fffff40:  3ffebad6 00000000 3fff3434 40223f35
3fffff50:  0204a8c0 3ffee318 02a93dee 00000000
3fffff60:  40104b62 02a93dee 3ffeead0 60000600
3fffff70:  4022d230 3ffeeaa8 3ffeead0 0884220c
3fffff80:  4022d256 3fffdab0 00000000 3fff2004
3fffff90:  3fffdc90 00000000 3fff3434 4022ce8b
3fffffa0:  40000f49 3fffdab0 3fffdab0 40000f49
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v00000000
~ld

Please visit:
192.168.4.1

Card Initialized.
HTTP server started

I tried updating the code by writing custom "server.streamFile()" function and adding
"Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";

to the header to allow downloading the txt file as an attachment.
The modified code is [Only handleDownload() function has been changed]:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

const char *ssid = "tiny-esp";
const char *password = "password";

ESP8266WebServer server(80);

String home = "
Hello! from ESP8266!
"
                "
<button>Download</button>";

void handleRoot() {
    server.send(200, "text/html", home);
}

void handleDownload() {

    int32_t time = millis();
    File dataFile = SD.open("datalog.txt");
    int fsizeDisk = dataFile.size();
    Serial.print("fsizeDisk: "); Serial.println(fsizeDisk);

    String WebString = "";
    WebString += "HTTP/1.1 200 OK\r\n";
    WebString += "Content-Type: text/plain\r\n";
    WebString += "Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";
    WebString += "Content-Length: " + String(fsizeDisk) + "\r\n";
    WebString += "\r\n";
    server.sendContent(WebString);

    char buf[1024];
    int siz = dataFile.size();
    while(siz > 0) {
        size_t len = std::min((int)(sizeof(buf) - 1), siz);
        dataFile.read((uint8_t *)buf, len);
        server.client().write((const char*)buf, len);
        siz -= len;
    }
    Serial.print(siz);
    Serial.println(" Bytes left!");

    dataFile.close();
    time = millis() - time;
    Serial.print(time); Serial.println(" ms elapsed");
}

void setup() {
    delay(500);
    Serial.begin(115200);
    Serial.println();

    WiFi.softAP(ssid, password);

    IPAddress apip = WiFi.softAPIP();
    Serial.print("Please visit: \n");
    Serial.println(apip);

    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
        Serial.println("\nCard failed, or not present");
        // don't do anything more:
        return;
    }
    Serial.println("\nCard Initialized.");

    server.on("/", handleRoot);
    server.on("/down", handleDownload);
    server.begin();
    Serial.println("HTTP server started");
}

void loop() {
    server.handleClient();
}

Now, when I press the Download button, a popup opens up in browser displaying "datalog.txt" has started downloading. But after about 20-30 seconds it says "Download failed". The esp freezes after printing the 'fsizeDisk'.
Meanwhile, the serial monitor reads:
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600

I don't understand what am I doing wrong. Please help!
EDIT: I added delay(2) and a Serial.println(cnt++) inside while(siz > 0) in handleDownload() for debugging:
int cnt=1;
delay(10);
while(siz > 0) {
    delay(2);
    Serial.println(cnt++);
    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    dataFile.read((uint8_t *)buf, len);
    server.client().write((const char*)buf, len);
    siz -= len;
}

What happens now is, I get
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600
1
2
3
4
5
6
7
8

The loop may hang up at any count(e.g. 10, 15, 17, 23, etc). Also, in my browser, it reads as 28% downloaded (for cnt=8) or so. So, file starts downloading but hangs up midway. I've tried increasing the delay upto 10 ms, but there has been no progress.

Try running blink on you hardware for a few minutes to illuminate hardware/IDE issues.

Ultimately this may be something you need to pursue with the authors of the ESP8266 port.  Perhaps you can try downloading a file without saving it anywhere (just throw away the data) or generate dummy data in a file and saving that.  You could also try using a small test file of known contents.  And try a different SD card.  How are you powering this?  The card might consume more current when being written.

I've already posted this question in esp8266 forum. There has been no replies yet. I'm powering this (NodeMCU) using USB2.0 from my laptop. I don't think SD card is an issue here. I'm not writing anything on the card, just reading it. I'll try using a file of small size (~2kB). I'll also try downloading a file without saving it anywhere.

try to add a yield() command in to your wihle-loop.
With yield() the ESP hast time to do his background jobs.

I tried adding delay(2) in the while-loop. Now the download starts, but it does not finish. I've tried delay upto 10 ms, but there has been no improvement. I'll try adding yield() instead. In the meanwhile, please see the EDIT.

authors: Игорь Мурзин

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to save a hex file into Arduino Flash to send it via Serial?
I have a text file with hex values formatted in the following style:
A0 3F 55 01 00 C7 55 01 00 C7 AA 29 71 11 00 0B
00 C7 AA 29 71 1F AA 29 71 11 55 01 A0 3F 55 DC
...

How can I save this data into my Arduino's Flash (to save RAM)? What libraries are needed? Is there any tool that can automatically create code for this purpose?
After I save this data into the Arduino's Flash, I want to send the data via Serial. I have to send it as binary.
A solution without saving it into the Flash would be also OK.
I am using an Arduino Due.

Flash program memory or flash EEPROM?

Flash program memory.

Use objcopy to turn it into a .o file, fabricate an appropriate .h file containing the symbols in the .o file, and then compile against the .h and link against the .o.

Replace the spaces with ,, prepend 0x to the start of each pair, so you get 0xA0, 0x3F, 0x55, ..., then wrap it in const byte myData[] PROGMEM = { ... your data ... }; - Personally I would write a small script to do it in Perl or PHP (I loathe Python with a passion).

If I understand your question correctly, you need to integrate this data into a .ino script.  Probably as a byte array. Then the script can read the array and Serial.write its content.
You could write a small tool in Python or else on your computer, that takes the text file and converts it into a .h header. Include that into your .ino script. Or use your favorite text editor to format the data into C++ code, and copy/paste that into your script.


text:
The fastest way to read out a digital pin state in an Arduino Due
What is the fastest way to read a digital pin status in an Arduino Due? Is it possible to achieve speed in the Nanosecond area?
With which type of code I can achieve this?
Edit: This question is not a duplicate please see my comment.

Yes, write to or read from the correct GPIO / PORT registers directly. Best case this needs only a few CPU cycles to read, i.e. a few nanoseconds. The processing time after that unknown, dependent on what you want to do with the read out data. Duplicate of http://arduino.stackexchange.com/questions/9117/sam3x8e-arduino-due-pin-io-registers. Also read http://forum.arduino.cc/index.php?topic=260731.0 .

Possible duplicate of SAM3X8E (Arduino Due) Pin IO registers

No it is not a duplicate. There you will find the answer how to set a digital pin as an output, but NOT how to set it as in input and read its pin state. Or atleast it is not explained detailed enough.
Also you will not find the appropiate answer to the question "the fastest" but only sadly an alternative to the digitalWrite.
You will not find any type of code example to set a pin as an input and to read from it, which actually for beginners like me would be very vital, if you would not forget that espiacially the "unnormal" register commands are very cryptic for a beginner.

ns? no. us? yeah.

The OneWire library uses it: https://github.com/PaulStoffregen/OneWire/blob/master/OneWire.h

@Jot : Where exactly? Could you please post as snippet?

@WilliamRoy all the defines and the directRead and directMode and so on functions are fast direct port writing. The OneWire.cpp show how a bitmask is stored and the DIRECT... defines are used.

@WilliamRoy Please see the GPIO library for a portable high speed Arduino library. https://github.com/mikaelpatel/Arduino-GPIO

If the pin is declared as input, let's say pin 13:
uint32_t pin_status;
pin_status = PIOB->PIO_PDSR & PIO_PDSR_P27;

If the pin is declared as output, let's say pin 13:
uint32_t pin_status;
pin_status = PIOB->PIO_ODSR & PIO_ODSR_P27;

Read the In out data register would be the fastest.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to use variables and functions across multiple .ino files
I have 2 .ino files (2 tabs) for one Arduino project/sketch: MySketch_File1.ino and MySketch_File2.ino.
I declared in MySketch_File2 variables and functions which I want to use in MySketch_File1, but I get this error massage:

error: 'a' was not declared in this scope

//MySketch_File1.ino
void setup(){
Serial.begin(9600);
Serial.println(String(a));
}

void loop(){

}

Second file:
//MySketch_File2.ino
int a;

How can I declare variables and functions one time in one .ino file and use it across multiple .ino files?

Do you mean multiple .INO files within the same sketch, or each in a completely separate sketch?

Within the same sketch, see edit.

It still raise the question - WHY? (why you want two sketch files and why share variables between them) as maybe you are trying to emulate something, which is already present and in much better and more usable form.

When you compile multiple files in the Arduno IDE the files first get concatenated together.
It happens in alphabetical order, except the main INO file (the one named the same as the folder it's in) is placed first.
In C the order in which things appear in the file matters. Basically you have to make sure that things (like variables, functions, etc) are defined before they are used.
This gets more complex when you have a hidden thing like file concatenation messing things up.
The Arduino IDE tries to hide some of it from you too by making function prototypes, so it doesn't matter what order you define functions in - however that "helpfulness" means you don't learn about the proper structure of a C program.
So what can you do? Well, simply make sure that all your global variables are defined in the main file, unless you know they are only going to be used within the file they are defined in.

What happens if you try to do what a C programmer should do? I mean, in one of the source (e.g. .ino) files you define the variable int a;, then in the other you declare it again with extern int a;. Will this work if 1) the variable is defined in the main ino and 2) if it is defined somewhere else but is declared in the main? I do not have the IDE installed here to test it myself ;)

Not sure. It may complain about multiple definitions of the same symbol, but may not. I'll test it.

It compiles, so yes you can do that, but why exactly would you, when you are then effectively defining it in both files anyway? Just define it in the first. If you want to make something portable between sketches then make it a library.

I think that the extern should be "ignored" (in fact you usually use the extern in the header file which is then included also in the c file defining it)

Yes, I agree that the global variables should be put in the first file so that everyone can access it. Or make a class... This was just the most classical solution (C/C++ compilers do not append source files)

It is simplest to put only one .ino file in a directory with the filename. Why does an `.ino` file have to be in a folder of the same name?
Option 1 (cleanest option): Create a user library.
Option 2  (workaround): Relative paths for #include aren't supported but you can use a symlink to make it appear that there is the same header file in every directory:
sketch1/
  sketch1.ino
  mylib.h
sketch2/
  sketch2.ino
  mylib.h (this is a symlink to sketch1/mylib.h)

Option 3: Avoid Arduino IDE entirely and build using avr-gcc. Example: http://thinkingonthinking.com/an-arduino-sketch-from-scratch/ and Will a .ino Arduino Sketch compile directly on GCC-AVR? This is much more complicated, but supports bigger projects using Makefiles.

In Arduino the sketch.ino is the main (and only) program, which runs on the processor.
If you upload another sketch to HW, then the previous one is overwritten and does not longer exist on the HW. So there is no way, they can share variables, as they never are run at the same time.
(You can store some values to EEPROM or to external devices, but it is other thing).
What you probabely want to do is use the second file as a library, which is collection of variables and functions, that more then one program can use. Anyway what is used is the text of the library, not the values assigned to variables in one sketch.ino - so other sketch.ino using the same library would have the functions and variables of the same name accessible, but as it is compiled to othe program, the values assigned in one sketch would not be visible in other sketch.
Can you specify, why you want to use variables and functions accross multiple .ino files?
If it is just to not have type it again and again and fix found bugs in each aned every copy separately, then you are looking for libraries.
If you want to share also values (like read and compute value in one .ino then upload another .ino and use the result) you are looking for persistent storages (EEPROM on the chip, SD card via some reader or something like that.
If you want have more Arduinos running at the same time and sharing some values, you are looking for networks, like I2C, Serial communication, Ethernet and such.
If you want run mor programs on one arduino at the same time, you are looking for multitasking where each program is interrupted repeatedly and other one is continued, fast enought to user not notice, or for creatinig more functions and call them from loop() one after one to eg. read sensors, then light LEDs then run motors. State automats can make your way here easier.

Now that the OP clarified the question, this is not the correct answer. He has two "tabs" open, meaning he has two source files for the same program

Ok, this shifted it somewhere else, but still I think it may be relevant to his intent - why he wants to separate the two files - using secondary files to be merged together by some IDE hack while he wants emulate how library do function is not the best approach, if he can use libraries as well

Of course.. Even if I usually tend to split (bigger) programs in smaller chunks (for instance, one file for the main loop, one for one of the peripherals, one for the interface, ...)

Yes, I think, that if I cannot see all relevant code on one (max two) screens, then something is probably wrong. The question is, what is wrong - and so the answers differs. If there are repeated parts, the answer is probably function. If there are lot of functions for one periferial/protocol, the answer is library for this. If the problem is just complicated, so if have a lot of code and functions, there is folding each function and then folding each group of folded functions. So my usual program includes lot of libraries and all functions are folded and main loop/ifs too.

And anything longer then few lines means better editor than Arduino IDE. (I use VIM for example.)

Arduino ide has terrible project mgmt capabilities. So two solutions.

Switch to a real ide.
Use an extern atteibute.

You can make this easier by naming only the main sketch file '.ino', and naming all other code files as '.cpp'. The compiler has to know about 'a' before you use it, so declare 'a' in the .ino file as `extern int a;' before its first use, to tell it what 'a' is. Not having that is the reason for the error message.


text:
What is the opposite of this data operation?
If I store in an array a double-value in this format, in which format I should be able to read the same double out?
double myDouble = 12.123456;
byte myArray[] = {0x00, 0x00, 0x00, 0x00};

myArray[0] = (myDouble >> 0);
myArray[1] = (myDouble >> 8);
myArray[2] = (myDouble >> 16);
myArray[3] = (myDouble >> 24);

Shifting a double? You don't really want to do that.

Please show the declarations of myArray and myDouble to show their exact type.

I edited the question.

You are better off making a union, that will be compiler independent, and won't give you the (possibly) odd results that trying to shift a double would give.
Example:
  union
    {
    byte myArray [4];
    double myDouble;
    } foo;

   foo.myArray [0] = Serial.read ();
   foo.myArray [1] = Serial.read ();
   foo.myArray [2] = Serial.read ();
   foo.myArray [3] = Serial.read ();

   double f = foo.myDouble;

Even then be cautious that whatever is sending you this double in 4 bytes is using the same encoding for doubles that the Arduino does. For one thing, double and float are the same on the 8-bit Arduinos (they are only 4 bytes).

in the simplest form (compiler dependent however), a pointer will do.

Would you mind developing your answer further, so that we can clearly see how it really answers the OP question?


text:
Is it possible to extend the reach of a PN532 NFC/RFID shield?
I am working off an Arduino Uno with an AdaFruit PN532 NFC/RFID shield. The goal is to have a shoe box, with a false bottom. Under that false bottom would be my prototype, which I hope will be able to detect any MIFARE tag that is in the box, above the false bottom.
The range obviously for these devices is practically touching, but I was was wondering if there is anyway to extend the reach of the NFC/RFID shield, so that the entire false bottom of the box could act as that antenna.

Note that NFC uses an air-coupled transformer, not an antenna proper.

Thats all greek to me..  the board i am using is the AdaFruit pn532, it looks like an antenna... can you explain the difference?

http://www.adafruit.com/products/364

It's actually a wire that goes through several loops and then connects to another power connection. An actual antenna is unconnected at the end, and the charge within it vibrates to emit EM radiation.

So what's on the board linked above and is there a way to extend its reach?

I suspect not. NFC is designed for short range for privacy reasons. Some RFID systems have longer ranges (a few meters). They work by using an electromagnet to create a switching magnetic field. The RFID/NFC chip takes power from the magnetic field and then modulates a signal onto it, which the sensor detects. In order for it to work the chip needs to be close enough to get as strong enough field to power itself, and to modulate that field.

is it possible then to build something that will increase that fields diameter?

Useful answer. +1

@erik The board you linked has an inductive loop on it, printed in PC traces. (The loops in the image.) You could probably cut the traces that connect to those loops and connect each end to some bell wire that you wrap around the perimeter of your box's false bottom. If you did that then the whole bottom of the box should serve as an RFID "pad". The thing I'm not sure about is if the circuit could tolerate the changes in resistance and inductance from the larger coil of wire and still work. An EE would be better able to judge that.


text:
How to call more than 10 different functions based on serial input?
I'm looking to basically call functions based on the serial ID I assign to it. For example, if I want to call function A I would type on the serial A and if I want to call function B then I would type B.
Now I have taken a look at some arduino.cc ASCII and other lookup tables but I'm still not getting my results. YES I can indeed make up serial calls 1 through 9 using char datatype but as you can see I'm only limited to 9 function calls and so this is where I'm looking for tips. How can I expand this serial ID as I'm calling it?
char id;
int led = 6; // the PWM pin the LED is attached to

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  id = Serial.read();
  /*
    will only read the 1st bit on the buffer so
    no 10s...90s because the whole char so we
    need to use Strings datatype somehow but
    the thing is that the Serial.Read func only
    reads the first byte. R&D?
  */
  if (id == '1') {
    digitalWrite(led, HIGH);
  } else if (id == '2') {
    digitalWrite(led, LOW);
  }
}

So in my above example I'm using char to communicate. I know there are other datatypes but not sure which is the best suited for the 100's of functions I would like to call via terminal.
I thought about using the alphabet A-Z as well as a-z to double the function calls but I would like to come up with something a bit more formal rather than single numbers or single letters (char).

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

A char can be 256 different values. However, data is read in one byte at a time. You may want to develop your own communication protocol to send multiple bytes. It doesn't even have to be complicated: just read x bytes, and then stop.

@Majenko than you for your help once again pal! I'll get to the link and read it all.

@uhours are you suggesting a for loop in the conditionals?

@Frank, A for loop before the conditionals, reading x bytes into an array. Exit the loop when the array is full. Use strcmp() to evaluate the contents. Also, indent your code.

@uhours thanks for the advise, I will read mute on that function you mentioned as I have never used it before.

It looks like you want to write some sort of command interpreter. You may want to look, for inspiration, at this simple Arduino command line interpreter.

First, you could use a string for the commands. You just need to ensure there is some special char to mark the end of a command - like the newline char. Read the input from the port one char at a time, building the string as you go:
char buffer[256];
uint16_t buffer_index = 0;
void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;   // Append EOS
      // Complete message - do something
      buffer_index = 0;   // Reset, ready for next message
    }
    else {
      // Append char to end of buffer
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

There are plenty of examples like this on this site.
Next, I don't recommend using an if statement with a hundred or more conditions. Instead, you can store pointers to each function in an array:
// Use a typedef to simplfy
typedef void (*function_type)(); // A function with no params and no return, change as needed
// Fixed array size
const int max_functions = 200;
// Create an array of 200 function pointers
function_type all_functions[max_functions] = {0};

So to call function #11:
all_functions[10]();

Now you just need a way to marry the function pointers to a name. A hash table could work here. A hash function converts a string to a number. There are lots of examples on the web. Here's one:
uint16_t djb2_hash(const char *str)
{
    unsigned long hash = 5381;
    int c;

    while (0 != (c = *str++)) {
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }

    // Note: we use the mod operator to make sure value
    // is less than array size
    return hash % max_functions;
}

Create two functions, one to add a function and one to retreive:
bool add_function(const char *name, function_type f)
{
  // Convert name to number
  uint16_t index = djb2_hash(name);  //  0 <= index <= max_functions
  if (NULL != all_functions[index]) {
    // There is already a function stored at this index
    Serial.print("Adding ");
    Serial.print(name);
    Serial.print("failed. index = ");
    Serial.println(index);
    return false;
  }
  else {
    // Store the function in the array
    all_functions[index] = f;
    return true;
  }
}
bool run_function(const char *name)
{
  uint16_t index = djb2_hash(name);
  if (NULL == all_functions[index]) {
    // Name not found
    return false;
  }
  else {
    // Call the function
    all_functions[index]();
    return true;
  }
}

Last, create some functions and add to hash table:
void f1() {Serial.println("F1");}
void f2() {Serial.println("F2");}
void f3() {Serial.println("F3");}

void setup() {
  Serial.begin(9600);
  add_function("F1", f1);
  add_function("F2", f2);
  add_function("F3", f3);
}

All that's left is to modify loop() to call the functions when a complete message is received.
void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;
      run_function(buffer);
      buffer_index = 0;
    }
    else {
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

If you enter "F1", "F2", or "F3" in the serial monitor, those functions should execute. Just make sure you change the serial monitor to append a newline.
Some notes: the hash function may not create a unique id for each string. You need to handle this situation. Also, the names are case sensitive. If you don't want that, convert everything to all upper case or all lower.

Your code works great, but, What can I do to call a Funct with parameters void funct_X(char letterX, int numberX); ...... ?

@NavasEma You could change the typedef to typedef void (*function_type)(char,int);.  And the run function to all_functions[index](arg1, arg2);

a state machine would be the most efficient approach here.
first, you need to process each valid input - making sure that it is between 0..9.
then you need to form a 2-digit number with that. for that to work, you will need to be able to tell when the input ends - lots of ways to do that.
the heart of the code would be something like this:
current_input = valid_input();  //obtain valid input
input = cmd_2dig(current_input); //2-dig commands
switch (cmd_2dig) {
  case 0: do_cmd0(); break;
  case 1: do_cmd1(); break;
  case ....
  default: reset_cmd(); //invalid command, reset command buffer
}


text:
How to check whether my Arduino is working? And how to fix this?
I tried my first project with Arduino Uno. But I can't upload any code. Power green LED is working and orange LED is always on, not blinking, and IC also getting hot. What can I do to fix this problem?

My suggestion is to find someone else with an arduino, and get them to test (with their computer, known to be working) uploading to your Arduino. That way, you can tell if the problem is with your computer or the Arduino.
You haven't mentioned what your first project was. The most common mistake #1 is to light up an LED without a resistor. If you do that for a split second, you might (OR MIGHT NOT!) get away with it. If you leave it running for a few seconds, you are almost certainly going to burn out your AtMega (the IC on the board). This might very well result in the symptoms you describe. If this has happened, and your chip (IC) is removable (some are, some aren't), you should be able to buy a new chip of the same kind. An Arduino Uno has an AtMega 328, you will want a DIP package (they are the removable ones), and you will want one with an Arduino Bootloader pre-programmed. Replacing the chip may OR MAY NOT fix the problem. Make sure you note down the orientation of the broken chip before you pull it out - it will fit in, but won't work (and could burn out!) if you put it in the wrong way. There should be a little dimple at one end of the chip, right on the end. It should look like this (possibly without the pin labeling sticker): http://www.jaycar.co.nz/productView.asp?ID=ZZ8726&w=atmega328&form=KEYWORD
If your chip is not removable, or replacing the chip doesn't help, then you will need to get a new Arduino.


text:
How to increase the detection distance on Arduino KY-032 obstacle Avoidance sensor?
We've got an Arduino KY-032 obstacle avoidance sensor, and have spent a decent time searching and researching to find a detailed data sheet/manual to figure out how it works; but there aren't any detailed information on the module.

One of the few instructions here says that the potentiometers on the chip are used to adjust the distance, but I've tried all different settings and the maximum I can get is 10 centimeters. I've tried different surfaces with different reflectivity levels, but it doesn't really differ much.
Any idea how to increase the distance on this? Anything to do with the enable jumper?
Update: Here's the related code to the obstacle detection:
void loop() {
  // check the network connection once every 10 seconds:
  val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
  if(full==1 && val==LOW) {
    Serial.print("Bin Full");
    delay(5000);
  } else {
    if (val == LOW) {
      // When the obstacle avoidance sensor detects a signal, LED flashes
      digitalWrite (Led, HIGH);
      delay(2000);
      if(digitalRead(buttonpin)==LOW) {
        delay(2000);
        if(digitalRead(buttonpin)==LOW) {
          full = 1;
        }
      }
      count++;
      //printCurrentNet();
      sendData();
    } else {
      digitalWrite (Led, LOW);
      if(full==1) {
          count = 0;
      }
      full = 0;
    }
  }
}

It could be code related. Can you add small snippet of your code (excluding anything unrelated to this issue)? Thanks!

@AnnonomusPenguin There you go. (:

It may just be defective.  Have you tested duplicate sensors? It may also just be low quality product.  Have you tried contacting the manufacturer?

How about this- test the sensor WITHOUT the Arduino Uno.

@Pedro What do you mean how we connected it to Arduino? We were using an Intel Galileo board and programming it with Arduino. There are tutorials if you look up.

The IR sensor module incorporates an internal 38KHz bandpass filter. The pot near the GND pin fine tunes the frequency of that signal, which is used to illuminate the IR LED.
The other pot adjusts the duty cycle of the signal. This controls the brightness of the IR LED.  Both adjustments effect the sensitivity and range of the device.
To achieve maximum sensitivity, it is absolutely necessary to use the 'EN' or 'Enable' pin.  When used correctly, however, additional optical shielding of the IR LED is required.  This can be done with a small cardboard tube commonly used as packing material or any of a variety of other materials.
If the Enable function is not used, the jumper must be installed on the board. The Enable pin cannot be used if the jumper is in place.
For more information, see: http://irsensor.wizecode.com/

The wizecode page has some nice info. However the R5 pot (near the EN jumper) does not change the duty cycle but directly the current to the IR LED - still affects the brightness though. Too much current seems to trigger false positives - depends on your additional optical shielding. I put some black heat shrink tubing over the sensor - with a hole punched in for the sensor to see though.
Also the R6 pot does not really "fine tune" the frequency, more like "coarse tune" - even a small nudge can detune by a kHz, greatly reducing the sensitivity.
If you use the EN jumper, a suddenly appearing object gives a short pulse, but then the disturbance signal suppression kicks in turns sensitivity down and 'unsees' the object. Also slowly appearing objects are not recognized for that reason. Only very near objects (a few cm) give a strong enough signal to overcome that sensitivity attenuation.
What I found somewhat irritating: Setting EN to LOW lets the IR LED steady on instead of off, which I would have expected. That might irritate the sensor more than necessary. Also draws more power (maybe even a lot, depending on R5 current setting).
Funny enough, you can get a somewhat analog behaviour from this sensor if you measure how long it takes from activating the EN pin to the sensor output getting low. The nearer the object is, the faster it reacts. Near objects take ~190us, farther objects more than 400us. Not nearly a linear behaviour though. Also depends on distance, size, angle, IR reflectivity and IR LED power.
However it can detect a person in more than 1m distance.

These Obstacle sensors don't always work as expected.I bought 3 of them, but only 2 worked properly.The other only worked to a distance of about 6-7cm.
By the way, the code seems to be fine, but there is no way to tell for sure without complete code.

Check This: http://irsensor.wizecode.com/

When the GREEN JUMPER is installed on the board (see picture), the IR LED will flicker continuously at 38kHz.  If the Enable (EN) function will not be used, the jumper must be installed .  When the jumper is removed, pin 4 of the 555 timer is held LOW (RESET) by R3, a 22K pull-down resistor. Then, if a HIGH condition is applied to the EN pin, the reset condition will be relieved and the 555 timer will begin to oscillate. The Enable function cannot be used if the GREEN JUMPER is in place.  You must remove the jumper on the board in order to use the EN (Enable) pin.

Well, the range of the sensor should be: "2-40cm"
I would suggest using the code below and changing the potentiometers to see if it makes any difference.
int Led = 13 ;// define LED Interface
int buttonpin = 3; // define the obstacle avoidance sensor interface

void setup ()
{
  pinMode (Led, OUTPUT) ;// define LED as output interface
  pinMode (buttonpin, INPUT) ;// define the obstacle avoidance sensor output interface
}
void loop ()
{
  if (digitalRead (buttonpin) == HIGH) // When the obstacle avoidance sensor detects a signal, LED goes on.
  {
    digitalWrite (Led, HIGH);
  }
  else
  {
    digitalWrite (Led, LOW);
  }
}

I wouldn't think that's required, it's very likely that the Sensor is malfunctioning.

@Mathsman100 But it is a way to prove so?


text:
atmega88 timer2 32.768KHz and Serial problem
I am trying to use atmega88 timer2 with a 32.768KHz crystal. I'm using a slightly modified version of Nick Gammon's code. I am using Minicore. No bootloader, 1MHz clock from internal oscillator, BOD disabled. Sleep is interrupted every 8 seconds. I use a counter to count 12 minutes. Since it overshoots about 8 seconds every 6 hours, I am subtracting 8 sec every 6 hours. I hope to eventually make a weather logger with this.
The code is mostly working in it's bare stripped down version, after I add a delay(100) after the digitalWrite. However, I also need Serial. When I enable Serial, it does not sleep anymore. Also, the serial output has a lot of excess weird characters. This happens at all baud rates, even 1200 (serial monitor set to same baud rate as in program). I think some interrupts are being called during digitalWrite and when the usart is powered on and it is messing with the sleep. I am a beginner regarding uC programming, and am really struggling with the datasheet and the code. Any help will be appreciated.
Here is the test code:
#include <avr/sleep.h>
#include <avr/power.h>

const byte tickPin = 4;// (do not use 3 and 11)

//byte intCounter = 0;
//byte leapCounter = 0;

int intCounter = 0;
int leapCounter = 0;

unsigned long prevTime = 0;
unsigned long currTime = 0;

// interrupt on Timer 2 compare "A" completion - does nothing
EMPTY_INTERRUPT (TIMER2_COMPA_vect);

void setup(){
  pinMode (tickPin, OUTPUT);

  Serial.begin(9600);
  prevTime = millis();
  Serial.print(" P: ");
  Serial.println(prevTime);

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);

  // set up timer 2 to count up to 256 * 1024  (8 seconds)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  255;                                     // (zero-relative)

  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);

  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_twi_disable();
//  power_timer0_disable();
//  power_timer1_disable();
  power_spi_disable();
  power_usart0_disable();
  power_adc_disable ();

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);

  // get ready ...
  sleep_enable();

}  // end of setup

void loop(){
  sleep_cpu ();
  ++intCounter;

  power_usart0_enable();
  Serial.print("I: ");
  Serial.print(intCounter);
  Serial.print(" L: ");
  Serial.print(leapCounter);
  currTime = millis();
  Serial.print(" C: ");
  Serial.print(currTime);
  Serial.print(" E: ");
  Serial.print(currTime - prevTime);
  Serial.println();
  prevTime = currTime;
  power_usart0_disable();
  delay(1000);

  if ((leapCounter > 30) && (intCounter == 1)){
    leapCounter = 0;
    intCounter = 0;
  }
  if (intCounter > 89){
    ++leapCounter;
    intCounter = 0;
    digitalWrite (tickPin, ! digitalRead (tickPin));
    delay(100);
  }
//  digitalWrite (tickPin, ! digitalRead (tickPin));
//  delay(100);
}  // end of loop

The chip is an Atmega88 (not P). It is drawing the same 6.5uA during sleep, with or without timer0 and timer1. So, I probably don't care if I have to leave them enabled.
I am planning to use a DHT11 and a ds18B20 and write the data to a w25Q64 flash, every 12 minutes. I'd prefer reading it all out via serial port every few weeks, without having to stop the uC.
update
Calling timer2 ISR, instead of handling wake up directly in main loop. Possibly more stable (not affected by Serial and digitalWrite)... but I am not sure.
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

//const byte tickPin = 4;// (do not use 3 and 11)

volatile bool t2flag = LOW;
volatile byte t2counter = 0;

byte leapCounter = 0;

//preventing digitalWrite from causing interrupt (did not help much)
EMPTY_INTERRUPT(PCINT2_vect);

void setup(){
  pinMode (4, OUTPUT);
  pinMode (1, INPUT_PULLUP); //set TX pin default HIGH

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);
  // set up timer 2 to count up to 256 * 1024  (8 seconds)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  255;                                     // (zero-relative)
  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);
  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_twi_disable();
//  power_timer0_disable();
//  power_timer1_disable();
  power_spi_disable();
  power_usart0_disable();
  power_adc_disable();
  wdt_disable();// reduces 6.5uA to 2.2uA @ 3.3V

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);
  sleep_enable();
}

//ISR to handle timer2
ISR (TIMER2_COMPA_vect){
  ++t2counter;
  if (t2counter > 89){t2flag = HIGH;}
}

void loop(){
  if (t2flag == LOW){

    power_usart0_enable();
    Serial.begin(9600);
    Serial.print("I: ");
    Serial.print(t2counter);
    Serial.println();
    Serial.flush();
    delay(10);
    Serial.end();
    power_usart0_disable();

    //blip the tickPin every 8 sec
    PORTD |= (1<<PD4);
    delay(10);
    PORTD &= ~(1<<PD4);

    delay(100);//helps a lot
    sleep_cpu();
    return;
  }

  ++leapCounter;
  if (leapCounter == 30){
    t2flag = LOW;
    return; //delay another 8 sec every 6 hours
  }
  if (leapCounter > 30){leapCounter = 0;}

  t2flag = LOW;
  t2counter = 0;

  power_usart0_enable();
  Serial.begin(9600);
  Serial.print("L: ");
  Serial.print(leapCounter);
  Serial.println();
  Serial.flush();
  delay(10);
  Serial.end();
  power_usart0_disable();

  //long blip every 12 minutes
  PORTD |= (1<<PD4);
  delay(100);
  PORTD &= ~(1<<PD4);
}

The problem is not always present. But when it appears, it happens the same way. After pressing reset button, first led blink is always after 8 seconds. After that, one of three things seem to happen. 1. Second flash is after 8 seconds and everything works as expected. 2. Second flash is after 3 seconds and all flashes after that are also after every 3 seconds. 3. Second flash happens immediately after first flash (and any delay() in the code) and this keeps on happening. In all cases, the serial output also shows the same pattern.
Sometimes it seems that wires connected to the serial or miso, mosi, sck may be causing this, but that is not always the case. The problem may occur even if these wires are not connected. Also, the problem may or may not occur with the same code (e.g. pressing reset after 30 sec may not show any problem, but pressing reset within 5 or 10 seconds leads to problem cases 2 and 3 above. So there is some kind of race condition, or buffer or interrupt noise or something.
I have to program with Arduino as ISP, as the bootloader is unable to sync with the ftdi chip for some reason while uploading sketch. But data transfer from the sketch with serial.print is working fine. So pulling out the miso mosi sck pins everytime is a hassle. Everything is on breadboard. I transferred full circuit to new breadboard (from old loose breadboard) but there is no change. So maybe not a breadboard issue.

this is not an Arduino question, but it is very interesting

Thanks. I didn't know where to ask, and the old arduino had a somewhat similar atmega8, I think (although not a watch crystal).

https://arduino.stackexchange.com/questions/13167/put-atmega328-in-very-deep-sleep-and-listen-to-serial

@jsotola Thanks for the link. However, that is not what I see. Enabling usart is waking up the uC even from power save (or at least seems like it). Besides, there is also the problem of garbled output even with correctly set baud rates.

I see two issues in this code.
The first is that you are trying to send data through an UART that has
been powered off. Serial.print() doesn't wait for the data to get out,
it merely stores it into a memory buffer. You should wait until
everything gets out before switching the UART off. This can be done by
calling either Serial.flush() or Serial.end(). I would use the
latter, as it feels safer to stop the UART before switching if off. But
then you have to Serial.begin() again on wakeup.
To avoid the garbled characters in the serial stream, you could try to
either pinMode(1, INPUT_PULLUP); or digitalWrite(1, HIGH);. This way
you ensure that the TX line stays HIGH (which is its normal idle
state) when the UART goes off.
The second issue is your use of the Arduino timekeeping functions
millis() and delay(). These functions rely on an interrupt triggered
by Timer 0. If you power off that timer, millis() and delay()
won't work. If you don't, SLEEP_MODE_PWR_SAVE does it for you while
sleeping. Then those function will work while awake, but millis() will
not count the time you spent sleeping.

Edit: There are two interrupts related to the UART that are enabled
by Serial.begin():

USART_UDRE, “Data Register Empty”, is used for transmission. It
fires when the hardware transmit buffer is ready to receive new data.
The corresponding ISR's job is to copy one byte from the transmit
memory buffer (the one Serial.print() writes into) into the hardware
transmit buffer.
USART_RX, “Receive Complete”, is used for reception. It fires when a
byte is received. The corresponding ISR copies this byte into receive
memory buffer (the one Serial.read() reads from).

The first one fires when transmitting. Once you wait for the end of the
transmission (say with Serial.flush()), you shouldn't see this
interrupt firing anymore.
The second one fires only when receiving. If you are not receiving
anything, this interrupt shouldn't fire. If the RX pin is floating, the
interrupt could be triggered by external noise. This can be prevented by
enabling the internal pullup on the RX pin. Alternatively, you can
disable the receiver part of the UART:
UCSR0B &= ~_BV(RXEN0);  // disable the UART receiver

Note that if you stop the UART with Serial.end(), both the transmitter
and the receiver are disabled, and you don't get UART-related interrupts
anymore.

Thanks. I will check if that fixes the serial issues. I did not know that millis would be halted during sleep, inspite of keeping timer0 enabled. Maybe I'll be able to check that if I can get serial to work reliably. However, I'm only using millis() as a rough estimate as it's running from the internal oscillator, so not a dealbreaker if it is messed up.

I checked, and your instructions fixed the garbled messages of the serial line. Also, millis() does indeed only count the wake time. However, it seems serial uses interrupts, so it is still causing some problems. I put the timer2 interrupt in an ISR, and it is slightly better. It causes a problem only if the serial wires are connected during reset.

@Indraneel: Re serial interrupts: see the edited answer. I don't know what you mean by “I put the timer2 interrupt in an ISR”.

Thanks for the update. I'll see if that helps. I think, writing to the LED pin may also be causing an interrupt. It is helping to put a delay after the write. I have edited my question above with the updated code.

@Edgar_Bonet Problem is mostly during startup, like if I press the reset pin for too long (1-2 seconds, instead of small tap). But problem shows up only after 1st sleep cycle is complete (after 1st 8 seconds). No difference on adding 0.1uF capacitor to reset pin.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Connecting HC-06 and LM35
Hello I am trying to send temperature data via bluetooth using the HC-06 module. Since TXD and RXD only allow 3.3V I have divided the circuit into two like the below image.
Is this method correct? or is there a better way to connect both two?

Any help is appreciated.

I think you have it backwards. You should be dividing the TX from the Arduino (5V) down to 3.3V for the RX into bluetooth.

@Majenko Thank you for your comment. I'm a little confused. Is the below picture correct. So the purple and green wires should be reversed?

No, the resistors should be on the green wire not the purple.

Is the lower module a bluetooth master? If I recall it correctly, the HC-06 module have their firmware set to slave only

"Who" is on the other end? Once HC-06 is paired with a master - Nexus 7, f/ex, or PC's with Bluetooth 2 - it will communicate just fine. Just remember the HC-05/06 are Bluetooth 2 devices and can't talk to BLE devices -- current iPhones and many current PCs.

As mentioned by chrisl, you cannot use HC-06 as a master device. Its firmware restricts it to behave only as a slave. So even if you are able to process the analog data from LM 35, you won't be able to send it using HC-06. It would be better if you go for HC-05 module and try the command AT+ROLE: x (x = 1 for master/0 for slave) to get the job done.
Coming to the 3v3 voltage constraint, I would suggest you to go for any Zener diode (in reverse biased mode) with 3.3V Reverse breakdown voltage. You can check the circuit for this here and order it from this link. If this is not possible anyhow, then you can also go for LM1117 3V3, but I would personally suggest you to go for zener diode. Comment back if you need any help in future.


text:
GSM cannot read SMS when Arduino is not reset for the first time after it is powered
I'm using a GSM Module with Arduino along with Node MCU. I have a supply of 9V, 2A in the DC jack of the Arduino and the GSM Shield. The Node MCU is powered from the 3.3V of the Arduino. I can receive messages fine in the GSM when the USB port of the Arduino (including the power supply I mentioned earlier) is connected to the laptop through and monitored using the serial monitor. However if I remove the USB port, the GSM cannot receive the messages anymore but when I press the reset button of the Arduino, it will start receiving messages again. Why does it only works when I reset the Arduino first after powering it up?
#include <SoftwareSerial.h>
#include <Wire.h>

SoftwareSerial gsmSerial(2, 3);

char incomingByte;
String inputString;

// Pin configurations.

const int outlet1Pin = 4;
const int outlet2Pin = 5;
const int outlet3Pin = 6;

const int ping1Pin = 7;
const int ping2Pin = 8;
const int ping3Pin = 9;
const int ping4Pin = 10;
const int ping5Pin = 11;
const int ping6Pin = 12;
const int signalPin = 13;

const int pingWaitTime = 3000;

void setup()
{
  Serial.begin(9600);
  gsmSerial.begin(9600);

  pinMode(outlet1Pin, INPUT);
  pinMode(outlet2Pin, INPUT);
  pinMode(outlet3Pin, INPUT);

  pinMode(ping1Pin, OUTPUT);
  pinMode(ping2Pin, OUTPUT);
  pinMode(ping3Pin, OUTPUT);
  pinMode(ping4Pin, OUTPUT);
  pinMode(ping5Pin, OUTPUT);
  pinMode(ping6Pin, OUTPUT);
  pinMode(signalPin, OUTPUT);

  initGSM();
  //Serial.flush();
  //gsmSerial.flush();
  //sendSMS("Test send.");

}

void loop()
{
  if (gsmSerial.available())
  {
    digitalWrite(signalPin, HIGH);

    delay(500);

    //Serial.println("Serial available.");

    while (gsmSerial.available())
    {
      incomingByte = gsmSerial.read();
      inputString += incomingByte;
    }

    inputString.toUpperCase();

    checkCommandAction(inputString);

    if (inputString.indexOf("OK") == -1)
    {
      gsmSerial.println("AT+CMGDA=\"DEL ALL\"");
      delay(1000);
    }

    inputString = "";
    gsmSerial.flush();

  }
  digitalWrite(signalPin, LOW);

}

void sendSMS(String text)
{
  Serial.println("Sending Text...");

  gsmSerial.println("AT+CMGF=1");
  delay(1000);

  gsmSerial.print("AT+CMGS=\"+numberhere\"\r");

  delay(1000);

  gsmSerial.print(text);
  delay(1000);

  gsmSerial.print((char)26);
  delay(1000);

  gsmSerial.println();
  Serial.println("Message sent!");
  delay(1000);
}

void initGSM()
{
  gsmSerial.println("ATE0");
  while (!gsmSerial.available())
  {
    gsmSerial.println("AT");
    delay(500);
    Serial.println("Connecting...");
  }

  Serial.println("Connected!");

  gsmSerial.println("AT+CMGF=1");
  delay(500);
  gsmSerial.println("AT+CNMI=1,2,0,0,0");
  delay(500);
  gsmSerial.println("AT+CMGL=\"REC UNREAD\"");
  delay(500);
  gsmSerial.println("AT+CMGDA=\"DEL ALL\"");
  delay(500);

  Serial.println("All messages deleted!");

  Serial.println("Sending Text...");

  gsmSerial.println("AT+CMGF=1");
  delay(500);

  gsmSerial.print("AT+CMGS=\"+639776811077\"\r");

  delay(500);

  gsmSerial.print("Device Initialized!");
  delay(500);

  gsmSerial.print((char)26);
  delay(500);

  gsmSerial.println();

  Serial.println("Message sent!");
  delay(500);
}

void checkCommandAction(String command)
{

  //Serial.println("Check Command.");

  if (command.indexOf("O1ON") > -1)
  {

    digitalWrite(ping1Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping1Pin, !HIGH);
    Serial.println("O1ON Enter");
    sendSMS("Outlet 1 Turned ON by text.");

  }
  else if (command.indexOf("O1OFF") > -1)
  {
    digitalWrite(ping4Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping4Pin, !HIGH);
    Serial.println("O1OFF");
    sendSMS("Outlet 1 Turned OFF by text.");
  }
  else if (command.indexOf("O2ON") > -1)
  {
    digitalWrite(ping2Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping2Pin, !HIGH);
    Serial.println("O2ON");
    sendSMS("Outlet 2 Turned ON by text.");
  }
  else if (command.indexOf("O2OFF") > -1)
  {
    digitalWrite(ping5Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping5Pin, !HIGH);
    Serial.println("O2OFF");
    sendSMS("Outlet 2 Turned OFF by text.");
  }
  else if (command.indexOf("O3ON") > -1)
  {
    digitalWrite(ping3Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping3Pin, !HIGH);
    Serial.println("O3ON");
    sendSMS("Outlet 3 Turned ON by text.");

  }
  else if (command.indexOf("O3OFF") > -1)
  {
    digitalWrite(ping6Pin, !LOW);
    delay(pingWaitTime);
    digitalWrite(ping6Pin, !HIGH);
    Serial.println("O1OFF");
    sendSMS("Outlet 3 Turned OFF by text.");
  }
  else if (command.indexOf("CHECKSTATE") > -1)
  {
    int state1 = !digitalRead(outlet1Pin);
    int state2 = !digitalRead(outlet2Pin);
    int state3 = !digitalRead(outlet3Pin);

    String toSend = "";
    toSend += "Outlet 1: ";
    toSend += String((state1) ? ("ON") : ("OFF"));
    toSend += "Outlet 2: ";
    toSend += String((state2) ? ("ON") : ("OFF"));
    toSend += "Outlet 3: ";
    toSend += String((state3) ? ("ON") : ("OFF"));

    sendSMS(toSend);
  }
}

void turnPingsOn()
{
  // The pins where the pings are connected are
  // configures as INPUT_PULL up, so we need to high
  // it by default.

  digitalWrite(ping1Pin, HIGH);
  digitalWrite(ping2Pin, HIGH);
  digitalWrite(ping3Pin, HIGH);
  digitalWrite(ping4Pin, HIGH);
  digitalWrite(ping5Pin, HIGH);
  digitalWrite(ping6Pin, HIGH);
}

Please show us the sketch you are using.

Updated, I use AT commands for sending and receiving SMS. It works fine if I connect it to the computer and open the serial monitor. However when I just use the dc jack, it won't receive any message.

how do you know that messages are not being received?

A relay will open if a certain message is received.

In theory you shouldn't rely on the 3.3V supply of the Arduino to power the NodeMCU board, it doesn't have enough power particularly when WIFI data is being transmitted.
Are you removing the USB while the system is live?  If so you are probably spiking various bits that don't like being spiked and that's why it breaks.
If you are removing the USB and THEN powering up the system, what happened when you power down you system and power it back up again after 10 seconds?  My guess is that it won't receive messages.  So there is a difference between applying power and resetting the board, which implies that you are very marginal on your power supply.
If you are using the SIM800 (?) module they need 2Amps to transmit, so if you are only supplying 2A it might not have enough power to cold start, but when reset it does.  So if you can try more power that might help.
Another thought might be you haven't got a proper ground (wall warts aren't normally grounded) so your USB connection is acting as a ground.  If this is the case then it should work when you PC is turned off.
Sorry this is a bit vague, but your question needs model names and part number for people to be a bit more specific.


text:
Combining two different coding program into one sketch
Im working on project that uses a relay module,arduino atmega328 and a 2 motor 12vdc. based on coding i give, the first code is the motor 1 will run based on the input switch. and the second code the motor will run based on the delay time. what im doing is, im going to combine these two coding into one sketch hoping these two coding will run together. but im confused on how to combine.
`int motorPin = 10; // pin that turns on the motor
int blinkPin = 9; // pin that turns on the LED
int watertime = 5; // how long to water in seconds
int waittime = 60; // how long to wait between watering, in minutes

void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
}

void loop()
{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  delay(watertime*3000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, LOW);  // turn off the motor
  digitalWrite(blinkPin, LOW);  // turn off the LED
  delay(waittime*6000);        // multiply by 60000 to translate minutes to milliseconds
}`

this is the coding to run the motor by using delay time
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == LOW) {
    // turn LED on:
    digitalWrite(ledPin, LOW);
  } else {
    // turn LED off:
    digitalWrite(ledPin, HIGH);
  }
}

this is the code which the motor will run based on the switch
for now, i dont have idea on how to combine these two coding.
the idea of my project is when switch is LOW(pin 3)  the Motor 1(pin 13) will HIGH until the switch is HIGH, the motor 1 will be LOW and stop.  At the same time,  there will be time delay for 10 second and the Motor 2 (pin 10)will active soon after switch is LOW and delaying time for 10 seconds and the Motor 2 will be active with time for 25 second  and stop and the next active for another 60 minutes

You won't have any idea until you learn to understand what those two individual codes are doing on each line.  Once you learn that then combining them becomes trivial.  So the thing to do is to go learn what all those lines of code mean and do.

If you want someone here to be able to help you then you might want to consider telling what the combined code should do.

@Delta_G okay i just edited what the code should do

Can you edit it again and be specific about what you want it to do?  How many seconds is "several seconds".  Should I write a routine to come up with a random number for that?  Or did you have some number in mind?  Can you see how frustrating it can be to try to help someone who doesn't even know what they want?

You will need to change the delay sketch to use non-blocking code. During execution of delay() the Arduino is just busy waiting and there is nothing like doing things at the same time on Arduino. You have to use code that runs fast enough sequentially to let it seem, as it is doing things simultaneously. Refer to the BlinkWithoutDelay example of the Arduino IDE. Learn how to use it, there are hundreds oft tutorials on the internet, including the Arduino documentation.

This question has been asked a number of times. Please see an old answer: https://arduino.stackexchange.com/questions/17277/altering-code-to-run-a-timer-while-checking-for-a-data-input/24644#24644

The simplest way of combining two programs is this:

Copy the content of the two programs into a single new .ino (program) file
Rename the first setup function setup_one
Rename the first loop function loop_one
Rename the other setup and loop functions setup_two and loop_two
Add the following code to the bottom of that file.

Code:
void setup()
{
  setup_one();
  setupr_two();
}
void loop ()
{
  loop_one();
  loop_two();
}

This is a very simplistic approach and it won't work for all cases.  It will work in this case, but you will find it will do program one then program two.  It will work because your constants don't clash (at the top of the program) you aren't using the same pin in the different programs, etc.
You need to learn what the code does though to really merge the programs, you will see better ways of doing it.  The best way to learn is to right down, in your native language, what each line of code does, so in the case of program one:
turn on the motor
turn on the LED
wait for 'watertime' seconds
turn off the motor
turn off the LED
wait for 'waittime' minutes

For program 2:
  read the state of the pushbutton value:
  If the button is in state low
    Turn off the LED -- Not sure  this might be on
  else
    Turn on the LED -- Not sure this might be off

Hopefully you should recognise those descriptions (they are the comments) and when you read through the descriptions you will realise why the code you put together using the above method "doesn't work".  It does, you just need to wait for 'waittime' minutes before you get a few microseconds to press the button.
If you want the motor to respond to the button then rearrange the natural language description to do what you want and then replace the English with the code and you should have a program that is close to working.  (Hopefully)


text:
Using a channel relay
im using 4 channel relay to switch the motor pump.  but when the arduino output is high and i check first with led. the led behavior were high too but when i attached to the relay input IN1,  the relay were low.  its like reversed action(the arduino is high, but relay was low then when arduino output is low,  suddenly the relay was high.  i try to edit the code hoping if i set arduino output is low then relay will be high but its still the same,  its reversed.  arduino output is low but the relay become high.  is there any way to make the relay to become high when the digital output is high?
however.. i didnt have the the actual circuit act but im using the digital pin as the output and some switches.  the project im work on is the automatic aquarium pump and water change which is the pump will automatically refill the water actuated by the float switch and will automatically drain the water and refill the new water in certain time.
im using pin 13 as the output.. and the pin 1 as the input which is a switch
as in picture im using a led as a output. but as soon i change to the relay, it become what i just said at the above

I see. How do I ask a good question about the Arduino?. What relay? What pump? i try to edit the code - what code? Please post your schematic (circuit). Edit your question to include these details and I am sure we will be able to help you.

@NickGammon alright sir, i just edited the post and you can refer to ths detail i given based on your questions

@AsrulAsyraff Could you please kindly post your code.

First of all, you'll soon blow up that LED. (Or the Arduino if you're really unlucky.) You need a current limiting resistor.
Secondly, most relays have two switch contacts: normally closed (N.C.) and normally open (N.O.). If you want your device to be off, unless the Arduino turns on the relay, use the N.O. connection. If you want your device to be on, unless the Arduino turns on the relay, use the N.C. connection.
It looks like you need N.O.
N.b: 'closed' means on (i.e. the switch is closed and current is allowed to flow).
Finally, you seem to be using an external pull-up resistor for you switch, which is completely unnecessary: the Arduino has an internal pull-up resistor on every digital pin that you can enable using pinMode(pin, INPUT_PULLUP).
Edit: you didn't connect the relay to the button pin instead of the LED pin, did you?

oh i see... because im just referring to the led on the relay but i didnt connect any load on the relay so im just looking on lights on the led which located at the relay module.  is this means that i should try to connect the load on the relay and see the really output based on NC/NO connection instead just looking on the relay led?

@AsrulAsyraff: You connected the relay to the switch pin, instead of to the LED pin.

i  changed the LED and connect into the relays input


text:
Why is the IDE not able to find the board despite it being clearly seen and selected?
i'm having an odd problem where despite having the correct port selected 3 times i'm still getting an error as shown below:  message:
Arduino: 1.8.9 (Windows 10), Board: "Adafruit Feather M0, Arduino, Off"

Sketch uses 20876 bytes (7%) of program storage space. Maximum is 262144 bytes.
Atmel SMART device 0x10010005 found
Device       : ATSAMD21G18A
Chip ID      : 10010005
Version      : v2.0 [Arduino:XYZ] Mar  5 2016 17:46:52
Address      : 8192
Pages        : 3968
Page Size    : 64 bytes
Total Size   : 248KB
Planes       : 1
Lock Regions : 16
Locked       : none
Security     : false
Boot Flash   : true
BOD          : true
BOR          : true
Arduino      : FAST_CHIP_ERASE
Arduino      : FAST_MULTI_PAGE_WRITE
Arduino      : CAN_CHECKSUM_MEMORY_BUFFER
Erase flash
done in 0.832 seconds

Write 21164 bytes to flash (331 pages)

[=====                         ] 19% (64/331 pages)
[===========                   ] 38% (128/331 pages)
[=================             ] 58% (192/331 pages)
[=======================       ] 77% (256/331 pages)
[============================= ] 96% (320/331 pages)
[==============================] 100% (331/331 pages)
done in 0.128 seconds

Verify 21164 bytes of flash with checksum.
Verify successful
done in 0.016 seconds
CPU reset.
Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

the upload was successful, but after the reset the board changed port or the sketch hangs and doesn't handle USB. I guess you have Serial Monitor open and it can't connect back to selected port after Upload, and prints the message "Couldn't find a Board on the selected port."

The SAMD boards connect to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.
A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by double clicking the reset button on board.

this reset will not always work: https://arduino.stackexchange.com/questions/85530/seeeduino-xiao-stopped-connecting-enter-bootloader-mode-is-not-working


text:
Invalid use of non-static member function
In order to explain my problem I used 3 classes: Actions, Triggers, and Combine.
Actions simulates an action function, that is defined externally.
Triggers has that function that needed to be executed.
Combine combines Actions and Triggers.
Now, void combine_funcs() is a member function of Combine class, when the match between Triggers and Actions happen -> passing a function to be executed.
Here void combine_funcs() is show with std::bind, but is was also tested straight foreward.
Error outsput is given below code.
class Actions
{
  typedef void (*cb_func)(uint8_t resaon);

private:
  cb_func exter_func;

public:
  void get_external_func(cb_func func)
  {
    exter_func = func;
  }
  void callAction(uint8_t i)
  {
    exter_func(i);
  }
};

class Triggers
{
public:
  void this_is_external_func(uint8_t i)
  {
    Serial.println(i);
  }
};

class Combine
{
public:
  Actions a;
  Triggers b;

  void combine_funcs()
  {
    a.get_external_func(std::bind(&Triggers::this_is_external_func, this,std::placeholders::_1));
  }
  void loop()
  {
    if (millis() > 10000)
    {
      a.callAction();
    }
  }
};

Combine combo;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Start!");
  combo.combine_funcs();
}

void loop()
{
  // put your main code here, to run repeatedly:
  combo.loop();
}

Compilation output:
/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: In member function 'void Combine::combine_funcs()':
    sketch_jul26a:36:34: error: cannot convert 'std::_Bind_helper<false, void (Triggers::*)(unsigned char), Combine*, const std::_Placeholder<1>&>::type' to 'Actions::cb_func' {aka 'void (*)(unsigned char)'}
       36 |     a.get_external_func(std::bind(&Triggers::this_is_external_func, this,std::placeholders::_1));
          |                         ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          |                                  |
          |                                  std::_Bind_helper<false, void (Triggers::*)(unsigned char), Combine*, const std::_Placeholder<1>&>::type
    /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:9:34: note:   initializing argument 1 of 'void Actions::get_external_func(Actions::cb_func)'
        9 |   void get_external_func(cb_func func)
          |                          ~~~~~~~~^~~~
    /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: In member function 'void Combine::loop()':
    sketch_jul26a:42:20: error: no matching function for call to 'Actions::callAction()'
       42 |       a.callAction();
          |                    ^
    /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:13:8: note: candidate: 'void Actions::callAction(uint8_t)'
       13 |   void callAction(uint8_t i)
          |        ^~~~~~~~~~
    /Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:13:8: note:   candidate expects 1 argument, 0 provided
    exit status 1
    cannot convert 'std::_Bind_helper<false, void (Triggers::*)(unsigned char), Combine*, const std::_Placeholder<1>&>::type' to 'Actions::cb_func' {aka 'void (*)(unsigned char)'}

EDIT_1 : Change Combine class to inherete other classes
class Combine : public Actions, Triggers
{
public:
  void combine_funcs()
  {
    get_external_func(this_is_external_func);
  }
  void loop()
  {
    if (millis() > 10000)
    {
      callAction(13);
    }
  }

yeilds same error:
/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: In member function 'void Combine::combine_funcs()':
sketch_jul26a:33:23: error: invalid use of non-static member function 'void Triggers::this_is_external_func(uint8_t)'
   33 |     get_external_func(this_is_external_func);
      |                       ^~~~~~~~~~~~~~~~~~~~~
/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:22:8: note: declared here
   22 |   void this_is_external_func(uint8_t i)
      |        ^~~~~~~~~~~~~~~~~~~~~
/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino: At global scope:
sketch_jul26a:60:6: error: redefinition of 'void setup()'
   60 | void setup()
      |      ^~~~~
/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:46:6: note: 'void setup()' previously defined here
   46 | void setup()
      |      ^~~~~
sketch_jul26a:68:6: error: redefinition of 'void loop()'
   68 | void loop()
      |      ^~~~
/Users/guydvir/Dropbox/Arduino/sketch_jul26a/sketch_jul26a.ino:54:6: note: 'void loop()' previously defined here
   54 | void loop()
      |      ^~~~
exit status 1
invalid use of non-static member function 'void Triggers::this_is_external_func(uint8_t)'

};

Does this Q+A help? https://stackoverflow.com/a/72450270/10292145

@VE7JRO can you explain why do I need a void* ?

why not set the object as a parameter?

@Juraj i tried, with no luck

@guyd - When I try to compile your code, I get different errors. I am using a different compiler than you are, so my first error leads me here: https://stackoverflow.com/questions/14261013/bind-is-not-a-member-of-std In the Arduino world, they point me here: https://forum.arduino.cc/t/include-functional-error/397411  The only questions I have for you is, why are you writing your code this way, and what problem are you trying to solve?

Why not using class inheritance, for example, class Combine public Action {}? However, solution aside, don't create classes for the sake of creating classes, all three of your classes are not necessary or should belong to somewhere else as methods.

I'll try to explain my bigger problem:
I have 2 classes I've written and tested. One is a Button-Read states including timeouts class, and second class deals with turning ON/Off lights including PWM lights. BOTH are used and tested before. Third library combines both including have on-flash parameters and MQTT command (as some kind og a wrapper) even have multiple instances of my third class.
I want to use all my 3 classes as a legacy that works, rather that re-write it all

I meant the parameter type should by a class and you pass an object there and execute the function on that object. a member function must be invoked on an object, that is why you can use that function as a parameter. it doesn't know on what object it should be executed.

@Juraj can you explain using example ?

maybe later today

You need to call this_is_external_func() on an object, but you don't provide one in callAction(). I see two alternatives: 1) Provide an object to call the method on. 2) Make the method a class function, which does not need an object.

@hcheung took your advice for inherete (see edit 1), but same results

the return type of bind is not the same type as the type of the original function

@Juraj Can you point ?

I changed your sketch with auto f = std:bind.... and a.get_external_func(f); and the error message is a little clearer.

@Juraj - GREAT!!! that was the first lead I got what did I do wrong.

The problem is, that the return type of bind is not the same type as the type of the original function so you can't set it with void get_external_func(cb_func func).
But it looks like in X->Y problem. If you do OOP, use objects.
I take the sketch in the question as a test so I want comment on other parts and how to do them properly. I just made minimal changes to pass the object and call the method (member function) with the object.

class Triggers
{
public:
  void func(uint8_t i)
  {
    Serial.println(i);
  }
};

class Actions
{
  Triggers* trigers;

public:
  void set_triggers(Triggers* t)
  {
    trigers = t;
  }

  virtual void callAction(uint8_t i)
  {
    trigers->func(i);
  }
};

class Combine
{
public:
  Actions a;
  Triggers b;

  void combine_funcs()
  {
    a.set_triggers(&b);
  }
  void loop()
  {
    if (millis() < 10000)
    {
      a.callAction(1);
    }
  }
};

Combine combo;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Start!");
  combo.combine_funcs();
}

void loop()
{
  // put your main code here, to run repeatedly:
  combo.loop();
}


text:
UART connection between Arduino Nano and NodeMCU
I'm trying to create an UART connection between a Nano and an NodeMCU, running MicroPython.
Code for trying is meaningless - Arduino says "HI", and ESP8266 should receive and print msg value.
Connections :
Nano Rx --> ESP Tx
Nano Tx --> ESP Rx
Nano USB -- > Mac running repl
ESP USB --> Linux running Arduino IDE
BUT- when I physically connect as described the ESP BOARD freezes, in a way I can't even connect it using repl. Only after disconnecting wires (not only powering off the Nano), ESP unfreezes.
Appreciate any help.

io 1 of esp8266 is RX, io 3 is TX. clear the wiring description

do you connect ground? which esp module you have?

hi @Juraj - Tx on Nano connects to Rx on ESP, and RX on Nano, connects to Tx on ESP

@Juraj no ground is connected. should it ????. connected to a NodeMCU

@Juraj - please explain what to clarify

You can't connect the same Serial to a computer over USB and to a Nano at the same time. Not only because the Nano is on 5 V which disturbs the 3.3 V side of the USB converter.
Disconnect the NodeMCU from computer, try to power it from Nano's 3.3 V pin (not for WiFI) and don't forget to connect ground between the MCUs.
Nano has one Serial, which is connected over USB to computer too. So there too you can't use the USB and RX TX pins at the same time. You could use SoftwareSerial to connect to NodeMCU.
The Nano TX to esp8266 RX should have logic level conversion to not to send 5V to esp8266 3.3V pin.


text:
Instances of a class inside another class - is there a way to control the amount?
I have a class with 12 instances of a button, to create a keypad( meaning that this is the only case I use 12 instances). But this class can be just a button array of any other number between 1-12. I'm looking for a way to minimize class overhead of 12 instances, when I most of the time use much less.
'.h' file:
class buttonArrayTFT
{
public:
  buttonArrayTFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft);
  void create_array(uint8_t R, uint8_t C, char *but_txt[]);
  uint8_t checkPress(TS_Point &p);

public:

protected:
  ButtonTFT _button0;
  ButtonTFT *_buttons[12] = {&_button0, &_button1, &_button2, &_button3,
                             &_button4, &_button5, &_button6, &_button7,
                             &_button8, &_button9, &_button10, &_button11};
private:
  ButtonTFT _button1;
  ButtonTFT _button2;
  ButtonTFT _button3;
  ButtonTFT _button4;
  ButtonTFT _button5;
  ButtonTFT _button6;
  ButtonTFT _button7;
  ButtonTFT _button8;
  ButtonTFT _button9;
  ButtonTFT _button10;
  ButtonTFT _button11;

private:
  uint8_t _num_items = 0;
};

http://www.cplusplus.com/doc/oldtutorial/templates/

@Majenko Can you please point?

As pointed out in a comment on your original question, a template is likely the best solution.
Templates allow you to write highly flexible code. I won't explain why; that's something that goes a little beyond the actual question. However, the following will show that you can create a template that means you can create a buttonArrayTFT class with N number of buttonTFT elements, so long as N is known at compile time. The link given as  a comment talks describes various aspects of templates but does not necessarily explain how to string it all together.
From the section Non-type parameters for templates, you will see that you can specify an integer as a parameter for creating N elements of an array member variable.
But what about the type parameter, T? You can simply omit it. You don't actually have to create a template for a type.
In your .h file:
template <uint8_t ARRAY_SIZE>
class buttonArrayTFT
{
public:
// One thing to remember about templates: you have to pack the definition
// into the header file with the declaration to avoid all manner of headaches.

    buttonArrayTFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft)
    {
    // Perhaps this is a good opportunity to check that the specified
    // size of the array is sensible, i.e. not zero and no more than 12.
        if ((ARRAY_SIZE == 0) || (ARRAY_SIZE > 12))
        {
            // decide how you want to handle this problem
        }
            // Add the rest of your constructor here
    }

    void create_array(uint8_t R, uint8_t C, char *but_txt[]);
    uint8_t checkPress(TS_Point &p);

    // This little piece of magic allows you to access buttonTFT 'x' of the
    // private _buttonArray as if a buttonArrayTFT class was an array
    buttonTFT &operator[](uint8_t index)
    {
    // Check that 'index' is a valid element in the array
        if (index > _num_items)
        {
            // decide how you want to handle this problem
        }
        return _buttonArray[index];
    }
private:
    buttonTFT _buttonArray [ARRAY_SIZE];
    // I recommend making this constant
    const uint8_t _num_items = ARRAY_SIZE;
};

I shall leave it up to you to sort out your privates, publics and protecteds, and I have left out ButtonTFT _button0; to keep you on your toes.
You'll also notice that the array is private, as before, but there is now no array-of-pointers-to-buttons. This is because there is no need; the magic buttonTFT &operator[](int index) allows you to access array elements directly.
In your .ino file, or as appropriate, you use the following code to create and then wield the class:
buttonArrayTFT<4> myFourButtonArray(/* constructor arguments as required*/);
buttonArrayTFT<12> myTwelveButtonArray(/* constructor arguments as required*/);

This gives you two instances of the class, with the respective number of buttonTFT elements! You can now access specific buttons using the following code:
myFourButtonArray[0];    // Returns a reference to the first buttonTFT
myTwelveButtonArray[10]; // Returns a reference to the eleventh buttonTFT
myFourButtonArray[n]     // Returns a reference to the 'n+1'th buttonTFT

On the assumption that the buttonTFT class has some kind of 'read' function that returns a TRUE or FALSE for the status of the button, you can write:
if (myFourButtonArray[0].read())
{
    // executed if the button is ON
}
else
{
    // executed if the button is OFF
}

A NOTE ON CONST-NESS:
The overloading of operator[], while wonderfully magic, is open to abuse. However, this is no different from your original code. The array of buttonTFT elements is private but there is public access to all the buttons almost as if the array was not private. In the case of your original code, one could write:
myButtonArray._buttons[0] = myButtonArray._buttons[1];

Now _buttons[0] points to the same buttonTFT as _buttons[1].
Ouch. Now myButtonArray._buttons[0]->read() is literally the same thing as myButtonArray._buttons[1]->read().
That said, my code does not make it a great deal better; the equivalent code:
myFourButtonArray[0] = myFourButtonArray[1];

Simply copies the right hand side over to the left hand side. You still have two distinct buttonTFT instances, with probably no memory leaks, but I am guessing that buttonTFT class may contain a reference to an Input pin, so the _button[0] pin will now be whatever _button[1] pin is because the member variable that stores the pin reference will be overwritten.
To solve this weakness, simply add the const qualifier to the beginning of the operator[] overload:
const buttonTFT &operator[](uint8_t index)
{ // };

Now the buttonTFT element cannot be altered. This of course brings in a new headache that all functions that rely on myArray[n] also need to be constant. It is up to you to determine how constant correctness should be interpreted and whether it is worth the hassle.

Well- so much information to learn :)) firstly - thank you very much for a concise answer. Some clarifications are needed (and perhaps some more will follow ). 1) I didn't know that .h file can get 'if' statements and not only headers. 2) you wrote return theArray[index] what parameter is theArray ? 3) the use of &operator - can you please explain how does it work ? 4) can you noe how the .cpp file will look like

theArray was likely meant to refer to _buttonArray member (rather than parameter).

I wrote the code example with my own member names and missed one of them when I was changing them to match yours. Answer has been edited.

@Guy.D (1) Yes, you can write whatever you want in a .h file, providing it is genuine C++ code of course. When it comes to templates, you cannot easily split the definition and the declaration into separate files because of the way the the compilation works. Google has plenty of articles on the topic. (2) My apologies, that was left over from when I wrote the example and couldn't remember what you had called your members.

@Guy.D (3) The '&' actually belongs to the buttonTFT type specifier, but convention dictates that it is written this way. The symbol means that the function returns a reference. The concept of Operators might confuse matters, so have a read about them in this article (4) I cannot show you how the .cpp file looks as I do not know what is in it! I can tell you that any code relating to the templated class belongs in the .h file, everything else goes in the .cpp file.

int x = 7; int& y = x, z = x; y is a reference to an int that been bound to x; essentially a new name for x. z is just an int (not a reference) and is just copy-initialized with x's value. So really, the & goes with the declared thing.  Same thing with pointers, int* u, v; u is a pointer to int; v is just an int.  For whatever reason most C++ users (not me) want to write the declarator next to the base type, even though that's not what it's connected to syntactically.  I guess they just want to pretend the language works differently from how it actually does.

@CharlieHanson I understand what & refers to, and that wasn't the actual question (perhaps lack of my English skills), what is the actuall use of operator member. Now, I wrote my class as you & majenko explained, but I got errors when I coded it back inside a library (.h and .cpp). Can you please point that out ?

@Guy.D An 'operator' is something that does operations on something else. Think of the simple code int x = 1 + 2. The '+' is the operator, and the compiler knows that int + int is the simple mathmatical sum. But what about myType t = &foo + &bar ? The compiler does not know how to 'add' one myType to another so you have to overload the operator and write the code that is to be executed. In order to remove confusion, the '+' is referred to as operator+. All operators, like -, '&&, (), etc. are similarly referred to as operator-, operator&&, operator().

@CharlieHanson and that way when using [] it returns a pointer the button's instance?

@Guy.D It will return whatever type you declare the operator function to return. In this case, you want operator[] to return a reference to a buttonTFT, not a reference to a buttonArrayTFT because that doesn't make any sense. You also don't want it to return a pointer because _buttonArray is an array of buttonTFT, not buttonTFT*. Also, as I explained in my answer, *(buttonTFT[x]) = (*buttonTFT[y]) will leave you with the left hand pointer pointing to the right hand pointer, but only for the duration of that line of code, so in theory nothing would actually happen.

You can use a template class to provide compile time parameters to your class to tune it. This is most often used in the context of providing a type for the class to operate on. However it's not limited to that. It's also often used to provide a storage size or other similar constant to the class.
They kind of work like preprocessor macros. You specify a token in the class and then give that token a value when you instantiate an object. That token can then be used all over the place in your class.
In your case you can provide the number of elements in your array of buttons as a template variable, for example (note: untested):
template <int N> class buttonArrayTFT {
    protected:
        ButtonTFT _buttons[N];
    public:
        void doSomething();
};

template <int N> void buttonArrayTFT::doSomething() {
    for (int i = 0; i < N; i++) {
        _buttons[i].doSomethingOnAButton();
    }
}

Of course you have to treat your objects a little differently since you can't make an array of pointers to predefined objects any more. Instead just a simple array of objects should be enough.
You then instantiate your class passing the number of elements you want:
// Array of 12 buttons
buttonArrayTFT<12> myButtons;
// and do something
myButtons.doSomething();

Does 'ButtonTFT _buttons[N]' replace the entire definition? in my code I use a pointer array to N instances, so it seems lacking something (or my understanding)

I wrote the class not inside a library, and all was well. BUT, when I write it inside my lib file, I get errors. How should it be noted that way ?

@Guy.D What errors are you getting?

Please see my answer below

@Guy.D Because the template is created at compile time you can't create a separate TU with it in - it effectively has to be 100% inline. It will only work in the header file.

There are more options to solve your question.

To use a template as recommended in the other answers is a fancy option, but if you use a template multiple times, it creates a real class for every template value and you will see it on used flash size.

The best option in my opinion is to provide the array to the class over a constructor. Create a global array of buttons and hand it over to buttonArrayTFT object over a constructor.
const uint8_t BUTTON_COUNT = 12;
ButtonTFT buttons[BUTTON_COUNT];
ButtonArrayTFT buttonArrayTFT(buttons, BUTTON_COUNT);

The ButtonArrayTFT class (simplified) would be like:
class ButtonArrayTFT {
private:
  ButtonTFT *buttons;
  uint8_t count;
public:
  ButtonArrayTFT(ButtonTFT *_buttons, uint8_t _count) {
    buttons = _buttons;
    count = _count;
  }

Other option is to use dynamic allocation on heap. If you would create a ButtonArrayTFT object only once at start and never delete it it would not cause heap fragmentation.
class ButtonArrayTFT {
private:
  ButtonTFT *buttons;
  uint8_t count;
public:
  ButtonArrayTFT(uint8_t _count) {
    count = _count;
    buttons = new ButtonTFT[count];
  }

I'm trying to "digest" all new things in one question (polymorphism,inline,&operator,template ...ahhhhhhh). I'll try understand the way you suggested in a while :) TNX!

The global approach is a good option if you don't mind having direct access to the buttons from anywhere within the code. Hiding them within a class reminds 'future me', and anyone else who inherits the code, that they're hidden for a reason. No idea what the reason is but it prevents unwanted fiddling. The dynamic allocation would benefit from a memory tracker; a static variable that increases by count * sizeof(button) in the constructor, plus maybe a static_assert, will prevent hitting a memory wall.

And +1 for the line about creating one complete class for each distinct number of buttons. I hadn't considered that if the same technique is used on numerous GUI elements the program space could soon evaporate.

I want to share my final updated library (thanks to answers by Majenko&Charlie), perhaps it'll help others.
.h file
template <uint8_t N>
class buttonArray_TFT
{
public:
  int8_t dx = 5;         /* define spacing between buttons */
  int8_t dy = 5;         /* define spacing between buttons */
  uint8_t scale_f = 100; /* change the cale of array. 100% take entire screen */
  uint8_t shift_y = 255; /* Shifts in y director*/
  uint8_t shift_x = 255; /* Shifts in x director*/
  int shrink_shift = 0;  /* shrink array in pixels, and shifts up/ down (+/-) */

  uint8_t &a = butarray[0].a;
  uint8_t &b = butarray[0].b;
  uint8_t &txt_size = butarray[0].txt_size;
  uint16_t &txt_color = butarray[0].txt_color;
  uint16_t &border_color = butarray[0].border_color;
  uint16_t &face_color = butarray[0].face_color;
  bool &roundRect = butarray[0].roundRect;

protected:
  ButtonTFT butarray[N];

public:
  buttonArray_TFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft);
  void create_array(uint8_t R, uint8_t C, char *but_txt[]);
  uint8_t checkPress(TS_Point &p);
};

and more in :
.h file :
template <uint8_t N>
buttonArray_TFT<N>::buttonArray_TFT(XPT2046_Touchscreen &_ts, Adafruit_ILI9341 &_tft)
{
  for (int i = 0; i < N; i++)
  {
    butarray[i].TS[0] = &ts;
    butarray[i].TFT[0] = &tft;
  }
}

template <uint8_t N>
void buttonArray_TFT<N>::create_array(uint8_t R, uint8_t C, char *but_txt[])
{
\\ Code
}

template <uint8_t N>
uint8_t buttonArray_TFT<N>::checkPress(TS_Point &p)
{
  for (uint8_t i = 0; i < N; i++)
  {
    if (butarray[i].checkPress(p))
    {
      return i;
    }
  }
  return 99;
}

You cannot split the code into two files. EVERYTHING for the buttonTFT class must be in the .h file, as both Majenko and I have said. I know it goes against all convention that you have otherwise been taught but templates are the exception to the rule.

@CharlieHanson - Thanks. I'll correct my answer. Appreciate explanaiton about operator