text:
Reading contents of ESP8266 Flash from inside sketch
I am aware that there is a way to create a dump of the flash via esptool, but is there a way to read the contents of the sketch (just the sketch, not the full flash or SPIFFS) memory via the sketch itself? As in, have a program on the ESP8266 able to read its own machine code from the flash to do something with? I do not need write access, just read access.
I would like to be able to create a backup of the current sketch in SPIFFS so that it is possible to revert a bad sketch so long as the reversion trigger isn't broken. (For example, if a later part of the boot process is messed up, or if a function acts slightly wrong, a button could be held, and it would restore from the saved image. The restore process is something that I've figured out from my previous question, but I would like a way to write the sketch to SPIFFS that does not require a separate manual upload or a wrapper around the OTA process.)
[edit:]
Thank you for the comments.
I have created this code that SHOULD have copied the sketch to SPIFFS. However, it does not seem to have done so properly (since the result does not have the same checksums as the original file, and attempts to write it yield a nonfunctional device). Can I have someone look over it and see if they can figure out why?
unsigned long addr = 0;
unsigned long rem = ESP.getSketchSize();
uint32_t *data = new uint32_t[SPI_FLASH_SEC_SIZE];
File f = SPIFFS.open("/fw.bin", "w");
while (rem > 0) {
  ESP.flashRead(addr, data, SPI_FLASH_SEC_SIZE);
  int sz = SPI_FLASH_SEC_SIZE * sizeof(uint32_t);
  if (rem < sz)
    sz = rem;
  f.write(reinterpret_cast<uint8_t *>(&data[addr]), sz);
  addr += SPI_FLASH_SEC_SIZE;
  rem -= sz;
  yield();
  Serial.println(rem);
}
f.flush();
f.close();

I started looking into this after your previous question (because it's something I think would be useful for me as well) - if you look at how EEPROM is done, you'll see it uses spi_flash_read -which is defined in tools/sdk/include/spi_flash.h - now I think the firmware would be loaded starting at address 0 - and perhaps this python code (obviously converted to c++) may help in determining the exact size of the loaded firmware

actually, ... there's ESP.getSketchSize() to get the size of the sketch :p - so, in theory, it's just a matter of using spi_flash_read to read the sketch (in chunks, obviously, since the sketch is larger than RAM) and write it out to SPIFFS

I can't seem to get that to work. I've posted the code I wrote in the question now, but something is not working. I get a file with different contents, though it IS the right size.

what would be nice is if you could read it to see what's there - the unit32_t looks wrong for a start, your data would be 4 x SPI_FLASH_SEC_SIZE

I can understand that flash reading may be done with 32bits at a time, but not sure if the address is being manipulated correctly ... perhaps addr += SPI_FLASH_SEC_SIZE * 4;?

I also think that you are only getting SPI_FLASH_SEC_SIZE bytes, rather than dword's (32 bits) ... so you'd be writing a fair amount of junk - again, not sure, the documentation is vague at best

I think you're reading of flash is slightly wrong
while ESP.flashRead takes a unit32_t pointer for output data, the read "count" argument is in bytes - looking at Updater.cpp code it does this
uint8_t buff[128];
for(int i = 0; i < binSize; i += sizeof(buff)) {
  ESP.flashRead(_startAddress + i, (uint32_t *)buff, sizeof(buff));
  .....
}

so, the the address and count are in bytes - given that SPI_FLASH_SEC_SIZE is 0x1000 or 4096, your code is doing the following

reading 4096 bytes into a 16384 buffer
writing 16384 bytes (so the last 12288 bytes are zero, or random, not sure)
adding 4096 to the address
subtracting 16384 from size
repeat until all read

So, the written size will be correct, but the data will be three quarters wrong :p
Therefore, your code should be
unsigned long addr = 0;
unsigned long rem = ESP.getSketchSize();
uint8_t *data = new uint8_t[SPI_FLASH_SEC_SIZE];
int sz = SPI_FLASH_SEC_SIZE;
File f = SPIFFS.open("/fw.bin", "w");

while (rem > 0) {
    ESP.flashRead(addr, (uint32_t *)data, SPI_FLASH_SEC_SIZE);
    if (rem < sz)
        sz = rem;
    f.write(data, sz);
    addr += SPI_FLASH_SEC_SIZE;
    rem -= sz;
    yield();
    Serial.println(rem);
}

f.flush();
f.close();

That seems to have worked very well. Thank you. I will note that as written, it causes a compile error since f.write does not accept uint32_t.
I still cast the data for flash read, but defined 'data' as a uint8_t instead.

Oops I missed a unt32


text:
Parsing Integers from Serial data stream
I'm trying to send sensor data from my Remote Control to my Bot via Bluetooth.
It's 6 numbers that I would like to have read as integers on the other side.
I'm printing them to Serial on the Remote side with the numbers separated by commas. I've also added a start marker "<" and an end marker ">".
The incoming data from the remote looks like this in the Bots Serial Monitor:
<1,1,1,1,1,512>
<1,1,1,1,1,512>
<1,1,1,1,1,513>
<1,1,1,1,1,512>
<1,1,1,1,1,512>
etc
Before adding in the markers I was trying to use Serial.parseInt() to do this, but I kpet getting out of order numbers (probably from no start marker?).
if (Serial1.available() > 0) {

 trig1 = Serial.parseInt();
 trig2 = Serial.parseInt();
 trig3 = Serial.parseInt();
 trig4 = Serial.parseInt();
 trig5 = Serial.parseInt();
 pot = Serial.parseInt();

if (Serial.read() == '\n') {
}
}

But now that I have the markers I don't know the best way to initialize the code.  Anyone have any ideas on how to parse these 6 numbers into usable integers?
EDIT:  I've wrote a code based on VE7JRO's comments.
uint16_t myArray[6] = {};
int counter = 0;

void setup(){

Serial.begin(9600);

}

void loop(){
  if (Serial.available() > 0) {
  char* pch = strtok(Serial.read,"<>,\r\n");
   }
while(pch != NULL){
  myArray[counter] = atoi(pch);
  pch = strtok(NULL, "<>,\r\n");
  counter += 1;
 }

 trig1 = myArray[0];
 trig2 = myArray[1];
 trig3 = myArray[2];
 trig4 = myArray[3];
 trig5 = myArray[4];
 pot   = myArray[5];

 Serial.print (trig1);
 Serial.print (", ");
 Serial.print (trig2);
 Serial.print (", ");
 Serial.print (trig3);
 Serial.print (", ");
 Serial.print (trig4);
 Serial.print (", ");
 Serial.print (trig5);
 Serial.print (", ");
 Serial.println(pot);
 }

I'm getting this error code: invalid use of non-static member function
for this line:
      char* pch = strtok(Serial.read,"<>,\r\n");

Other than that. I subbed out the test input that  VE7JRO put in and inserted "Serial.read". Not sure if that is the correct way to do this.  Any ideas?
I tried your second sketch.  It kind of worked.  The data that printed to the serial monitor looked like this:
1, 1, 1, 1, 1, 519
518, 1, 1, 1, 1, 519
1, 1, 1, 1, 19, 9
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 519, 518, 1, 518
1, 1, 519, 518, 1, 518
1, 1, 518, 518, 1, 518
1, 1, 1, 1, 1, 8
1, 1, 1, 1, 1, 519
1, 1, 518, 1, 1, 1
8, 1, 518, 1, 1, 1
1, 1, 519, 1, 1, 1
1, 1, 1, 519, 1, 1
1, 1, 1, 519, 1, 1
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 519, 8
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 520
it should have all been   1, 1, 1, 1, 1, 518(ish).

The parseInt has a timeout. That can slow down a sketch. You could fill a buffer with data (one byte each time) and when all the data is read then do a sscanf. For parseInt you have to skip the comma. The "<" and ">" markers is very good. Please give a minimal sketch that reads data from the serial monitor so we can test it.

Here is a sketch that uses strtok() and atoi() to parse the data and store the results in an integer array.
char testInput[] = "<1,2,3,4,5,512>\r\n";
uint16_t myArray[6] = {};

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(testInput,"<>,\r\n");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "<>,\r\n");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }

}

void loop(){}

EDIT
Based on your comments, I have another sketch for you to try.
// Sample input: <1,2,3,4,5,512>
char testInput[40];
uint16_t myArray[6] = {};
int counter = 0;

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

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', testInput, 40);

    char* pch = strtok(testInput,"<>,\r\n");

    while(pch != NULL){
      myArray[counter] = atoi(pch);
      pch = strtok(NULL, "<>,\r\n");
      counter += 1;
    }

    Serial.print (myArray[0]);
    Serial.print (", ");
    Serial.print (myArray[1]);
    Serial.print (", ");
    Serial.print (myArray[2]);
    Serial.print (", ");
    Serial.print (myArray[3]);
    Serial.print (", ");
    Serial.print (myArray[4]);
    Serial.print (", ");
    Serial.println(myArray[5]);

    counter = 0;
  }
}

This is very helpful!  I think I understand most of it.
Does this really all run in the setup?
I don't want to print the array, but rather use each int as a variable in the rest of my sketch.  Is there a function to use for that?   Sorry I'm a bit of a beginner and just barely grasping this as a whole

All the code is in setup() for testing purposes. The integer array contains the 6 integers and can be used as variables in the rest of your sketch. Every time you receive new data, it should be parsed using strtok().

So would this give me the variables from the the array?
trig1 = myArray[1];
trig2 = myArray[2];
trig3 = myArray[3];
trig4 = myArray[4];
trig5 = myArray[5];
pot = myArray[6];
I can't test right now otherwise I would just test myself.  Excited to find the answer!

Yes, you could do that, or just use the array directly e.g. if(myArray[0] > 1){ //do something}.

Thank you so much, this was very helpful!

I edited the OP with my code.  Getting an error on one of the lines

I edited the OP with the results of your second sketch. Mixed results.

Try sending a \n at the end of your data: "<1,1,1,1,1,512>\n"

source: Stack Exchange

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

sort: votes


text:
How do I start a task and have it run for a set amount of time?
I have a project where I need to turn a 24V solenoid on for a set amount of time, then have it turn off. I am rather new to Arduino and not certain how to do this or really where to start. Ideally the time would be displayed on a LCD screen as well but this is purely aesthetic. Any advice, help, examples ect would be appreciated. Thanks!

start with example sketches that blink an LED  ..... these can be found in the arduino IDE

The online example has explanation: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

Use millis();
Record millis() in a long variable like below when the solenoid starts
StartTime = millis();
to switch off solenoid after 60 seconds you may do
if ( (millis() - StartTime)/1000 ) >  60
{
   // switch off solenoid
}

enjoy coding.
There are other ways as well to achieve this... but this is being easiest  and you don't have to wait caused by using delay();

Division is a very expensive operation on many Arduinos. It is thus better to write if (millis() - StarTtime >= 60000).

Hmm.. Good to know that..
But would you explain what do you mean by "Expensive" does it draw more power?

The AVR MCUs do not have hardware support for division, which is thus done by software, bit by bit, and costs quite a lot of CPU cycles. Power consumption should not be affected, unless you care about it. If you do care, you most likely keep the CPU in sleep mode most of the time, and wake it up only when there is work to do. Then, all the cycles you burn doing non-essential operations keep the CPU awake for longer, and cost energy.

Hmm... ok . Thanks  for the information Edgar !!

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


text:
fail to pass a value in constructor
I'm making a JSON lib dedicated for my own needs, based on ArduinoJSON v6.
I try to define StaticJsonDocument<_docSize> doc in a parametric way but I get this error and I cant find the reason for it:
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp: In constructor 'myJSON::myJSON(char*, int, bool)':
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:28: sorry, unimplemented: use of the value of the object being constructed in a constant expression
         StaticJsonDocument<_docSize> doc;
                            ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: error: 'this' is not a constant expression
         StaticJsonDocument<_docSize> doc;
                                    ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: note: in template argument for type 'unsigned int'
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:41: error: invalid type in declaration before ';' token
         StaticJsonDocument<_docSize> doc;
                                         ^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

I paste only relevant part of the code
myJSON.h :
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
int _docSize=100;
bool useSerial;
char _filename[30];

public:
myJSON(char *filename, int docsize, bool useserial=false);
bool file_exists();//char *file=_filename);
bool file_remove();
bool format ();

};
#endif

myJSON.cpp:
#include "Arduino.h"
#include "myJSON.h"
#include "FS.h"
#include <ArduinoJson.h>

myJSON::myJSON(char *filename, int docsize, bool useserial) {

        _docSize = docsize;
        useSerial = useserial;

        StaticJsonDocument<_docSize> doc;

        if (useSerial) {
                Serial.begin(9600);
        }
        if (!SPIFFS.begin()) {
                if (useSerial) {
                        Serial.println("Failed to mount file system");
                }
        }
        else{
                sprintf(_filename,"%s",filename);
        }
}

A class that uses <...> is called a template class.  That class uses a form of substitution at compile time to create a concrete class with those values and tokens substituted.
It is then that concrete class that is used to instantiate your object(s).
However, you are trying to use a runtime variable to convert a template class into a concrete class, and that can't be done at compile time - and there is no such thing as a runtime template in C++.
You need to re-think your implementation methodology.

thank you for explaining.  My intention is to to be able to define size of JSON buffer- is there a way doing so the way I need it ?

I would suggest create the JSON object outside your class and pass that object to the constructor. Without knowing what ArduinoJSON does with the buffer and how it's instantiated I can't comment.

OK-  that it was a good enough workaround. TNX


text:
Arduino clients suddenly not able to connect (or publish) to MQTT
we are struggling with a project that has things (arduinos as clients) communicating to our MQTT broker (mosquitto) running on a DigitalOcean droplet (inside a docker). We have about 200 things at different locations sending about 20msg per minute each. Last week - after months without any issues - 20 clients suddenly were not able to connect to the server/publish anymore although they have been online. Today 4 other clients “went offline” the same second.
The latter 4 clients were fixed by simply restarting them. With the aforementioned 20 clients, we were able to test one (remotely) and we reflashed it (nothing changed with MQTT settings though) and it was then able to connect to the broker again...
First we thought it was a network issue but it all seems to be fine. Can you help us troubleshooting the issue? We run a DigitalOcean droplet for our mqtt server.

There’s not nearly enough information here to properly debug, but it sounds like a counter overflow to me. Things work fine for months, then an integer overflows, your code wasn’t prepared to deal with reading garbage, boom, dead in the water. Just a hunch.

Please post the code, versions of libraries and IDE used.


text:
'Var' does not name a type!
I don't have much experience in C++ programming. I'm getting this error
'z' does not name a type!!!
which I have't seen in MATLAB or python... What's wrong??? It is so simple!!!
float x=10; float y=50; float z;
z=x*y;

void setup() {
  // put your setup code here, to run once:
}

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

float z=x*y; will work

You cannot put an expression statement outside a function. Only the variable declarations can be placed outside functions (and those variables are called globals/global variables).
Try the following:
float x=10; float y=50; float z;

void setup() {
  // put your setup code here, to run once:
  z=x*y;
}

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

Update
What even is easier and also works (thanks to Ruslan and Juraj):
float x=10; float y=50; float z=x*y;

void setup() {
  // put your setup code here, to run once:
}

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

Thank you. pretty much basic thing that I didn't know about C++.

You can put an expression outside a function (e.g. float z=x*y; does have an expression x*y in it, and may appear in namespace scope). What you can't put there is an expression statement (or any other type of statements).

@Ruslan Thanks for the clarification; I added the word statement in my answer.

and float z=x*y;


text:
How to upload and store settings/variables from computer on the arduino?
I'm literally as green of a noob as I can be at this moment. Been watching a ton of tuts as I plan my project, but can't seem to find anything about settings being uploaded from an external source, and then stored on the arduino.
I want to create a board with multiple buttons. I want these buttons to then transmit MIDI PC/CC based on customizable settings uploaded via a computer. So, I'll create an app that can "create" the settings (json?) for each button. Ideally, I'd just connect the board, create the settings, then upload it to the device.
I've been reading about storing things like this in EEPROM, but that has a limited life span (which scares me). So, do I store these variables in EEPROM, or do I just compile and upload the app that has the new values in the variables?
I'm just looking for a possible direction and links for research.
Thanks in advance.

interesting project .... perhaps you can store the settings in a file on an SD card

Re “or do I just compile and upload the app”: that would store the settings with the app, in the flash memory, which has a shorter life span than the EEPROM.

wow!? a downvote for wanting guidance?

https://arduino.stackexchange.com/tour

Your question is quite broad, so I will give you some directions for the different parts.

Communication with the PC to receive settings: For the Arduino Uno you are basically left with the Serial (UART) interface to communicate with the PC. For wired communication you can simply use the USB port. On your PC you need a program to send the settings over the serial com port to the Arduino. You can either use any serial terminal program or you can write your own. That depends on your needs. On the Arduino you need code to parse the serial communication to get the settings. It seems, that your can be rather complex (not just simple numbers of the same type). So you should implement a basic message protocol. It is common to use the newline character (\n) as the delimiter at the end of a message. In your code you read the serial data into a buffer, until you read a newline character. Then you start to process the message in a whole. You can see the implementation of this protocol in the SerialEvent example that comes with the Arduino IDE. Then you can use JSON as text based data format to transmit it to the Arduino. There you can use the Arduino JSON library to decode the data and get the settings. If you don't want to use JSON, you can also use a simpler protocol.
Saving the received settings: Without any further hardware the EEPROM is the way to go. The "life span", that you mention, are the possible number of write cycles, until a cell is not longer garanteed to work correctly. Read cycles don't do any harm here. Atmel gives a number of 100.000 write cycles, but notice, that this is the minimum garanteed number. (Have a look at this question for further info) Do you really change the settings this often? Make a short calculation like this: Imagine that you want to change the settings 10 times a day on every day in the year. Even then you get about 27 years with the EEPROM write cycles, far enough for other components to break. But if you really want to go safe here, you can use wear leveling. With this technique you rotate through different EEPROM cells to save your settings. You use more space in EEPROM, but each individual cell will get only a fraction of the write load. There are even libraries ready to use for this. A quick google search gave me the EEPROMWearLevel library, though I haven't used it myself. Depending on the total size of your settings, you might get a life span multiple times bigger with this. If you still don't want to use EEPROM, you can do as jsotola wrote in his comment: You can by a SD card module for Arduino and a fitting SD card and save the data there. This will lead to more programming overhead, especially, if you want to use a file system to also be able to read and write the SD card on the PC. (Note: The storage chips in SD cards have the same problem with limited write cycles, so they have the wear leveling incorporated into the hardware of the card)

You might as well decide, that you don't need the settings to be persistent between resets. Then you can just use variables and fill them with the settings from the Serial interface code.
You yourself have to decide, what the best way to go is here.

Thank you for taking the time to answer my questions. I appreciate it.

If you consider my answer as correct/fitting, please accept it as correct :)

I think I'm going to go the route of saving to the EEPROM. Here goes nothing...


text:
Problem interfacing both esp8266 and EM18 with Arduino Uno
I have connected esp8266 with Arduino Uno and programmed 8266 with Arduino IDE to send data to firebase over WiFi. Now I also want to interface EM18 RFID Reader with Arduino in order to read the RFID tag and send information to firebase through esp8266. I have integrated the code for the same.
Now after uploading the code, only one of the interface works at a time, i.e if both esp8266 and EM18 are connected to Arduino, esp8266 connects to WiFi and sends data(verification data to check esp8366 is working) also, but not the data I want because EM18 is not reading the tag id. Having uploaded the same code if I remove connections with esp8266, the EM18 works fine(i.e. ID is printed in serial monitor after being read by EM18 Reader module).
Please help me with this, how can I send the information read by EM18 to esp8266 because they are not working together.
P.S. In my code there is different Rx Tx pin defined for esp8266(digital pin 0,1) and for EM18(digital pin 9,10(random)). Used softwareserial library for defining new Rx Tx.
My Connections:
Arduino and ESP8266
RX with RX;
TX with TX;
GND with GND;
3.3V with VCC;
3.3v with CH_PD;
GND with GPIO0(To Flash ESP8266);
Arduino's Reset pin is connected to Ground
Arduino and EM18 RFID Module
5v wuth VCC;
GND with GND;
Pin 13(Set as Rx) with TX;
My Code:
#include <BearSSLHelpers.h>
#include <CertStoreBearSSL.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiClientSecureAxTLS.h>
#include <WiFiClientSecureBearSSL.h>
#include <WiFiServer.h>
#include <WiFiServerSecure.h>
#include <WiFiServerSecureAxTLS.h>
#include <WiFiServerSecureBearSSL.h>
#include <WiFiUdp.h>

#include <Firebase.h>
#include <FirebaseArduino.h>
#include <FirebaseCloudMessaging.h>
#include <FirebaseError.h>
#include <FirebaseHttpClient.h>
#include <FirebaseObject.h>

#include <ArduinoJson.h>

#include <SoftwareSerial.h>
//firebase and wifi
#define FIREBASE_HOST "my-shopping-d.firebaseio.com"
#define FIREBASE_AUTH "rkyF4AuzssSIO5VYRO6iP"
#define WIFI_SSID "****"
#define WIFI_PASSWORD "****"

const int disp=9;
//int j;
int tx=10,rx=13;
SoftwareSerial emSerial(rx,tx);  //EM18 Rx,Tx
int buttonState2 = 0;
int count = 0;                                          // count = 0
char input[12];                                         // character array of size 12
int count_arr[5]={0,0,0,0,0};
int i,cnt,total=0;
int price[5]={295,20,50,500,15};
char id_arr[6]={'2','F','7','E','3'};
char *myStrings1[] = {"Rice Rs.295", "Oreo Rs.20", "Silk Rs.50",
                     "Ghee Rs.500", "Nestle Rs.15", "TOTAL : "
                    };
char *myStrings2[] = {"Removed Rice Rs.295", "Removed Oreo Rs.20", "Removed Silk Rs.50",
                     "Removed Ghee Rs.500", "Removed Nestle Rs.15", "TOTAL : "
                    };

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

   //connect to wi-fi
   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);

   pinMode(disp,INPUT);
}
 Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Serial.println("Firebase Connected");
}

int n = 0;

void loop()
{

   if(emSerial.available())
   {
    Serial.println("Card reader");
      count=0;
      while(emSerial.available() && count < 12)          // Read 12 characters and store them in input array
      {
         input[count] = emSerial.read();
         count++;
         delay(5);
      }
      Serial.print("id inpiut");
      Serial.println(input);
      for(i=0;i<5;i++)
      {
        if(input[10] == id_arr[i])
        {
          cnt=i;
          break;
        }
      }

      if(count_arr[cnt] == 0)
      {
        total=total+price[cnt];
        Serial.println(myStrings1[cnt]);
        Serial.print("TOTAL : ");
        Serial.println(total);
        count_arr[cnt]=1;
      }
      else if(count_arr[cnt] == 1)
      {
        total=total-price[cnt];
        Serial.println(myStrings2[cnt]);
        Serial.print("TOTAL : ");
        Serial.println(total);
        count_arr[cnt]=0;
      }

   }
      buttonState2 = digitalRead(disp);   // read the state of the pushbutton value:

      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if (buttonState2 == HIGH)
      {

        j=1;
        for(i=0;i<5;i++)
        {
          if(count_arr[i]==1)
          {

            Firebase.setString("Items in Cart: ", myStrings1[i]);
             // handle error
            if (Firebase.failed())
            {
               Serial.print("setting /message failed:");
               Serial.println(Firebase.error());
               return;
            }
            delay(1000);
            String name = Firebase.pushInt("Total: ",total);
             // handle error
            if (Firebase.failed())
            {
                Serial.print("pushing /logs failed:");
                Serial.println(Firebase.error());
                return;
             }
            //j++;
          }
          delay(2000);

        }
      }
      int test = 5;
  String name = Firebase.pushInt("cart",test);
  // handle error
  if (Firebase.failed()) {
      Serial.print("pushing /logs failed:");
      Serial.println(Firebase.error());
      return;
  }
  Serial.print("pushed: /cart/");
}

You can only reliably (for given values of "reliably") use one SoftwareSerial at a time.

I have added connections and code, plz see and reply :)

Do you have the EM18 wired to the Arduino's pins 10 and 13, or the ESP8266's pins 10 and 13?

Em18 is wired with pin 13, i do not need tx pin for em18(only one way communication), and esp8266 is connected with default tx rx pins of arduino

Which pin 13? ESP8266 pin 13, or Arduino pin 13?

Arduino pin 13 set as Rx using softwareserial

So... you run code on the ESP8266, and expect it to somehow be able to make the Arduino's pin 13 do something...?

Haha, it's running though, because after uploading the code in esp8266(when both esp and EM18 are connected to Arduino) if I remove connections of esp8266 from Arduino then the EM18 reads the RFID tag and prints it on serial monitor.

Then you must have some code installed into the Arduino that does that.


text:
Using an Android bluetooth terminal to change preset states on 8x8 LED matrixes
I'm trying to create eyes for a project, and while I have been able to properly program the different expressions, and have them triggered by commands from the COM3 terminal, I have not been able to make any commands from the Bluetooth Terminal on my phone work.
Details:
Mega2560
2x 8x8 LED Displays - MAX7219
HC-05 Bluetooth Transceiver - default Baud - 9600
Using LEDControl.h, SoftwareSerial.h
This is the loop on my device, when I type the commands A, B, etc. into the COM3 terminal it works just fine, but the same commands on the phone are just interpreted as ASCII, even when I put parentheses around them.
void loop()
{
  // Feed any data from bluetooth to Terminal.
  if (EEBlue.available()){
  Serial.write(EEBlue.read());
  }
  if (Serial.available())  //verifies if there is serial data available
  {
    char cmd = Serial.read();

    if(cmd == 'A') {
      display_eyes(eye_neutral_l, eye_neutral_r);
    }
    if(cmd == 'B') {
      display_eyes(eye_shock_l, eye_shock_r);
    }
    if(cmd == 'C') {
      display_eyes(eye_love_l, eye_love_r);
    }
    if(cmd == 'D') {
      display_eyes(eye_suspicious_l, eye_suspicious_r);
    }
    if(cmd == 'E') {
      display_eyes(eye_happy_l, eye_happy_r);
    }
    if(cmd == 'F') {
      display_eyes(eye_hurt_l, eye_hurt_r);
    }
    if(cmd == '1') {
      display_eyes(eye_mad_l, eye_mad_r);
    }
  // Feed all data from termial to bluetooth
  EEBlue.write(Serial.read());
  }
}

The serial data, that you use in your Arduino program, is checked against ASCII values, so you actually really need to send ASCII. What exactly to you mean by "are interpreted as ASCII" on the phone? What terminal program do you use on the phone? And what data output do you get on the PC terminal, when you send data over bluetooth? You are echoing it there, so you should be able to see, what is actually received on the Arduino.

Oh, I just saw, that you only react to command with eye expressions, when there is something on Serial, which as I assume is connected to the PC. When there is data on the EEBlue interface, you just echoing it to Serial, but you don't process it.

So do I need to add something like char cmd = EEBlue.read(); ?

Your problem is, that you read from the EEBlue serial interface, but you are just echoing it over Serial and don't do anything with it. The display code is only executed, when the commands come through Serial.
The simplest way is to copy the code in the if(Serial.available()) statement into the if(EEBlue.available()) statement and changing the read to use EEBlue. Of course you should delete the existing EEBlue.read() from this statement.
But that way would mean to have double the code to maintain. It is cleaner to first read data from either serial interface and then process it. Something like this:
if(Serial.available()){
    cmd = Serial.read();
} else if(EEBlue.available()){
    cmd = EEBlue.read();
}

// insert the code to check the cmd variable for the expected values and act accordingly

cmd = 0; // Resetting the cmd to prevent multiple executions of one command


text:
A1-A5 pins not declared in this scope error
When I set my board to 'Generic ESP8266 module'  then only A0 pin of arduino is working while all other analog  pins are coming out of scope ,
 when I set the board to 'arduino /genuino uno' ,
 then "Error compiling for board Arduino/Genuino Uno." this error is coming how to set the board such that all analog pins with ESP8266 will work?

To my knowledge the ESP8266 only has 1 analog input pin, so the others being out of scope is completely correct, because they just don't exist on this board

and for what board do you want to compile and upload?

If you look at the ESP8266 pinout diagram (for example here), you will only find 1 analog input: A0. This is because the ESP8266 simply just has 1 analog input. The Arduino IDE states A1-A5 being out of scope, because on that board these inputs just don't exist. That is completely correct.
Also: When you try to compile code, that is meant for an ESP, for the Arduino Uno board, it will naturally fail, because it is just different hardware. The ESP basis code just cannot run on the Uno.
You will have to compile the code for the board, that you actually want to use AND you can only use codes/libraries, that are meant for your board. You cannot mix them in general. Only some function might be transferable (if so, it will not be easy) and WiFi is definitely not something to transfer to the Uno, which doesn't have the hardware for it.

thanks for your help, is there any way i can use two analog pins on arduino and use wifi and connect to internet as well

You can try to multiplex the one analog pin, by connecting only 1 analog signal at a time to the input (for example switched through a MOSFET by a GPIO pin). You then have to activate that input signal through the code, perform a measurment with the ADC, switch to the second input signal and perform a measurement there too. Depending on what you want to connect to the analog pin, it may also be possible to just power one of the sensors at a time.

Or you can instead use an ESP32, which seems to have 2 individual ADCs which many usable pins each.

use two analog pins on arduino you were just told the ESP8266 only has one


text:
How to send message to multiple number using arduino and SIM900A mini v3.8.2?
I am using this code to send message using Arduino Uno & SIM900A mini v3.8.2 module. But I need to send same message on multiple numbers.
#include <SoftwareSerial.h>
SoftwareSerial SIM900A(10,11);
void setup()
{
  SIM900A.begin(9600);
  Serial.begin(9600);
  Serial.println ("SIM900A Ready");
  delay(100);
  Serial.println ("Type s to send message or r to receive message");
}
void loop()
{
  if (Serial.available()>0)
   switch(Serial.read())
  {
    case 's':
      SendMessage();
      break;
    case 'r':
      RecieveMessage();
      break;
  }
 if (SIM900A.available()>0)
   Serial.write(SIM900A.read());
}
 void SendMessage()
{
  Serial.println ("Sending Message");
  SIM900A.println("AT+CMGF=1");
  delay(1000);
  Serial.println ("Set SMS Number");
  SIM900A.println("AT+CMGS=\"+639176363802\"\r");
  delay(1000);
  Serial.println ("Set SMS Content");
  SIM900A.println("Sample Message");
  delay(100);
  Serial.println ("Finish");
  SIM900A.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  Serial.println ("Message has been sent");
}
 void RecieveMessage()
{
  Serial.println ("SIM900A SMS");
  delay (1000);
  SIM900A.println("AT+CNMI=2,2,0,0,0");
  delay(1000);
  Serial.write ("Unread Message done");
 }

Thank you in advance

Pass the number as a parameter to SendMessage, and call the function multiple times. NB: Many providers will block messages that are sent too rapidly to prevent spamming.

I'm sorry but can you please elaborate it more because i can't understand it clearly. I'm new at using arduino. Thank you :)


text:
How to power Arduino nano and LED strip?
I am making a project that uses an Arduino nano and a sound detector module to power a 1m LED strip. I got the idea from this video and I am not sure how to power it. My LED strip flashes for a split second and turns off, and people say that the usb power source I am using is not enough power. I am worried though that if I use a more powerful power source that it will fry my Arduino. I am very new to this and I have no idea what to do.

How many LEDs on your strip? Is it an RGB, RGBW, or WS2812 strip?

it is WS2812 with 60 LEDs

When using a power source, which can provide more current with the same voltage, you cannot fry your Arduino with the change. The components will draw the current they need, not more. The rest is reserve and not a problem. You can only fry components, if you draw more current through them, as they are capable of. For example: You can fry your PCs USB port, if you draw too much power for lighting the LEDs. If you give power to too many LEDs through the Arduino (for example by using Vin for power and connecting the strip to 5V), the strip will draw too much power for the regulator and fry it.

Ok, so minimum current capacity you need is 60 * 0.02mA * 3, which is 3.6A. Plus some more to power the Arduino. You want a 4A power supply or better really.

That is for all LEDs on white and full brightness.

Ok, thanks. So if I use a 4A power source, can I connect it to the vin and then connect that to the 5v on the LED?

No. Use a 5V 4A power supply. Connect it to both the LED strip and the 5V of the Arduino.

ok, and I connect the gnd on the supply to the one on the LED strip and on the arduino, right?

Yep. Connect all grounds. https://majenko.co.uk/blog/importance-sharing-grounds

A simple solution would be to cut the LED strip to a shorter length (use fewer LED's).  If you avoid using full-on white you should be able to power 10 LED's from a standard USB port.

For the 5v4a power source, do you know where I could get the female part?

WS2812 can draw 60mA when on full white, x 60 LEDs = 3.6A.  If you have a 4 to 5A external 5V supply powering all the components, you'd be okay.  If you're trying to power the strip from the Nano 5V line thru its regulator, the regulator will overheat and shutdown.

You could use a relay and have a larger power supply that will light up the LED strip on the other side, after the relay gets the signal to turn on.

Is there any way I could do this without external hardware though? Apart from the sound detector, Arduino, led strip, some wires, and a usb cable,  I would prefer not to buy anything else, as I need this for a school project and it would take too long to ship.

@Ethangarret You could do it with just the battery and a transistor if you have those, otherwise probably not the arduino nano just can't supply the energy that is needed.

ok, thanks. Would it work if I power the led and Arduino separately?

Yes, and then you could use a switch to turn it on and off.

That is, if they are connected by that switch.

You don't need a relay or transistor here. The LEDs will only be turned on, if you tell them to do so over the data line. It needs just a strong enough power supply that is connected to the Arduino AND the LED strip directly (not through the Arduino). Over the data line the Arduino can then tell the LEDs to light up in the requested pattern.

@chrisl I was saying use a relay and transistor to turn it on and off. And what data line?

The OP stated in the comments, that he uses WS2812 LEDs. The WS2812 is actually the driver chip for every LED in the strip. And the LEDs in the strip actually consist of 3 LEDs in one case making them RGB. And the WS2812 chips are controlled via a single data pin. You can just write the value zero to every LED and the strip will be shut off. No need for a relay or transistor here.

But how would you right zero with the nano

The chips have their own protocol, but there are libraries like Adafruits Neopixel library or the FastLED library. There are tons of tutorials for that on the web, easily to find when you google WS2812 Arduino. You only need 1 pin for it. On setup you use the library function to initiate the strip with all LEDs off. I have build a room light with that myself.

@chrisl Oh that is interesting I’ll have to look into this sometime

@chrisl but the nano couldn’t supply the LEDs, but I see what you mean by no relay, I can’t believe I made that mistake, haha


text:
Arduino Uno - Variables randomly changing
So I have a circuit for a timer (I don't think it is the problem)

Sorry for it being a little messy.
And I have this code (probably the problem):
// LiquidCrystal - Version: Latest
#include <LiquidCrystal.h>

/*

*/

const int switchUnitButton = 9;
const int selectButton = 10;
const int startButton = 8;
const int stopButton = 7;
const int d4 = 5;
const int d5 = 4;
const int d6 = 3;
const int d7 = 2;
const int rs = 12;
const int en = 11;
String unit = "sec";
int unitCycle = 1;
int secCount = 0;
int minCount = 0;
int hourCount = 0;
int dayCount = 0;
int switchUnitState;
int prevUnitState;
int selectState;
int prevSelectState;
int startState;
int prevStartState;
int stopState;
int prevStopState;
LiquidCrystal lcd = LiquidCrystal(rs, en, d4, d5, d6, d7);

void setup() {
  Serial.begin(9600);
  pinMode(switchUnitButton, INPUT);
  pinMode(selectButton, INPUT);
  pinMode(startButton, INPUT);
  pinMode(stopButton, INPUT);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  switchUnitState = digitalRead(switchUnitButton);
  selectState = digitalRead(selectButton);
  startState = digitalRead(startButton);
  stopState = digitalRead(stopButton);

  if (switchUnitState == HIGH) {
    if (prevUnitState != switchUnitState) {
      if (unitCycle < 4) {
       unitCycle++;
      } else if (unitCycle == 4) {
       unitCycle = 1;
      }
    }
  }

  Serial.print(unitCycle + "\n");

  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

  lcd.setCursor(0, 0);
  lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));
  lcd.setCursor(0, 1);
  lcd.print("Hr: " + String(hourCount) + " Day: " + String(dayCount));

  prevUnitState = switchUnitState;
  prevSelectState = selectState;
  prevStartState = startState;
  prevStopState = stopState;
}

And sometimes without me clicking a button the unit value changes or sometimes when I click the selectButton for the amount to go up it changes which unit it is adding to. And sometimes the string has parts before it from other units like "inhour" what is happening?

Your second button is wired wrong - or is that just a "typo"?

Oh, and all that String abuse will cause untold problems. You don't need any of it.

So I should just use unitCycle for which unit rather than the changing string? And yes that button was a "typo";

I fixed that "typo"

There is never any call to change a string like that or use it as a state variable. Just print a different word depending on what the cycle is. And don't forget to use F() for your literals to save RAM.

@Majenko Alright I'll look into that, thanks

Seems you forgot to debounce the buttons.

You are seriously abusing the String class.  There is absolutely no need to use any Strings at all in your program.
For example:
  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

would be better written as:
  if (unitCycle == 1) {
    Serial.println(F("sec"));
  } else if (unitCycle == 2) {
    Serial.println(F("min"));
  } else if (unitCycle == 3) {
    Serial.println(F("hour"));
  } else {
    Serial.println(F("day"));
  }

And:
  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

as:
  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unitCycle == 1) {
        secCount++;
      } else if (unitCycle == 2) {
        minCount++;
      } else if (unitCycle == 3) {
        hourCount++;
      } else {
        dayCount++;
      }
    }
  }

And then the cardinal sin:
lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));

All that string creation, concatenation, and destruction is just evil.  Instead, use:
lcd.print(F("Sec: "));
lcd.print(secCount);
lcd.print(F(" Min: "));
lcd.print(minCount);

Haha, alright, thanks for your time, and help!

@BeastCoder2 You might want to read this: https://majenko.co.uk/blog/evils-arduino-strings

Alright I will, your website is really cool!

eyeroll... I had one wire in the wrong pin...


text:
Connecting (SD or HD) TV screen to Arduino
I had a thought about making myself an arcade cabinet. I found a nice cheap and sturdy 8 directional arcade joystick online, and now I'm thinking about the possible ways of displaying graphics.
I would like to know how can I send graphical data to a large screen using Arduino. When I was researching this I saw "TV Text" library that allows sending PAL and SECAM signals, but that's not the "modern" way. Is there a way of using DisplayPort or HDMI to simply use a cheap used PC monitor? Maybe there are other protocols that I can use? I'm looking for a "cheap" way to create a display that's physically as large as screen of arcades from "the good old days".

If you can find one (they're discontinued now, so you will only get a used one), you want one of the original Gameduino shields. Then you can use VGA.

Better would be to ditch the Arduino and use a Raspberry Pi with the RetroPi operating system image.

@Majenko I understand there are many "out of box" solutions that handle games, but I just want this project to be an excuse to gain the know-how to create high quality display with my hardware in the future. I'm looking for some way that doesn't require using retro hardware, and can be used in my future proijects.

https://www.gammon.com.au/forum/?id=11608 -> https://www.youtube.com/watch?v=dtfNhh6GZ-s

Also if you don't want to use ready-to-go solutions, ditch the Arduino. Especially with AVR based Arduinos you will never get something that can be in any way called "high quality" and when adding functionalities you will run very fast into pure physical limitations. Doing this with an AVR Arduino can be called masochistic.

I agree with the other posters that the Arduino just isn't up to the job. It doesn't have any native display hardware, and an AVR-based Arduino isn't up to the job of doing it through software. The Arduino is good at I/O. Use a PI if you want to drive a display.

I'm just going to post things that I found thanks to comment by Juraj.

"TV Text" library - PAL, SECAM, NTSC
"VGAX" library - VGA

And with large dedication to everyone who wrote that "it's impossible" I give you a blog post of someone who actually did create he's own NTSC console and a game from scratch (called "The Box") using ATmega328P with external 16Mhz crystal. And he did it in 2013.
http://petenpaja.blogspot.com/2013/11/toorums-quest-ii-retro-video-game.html
Original sources were deleted, but I think they can be found when looking for Toorum Quest 2
I think I'll try analyzing the VGAX. It looks promising.
EDIT:
There actually is HDMI shield for Arduino!
https://github.com/techtoys/HDMI-Shield/tree/master/Ra8876_Lite
And a nice and very easy VGA tutorial here:
http://www.pyroelectro.com/tutorials/arduino_basic_vga/

I tested TVout library once. It uses composite video signal. The demo has a rotating 3D wireframe cube. https://www.youtube.com/watch?v=ZT46khR2A3c

I think most of us stumbled across your phrase "high quality". The quality, that you can get from it is very limited. You won't get video quality that can hold up to the standards we are accustomed to from HDMI and Displayport. If this is sufficient, then of course it is possible.

@chrisl There actually is a solution that gives you "high quality" It just costs 50USD https://www.youtube.com/watch?v=MUeIY_gLn3c

That looks quite interesting. Good to know, that you can buy such a thing. Though it is worth mentioning that it doesn't seem to work with an Uno. My guess is, that AVR based boards will not work with it.


text:
Installing Arduino IDE in the new Ubuntu Disco Dingo
I tried installing the Arduino IDE in the newly released Ubuntu 19.04 Disco Dingo.
I downloaded the file from the official downloads page. I chmod +x ed the file and ran the install script. Then, it says:
Adding desktop shortcut, menu item and file associations for Arduino IDE...
rm: cannot remove '/usr/local/bin/arduino': No such file or directory
Removing symlink failed. Hope that's OK. If not then rerun as root with sudo.
touch: cannot touch '/root/.config/mimeapps.list': No such file or directory

/usr/bin/xdg-mime: 848: /usr/bin/xdg-mime: cannot create/root/.config/mimeapps.list.new:
Directory nonexistent`
Then, I again ran it as root user with su root but it still gave the same error...
Will this cause a problem..? I mean, I had prior issues related to uploading the sketch in earlier Linux IDE installations. Will this cause a problem...?
`

It is not required to run the installer. You may unpack it in a folder (under your $HOME folder, not a system folder) and make a shortcut (symbolic link) to the 'arduino' file. Put the shortcut on the desktop. Perhaps add yourself to the DIALOUT group and perhaps a permission has to be added when using a programmer to burn the bootloader.


text:
Programfault when dereferencing a 64bit int on due
I am running into a strange behaviour with my code. The following works without problems on an Arduino Nano but it seems to crash on a DUE
void putData64(byte* packet, int pos, uint64_t data)
{
    uint64_t* h= (uint64_t*) (packet+pos+2);
    *h= data;
}

the problematic line seems to be the second one (*h= data) as commenting it out lets the program run without problems.
Similar, the following lines cause a problem on a DUE but run fine on a Nano:
char* data;
// ... data is filled with something
uint64_t* t= (uint64_t*) (data+1);
uint64_t test= *t;

Is there something I am missing?

Probably a memory alignment problem.

What are you trying to do? If you want to use bytes and byte pointers, that is okay. If you want to use 64-bit and pointers to it, that is also okay. But you have mixed the two. Why would you want to point halfway to a 64-bit value. I suggest to start over.

I concur with Majenko's comment: it's probably a memory alignment
problem. I don't know the specifics of the Due, but when you access
memory in chunks of 32 bit data words on a 32 bit CPU, it can
happen that the architecture requires the data words to be aligned to
32 bit (i.e. 4 byte) boundaries. This means that the address
of an uint32_t or uint64_t should be a multiple of 4. Maybe
even 8 for a uint64_t, you will have to check.
The only solution to this issue is to fill the packet byte by byte:
void putData64(byte* packet, int pos, uint64_t data)
{
    union {
        uint64_t integer;
        byte bytes[8];
    } h = { .integer = data };
    for (int i = 0; i < 8; i++) {
        packet[pos+2+i] = h.bytes[i];
    }
}

Note that the AVR (in the Nano) is an 8 bit architecture with no
alignment constraints whatsoever.

Thank you. I was aware of the fact of 8bit vs 32bit. I haven't tried your code but it seems right. What did the trick for me in the end was the following:
void putData64(byte* packet, int pos, uint64_t data)
{
    uint32_t* out= (uint32_t*) (packet+pos+2);
    uint32_t* in=  (uint32_t*) data;
    *(out++)= *(in++);
    *(out++)= *(in++);
}

@user2912328: You mean in = (uint32_t*) &data? Note that, although this could work, it is quite fragile. Unless you can prove that packet+pos+2 is always a multiple of 4, there is a risk that out ends up being an incorrectly aligned (and thus invalid) pointer. If you have no guarantees on the alignment of packet+pos+2, the only valid solution is to copy the data byte by byte.

yes you are right about both points. Missing & and multiple of 4


text:
How to run Arduino codes in Java netbeans?
Having a hard time searching the net on how to run arduino codes on java. Can somebody please help me. Thank you.

Arduino code is C, not Java. So you'd need to translate it to java.

It may help if you explain what your intended outcome is.  Your PC (or even an raspberry pi) doesnt have the same GPIO as an arduino. If your code does not interface with any of that, and you are just wanting to port the c++ code to java, there are ways to do that(this would not be the place to look for help with that though)  But maybe try and explain what it is your actually trying to accomplish.

I would like to send sms using arduino and java. But i can't do it. I already made a communication between them but still it doesn't work. What should i do? And what do you guys think of my mistake?

We cannot say anything about your mistake, since you didn't gave us any information. The Arduino itself  cannot run java. I assume you try to let a java program on your PC communicate with the Arduino. Then just google for java serial communication

What i want is to send sms using arduino and java

Java is a programming language. Arduino is a platform that is mostly accessed by the C++ programming language. You cannot run "Arduino code" in Java.

The Arduino can't run Java. Full stop.


text:
Can't POST data with Arduino and ESP8266
I'm having problems with my Arduino UNO and the ESP8266 module.
I need to send values from Arduino to my PHP web page in this way:
http://www.server.com/km/db.php?id=53
the ESP8266 module is working fine, it powers up and connects to my Wi-Fi without problems, but I'm not able to send the values to my PHP page.
This is my code:
    #include "SoftwareSerial.h"

String ssid ="NETGEAR80";
String password="mypassword";

SoftwareSerial esp(10, 11);// RX, TX

String data;

String server = "http://www.server.com";
String uri = "/km/db.php";//
int DHpin = 8;//sensor pin
byte dat [5];
String temp ,hum;

void setup() {
pinMode (DHpin, OUTPUT);
esp.begin(9600);
Serial.begin(9600);
reset();
connectWifi();

}

void reset() {
esp.println("AT+CWMODE_DEF=1");
esp.println("AT+RST");
delay(1000);
if(esp.find((char*)"OK") ) Serial.println("Module Reset");

}

void connectWifi() {
Serial.println("Collegamento");
String cmd = "AT+CWJAP_CUR=\"" +ssid+"\",\"" + password + "\"";
esp.println(cmd);
Serial.println(cmd);
delay(4000);
if(esp.find((char*)"OK")) {
Serial.println("Connected!");
}
else {
connectWifi();
Serial.println("Cannot connect to wifi"); }
}

void loop () {

temp=11;

data = "id=" + temp;// data sent must be under this form

httppost();

delay(1000);

}

void httppost () {

esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
if( esp.find((char*)"OK")) {
Serial.println("TCP connection ready");
} delay(1000);

String postRequest =
"POST " + uri + " HTTP/1.0\r\n" + "Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n" + "Content-Length: " + data.length() + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n" + "\r\n" + data;

Serial.println(postRequest);

String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

esp.print(sendCmd);

esp.println(postRequest.length() );

delay(500);

if(esp.find((char*)">")) { Serial.println("Sending.."); esp.print(postRequest);

if(esp.find((char*)"SEND OK")) { Serial.println("Packet sent");

while (esp.available()) {

String tmpResp = esp.readString();

Serial.println(tmpResp);

}

// close the connection

esp.println("AT+CIPCLOSE");

}

}
}

This is the output on the Serial Terminal:
Module Reset
Collegamento
AT+CWJAP_CUR="NETGEAR80","calmgrasshopper675"
In attesa..
Connected!
POST /km/db.php HTTP/1.0
Host: www.skeetty.com
Accept: */*
Content-Length: 17
Content-Type: application/x-www-form-urlencoded

id=11&humidity=10
POST /km/db.php HTTP/1.0
Host: www.skeetty.com
Accept: */*
Content-Length: 17
Content-Type: application/x-www-form-urlencoded

The code works fine till the POST, but then no answer is received.
This condition:
if(esp.find((char*)">")) { Serial.println("Sending.."); esp.print(postRequest);

is never verified.
I can't understand if there is something wrong with the POST format, with the URL or something else.
Can you help me, please?

EDIT 26/04/2019
This is the output if I manually write the AT commands directly to the ESP8266 module through the Serial Monitor.
AT+CWJAP="NETGEAR80","my_password"

WIFI CONNECTED
WIFI GOT IP

OK
AT+CIPMUX=1

OK

AT+CIPSTART=1,"TCP","www.server.com",80

1,CONNECT

OK

If I use the Arduino code, it never connects to the server and the string "TCP connection ready" do not show, so I think it is not able to correctly connect to the server. Maybe, it's for a formatting error? I can't find the reason.

EDIT2 with @Juraj code.
    #include <SoftwareSerial.h>

SoftwareSerial Serial1(10, 11);
#define Trash "Trash3"
#define DHTTYPE DHT11
#define DHTPIN 2
#define TRIGGER_PIN 4
#define ECHO_PIN 3

float humidity, temp_f;
int distance;
long duration;

String buff(64);
String getStr(128);

void setup() {

Serial.begin(9600);

Serial1.begin(9600);
//Serial1.resetESP();
delay(2000);
Serial1.setTimeout(5000);

if (!connectWiFi()) {
Serial.println("Can not connect to the WiFi.");
while (true)
; // do nothing
}
Serial.println("OK, Connected to WiFi.");

sendCommand("AT+CIPSTA?");
sendCommand("AT+CIPDNS_CUR?");
sendCommand("AT+CIPSTAMAC?");
}

void loop() {

temp_f = 11;

// connect to server
if (sendCommand("AT+CIPSTART=\"TCP\",\"www.skeetty.com\",80")) {
Serial.println("connected to Cloud");

// build HTTP request
getStr = "GET /km/db.php?id=";
getStr += temp_f;
getStr += " HTTP/1.1\r\n";
getStr += "Host: expository-spoke.000webhostapp.com\r\n\r\n";

// open send buffer
buff = "AT+CIPSEND=";
buff += getStr.length();
if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data

// send HTTP request
Serial.println(getStr);
Serial1.print(getStr);

// print HTTP response
if (Serial1.find("+IPD,")) { // response received
int l = Serial1.parseInt();
while (l > 0) {
if (Serial1.available()) {
Serial.write(Serial1.read());
l--;
}
}
Serial.println("--------------");
} else {
Serial.println("no response");
}
} else {
Serial.println("send error");
}
sendCommand("AT+CIPCLOSE");
} else {
Serial.println("Error connecting");
}
}

bool connectWiFi() {

if (!sendCommand("ATE0")) // echo off
return false;
if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
return false;
if (!sendCommand("AT+CWMODE=1")) // set STA mode
return false;
return sendCommand("AT+CWJAP=\"NETGEAR80\",\"calmgrasshopper675\"");
}

bool sendCommand(const char* cmd) {
Serial.println(cmd);
Serial1.println(cmd);
while (true) {
buff = Serial1.readStringUntil('\n');
buff.trim();
if (buff.length() > 0) {
Serial.println(buff);
if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
return true;
if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
return false;
}
}
}

it never connects to the Wi-Fi network because sendCommand() always return false.

Comments are not for extended discussion; this conversation has been moved to chat.

Did you solve it? How?

No, I didnt solve it so I changed my hardware.


text:
Need help with buttonstate
I'm creating a program that works like a piano. I have four button, a piezo buzz and an LCD screen. I'm having a little trouble with the buttonstate.
Here is my program, when I run it the piezo buzz doesn't stop producing sound. The way it's suppose to work is when I push the green button, the piezo is suppose to produce a C sound but it doesn't. Can anyone please tell me what I've done wrong?
code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

int buttonyellow = 3;
int buttonred = 4;
int buttongreen = 5;
int buttonblue = 6;

int C,D,E,F;
int buzz = 7;

int buttonstate;

void setup()
{
  lcd.begin(16, 2);

  lcd.print("hello, world!");

  Serial.begin(9600);
  pinMode(buttonyellow,INPUT);
  pinMode(buttonred,INPUT);
  pinMode(buttongreen,INPUT);
  pinMode(buttonblue,INPUT);
}

void loop()
{
  lcd.setCursor(0, 1);

  lcd.print(millis() / 1000);

  C = digitalRead(buttonyellow);
  D = digitalRead(buttonred);
  E = digitalRead(buttongreen);
  F = digitalRead(buttonblue);

  buttonstate = digitalRead(C);
  if(buttonstate == HIGH){
    tone(buzz,523);
  }  else if ( buttonstate == LOW) {
    tone(buzz,1000);
  }else{
   noTone(buzz);
  }
  delay(50);
}

what is buttonstate = digitalRead(C);? if (C == HIGH){  was the plan?

have a really good look at your if-else block ..... what value of buttonstate will allow noTone(buzz); to run?

As jsotola has pointed out, there is a mistake in your code. Remove the line
buttonstate = digitalRead(C)

and replace
if(buttonstate == HIGH)

with
if(C == HIGH)

Moreover, I suggest you take a look at the debouncing example in order to make the sound "smoother" ie no jitters because of the button


text:
nodeMCU - when DC is active on pin the do this
i have a nodeMCU v3(esp8266)
and what i want is: when i send  DC 5v or 3v to a pin=D1 (idk if its possible to send 5v directly to pin) then to activate the D0 for 20Seconds
like this:
 if (D1==Sends signal){
    digitalWrite(pinD0, HIGH);
      delay(20000);  //pinD0 is active for 20 seconds

  }else{
     digitalWrite(pinD0, LOW);

  }

you can connect 5v to the gpio through a red LED or a level shifter, then just use digitalRead()

my question is:
if i can ping a D0 pin  from another device  and nodemcu to activate D1 pin for 20 seconds if recived ping(signal) in pin D0


text:
SOLVED Accelerometer/gyro MPU6050 is freezing after random time
SOLVED: I "solved" the problem by cycling my Arduino's power and I haven't had an issue since. I would still like to figure out what was going on. I still think it's something in that MPU6050 library with getMotion. But anyway, if anyone eventually has any ideas post it up. Thanks

Original question:
I'm using an MPU6050 accelerometer/gyro that controls a servo through a Mega.
QSTN: The sensor simply stops reading after an arbitrary time, usually between 2-4 minutes. I have to reinitialize the serial monitor/MPU to get it to work again which is not good. I suspect it has something to do with getMotion but I can't put my finger on it.
Any ideas? Thanks. Code is below:
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"

MPU6050 mpu;

int16_t ax, ay, az;
int16_t gx, gy, gz;

Servo servo1;

int val;
int prevVal;

void setup()
{
    Wire.begin();
    Serial.begin(38400); //38400

    Serial.println("Initializing MPU6050");
    mpu.initialize();
    Serial.println(mpu.testConnection() ? "CONNECTED" : "Connection failed");
    servo1.attach(9);
}

void loop()
{

    mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    val = map(ay, -17000, 17000, 0, 179);

    if (val != prevVal)
    {
        servo1.write(val);
        prevVal = val;
        Serial.println(val);
    }

    delay(75);

}

I suspect something with the i2c bus. There can be many problems with a i2c bus. For example a bad quality breadboard or long wires. For the arduino mega you need a level shifter for the sda and scl. Can you show a photo of the wiring between the arduino mega and the mpu-6050? Could you upgrade to a 3.3v arduino board, a mpu-9250, and the ahrs filter? Then you can use this guide: https://learn.sparkfun.com/tutorials/mpu-9250-hookup-guide When we ask extra information, please add that information to your question.

Can you measure the voltage on the SCL and SDA lines, when the freezing happens? Despite the rather short (and supposely rare in relation to the whole time) transmission period, both lines should be HIGH. If you see one of the lines being LOW for a longer time, then the I2C communication freezes for some reason during transmission, blocking the bus. May be a good starting point for debugging.

I suspect you may be right about the I2C but I think it may be a library issue. I tried a second breadboard and I've heard of the wire issues with I2C but these are standard hobby jumpers. Why do you think the level shifter is necessary at clock and data? I hooked it straight to the 3.3v on the Mega but it also appears to be 5v tolerant because I tried that out too and left it on all day and it was working okay. I unfortunately don't have an oscilloscope or multimeter on hand but I can look into that.

I "solved" the problem by cycling my Arduino's power and I haven't had an issue since. I would still like to figure out what was going on. I still think it's something in that library. But anyway, if anyone eventually has any ideas post it up. Thanks


text:
nodeMCU - 2 loops at a time - one continuously and second every 10 seconds
i have nodeMCU v3(esp8266) so i need to make 2 checks
1 check is the pin D1 which needs to be done continuously  and another check is web link check every 10 seconds,
problem is coz when i put delay then it stops the first check
void loop() {

 if (digitalRead(pinD1)==1){
       digitalWrite(pinD0, HIGH);
       delay(20000);
 }else{
       digitalWrite(pinD0, LOW);
 }

      loop2();

}

void loop2(){
   if (json1=="ON"){
    digitalWrite(pinD0, HIGH);
      delay(20000);
}else{
     digitalWrite(pinD0, LOW);
               delay(10000);

  }
}

loop2()  is not a loop, it is a subroutine or a function .... why don't  you give it a descriptive name like updateD0()?

Rather than using delay, use millis() and a variable to check if the some time has expired
void loop()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (digitalRead(pinD1)==1){
            digitalWrite(pinD0, HIGH);
            check = now + 20000;
        } else {
            digitalWrite(pinD0, LOW);
            check = now;
        }
    }
    loop2();
}

void loop2()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (json1=="ON"){
            digitalWrite(pinD0, HIGH);
        } else {
            digitalWrite(pinD0, LOW);
        }
        check = now + 20000;
    }
}


text:
ESP8266 crashes when trying to copy a string into a big char
I'm trying to parse with tinyxml2 a modest XML (3.4kb) to retrieve some data.
My ESP8266 crashes every time I try to use the toCharArray method.
here's my code
// here I'm getting an http request
String payload = https.getString();

// checking the payload, it seems fine in console but I get some garbage characters when àèéùìò are printed
Serial.println(payload);

// Length (with one extra character for the null terminator)
int str_len = payload.length() + 1;

// Prepare the character array
char xml[str_len];

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here

the length of the string is something around 3900, which I'm not sure can fit this kind of array on this device. If it's the case, what will be a better strategy ?
As you can imagine I'm just starting with the c language :)
EDIT: https.getString().c_str() + less variables was the right way to save memory

variables declared inside functions are created on the stack, the total size of these variables is 4kb - 3900 is getting pretty close - you'll want to use malloc (and free) to use heap memory instead

another option is, if you know the absolute maximum payload could be, create a global buffer to use

Function local variable are created on the stack, and in the case of an ESP8266, the total size is limited to 4096 Bytes - so, 3900 for one variable is cutting it close.
I would recommend you either use malloc/free
int str_len = payload.length() + 1;

// Prepare the character array
char *xml = (char *) malloc(str_len);

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here
//
// when done, free the memory malloc'd

free(xml);

or, if you know an absolute maximum size for the string, e.g. 5000, make char xml[5001]; in the global scope

tried declaring a char with a size of 6000 in global and it reboots
<<<stack<<<
ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa, the size of the string is ~5700

got a compile error with malloc -> src/main.cpp:74:35: error: invalid conversion from 'void*' to 'char*' [-fpermissive]

yeah, sorry was in a rush - hang on - there, fixed

tried declaring a char with a size of 6000 in global and it reboots - really? that does seem odd

still no luck (event with malloc, which seems to work fine) but I think the problem could be elsewhere. For the sake of documentation I'll post the gist of the main file -> https://gist.github.com/leRenart/1b72db23371839fd5a7799ece63ad8ed

so with malloc it crashes with the same "cause"?

it crashes every time I did a myString.toCharArray(), so I've finally opted to get rid of some variables, and ended with passing the result of the GET directly into the xml parser          doc.Parse( https.getString().c_str() ); I've tested it for many hours without any problem. I think I was using too much memory, but again, I'm not sure (if you wanna take a look into my code I've posted a gist of it). This is frustrating me because for no apparent reason (as the input is the same) this morning is keeping crashing and I can't figure why. To me all of this is learn by (wrong)doing...


text:
What is the maximum number of sensors that can be operated on a single Aurdino unit
I currently have an Aurdiuno uno and a motor driver shield: (http://www.hobbytronics.co.uk/arduino-motor-shield).
Now, I would like to run the following mechatronic devices:
3 bi-direction motors,
1 servo,
1 hall effect sensor (digital),
2 infra-red sensors,
1 magnetometer,
1 ultrasonic sensor,
Will the Aurdiuno uno paired with the motor sheild be able to run these components or will I need to buy an Aurdiuno mini? Could I please gain some insight into how you figure out what pins are required and how would i connect the sensor pins to the motor sheild since it does not have any direction slip on connections like the Aurdiuno Uno. Will I need to solder the sensor connections on?
Thankyou

Will the Aurdiuno uno ... buy an Aurdiuno mini?

The main differences between the uno and mini are:

footprint
6 (uno) vs 8 (mini) analog inputs

You will get two extra analog inputs and a much smaller size at the cost of the shield not fitting anymore.

Now, I would like to run the following mechatronic devices: 3 bi-direction motors, 1 servo, 1 hall effect sensor (digital), 2 infra-red sensors, 1 magnetometer, 1 ultrasonic sensor, Will the Aurdiuno uno paired with the motor sheild be able to run these components?

According to the website the shield supports up to 4 motors or 5 servos, so i would guess that it would work.
if the shield can't do 3 motors and 1 servo at the same time, then you can just use the servo library and a pin for that.
The shield requires 3 pins to function; so you need 3 or 4 pins depending on configurations.
Inputs 1 digital, 4 analog; 1 Digital I\O, 1 Analog In
so it looks like you need 4-5 DIO pins and 4 analog pins, which the uno has so yes.
If you were using motor driver boards instead of a shield the cost would be
2x PWM per Motor/driver combo = 6 PWM
1 DIO for servo
1 DIO for digital input
4x Analog Inputs
Which also fits in the budget all 6 of the PWM DIO pins, + 2 more (leaving 6 of the 14) and 2/3rds of the analog pins (also good you can leave A3,4 alone since they share a timer and only use the other ones)

Thanks for the concise answer. Just to clarify when you say budget is that the number of pins avaliable?


text:
Firmware gets stuck at obj.printto(client) in esp32
I am using an ESP32 to capture some data and then sending it over using ArduinoJson. However, sometimes, the firmware gets stuck at the line where it is transmitting data at obj.printTo(client). I have the logs for the same. Do you have any idea as to what might be making it freeze? And any way to avoid it in the future.
Logs:
12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...
12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...
12:47:11.229 -> [E][ssl_client.cpp:33] handle_error(): UNKNOWN ERROR CODE (004E)  12:47:11.229 -> [E][ssl_client.cpp:35] handle_error(): MbedTLS message code:-78
12:47:11.229 -> [V][ssl_client.cpp:245] stop_ssl_socket(): Cleaning SSL connection.
12:47:11.229 -> request sent
12:47:12.217 -> esp32/Arduino CI has failed
12:47:12.217 -> reply was:
12:47:12.217-> ==========
12:47:12.217 ->
12:47:12.217 -> ==========
12:47:12.217 -> closing connection
The send code:
jsonBuffer.clear();
JsonObject &rootObject = jsonBuffer.createObject();
JsonObject &dataObject = rootObject.createNestedObject("data");
JsonArray &X1dataObject = dataObject.createNestedArray("X1");
JsonArray &Y1dataObject = dataObject.createNestedArray("Y1");
JsonArray &Z1dataObject = dataObject.createNestedArray("Z1");
JsonArray &T1dataObject = dataObject.createNestedArray("T1");

vTaskDelay(10);

if (send_flag) {
  digitalWrite(2,0);
  send_flag = false;
  int connection_iterator = 0;
  int connection_iterator2 = 0;
  for (int iterator = 0; iterator < SAMPLE_SIZE; iterator++) {
    X1dataObject.add(X1dataArray[iterator]);
    Y1dataObject.add(Y1dataArray[iterator]);
    Z1dataObject.add(Z1dataArray[iterator]);
  }
  T1dataObject.add((float)(analogRead(NTC)*0.0244));

  rootObject["coreid"] = String(low, HEX) + String(high, HEX);
  //rootObject["coreid_high"] = String(high, HEX);
  rootObject["sample_time"] = int(time_taken);
  rootObject["firmware_version"] = FIRMWARE_UPDATE_VERSION;
  rootObject.prettyPrintTo(Serial);
  Serial.print("connecting to ");
  Serial.println(host);
  while ((!client.connect(host, httpsPort)) && !setup_mode) {
    connection_iterator++;
    Serial.println("connection failed! Retrying..");
    delay(5000);
    if (connection_iterator >= 10)
      ESP.restart();
  }
  if (client.verify(fingerprint, host)) {
    Serial.println("certificate matches");
  } else {
    Serial.println("certificate doesn't match");
  }
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.print("requesting URL: ");
  Serial.println(url);
  client.println(String("POST ") + url + " HTTP/1.0");
  client.println(String("Host: ") + host);
  client.println("Cache-Control: no-cache");
  client.println("Content-Type: application/json");
  client.print("Content-Length: ");
  client.println(rootObject.measureLength());
  client.println();
  rootObject.printTo(client);
  Serial.println("NUMBER OF INTERRUPTS:");
  Serial.println(interruptCounter);
  Serial.println("request sent");
  while ((client.connected()) && !setup_mode) {
    connection_iterator2++;

    String line = client.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
    Serial.println("Waiting for response");
    delay(500);
    if (connection_iterator2 >= 40)
      break;
  }
  String line = client.readStringUntil('\n');
  if (line.startsWith("{")) {
    Serial.println("esp32/Arduino CI successfull!");
  } else {
    Serial.println("esp32/Arduino CI has failed");
  }
  Serial.println("reply was:");
  Serial.println("==========");
  Serial.println(line);
  Serial.println("==========");
  Serial.println("closing connection");
  digitalWrite(LED_BUILTIN, LOW);
  // readRegister(INT_SOURCE, 1, &dummy_read);
}

I see that you are using SSL. SSL uses a lot of RAM and it is possible that the stack and the heap are colliding which will corrupt the running sketch. I recommend you add the amount of free heap to your log statements so that you can see how it changes, which will help you see if this is what is happening.
To obtain the free heap you can use esp_get_free_heap_size() - there's more documentation about this function in the espressif online documentation.

I will surely log the heap size but this doesn't seem to be happening as the code is not getting corrupted or even crashing. Just that after some time it throws a handle_error and resumes to what it should be doing. However, I will still log the heap size and watch the deviations.

I did the testing and the heap doesn't seem to be the issue. After a successful transfer, there is still about 75% of the heap memory available.

@peeyushtekriwal I think you'll need to post your code for anybody to be able to help you further.

Understandable. I will add the code above

So I have found out that apparently there is some issue working with WiFiClientSecure to send large data packets. The secure line sends data in small packets which take up a lot of time and also if the server gets unavailable at any moment, the program will get stuck there. This problem, however, was not this prominent when I used the same mechanism in esp8266.  Nevertheless, the solution would be to use a buffer to send the data.
Also, this version of code was written with ArduinoJson V5. But, even after migrating to ArduinoJson V6 the problem persists. It seems that whatever new JsonDocument feature has been implemented in the new version is still far from providing the efficiency of a buffer and it recoils back.
However still, if anyone else finds a better solution, please do update.

Latest development: I picked up this issue after a long time after not being able to solve it and still cannot find any leads. The chip seems to establish a connection with the server but somehow, it gets stuck and is unable to continue. The point to be noted is that the same mechanism is working with ESP8266.


text:
How to get more than the 16 Analog INs on a Arduino Mega for using like 24 piezo sensors
i bought an Arduino Mega2560 and flashed it with usbmidi. So now it comes up as a midi device.
I need more than those 16 analog ins to be able to put all my 24 piezo sensors into it to receive midi signals from it. I still have no idea how i have to put the piezo pieces into the arduino but also no clue as how to get more than those 16 analog slots. Any way to use the digital inputs as well or do i need some extension shield or so? I'm a total beginner with arduino...

When you are a total beginner, can you start with 16 piezo sensors? You could buy two arduino leonardo boards: https://www.arduino.cc/en/Main/Arduino_BoardLeonardo or use multiplexers: https://www.gammon.com.au/forum/?id=11976 or external ADC (as Michel Keijzers wrote in his answer). A digital pin for a piezo sensor is possible, but then you can not tune the level in software, so I prefer analog inputs.

I already have an Arduino Mega flashed with hiduino (
https://github.com/ddiakopoulos/hiduino) ... :/
Also it's for a setup with a lot of bells. A friend is making music (bells and chimes) which i want to connect the piezos to and then send midi signals to me to visualize the sounds^^

You can customize a controllino on their page
https://www.controllino.biz/controllino-myplc/
I just looked at it and it seems you can get 24 analog outputs.
Don't know what the cost is though.

You need one (or more) external ADC (analog digital converters).
For example the ADS1115, the link shows an Adafruit model and how to use it.
In a DIP format (to be used on breadboards/prototype boards) it will be hard to find a 16 channel ADC, but you can add multiple I2C (or other) 4 channel ADCs to one Arduino Mega.


text:
How to write a function to return matrix?
I need a function to return a 2x2 rotation matrix, something like:
float matrix(float phi){
  float R[2][2] = { {cos(phi), -sin(phi)},
                    {sin(phi),  cos(phi)} };
return R;
}

But it doesn't work obviously. What is the best way to write this function?

One way would be to make the function return a pointer to float ie create a new array and return it
float** matrix(float phi){
   float** R= (float **)malloc(2 * 2 * sizeof(float));
   R[0][0]= cos(phi);
   R[0][1]= -sin(phi);
   R[1][0]= sin(phi);
   R[1][1]= cos(phi);
   return R;
}

Do not forget to free the memory once you do not need it any more!
However, I would advise you not to do it but rather pass the array to the function. See How can I declare an array of variable size (Globally) and Is using malloc() and free() a really bad idea on Arduino? for an explanation why it might not be a good idea to allocate the memory in the function (in an embedded aka Arduino environment)

This is not how you create a 2D array. Here, R[0] and R[1] are uninitialized float * pointers, and R[0][0] is dereferencing one such pointer. This is undefined behavior likely to crash the program.

Wow...  C++ is too hard to program.

@ Edgar Bonet,  so how can I write this function?

You cannot return an array from a function. There are several
alternatives, though. One of them is to allocate the memory for the
array within the function, as suggested by user2912328's answer. I would
not recommend this approach though, for the reasons already stated in
that answer.
For an overview of the other possible options, see this response to the
question “Returning an int array from a function”.
Now, your problem is slightly different, as you have a 2D array.
The C/C++ syntax for dealing with those is tricky, but here we go.
If you opt for the “static array” solution (make sure you understand the
implications), you could write:
float (*matrix(float phi))[2]
{
    static float R[2][2];
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

and you would use it like this:
float (*M)[2] = matrix(angle);

If you instead let the caller manage the allocation, then
float (*matrix(float phi, float (*R)[2]))[2]
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

Or maybe forgo the return value to make the syntax simpler:
void matrix(float phi, float (*R)[2])
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
}

and you could use it like:
float M[2][2];
matrix(angle, M);

The “array in a struct” solution is more straightforward.
If the syntax for dealing with 2D arrays bothers you (which would be
understandable), you can instead use arrays of pointers to 1D arrays.
This are easier to deal with but trickier to allocate. That approach
could warrant another answer...

Edit: One common way to simplify a convoluted array syntax is to use
typedefs. As an identifier for a 2x2 array decays to a pointer to an
array of 2 floats, you can name that type:
typedef float (*pmatrix)[2];  // pointer to an array of 2 floats

Then, instead of
float (*matrix(float phi))[2] { ... }
...
float (*M)[2] = matrix(angle);

you would write
pmatrix matrix(float phi) { ... }
...
pmatrix M = matrix(angle);


text:
Two buttons, one LCD
I'm trying to make a program that whenever a button is push, a different word will show on a lCD screen. However, it seems that the two buttons provide the same output ("Screen A"), it's like there is no difference between them, and I'm not sure what's the cause.
The code is very simple:
const int buttonPin1 = 13;     // the number of the pushbutton pin
const int buttonPin2 = 12;     // the number of the pushbutton pin

int buttonState = 0;

long randNumber;

void setup() {

  for(int x=0; x<2; x++)
  {
    pinMode(buttonPin[x], INPUT);
  }

}
    void loop() {

      for(int x=0; x<2; x++)
      {
        buttonState = digitalRead(buttonPin[x]);

        if (buttonState == HIGH && buttonPin[x] == 13) {
          lcd.print("  Screen A ");
        }
        if (buttonState == HIGH && buttonPin[x] == 12) {
          lcd.print("  Screen B ");
        }
      }

    }

Any help is appreciated

You are missing the definition of your buttonPin[] array.

I guess it's something with the circuit ... can you add it to your question.
Also, make sure buttonPin has the values 13 and 12 in the first and second index.
Btw, The following code is functionally identical:
void loop()
{
    if (digitalRead(buttonPin[0]) == HIGH)
    {
       lcd.print("  Screen A ");
    }
    if (digitalRead(buttonPin[1]) == HIGH)
    {
       lcd.print("  Screen B ");
    }
}

If you want to have the loop and a flexible amount, use something like:
#define NR_OF_PINS 2

int buttonPins[NR_OF_PINS] = { 8, 9 };
String screens[NR_OF_PINS] = { "Screen A", "Screen B" };

void loop()
{
    for (int pin = 0; pin < NR_OF_PINS; pin++)
    {
        if (digitalRead(buttonPins[pin]) == HIGH)
        {
            lcd.print(screens[pin]);
        }
    }
}

Update
My answer is related to the code before you edited.
Remarks:

After your edited code, you forgot to declare buttonPin:
int buttonPin[] = { buttonPin1, buttonPin2 };
You do not use long randNumber
Instead of a global variable int buttonState  you can create it locally in the loop function (although you do not need it according to my code above).
buttonState = digitalRead(buttonPin[x]);
Also, what you high likely want to add is button debouncing (check the arduino example about this), unless you add a delay after showing a screen of a considerable amount (like 100 ms or more).


text:
Arduino and Processing Call and response not working
I have been trying to develop a connection from the arduino IDE to Processing so I can send data measured on the arduino Pins to processing to display.
I first packaged the 10-bit integers I was receiving from the arduino into characters each with their own byte. For example, 1023 was a 10-bit integer which i packaged into 4 8-bit characters, 1, 0, 2 and 3. These could then be sent over the serial port and were reconstructed on the other end by processing.
However, I have been trying to make a call and response relationship between the two where after one program is done receiving and processing the data, it asks the other to send the next set.
I used the example code given on the arduino website which works fine on its own. But when i try and implement the character packaging to it, it stops working. The output in processing always miss out the first couple of characters.
Whats more is that i deleted the myPort.print('A') from the processing code, and arduino was still sending data repeatedly, despite processing not sending it's response back.
It is a vague question, but where have i gone wrong when implementing the packaging code? and why does the arduino keep sending data regardless of whether processing responds.
Thanks a lot
===================================
Arduino Code:
int inByte = 0;

//void establishContact();

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  establishContact();
}

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

  if (Serial.available() > 0) {
    // get incoming byte:
    //inByte = Serial.read();

      int MzValue = analogRead(A0);
      int FzValue = analogRead(A1);
      int FyValue = analogRead(A2);

      char Mz_Str[10];
      char Fz_Str[10];
      char Fy_Str[10];

      sprintf(Mz_Str, "%d", MzValue);
      sprintf(Fz_Str, "%d", FzValue);
      sprintf(Fy_Str, "%d", FyValue);
      // Now str contains the integer as characters

      Serial.write(Mz_Str);
      Serial.write(",");
      Serial.write(Fz_Str);
      Serial.write(",");
      Serial.write(Fy_Str);
      Serial.write(",");
      Serial.write("\n");

      delay(20);
  }
  else {
    delay(20);
  }
}

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.print('A');   // send a capital A
    delay(1000);
  }
}

===================================
Processing Code:
import processing.serial.*;

  Serial myPort;                       // The serial port
  boolean firstContact = false;        // Whether we've heard from the microcontroller
  String val;     // Data received from the serial port
  int numValues = 3;
  float[] values = new float[numValues];
  int inByte = 0;

  void setup() {
    size(256, 256);  // Stage size
    noStroke();      // No border on the next thing drawn

    // Print a list of the serial ports for debugging purposes
    // if using Processing 2.1 or later, use Serial.printArray()
    println(Serial.list());

    // I know that the first port in the serial list on my Mac is always my FTDI
    // adaptor, so I open Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
    String portName = Serial.list()[0];
    myPort = new Serial(this, portName, 9600);
  }

  void draw() {
    // read a byte from the serial port:
    if ( myPort.available() > 0) {
    inByte = myPort.read();
    }
    //print(inByte);
    // if this is the first byte received, and it's an A, clear the serial
    // buffer and note that you've had first contact from the microcontroller.
    // Otherwise, add the incoming byte to the array:
    if (firstContact == false) {
      if (inByte == 'A') {
        myPort.clear();          // clear the serial port buffer
        firstContact = true;     // you've had first contact from the microcontroller
        myPort.write('A');       // ask for more
        println(inByte);
      }
    }
    else {
        val = myPort.readStringUntil('\n');         // read it and store it in val
        println(val); //print it out in the console
        values = float(splitTokens(val, ","));

        myPort.write('A');
        delay(20);
      }
    }

Serial.print(MzValue); will do the same as your 'character packaging'

you don't read the available character, so it is remains available

Processing + Firmata is also a potential solution.

Why not just send all the data at once, in a comma separated list, with a \n char as a "end of message" delimiter?
Here are 2 test sketches. The Arduino sketch sends the A0 to A2 values to serial every 500ms, and the Processing sketch displays the received data. Parsing the received data into an integer array is more of a Java question, not an Arduino one, so I'll leave that up to you.
Arduino
// Send the values of A0, A1 and A3
// to serial every 500ms.
// 2416 bytes.
char data[20];
char buffer[6];

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

void loop(){
  itoa(analogRead(A0), buffer, 10);
  strcat(data, buffer);
  strcat(data, ",");
  itoa(analogRead(A1), buffer, 10);
  strcat(data, buffer);
  strcat(data, ",");
  itoa(analogRead(A2), buffer, 10);
  strcat(data, buffer);
  strcat(data, "\n");
  Serial.write(data);
  memset(data, 0, sizeof(data));
  delay(500);
}

Processing
// Display the data received from the serial port, sent every
// 500 ms from the Arduino. The values sent are from A0, A1
// and A2, and were sent concatenated together, as a comma
// separated list, followed by a \n char.
import processing.serial.*;
import java.awt.TextArea;
Serial myPort;
TextArea myTextArea;
String input;

void setup(){

  try{
    myPort = new Serial(this, Serial.list()[0], 9600);
  }
  catch(Exception e){
    System.err.println(e);
    e.printStackTrace();
  }

  myTextArea = new TextArea("", 23, 49, 1);
  this.add(myTextArea);

  size(500, 380);

}

void draw(){

  if(myPort.available() > 0){
    input = myPort.readStringUntil('\n');
    myTextArea.append(input);
  }

}

EDIT
As Juraj mentions in his comments, I could have just used Serial.print() 6 times instead of the char arrays. Here is a second Arduino sketch that uses Serial.print(). Before you use it, be aware that it's compile size is 288 bytes more than the char array method. Imagine that :)
// Send the values of A0, A1 and A3
// to serial every 500ms.
// 2704 bytes.
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.print(analogRead(A0));
  Serial.print(",");
  Serial.print(analogRead(A1));
  Serial.print(",");
  Serial.print(analogRead(A2));
  Serial.print("\n");
  delay(500);
}

Why not print the data to Serial as Serial.print(analogRead(A0)); Serial.print(',');...?

@Juraj That would work too :)

it would be 6 simple lines. no buffers, no C functions. and why memset again?

you need only buffer[0] = 0; at the start of the loop to 'clear' the string

I know. I like using memset() to set the entire array to 0's. How about this: memset(data, 0, 1); It results in the same compile size as buffer[0] = 0; and does the same thing. Of course, no one is forcing you to use memset().


text:
Random without parameters
During a programming contest, I used the following line of code:
symbols[i] = random() & 0b11;

After the contest, when I looked into the Arduino reference, I found out random takes one or two parameters. Based upon that, I would expect the code not to compile. However, this code somehow worked as I expected. (Assigning a random number from 0 to 3) How come?

Simple: random() isn't an Arduino function - it's a standard C function.

Function random()
long random(void)
The random() function computes a sequence of pseudo-random integers in the range of 0 to RANDOM_MAX (as defined by the header file <stdlib.h>).
The srandom() function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be returned by rand(). These sequences are repeatable by calling srandom() with the same seed value.
If no seed value is provided, the functions are automatically seeded with a value of 1.
-- AVR LIBC Manual Page

The Arduino functions themselves, actually use the random function without arguments. See source code


text:
Controlling keyboard LEDs with USB Host Shield
I've got a USB keyboard connected to my Arduino Uno with a USB Host Shield. I'm reading keystrokes using this example from the USB Host Shield library.
I need to toggle the LEDs in the keyboard (that indicate the state of Caps Lock, Num Lock etc.)
This thread mentions using Usb.setReport(), but this method doesn't seem to exist any more: there's no such method in Usb.cpp in the library. There does seem to be a method called SetReport in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.
What I'm currently doing:
void keyboard_setup(){
    static HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }
    delay(200);
    HidKeyboard.SetReportParser(0, &Prs);

    static USBHID usbhid(&Usb);
    uint8_t leds = 1;
#define KBD_ADDR 1
#define KBD_IF 0
    usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
    delay(100);
    leds = 255;
    usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
    delay(100);

Neither call to SetReport seems to work, and I'm not certain the values of KBD_ADDR or KBD_IF are correct (I'm using ones that I've seen in examples), or event that calling SetReport is right .
What am I doing wrong?

I posted an answer but deleted it.  My 1st thought was that you were creating your own instance of the SetReport method (which you are) that didn't work w/any USB device.  But looking at your code again - I'm not so sure.

@st2000 I'm creating my own instance of USBHID, which I don't otherwise use, because I seem to need it to use SetReport(). I'm not sure if that's the right approach though.

This is going to take a bit of thinking for me.  But I think the best way to go about controlling the keyboard LEDs is to expose SetReport to your Sketch by adding a wrapper method to the USBHost library.  Otherwise, I'm thinking you need to setup all the USB stuff in your Sketch - which the driver already is capable of doing.

I thought NicoHood/HID github page was the answer, but I think it works with custom keyboard and does not necessary work w/standard USB keyboard LEDs.

the NicoHood/HID uses an Arduino to emulate a keyboard .... there is no actual keyboard involved

There does seem to be a method called SetReport in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.

The method arguments of the new SetReport() method aren't quite the same and some are in a different order.
The old method signature was:
uint8_t setReport( uint8_t addr, uint8_t ep, unsigned int nbytes, uint8_t interface, uint8_t report_type, uint8_t report_id, uint8_t* dataptr );

...while the new one is:
uint8_t SetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);

It seems to me the equivalent call would be:
usbhid.SetReport( 0, KBD_IF, 0x02, 0, 1, &leds );