text:
Typedef not accepted as a data type in a function?
I know I'm in a C++ compiler, but I typically create a typedef from structures, probably a holdover from earlier C programming. So this has my head spinning. I create a Typedef from a structure. After that, I have no trouble declaring a global or local version of that structure anywhere in a function, or outside of all functions (global). But when I try to create a function with this typedef as an arg, or even a function arg with a pointer the such a typedef, the compiler complains (and the complaint doesn't seem to make sense). Example...
typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint16_t codeID;

// a few more vars

  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
  uint8_t future[10];
} Sunstates;

So now, this typedef seems as good as any other. Either of these statements compile fine...
Sunstates sunStates;
Sunstates * pSS = &sunStates;

But if I now try to create a function, with either an instance of this data type or a pointer to it, like so...
void systemDataVerify(Sunstates *pST) {  }

The Arduino compiler offers this confusing error message...

Arduino: 1.8.3 (Windows XP), Board: "Arduino Nano, ATmega328"
SolarControler_21a:393: error: variable or field 'systemDataVerify'
declared void
void systemDataVerify(Sunstates *pSS) { }
                   ^

SolarControler_21a:393: error: 'Sunstates' was not declared in this
scope
SolarControler_21a:393: error: 'pSS' was not declared in this scope
void systemDataVerify(Sunstates *pSS) { }
exit status 1 variable or field 'systemDataVerify' declared void

The fact that it doesn't like me declaring a function void is odd, but not as troubling as it calling my function a 'variable or field' and definitely not as strange as it saying my datatype (Sunstates) was NOT "declared in this scope." The data type was defined immediately before the function... and the fact I could declare both instances of the type AND pointers to it kind of proves it exists within the scope. Can someone help me understand why the compiler is complaining?
Edit... I was asked to include a short sketch that shows the problem...
uint8_t somefunction() {
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
} Sunstates;

Sunstates sunStates; // create an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p) {
  return;
}

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

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

Now... I have discovered that if I remove the 'somefunction()' definition before the Structure definition, the problem goes away. And I'm using Arduino 1.8.3 to compile this.

Please make a small sketch that shows the problem. It compiles when I try to make a small sketch.

Check the syntax of whatever precedes your function definition. This sounds like the compiler lost sync and isn't expecting a function definition to start here. As a test, can you define a different function here instead?

Well I actually had a really complex function before it, and the project was already pretty huge. Thats why I created such a small sketch to isolate the problem, with the simplest function I could think of. there's nothing really before it. It was easy enough to eliminate all functions before my structure, but it does seem like a compiler bug at this point.

I do not get this error in Arduino IDE 1.8.5 with snippet you provided, but I get it in Sloeber Eclipse plugin. The later attached sketch fails to compile in Arduino IDE 1.8.5 too.
The error is in Arduino build chain ino to cpp conversion for the C++ compilation. Put the typedef declaration into .h file and include it in ino.
EDIT: Details are in my newer answer to a similar problem.

Hmm.. well all I've ever used was the official Arduino 1.8.3 (though I've been dying to try that Eclipse plugin!). Well thanks! I'll try that .H file approach. But the fact it compiles for YOU at least tells me I'm not crazy, and that the code SHOULD be compiling. For now, I've found a work-around... I can just make my function take a void * , and then within the function body make a new pointer to that struct type, and finally cast the passed void pointer to initialize it. That seems to work.

I'm accepting this answer, even though I haven't upgraded my IDE yet, because putting the structure and typedef near the top of the file ( before any functions are declared, but after all other header files) solves the issue. Still, I've updated my post with a short sketch that illustrates the problem reliably, and I'd be interested in a confirmation that your 1.8.5 does compile it without error. Not that I don't trust compiler improvements, but my current project is complex enough that regressive testing is very time consuming, So I'd rather save that upgrade for a "rainy day" :-)

the attached sketch fails in IDE 1.8.5 too

But putting the typedef struct in an H file works? If so, between that suggestion, and my workaround, we till at least have an answer.

yes .h works. it is the same like putting the typedef to the top of the ino

So now the only remaining question, if my original sketch was not breaking any C/C++ rules, do you think maybe I should post this observation in the official Arduino.cc forum? There seem to be a lot of folks there who directly work on development, and might be interested in making a future compiler fix.

it is ino to cpp conversion problem. the coversion does, if I am not mistaken,  the arduino-builder https://github.com/arduino/arduino-builder

one of the things done by the builder is creating forward declaration of functions. my hypothesis is that your order of function, variable and typedef leads to wrong order of forward declarations

It's not a compiler bug, @alm.
If I take the Minimal, Reproducible Example provided by the OP, and compile it, and then look at the intermediate file produced by the IDE (not the compiler) you can see what is happening:
#include <Arduino.h>
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
uint8_t somefunction();
#line 18 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
void systemDataVerify(Sunstates *p);
#line 22 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
void setup();
#line 26 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
void loop();
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
uint8_t somefunction() {
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
} Sunstates;

Sunstates sunStates; // create an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p) {
  return;
}

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

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

You will notice that the IDE "helpfully" produces function prototypes for your functions, and that the order in which it does that means that it puts the prototype for void systemDataVerify(Sunstates *p); before the typedef for the structure, leading to the error message.
The solution is simple. Put your own function prototype into your source, thus telling the IDE to not bother, like this:
uint8_t somefunction() {
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
} Sunstates;

void systemDataVerify(Sunstates *p);  // <<<<<< ---- function prototype

Sunstates sunStates; // create an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p) {
  return;
}

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

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

Looks like a compiler bug to me. Perhaps that should be passed along to the compiler people.

It's not a bug in the compiler, arguably it is an idiosyncrasy of how the IDE works. No point in submitting bug reports to the compiler-writers. You could conceivably raise an issue on Github for the IDE complaining about the way they generate function prototypes.

For more information see my answer here. In it I mention:

The function prototype generation however can lead to obscure error messages if you are not careful.

The dreaded automatic function prototype generator strikes again!

Here I am 5 years after the OP with the same issue. I'm on Arduino IDE Version: 2.2.1 Date: 2023-08-31T14:35:44.802Z. And I'm using the Adafruit ATSAMD21 M0.
Note that my offending typedef is already in a .h file placing it after everything it needs and before any use so that fix doesn't work for me.
I've discovered what does work around this issue:
Changing this:
int storeXXX( framBlock *fb ) {
To this:
int storeXXX( struct _framBlock *fb ) {
That is, use the 'real' type for function arguments.
The typedef appears to be Ok everywhere else, locals, globals, before and after the point of the error report, etc. Just not as a function argument.
Note that the OP found a similar solution in using void * as the type of his typedef'd pointer. I saw no mention of using the 'real' type which is a more straight forward fix.
Looks like a compiler bug to me. Perhaps that should be passed along to the compiler people.

See my answer.


text:
eclipse photon with cdt-arduino plugin can't upload sketches
i've recently decided to give eclipse-photon-cdt a shot. i use it with the built in arduino plugin, downloaded my feather m0 board config and tried to upload an empty sketch. failed, the console shows it tries to connect but fails. of course arudino ide 1.8.5 succeeds wonderfully.
point is if i copy paste the command line activating bossac i get the same result. i also know why. when using scripts i need to use a python scripts that uses serial signaling to reset the feather into bootloader mode. arduino ide does it on his own probably using java. eclipse doesn't do that which sounds like a huge bug to me.
am i missing something ? or did they actually assumed i'll press twice on the reset button on the board each and every time i want to upload a sketch ?

if you want to use Eclipse with Arduino, use Sloeber plugin

that's a poor answer, it tell me don't use that tool, use another, i'm not keen on eclipse i can use any other tool or build system like cmake\make\platformio or frameworks like zephyr or mynewt that already have it and use vim\sublime etc... suggesting another tool does not solve my problem only promoites that you are using another tool you like better.

It is not an answer. Majenko wrote a good answer. It is "If you want to use Eclipse". Sloeber integrates into Eclipse the Arduino build tools and hardware packages of Arduino IDE. the reset there works

It sounds to me like Eclipse doesn't know how to reboot the board into the bootloader.
Traditional Arduinos automatically boot into the bootloader when the board is reset, and the board resets every time you open the serial port thanks to the USB chip having DTR connected (through a capacitor) to the reset pin of the man MCU.
Chips with a direct USB connection can't do that (boards like the M0 Feather, the Leonardo, etc).  Instead they have to be rebooted by opening the serial port at 1200 baud and then closing it again.
With the "traditional" boards the IDE neither knows, nor cares, about rebooting the board - it just happens. However with direct USB boards the IDE has to have specific code to perform the reboot at the right time. The Arduino IDE has that code. However I would guess that the Eclipse plugin either doesn't implement that, or doesn't have the ability to implement it.
So you will have to manually reset the board for programming.

i thought so. it's interesting about the AVR's didn't know that, is the capicitor resides inside the MCU or is it external part that is connected to the USB ? also the DTR is set or reset when the port opens ? AFAIK it's supposed to be set when the port is open, but if u want to reset the board you want to pull down the reset pin meaning you want DTR to be unset. can you please elaborate ?

Capacitor is external. DTR is an active low signal.

source: Stack Exchange

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

sort: votes


text:
How to repeat the code
I want to make my biped robot keep walking, but it only move for twice, this biped robot project is important for my Capstone project. The code below is the code that I used
#include <Servo.h>

int HipR_Pin = 9;
int HipL_Pin = 10;

int KneeR_Pin = 5;
int KneeL_Pin = 6;

int AnkleR_Pin = 3;
int AnkleL_Pin = 11;

Servo HipR;
Servo HipL;

Servo KneeR;
Servo KneeL;

Servo AnkleR;
Servo AnkleL;

void setup() {
  HipR.attach(HipR_Pin);
  HipL.attach(HipL_Pin);
  KneeR.attach(KneeR_Pin);
  KneeL.attach(KneeL_Pin);
  AnkleR.attach(KneeR_Pin);
  AnkleL.attach(KneeL_Pin);
}

void loop() {

  for (int i=0; i < 7; i++)
  {
    RightStep1;
    LeftStep1;
    RightStep2;
    LeftStep2;
    RightStep3;
    LeftStep3;
    RightStep4;
    LeftStep4;
  }
  ;
}

void RightStep1()
{
  HipR.write(80);
  HipL.write(80);
  KneeR.write(100);
  KneeL.write(100);
  AnkleR.write(20);
  AnkleL.write(20);

}

void LeftStep1()
{
  HipR.write(90);
  HipL.write(90);
  KneeR.write(70);
  KneeL.write(70);
  AnkleR.write(20);
  AnkleL.write(20);

}

void RightStep2()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(80);
  KneeL.write(80);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep2()
{
  HipR.write(60);
  HipL.write(60);
  KneeR.write(90);
  KneeL.write(90);
  AnkleR.write(20);
  AnkleL.write(20);

}
void RightStep3()
{
  HipR.write(40);
  HipL.write(40);
  KneeR.write(60);
  KneeL.write(60);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep3()
{
  HipR.write(50);
  HipL.write(50);
  KneeR.write(70);
  KneeL.write(70);
  AnkleR.write(20);
  AnkleL.write(20);

}
void RightStep4()
{
  HipR.write(60);
  HipL.write(60);
  KneeR.write(60);
  KneeL.write(60);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep4()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(50);
  KneeL.write(50);
  AnkleR.write(20);
  AnkleL.write(20);

}

when describing a problem, you have to say exactly what happens ..... but it only move for twice does not describe the observed action ..... because it could mean that the robot takes two steps or it could mean that only two of the servos move or it could mean that one servo moves twice .... each of those conditions would be caused by different program bugs

This may not be a direct answer to your question but... when I see so
much code repetition, I cannot help but suggest you try to avoid
repeating yourself. All your Step() functions do exactly the same
actions, only with different data. You can then factor the actions
into a single function, and provide it different data as parameters.
There are many ways to achieve this in C++. I am going to show four of
them, in order from the most basic to the most esoteric.
The simplest one is to use a plain function and give it the angles as
parameters. This is basically what Michel Keijzers’ answer suggests. My
take on it would be
void Step(uint8_t hip, uint8_t knee, uint8_t ankle)
{
    HipR.write(hip);
    HipL.write(hip);
    KneeR.write(knee);
    KneeL.write(knee);
    AnkleR.write(ankle);
    AnkleL.write(ankle);
}

which you can then use in the main loop as
Step( 80, 100,  20);  // right 1
Step( 90,  70,  20);  // left 1
...

The next step in code modularity would be to group all the angles for a
single step into a compound data structure called a struct, then the
function to perform a step takes a single parameter which is this data
structure:
struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
};

void doStep(Step s)
{
    HipR.write(s.hip);
    HipL.write(s.hip);
    KneeR.write(s.knee);
    KneeL.write(s.knee);
    AnkleR.write(s.ankle);
    AnkleL.write(s.ankle);
}

These structs would be defined as
Step RightStep1 = { 80, 100,  20};
Step LeftStep1  = { 90,  70,  20};
...

and used in loop() as
doStep(RightStep1);
doStep(LeftStep1);
...

One step further, you can embed the function within the data structure.
The embedded function then becomes a “method” of the data structure
which is now called an “object”:
struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void perform() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

The structs can be defined just as before, and used as
RightStep1.perform();
LeftStep1.perform();
...

One last technique involves making the objects themselves behave as
functions that can be called. This kind of callable object is called a
“functor”, and is kind of syntactic sugar over a method call. We just
have to rename the relevant method as operator():
struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void operator()() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

The structs are still defined in the same way, but now they can be used
as if they were plain functions:
RightStep1();
LeftStep1();
...

I suggest you use whatever technique you feel the most comfortable with.
There is a logic progression though: the more you improve your C++
skills the more comfortable you will be with the latest ones.

In addition to @Gerben's answer, you aren't giving any time for your movements to complete.  .write() doesn't wait for the movement to complete - it just sets the target angle.  You should add enough delay(...) calls to wait for your movements to finish before you start a new one.

To call a function you need to add parentheses after the function name.
void loop() {

  for (int i=0; i < 7; i++)
  {
    RightStep1();
    LeftStep1();
    RightStep2();
    LeftStep2();
    RightStep3();
    LeftStep3();
    RightStep4();
    LeftStep4();
  }
  ;//<<--also remove this stray semi-colon
}

Instead of all the different step functions you can better parameterize them for example
void LeftStep4()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(50);
  KneeL.write(50);
  AnkleR.write(20);
  AnkleL.write(20);
}

will be
void LeftStep4()
{
  Move(70, 70, 50, 50, 20, 20);
}

and create a function
void Move(int hipR, int hipL, int kneeR, int kneeL, int ankleR, int ankleL)
  HipR.write(hipR);
  HipL.write(hipL);
  KneeR.write(kneeR);
  KneeL.write(kneeL);
  AnkleR.write(ankleR);
  AnkleL.write(ankleL);
}

The other functions will also be one liners like the first function LeftStep4.

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


text:
How do I connect my Luxorparts keypad to my Arduino?
I just bought a 12 digit keypad from Luxorparts and it doesn't come with any schematics showing how it's wired at all. How do I figure out how to connect it to my Arduino?

There's a guide here that helped me out: Keypad Tutorial, that will show you the means of figuring out how the keypad is wired. I followed it and figured out that for that specific keypad (the Luxorparts keypad) the setup is as follows:
(From left to right on the keypad pins and on the rows and columns)
Pin1: Not connected
Pin2: Connected to the 2:nd collumn
Pin3: Connected to the 1:st row
Pin4: Connected to the 1:st collumn
Pin5: Connected to the 4:th row
Pin6: Connected to the 3:rd column
Pin7: Connected to the 3:rd row
Pin8: Connected to the 2:nd row
Pin9: Not connected
I modified the example code from the link above to reflect this specific Keypad:
#include <Keypad.h>

const byte ROW0 = 3;
const byte ROW1 = 8;
const byte ROW2 = 7;
const byte ROW3 = 5;

const byte COL0 = 4;
const byte COL1 = 2;
const byte COL2 = 6;

const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { ROW0, ROW1, ROW2, ROW3 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { COL0, COL1, COL2 };

// Create the Keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

#define ledpin 13

void setup()
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);
}

void loop()
{
  char key = kpd.getKey();
  if(key)  // Check for a valid key.
  {
    switch (key)
    {
      case '*':
        digitalWrite(ledpin, LOW);
        break;
      case '#':
        digitalWrite(ledpin, HIGH);
        break;
      default:
        Serial.println(key);
    }
  }
}

To run that, simply connect each pin from the keypad, in order, to the arduino, so the second pin from the keypad goes to the second digital pin on the Arduino and so on.
I asked the question after I'd already figured out the answer in hopes of helping anyone else who bought that specific keypad.


text:
How to pass 2 parameters with RCSwitch library?
I'm learning Arduino's world, but knowing very little about C and C++.
I'm trying to achieve a little RF transmitter which should send the temperature and  humidity from a DHT-11 sensor to a Raspberry Pi.
I'm using the RCSwitch library to send information with the Arduino, and the 433Utils library to receive it on the RPI.
Using those 2 libraries demos, I was able to send an integer, holding temperature or humidity information (mySwitch.send("00001010");), and read it on the RPI.
But how can I send both informations so that the RPI will know which one is the temperature and the humidity ?
I know I could just send both and assume the lowest is the temperature, but this would be very messy and not very rewarding.
EDIT :
Following Edgar's answer in https://arduino.stackexchange.com/a/52992/11604, I know write:
void send_string(const char *str){
    int i = 0;
    for (char *p = str; *p; p++ ) {
        mySwitch.send((i<<8) + *p, 16);
        i++;
    }
}

void loop() {
    delay(1000);
    h=40.650;
    t=32.0078;
    hic=33.586;
    String x = "$H" + String(h) + "T" + String(t) + "HI" + String(hic);
    send_string(x.c_str());
}

Works perfectly ! (see his complete answer for the RPI-side code)

mySwitch.send("T45H50");, mySwitch.send("[45;50]");, mySwitch.send("T45"); mySwitch.send("H50");...

Are you really sending an integer, or are you sending an ASCII representation of the binary bits of an integer?

The send() method take either an integer, a string byte representation or a tri-state code, I cannot send a string directly

The library you have chosen is not designed for transmitting information between nodes. It is intended for sending simple ON/OFF commands to RF-connected switches.  Bending it to send data in the way you want would be difficult.  Not impossible, but difficult.
Instead you should be considering a more suitable system, such as the popular RadioHead library. It appears to have Raspberry Pi support out of the box:

Raspberry Pi Uses BCM2835 library for GPIO http://www.airspayce.com/mikem/bcm2835/ Currently works only with RH_NRF24 driver or other drivers that do not require interrupt support. Contributed by Mike Poublon.

Alternatively a small Arduino as an interface between the RF module and the Pi may be another option.

I think this library is what I was looking for, thanks ! But I don't understand your last sentence, in what is this different than what I'm doing ?

Actually, RadioHead is far too complicated when you don't fully understand what you are doing (hope I'll get it someday). I found a very good answer with RCSwitch https://arduino.stackexchange.com/questions/52989/how-to-transmit-string-data-using-the-rc-switch-library.


text:
Passing out an argument
I can't figure out why test is not passed properly to test1
#include <Arduino.h>

char *test1;
char *status_reply(char *test) {
        int ans_rel = 1;
        int ans_led = 0;
        int ans_sw = 1;
        sprintf(test,"%d%d%d",ans_rel,ans_sw,ans_led);
        Serial.println(test);
}

void setup() {
        Serial.begin(9600);
        status_reply(test1);
        Serial.println(test1);
}

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

While commenting on an answer to a previous question of yours, I suggested you read the section Arrays and Pointers of the C FAQ. Judging from from this new questions, it seems you failed to do so. Please, read it! Otherwise you will spend lots of time asking here related (and off-topic) questions.

@EdgarBonet well I did read it. I must say that the main purpose or motivation of declaring a char as char* - is quite unclear

To be clear- I understand the technicalities of such definitions, but not when or why to use each one of them. It is a whole different from Python

This is not about Arduino. It is C. You have only a pointer to char now. You must allocate memory for the c-string.
char test1[128];
If you pass pointer to sprintf, the function will write to memory where the pointer points. Something somewhere in memory will be overwritten and the following print will print the string, but later the memory will be used for something else and your c-string disappear.

thank you. There's something I'm missing : 1) In any other case if I would init char *test1="hello world" at the beginning, and print it Serial.println(test1) - I would have get proper value. 2) In code here - when I create test inside it does print it as expected, but not passing its value to test2 ?

char *test1="hello world" would be a pointer to a global allocated constant c-string and should be const char *test1="hello world". I enhanced the answer.


text:
Can client IP address be obtained from Arduino Ethernet2 library for W5500 during client.connected() call?
I've found posts explaining how to get client IP by modifying the W5100 Ethernet library and the Adafruit CC3000 library but not the Ethernet2 lib for W5500 chip, which is different enough that the W5100 mod won't work. I suspect the TCP Socket struct will contain it, but haven't been able to find its declaration anywhere to confirm this so I can modify the library to make it accessible.

in Ethernet library 2.00 (it is not Ethernet2), EthernetClient has remoteIP()

Use the new update of the 'old' Ethernet library. It is version 2.00 and you can install or update it in the Library Manager in IDE. Note, it is not Ethernet2 library. The new Ethernet library supports W5500 and has client.remoteIP().
example
  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());

New features in version 2.0.0
  Auto-detection of W5100, W5200, and W5500 Ethernet hardware.

The version cited here is for the W5100 chip and won't work with the W5500, as mentioned on the Arduino reference page for the Ethernet library - "Ethernet library (Ethernet.h) manages the W5100 chip, while Ethernet2 library (Ethernet2.h) manages the W5500 chip; all the functions remain the same."

https://github.com/arduino-libraries/Ethernet/releases

Thanks, the link was helpful. As I thought, I already had it installed in my Arduino IDE. When I looked at the source file names I saw W5100.cpp and thought nothing had changed. Looking at the code, though, I see additions to handle W5200 and W5500.

This solution works: http://forum.arduino.cc/index.php/topic,82416.0.html if "W5100.readSnDIPR(_sock, remoteIP);" is replaced with "w5500.readSnDIPR(_sock, remoteIP);" [note the lower case 'w']. I didn't think it would because I can't find readSnDIPR() in the Ethernet2 library source, but after reviewing the Wiznet 5500 data sheet (https://www.mouser.com/pdfdocs/w5500_ds_v100e.PDF) I realized it was probably a read of the "Socket n Destination IP Address" register and decided to try it and see if it linked. It did, and successfully returns the remote IP after connecting.

and why do you use an outdated library? Ethernet2 is now obsolete

From Arduino reference page for Ethernet library: "Ethernet library (Ethernet.h) manages the W5100 chip, while Ethernet2 library (Ethernet2.h) manages the W5500 chip; all the functions remain the same." The current version of Ethernet2 is V2, btw, and it does not have a remoteIP method in its client class.

the new version is less then a month old. the docs are not updated

I have the latest version available via the Arduino IDE. Perhaps you should post a link here to the later version for the benefit of others.


text:
When using an Arduino as an ISP, is the capacitor required or not?
Looking at Arduino as ISP and Arduino Bootloaders, it is stated

The 10 µF electrolytic capacitor connected to RESET and
  GND of the programming board is needed only for the boards that have
  an interface between the microcontroller and the computer's USB, like
  Mega, Uno, Mini, Nano. Boards like Leonardo, Esplora and Micro, with
  the USB directly managed by the microcontroller, don't need the
  capacitor.

Some of the Fritzing diagrams show the electrolytic capacitor connected between the RESET and GND pins:

But it is not shown in all of the images on that page.
Nor it is shown in this image from Nick Gammon's Atmega bootloader programmer (see original image):

So, is the capacitor really needed, when using a Mega or Uno as an ISP, and if so, why exactly?

I was wondering after having written this answer to the question How to install new ATMEGA firmware via the ISP pins? for a 3D Printer control board.

The purpose of the capacitor is to prevent the "master" Arduino (the Mega in the first image above) from resetting when the serial port is opened.  If that board resets, then programming fails.
There are many ways of preventing that reset - some more permanent than others - but the capacitor trick is one of the simplest.
So yes, you do need the capacitor unless you have made other modifications to prevent the reset.
I think the purpose of the second image is more to illustrate how to use the ICSP headers and where to connect the target's reset pin on the master. It is to be seen as complementary to the first image.

Edit:
It seems what you are using is not Arduino As ISP, but instead something written by Nick Gammon that acts as a standalone programmer.  The rules for Arduino As ISP do not apply in this case. Since you are not programming via the master Arduino (as you would with Arduino As ISP) there is no need to prevent the master from resetting.

Here's a little history about the auto-reset system:
Originally, when the Arduino used the FT232, the DRT signal would reliably reset it automatically. The operating system (all operating systems) would automatically assert DTR when the port was opened, and all was well.
Then, out of the blue, and without telling anyone, Future Tech removed that auto-DTR asserting from the FT232 driver for Windows. Since Windows doesn't control DTR for you, but leaves it up to the driver or the software (and all other operating systems automatically control DTR for you - Windows has to do the opposite of everyone else - it's in their remit...!) all of a sudden the boards stopped resetting properly for programming.
So Arduino added specific reset code into the IDE to get around the problem (interestingly enough: if you watch the DTR pin on Linux you see it being asserted multiple times when programming - both the OS and the IDE are toggling it).
But then Arduino moved to the ATmega8U2 (and later the ATmega16U2) chip which uses the standard CDC/ACM instead of the custom FT232 driver. Now the auto DTR assertion was working again, but they kept the manual assertion in the IDE to cope with older boards in Windows.
I guess they didn't put the DTR assertion workaround in the bootloader programming code since you don't really want DTR asserted at that point anyway.
So if you have an FT232-based Arduino and are running Windows I guess there is no need for the capacitor, since DTR won't be asserted by the OS.
However in Linux and OS X, regardless of the USB chip, you will need the capacitor, since it will always assert DTR.
But then along came China and threw the CH340G into the works.  Now we have a third option, with dodgy drivers from who knows where. And who has the slightest clue what they do? Do they assert DTR for you? Your guess is as good as mine.  If it doesn't, then you won't need the capacitor. If it does, then you will.
It's all such a mess now thanks to too many options and combinations.  It's simpler just to have the capacitor regardless, since it won't stop it working if it's not actually needed in your specific configuration.

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

If you're using Nick Gammon's programmer, the RESET signal to the target board comes from the Arduino programmer - from Pin 10. Read his instructions:
https://www.gammon.com.au/bootloader
You modify the 6 pin cable as shown on his website.


text:
Running code through functions
I am making a led cube where sequential lighting is used. So basically i need to repeat my commands for a given time. After much reasearch nothing turned up so decided to ask here.

Here is the code i need to reproduce in a working format
void loop(){
  runfor(500){
    DigitalWrite(5,HIGH);   //this is the command to be executed in other
                            //function
  }
}
void runfor(uint32_t duration){
  int timer = millis();
  while((millis()-timer)<=duration){
  //DigitalWrite(5,HIGH); will execute here
  }
}

So basically DigitalWrite(or any other code if used) will be repeatedly executed for 500 milliseconds

EDIT due to misunderstanding the question.
If you want to be able to pass instructions into a function, you will have to have a function for each set of instructions (that is, you cannot pass arbitrary statements as a function parameter), and then you adjust your runfor() function to accept a pointer-to-a-function parameter.
typedef void (*callback_function)(void);  // defining the type here makes the code easier to read when used in other places.

void runfor(uint32_t duration, callback_function patternCode){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
    patternCode();
  }
}

void pattern1() {
  // Light pattern #1
}

void pattern2() {
  // Light pattern #2
}

void setup() {
  // Setup code
}

void loop() {
  runfor(1000, pattern1);
  runfor(2000, pattern2);
}

ORIGINAL ANSWER
Your starting pseudo-code is nearly there.
void runfor(uint32_t duration){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
  }
}

Changes I made:

change int to uint32_t to accommodate all possible values of millis().
change for keyword to while, which is the correct keyword for the loop type you want.
added semicolon after your timer assignment, per C syntax.

Im sorry, I'll edit my post. Thanks for informing!

I’m not sure I understand. What kind of answer are you looking for?

jose can u c  I mean a reform to the code so it basically 'accepts' function from say loop() and runs the commands in the ensuing { } braces. Also can you please post comments on my questions to the question comments so that others can understand?

Your timer variable wants to be uint32_t.

@A.Shetye The code sample provided in the answer does what you are asking. Your initial example in the question was very close to correct already!

I suppose I am misunderstood. The // part here is not any sample code. So if i do runfor(50){ <place code here} from say loop(), it should run the given code for 50 milliseconds. So i suppose my current code cant do that?

I changed my answer, now that I understand you.


text:
Arduino: command not found
After installing the Arduino IDE on MacOS (1.8.5), I am trying to run some commands in the terminal to flash the firmware on an Uno R3.
I have successfully connected and uploaded through the GUI, but would like to use the command line for the johnny-five API (https://github.com/rwaldron/johnny-five/wiki/Getting-Started).
However, when running
arduino --install-library "Firmata,Servo"

I get the following error:

-bash: command not found

How do I install the command line interface?

simple google search gives this https://playground.arduino.cc/Learning/CommandLine

I was on that page earlier today. It says the CLI has been available since 1.5, but it isn't bound to anything on the command line on my machine after installing 1.8.5.

Not really an arduino question, more of a linux one.    Command not found means there is no program "arduino" in your path

Yes... I thought this community would likely have better knowledge as to what the actual path is...

Depends on where you installed it...   have you done something like sudo apt-get install arduino

I ran sudo npm i arduino --unsafe-perm on MacOS.

npm is the Node.JS package manager. It has nothing to do with the Arduino IDE, it just installs a Node package with the name 'arduino'.

the arduino builder is installed with IDE. you must only ensure that it can be found. try full path for execution. I can't give you details for Mac.

I can successfully upload with the builder...  What is the Linux path?

the installation folder of the IDE. it is the 'arduino' file. it starts the IDE if invoked without parameters

Arduino has a new CLI https://blog.arduino.cc/2018/08/24/announcing-the-arduino-command-line-interface-cli/

Instructions to installing and binding the Arduino CLI can be found at
https://github.com/arduino/arduino-cli#getting-started
Once you install the binary, copy the executable into a directory which is in your PATH environment variable (such as /usr/local/bin/).
Note: You may have to rename the binary to arduino-cli.


text:
Why is there no embedded c code in arduino libraries?
When I took a look at how the arduino libraries were coded I expected to see register names like I/O registers(PINx,DDRx,PORTx) and other such registers with values assigned to them but instead I saw normal C code with functions and a class.
Why isn't there any embedded C in the structure of the library? Am I misunderstanding something very basic? Please help me understand.

If you take a look at the Arduino core library (e.g., the AVR version of
wiring.c), you will see lots of low-level register access. That's
why the core code is specific to a processor architecture.
Other libraries are built on top of the core API in order to be
portable.

Then why do people even code using low-level registers when they can just use the core API?

@Roshan: 1. Performance: digitalWrite(), for example, is more than 100 times slower than direct port access. 2. Hardware features: the core only provides access to the most generic stuff, you can fully exploit the hardware capabilities only if you access the hardware directly.

Because the Arduino API abstracts those things.
If you put that kind of low-level code into a library the library becomes non-portable.  By sticking to the Arduino API (digitalWrite, pinMode, etc) the library can be used on all boards.


text:
setting output analog/digital pin to ground
So I need to automaically eject a CD from a Blu-Ray drive, I have a wire welded on the drive's card that if manually connected for a split second (pulse) to the ground of that same card on the drive, will eject the CD. Now in order to do that automatically I'm using an Arduino Nano and I connected that wire to an analog pin "d1" set its mode to Output and connected the grounds of both Arduino and drive together. Here's my code 1
int ds1 = A2; //pin that indicates the existence of the CD inside the drive if HIGH and its inexistance otherwise
int d1 = A3;  //pin connected to the wire that if connected to ground ejects the CD

void setup() {
  Serial.begin(9600);
  pinMode(ds1, INPUT);
  pinMode(d1, OUTPUT);
  while((!analogRead(ds1))) //if the CD isn't inside the drive wait
  {}
}

void loop() {
  analogWrite(d1,0); //eject CD
  delay(500);
  while(!analogRead(ds1)) //if the CD isn't inside the drive wait
  {}
  delay(1000);
}

I'm thinking that maybe setting the pin to 0 doesn't necessarily mean I connected it to the gnd, it's just a possibility if you see anything wrong with the code or have any suggestion please help me

https://majenko.co.uk/blog/what-exactly-gpio-pin

pinMode(d1, OUTPUT); sets the pin LOW (0 zero) connected to ground

while(!digitalRead(ds1)) would be better at first line in loop. then you can leave it out from setup()

what do you mean by Blu-Ray drive?  ..... is this a drive on a computer or is it a Blu-Ray player?

a blu-ray player not connected to a computer

Yes, setting a pin to OUTPUT and setting it LOW effectively connects the pin to ground (via a few ohms of resistance).
There's a couple of things wrong with your code, though, which you should address:

Use digitalWrite() not analogWrite().

analogWrite(pin, 0) is effectively the same as digitalWrite(pin, 0), but it's ambiguous to someone reading your code.

You never "release" the pin, so once it goes LOW it stays LOW.  You should emulate open drain by setting it to INPUT when not using it.
You should get into the habit of putting repeated code into functions to make it more understandable what's going on.

For example:
void setup() {
  Serial.begin(9600);
  pinMode(ds1, INPUT);
  pinMode(d1, INPUT);
  waitForCD();
}

void loop() {
  triggerEject();
  waitForCD();
  delay(1000);
}

void triggerEject() {
  pinMode(d1, OUTPUT);
  digitalWrite(d1, LOW); // Press the button
  delay(100); // This is how long the button is pressed for
  pinMode(d1, INPUT); // Release the button
}

void waitForCD() {
  while(!analogRead(ds1)) //if the CD isn't inside the drive wait
  {}
}

!analogRead(ds1) will only ever be true if the voltage at pin A2 is exactly zero volts. If you really want to read an analog voltage here you should find a threshold value that the value is compared to:
while (analogRead(ds1) < 100)) {}

Or it may be that you actually want to use digitalRead()...

Setting a digital PIN to LOW doesn't set it to GND. It set it to 0. Just try for example with a HC12: to set it, you must link its SET PIN to GND. If you link the SET pin to real GND, it works. If you link it to D8 (eg) and set D8 to LOW, it doesn't work.

@Peter I disagree entirely. When you set a pin to LOW it activates a low-side N-channel MOSFET with very low resistance to connect the pin to GND. Worst case would be 20Ω, but more likely <1Ω for the low-side. Which pales into insignificance compared to the 1kΩ resistor that the module slaps in there. Since it uses an STM8 MCU the input LOW threshold is 0.3VDD, which at 5V is 1.6V, which even with 20Ω plus 1kΩ against the 10kΩ pullup is a good 3-4x higher than the voltage the Arduino would give at that pin (0.46v). I suspect you just forgot to set the pin to OUTPUT mode.

Take a HC12 (eg) and read the DataSheet: if you put SET at GND, the HC12 will turn into setting mode. So try and you'll see it's true. Now, link to a PIN on the Arduino, set it to LOW. You'll see the HC 12 don't enter in setting mode (we've made also test with Ax PIN and result is the same. And "of course" we are in OUTPUt!) . Seems if you want to get a "real" GND you must trigger a NPN. Maybe using LOW it's "near to be GND" and so, in some case it will work.

NPN will be even worse as you impose a 0.7v junction voltage drop on to of the resistive divider. I don't have a HC12, but please do some voltage measurements on the stm8 io pin and show me that its above 1.6v when pulled low by an Arduino.

https://arduino.stackexchange.com/questions/69003/is-digitalwritepinnumber-low-different-from-ground-pin

I don't know what relevance you think that has.

Ah, It seems to depend on the HC12! With some, it works, with other no... I'll investigate to see if some are clones of clones

@Peter You are waiting the required amount of time after pulling SET low before trying to use it...?

yes. After testing I confirm: SET on D5 and D5 as LOW. It works one or two times and we can set the HC12. Then, we start to receive bad value from AT command. To get "again" good values, we need to connect SEt to "real GND". And in that case, we can send as many AT cmd we want, we never get bad return. It's very strange....


text:
Atmel studio 7 vs Arduino IDE for register level coding?
Which one is better to get started with register level embedded c coding?
Also which one is used professionally?

doesn't matter. 2) Arduino shouldn't be used professionally.

I actually wouldn’t recommend either for professionally developing for Atmel chips. Although Atmel Studio is a nice enough IDE (the simulator is amazing!), it does make it very difficult to unit test your code or to set up a build server. I would personally recommend you set up a Make (or possibly CMake) based setup directly on top of the avr-gcc tool chain and then simply use the text editor of your choice.
As for learning about programming against raw registers, I have to recommend Atmel Studio and one of their XPlained evaluation boards. Atmel Studio includes a simulator that actually shows you, bit by bit, the current state of the registers.

How do you set up a Make based setup directly on top of the avr-gcc tool chain. i don't know how to go about doing it. So, it would be great if you could give some insight on how to do it.

Here’s an avr template I created and a digital thermometer project I’ve been working on based on it.

Atmel Studio for professional. Arduino is for fun and is normally the first step into embedded c programming using the atmega328 (Arduino)


text:
HC-05 and cheap Nano clone not powering on
I have a HC-05 module which works absolutely fine with an Arduino Uno. Because I need to reduce the size of it, I tried using an Arduino Nano.
After correctly wiring it up to the Nano, sometimes the LED doesn`t turn on, or sometimes it does not appear in the devices listing of my smartphone. It also resets randomly the Arduino. I have tested it and it fully works without any problems with the Uno.
I think it is a power issue, but not from my computer or any other computer because I tried on all my computers.

Are you powering it from 3.3V or 5V?

the regulator on the nano may not be able to supply enough current for the HC-05. See if you can find a part number on the regulator and look up its specs.

@ChadG If it's running from the 3.3v pin then it may even be using the internal 3.3v regulator of the CH340G, in which case you'd be lucky to get a few tens of mA from it...

Please provide a schematic and the type of HC-05 module you have. The HC-05 itself runs in 3.3V, but most modules, that you can buy, add an extra voltage regulator for 5V, so that you can power it directly from the Arduino.


text:
ssPin, resetPin, updatePin, ps0, ps1, osk - was not declared in this scope
The code below produces the  error:

ssPin was not declared in this scope

This error is repeated for all elements of DDS, i.e. ssPin, resetPin, updatePin, ps0, ps1 and osk
Can anyone spot the problem?
#include <SPI.h>
#include <AD9954.h>
AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

void setup() {
SPI.begin();
SPI.setClockDivider(4);
SPI.setDataMode(SPI_MODE0);
delay(500); // let things get set up...

DDS.initialize(400000000); // initialize DDS with 400 MHz clock

}

void loop() {

 DDS.setFreq(25000000); // set DDS to 25 MHz
  delay(2000);

}

The line:
AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

does not have any content above it which declares that those variables exist. You can declare them like
const uint8_t ssPin, resetPin, updatePin, ps0, ps1, osk;

You'll likely also want to assign values to them, corresponding to the pins being used:
const uint8_t ssPin=4, resetPin=5, updatePin=6, ps0=7, ps1=8, osk=9;

(the actual values should be the pin numbers being used in your particular case.)
The file AD9954.h declares these variable names as private inside the class. They aren't available for use outside the class. The call to DDS(...) is the constructor, where you pass in pin definitions, and the values get assigned to those variables inside the class. But you can pass in literals or other variables in the constructor. You could even declare the same variable names in your main source file, but you can't ever directly access private variables from outside the class.

Thanks. However, when I look through AD9954.h I see that the variables have been declared as private within the AD9954 class but it doesn't seem to pick these up.

Right, they are private to the class. They aren't available for use outside the class. The call to DDS(...) is the constructor, where you pass in pin definitions, and the values get assigned to those variables inside the class. But you can pass in literals or other variables in the constructor. You could even declare the same variable names in your main source file, but you can't ever directly access private variables from outside the class.

Ok, thanks for the very clear explanation, I understand the problem now. I've not done any Arduino work for a while so need to get my brain back in gear. Thanks.

As a final comment on this, the line in question (AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);) is used to pass the actual Arduino pin numbers for those pin assignments to the object. In the working version I used the following line: AD9954 DDS(2, 3, 4, 5, 6, 7);


text:
How come my switch is triggering with out pushing the button?
New here, sorry If my formatting is bad.
int button = 2;
int relay = 3;
int speaker = 4;

void setup()
{

  pinMode(button, INPUT_PULLUP);
  pinMode(relay, OUTPUT);
  pinMode(speaker, OUTPUT);

}

void loop()
{
  if(digitalRead(button) == 0)
  {
    digitalWrite(relay, HIGH);
    tone (speaker, 100, 300);
    delay (3000);
  }
  else
  {
    digitalWrite(relay, LOW);
  }
}

I want the relay to trigger and stay open only while the button is pressed.   However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.
If i remove the tone (speaker, 100, 300); it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

how is the speaker wired?

@Gerben, sorry, I had it right on the board but copied it wrong to here.

@Juraj, The red wire is in pin 4 and the black is in GND on POWER

is it a piezo speaker? because normal speaker should not be connected without resistor?

@juraj The piezo is a speaker, however that can't be the issue entirely as even if I don't plug in the speaker, just the code causes the error.

I can't see any red or black wires in your question.

I want the relay to trigger and stay open only while the button is
  pressed. However for some reason touching pin 2 triggers the relay and
  sound, even if I'm not connecting it to the ground.

Touching a pin is like connecting it to ground with a resistor (human body is conductive). It may or may not be stronger then the pull-up resistor.

If i remove the tone (speaker, 100, 300); it only triggers when the
  button connecting pin 2 to ground is pressed, but obviously doesn't
  play the tone.

Activation of the neighbor pin influences the pull-up on pin 2. Try external pull-up on pin 2.


text:
How can I power MKR1000 and 25 NeoPixels 24hrs or longer?
I have an arduino MKR1000 which I would like to run off battery power for a few days with 1-3 dimly lit NeoPixels active. Every day for an hour there will be 10 NeoPixels active. Brightness for both set to 15. I'm having 2 issues. The NeoPixels start to morph into another color after an hour or thereabouts, and the MKR seems to lose track of time, as the Leds don't turn on and off on the right hour. I have also noticed that if I have the usb and battery both plugged into the MKR, the serial monitor stops working. What should I do?

What size and type of battery?

Neopixels need 5V which you won't have if you are using the lipo battery input.

It's a LiPo battery 3.7V and 2000mAh

I have followed Adafruits guide for these NeoPixels, and they write that a LiPo is ok for smaller strips of LEDs, is this incorrect?

Yes, you can feed the neopixel with 3.3~3.7V... just be sure that the pin that controll this ledstrip work with also 3.3V logic (I don't know if the MK3 work with 5V or 3.3V logic)

It's 3.3V but now I am thinking, should I have connected the battery to the white charger instead of VIN?


text:
Push button control of multiple relays
I'm new to arduinos and have not been able to find/create a working bit of code for my project. I'd like to control several different relays (standard 5v optical relays) with push buttons. I want one pushbutton1 to turn on/off relay1, pushbutton2 to turn on/off relay 2, etc.
I ran into troubles using delay statements as debouncers because I guess it locked out the remainder of the code while it ran? I then tried to use a flagging approach covered here:
https://github.com/VRomanov89/EEEnthusiast/blob/master/03.%20Arduino%20Tutorials/01.%20Advanced%20Button%20Control/ButtonSketch/ButtonSketch.ino
const int numOfInputs = 2;
const int inputPins[numOfInputs] = {2,3};
const int outputPin = 10;

int LEDState = 0;
int inputState[numOfInputs];
int lastInputState[numOfInputs] = {LOW,LOW};
bool inputFlags[numOfInputs] = {LOW,LOW};
int inputCounters[numOfInputs];

long lastDebounceTime[numOfInputs] = {0,0};
long debounceDelay = 50;

void setup() {
  for(int i = 0; i < numOfInputs; i++) {
    pinMode(inputPins[i], INPUT);
    digitalWrite(inputPins[i], HIGH); // pull-up 20k
  }
  Serial.begin(9600);
  pinMode(outputPin, OUTPUT);
}

void loop() {
  setInputFlags();
  resolveInputFlags();
  resolveOutputs();
}

void setInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    int reading = digitalRead(inputPins[i]);
    if (reading != lastInputState[i]) {
      lastDebounceTime[i] = millis();
    }
    if ((millis() - lastDebounceTime[i]) > debounceDelay) {
      if (reading != inputState[i]) {
        inputState[i] = reading;
        if (inputState[i] == HIGH) {
          inputFlags[i] = HIGH;
        }
      }
    }
    lastInputState[i] = reading;
  }
}

void resolveInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    if(inputFlags[i] == HIGH) {
      // Input Toggle Logic
      inputCounters[i]++;
      updateLEDState(i);
      printString(i);
      inputFlags[i] = LOW;
    }
  }
}

void printString(int output) {
      Serial.print("Input ");
      Serial.print(output);
      Serial.print(" was pressed ");
      Serial.print(inputCounters[output]);
      Serial.println(" times.");
}

void updateLEDState(int input) {
  // input 0 = State 0 and 1
  if(input == 0) {
    if(LEDState == 0) {
      LEDState = 1;
    }else{
      LEDState = 0;
    }
  // input 1 = State 2 to 6
  }else if(input == 1) { // 2,3,4,5,6,2,3,4,5,6,2,
    if(LEDState == 0 || LEDState == 1 || LEDState > 5) {
      LEDState = 2;
    }else{
      LEDState++;
    }
  }
}

void resolveOutputs() {
  switch (LEDState) {
    case 0:
      digitalWrite(outputPin, LOW);
      break;
    case 1:
      digitalWrite(outputPin, HIGH);
      break;
    case 2:
      analogWrite(outputPin, 30);
      break;
    case 3:
      analogWrite(outputPin, 70);
      break;
    case 4:
      analogWrite(outputPin, 100);
      break;
    case 5:
      analogWrite(outputPin, 155);
      break;
    case 6:
      analogWrite(outputPin, 255);
      break;
    default:
    break;
  }
}

But was unable to alter the code to get it to work... could someone help me write a bit of code which will allow me to do what I want it to do? I'd rather not buy a matrix-style shield to accomplish this, but I will if I have to.
What I want to do:

Turn on relay1 by pressing momentary pushbutton1
Turn off relay1 by pressing momentary pushbutton1
Turn on relay2 by pressing momentary pushbutton2
Turn off relay2 by pressing momentary pushbutton2
etc.
etc.

Thank you in advance!

To use this sketch, you will need the Bounce2 Library, and two N.O. switches connected between GND and the Arduino Digital Pins specified. I'm not sure if there is a limit to the number of Bounce2 objects you can create. Have a look at the Bounce2.h and Bounce2.cpp files.
#include <Bounce2.h>
byte buttonOneState = 0;
byte buttonTwoState = 0;
const byte buttonPin1 = 4;
const byte buttonPin2 = 5;
const byte debouncerInterval = 50;

// Instantiate ONE OR MORE Bounce2 object(s).
Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  debouncer.attach(buttonPin1);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2);
  debouncer2.interval(debouncerInterval);
}

void loop(){

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      if(buttonOneState == 0){
        Serial.println("Turn Relay 1 ON");
        buttonOneState = 1;
      }
      else{
        Serial.println("Turn Relay 1 OFF");
        buttonOneState = 0;
      }
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      if(buttonTwoState == 0){
        Serial.println("Turn Relay 2 ON");
        buttonTwoState = 1;
      }
      else{
        Serial.println("Turn Relay 2 OFF");
        buttonTwoState = 0;
      }
    }
  }

}

Forgive my ignorance: which line does it specify the output pin for me to connect to the relay? Thank you so much for your help - this is much more concise than my attempts!

The sketch doesn't specify the relay pin numbers. I left that up to you to decide which ones to use. You can control the ON/OFF commands for the relays where the "Serial.println..." statements are located in the sketch. Keep in mind that some optical relay modules require a LOW signal to turn them ON, and a HIGH signal to turn them OFF. It's important to ensure you are getting the desired output first, and the print statements are an easy way to do this.

Okay beautiful, thank you very much! Good point on the relays; I'll have to check the datasheets. I'll post what I have once I have it working.

You can use this Button library from JChristensen (in GitHub)
You only need to read the brieve (altough usefull) documentation and you can control, no only the state of many buttons, you also can read the time that the buttons are pressed.
Hope you can solve your little problem :D
TIP: Try with 50ms of delay when you instantiate the button object

Here is the final solution I've implemented:
/*  Thanks to VE7JRO for giving me this solution to my problem.
 *  Thread found at https://arduino.stackexchange.com/questions/55540/push- button-control-of-multiple-relays
 */

#include <Bounce2.h>
byte buttonOneState = 0;
byte buttonTwoState = 0;
byte buttonThreeState = 0;
byte buttonFourState = 0;
const byte buttonPin1 = 2;
const byte buttonPin2 = 3;
const byte buttonPin3 = 4;
const byte buttonPin4 = 5;
const byte relayPin1 = 9; //Relay pin 1
const byte relayPin2 = 10; //Relay pin 2
const byte relayPin3 = 11; //Relay pin 3
const byte relayPin4 = 12; //Relay pin 4
const byte debouncerInterval = 50;

// Instantiate ONE OR MORE Bounce2 object(s).
Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();
Bounce debouncer3 = Bounce();
Bounce debouncer4 = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  debouncer.attach(buttonPin1);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2);
  debouncer2.interval(debouncerInterval);
  debouncer3.attach(buttonPin3);
  debouncer3.interval(debouncerInterval);
  debouncer4.attach(buttonPin4);
  debouncer4.interval(debouncerInterval);
  pinMode(relayPin1, OUTPUT); //Define pin as output
  pinMode(relayPin2, OUTPUT); //Define pin as output
  pinMode(relayPin3, OUTPUT); //Define pin as output
  pinMode(relayPin4, OUTPUT); //Define pin as output
}

void loop(){

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      if(buttonOneState == 0){
        Serial.println("Turn Relay 1 ON");
        digitalWrite(relayPin1, HIGH);
        buttonOneState = 1;
      }
      else{
        Serial.println("Turn Relay 1 OFF");
        digitalWrite(relayPin1, LOW);
        buttonOneState = 0;
      }
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      if(buttonTwoState == 0){
        Serial.println("Turn Relay 2 ON");
        digitalWrite(relayPin2, HIGH);
        buttonTwoState = 1;
      }
      else{
        Serial.println("Turn Relay 2 OFF");
        digitalWrite(relayPin2, LOW);
        buttonTwoState = 0;
      }
    }
  }

  // Button 3
  if(debouncer3.update()){
    if(debouncer3.read() == 0){
      if(buttonThreeState == 0){
        Serial.println("Turn Relay 3 ON");
        digitalWrite(relayPin3, HIGH);
        buttonThreeState = 1;
      }
      else{
        Serial.println("Turn Relay 3 OFF");
        digitalWrite(relayPin3, LOW);
        buttonThreeState = 0;
      }
    }
  }
  // Button 4
  if(debouncer4.update()){
    if(debouncer4.read() == 0){
      if(buttonFourState == 0){
        Serial.println("Turn Relay 4 ON");
        digitalWrite(relayPin4, HIGH);
        buttonFourState = 1;
      }
      else{
        Serial.println("Turn Relay 4 OFF");
        digitalWrite(relayPin4, LOW);
        buttonFourState = 0;
      }
    }
  }

}


text:
Passing a reference as a variable
I have a function for manually jogging a stepper motor using the AccelStepper library. At the beginning of the function I would like the motor in question to be selected until told to stop.
Here is what I imagine it would look like:
AccelStepper X_Axis(AccelStepper::DRIVER, 3, 2);
AccelStepper Y_Axis(AccelStepper::DRIVER, 5, 4);
AccelStepper Z_Axis(AccelStepper::DRIVER, 7, 6);

void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  if (Dir == 0){i = 1;}else{i =- 1;}
  setSpeed(i * Spd);
  switch(axis)
    {
      case 1:
      axis = X_Axis;
      break;

      case 2:
      axis = Y_Axis;

      case 3:
      axis = Z_Axis
    }
  while (!Serial.available()){

      axis.runSpeed();
    }
  }

The axis variable should map to whichever axis is called and so control the desired stepper.
How can I achieve this?
Note: I submitted this to StackOverflow with no response. Any help would be appreciated

Don't cross post. You already asked this on SO.

How about using an array?
const int x = 0;
const int y = 1;
const int z = 2;

AccelStepper axis[] = { {AccelStepper::DRIVER, 3, 2}, ... };

void ManualJog(int Dir, int Spd, int axisIdx)
{
   axis[axisIdx].runSpeed();
}

To do it in the form you have, you would want to use a pointer.
void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  AccellStepper *thisAxis = NULL;

  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  switch(axis)
  {
    case 1:
      thisAxis = &X_Axis;
      break;

    case 2:
      thisAxis = &Y_Axis;
      break;

    case 3:
      thisAxis = &Z_Axis
      break
  }

  if (thisAxis != NULL) {
    while (!Serial.available()) {
      thisAxis->runSpeed();
    }
  }
}

Briefly: the & before the name of a variable in assignment means "Give me the address of this variable".  A * before a variable when declaring that variable means "Make this variable hold the address of another variable of this type".  You then have the address variable hold the address of your chosen axel, and then "dereference" that with the "poiner dereference operator" -> (instead of using .).
A check is added to see if thisAxis has actually been assigned anything or not, although you could use the default: case in your switch to abort on an invalid axis number instead.
Depending on how the rest of your program works, though, it may be possible to not use the "axis" integer at all, but pass a reference to the correct stepper to the function:
void ManualJog(int Dir, int Spd, AccelStepper &axis) {
  int i;
  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  while (!Serial.available()) {
    axis.runSpeed();
  }
}

In this example the & before the axis variable in the function prototype means "Pass me the address of the variable", and a new variable is created located in the same memory space. This is the pass by reference operator in C++.

I very much don't like using "magical numbers" to select the axis. It would be much nicer (and faster) not to pass int axis into ManualJog method, but pass a reference to AccellStepper so the code is more readable.

@FilipFranik I agree wholeheartedly - however judging by the way the question is worded, and how the function looks like it's meant to work, at some point the correct axis is going to have to be "selected", and that will probably mean setting a pointer at some point in the sequence.

Brilliant, thank you for this. Pointers are something I have not dealt with before. you are correct in that i wish to select the reference of the motor depending on the input. I will give this a go and respond with my working code.


text:
Memory leakage caused by String Concatenation
In this link, section "Memory, memory, memory" it's been told that doing many String concatenations in sequence, e.g.: using operator+() multiple times, will cause memory fragmentation, which may lead to the fact that total heap not being totally used.
An alternative I'm suggesting is using strcat() with char buffers and not using Strings at all, and then convert from resultant char buffer to String if a String is needed at the end?
Would that be an escape from fragmentation of the heap?
Clarification: I will specify the upper bound of the char buffer beforehand, as if I know the maximum needed/to-be-used size.

Useful read: The Evils of Arduino Strings

If you size the buffer to be able to hold your final string, then yes, that method will avoid the fragmentation caused by the String concatenation function.
Note that String holds the string as a C-style char array internally; it is the concatenation procedure which dynamically allocates and deallocates memory, causing the fragmentation.

I wonder, if simply by allocating and deallocating then memory is fragmented, a char buffer then causes fragmentation! (I mean since I will be freeing it) But since the allocated size is fit to requirements then it's still a lot better than String concatenation. Agree?

What the String object does is allocate a new piece of memory large enough to contain the resulting concatenated data, copies both source strings to the new memory, and then deallocates the old memory (of the first String). This means there is a free bit of memory that is now smaller than any subsequent needs for future concatenation of the string in question, so that bit of free memory could be used again by some other function, but it won't be used again by the String being concatenated onto.

I think that the the standard C string manipulators are better for small micros than the String object, though they are more complicated to use. Both methods work in many cases, but you must be aware of how they work so you can understand when debugging problems.

Your method would reduce the fragmentation. But will your application need do this once? A few times? Must it run forever? If your application uses malloc()/free() or new/delete pairs often, it will fragment the heap, causing it to grow, and eventually cause a stack collision. This is not so much about the Arduino being a resource-limited device; it will eventually happen in any continuously running device with a fixed amount of memory.
If you can set an upper bound to the buffer requirements, then pre-allocating a buffer-pool globally, locally as a file-level- or local-static, or on the heap (using malloc() [1]) - an array of "big-enough" buffers and enough of them for your application. Then always allocate/de-allocate one of these and you will avoid fragmentation. Your application (or buffer-handler library) will have to keep track of which buffers are free and which are in use, just as the system allocators do. But in exchange for writing this way, you get to allocate and deallocate memory, forever, fragmentation-free. Every request, and every return is the same size, so any free piece can fill a request with no need to grow the pool.
My personal preference is a static allocation (file-level or globally visible) because 1) it comes from lower memory which has the same effect as allocating it on the heap, and 2) it is declared as an array of arrays so array-indexing syntax works without manually having to write around it as you might if you malloc()ed on big chunk.
Note[1]: Though I have cautioned against using malloc() and free() calls, here and elsewhere on the site, the cause of fragmentation is repeated allocation and de-allocation from/to the heap. In this case, though, I'm suggesting using malloc() to allocate memory which will be kept for the rest of the program run.

When setting an upper-bound e.g. char buff[ 100 ], am I not allocating it on the stack? I want to use the heap instead. Because the stack in esp8266 I'm working on is only 4KB if I'm not mistaken.

I was not clear that the buffer pool needs to be allocated made statically - that is, as a global, a static, or from the heap (with malloc()). I've updated my answer to clarify that.


text:
Shutdown the LED of my GY-85 sensor
I would like to shutdown the LED of my GY-85 (gyroscope) component. Is it possible?

use black paint

it's about energy, not visual comfort

next time you ask a question, please include that kind of information in your question

According to this schematic, no. The LED is connected directly to power.
You will need to physically remove the LED to turn it off.


text:
"not declared in this scope" error message
Error message 'dir1PinL' was not declared in this scope. keeps coming up. Any ideas?
#include "Arduino.h"

/*motor control*/
void go_Advance(void)  //Forward
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Left(void)  //Turn left
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void go_Right(void)  //Turn right
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Back(void)  //Reverse
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void stop_Stop()    //Stop
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, LOW);
}

/*set motor speed */
void set_Motorspeed(int speed_L, int speed_R)
{
  analogWrite(speedPinL, speed_L);
  analogWrite(speedPinR, speed_R);
}

//Pins initialize
void init_GPIO()
{
  pinMode(dir1PinL, OUTPUT);
  pinMode(dir2PinL, OUTPUT);
  pinMode(speedPinL, OUTPUT);

  pinMode(dir1PinR, OUTPUT);
  pinMode(dir2PinR, OUTPUT);
  pinMode(speedPinR, OUTPUT);
  stop_Stop();
}

void setup()
{
  init_GPIO();
  go_Advance();//Forward
  set_Motorspeed(255, 255);
  delay(5000);

  go_Back();//Reverse
  set_Motorspeed(255, 255);
  delay(5000);

  go_Left();//Turn left
  set_Motorspeed(255, 255);
  delay(5000);

  go_Right();//Turn right
  set_Motorspeed(255, 255);
  delay(5000);

  stop_Stop();//Stop
}

void loop()
{
}

This is the entire error message:
Arduino: 1.8.6 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Advance()':

smartcar-lesson1:20:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:21:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:22:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:23:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Left()':

smartcar-lesson1:27:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:28:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:29:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:30:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Right()':

smartcar-lesson1:34:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:35:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:36:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:37:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Back()':

smartcar-lesson1:41:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:42:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:43:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:44:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void stop_Stop()':

smartcar-lesson1:48:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:49:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:50:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:51:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void set_Motorspeed(int, int)':

smartcar-lesson1:57:15: error: 'speedPinL' was not declared in this scope

   analogWrite(speedPinL,speed_L);

               ^

smartcar-lesson1:58:15: error: 'speedPinR' was not declared in this scope

   analogWrite(speedPinR,speed_R);

               ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void init_GPIO()':

smartcar-lesson1:64:10: error: 'dir1PinL' was not declared in this scope

  pinMode(dir1PinL, OUTPUT);

          ^

smartcar-lesson1:65:10: error: 'dir2PinL' was not declared in this scope

  pinMode(dir2PinL, OUTPUT);

          ^

smartcar-lesson1:66:10: error: 'speedPinL' was not declared in this scope

  pinMode(speedPinL, OUTPUT);

          ^

smartcar-lesson1:68:10: error: 'dir1PinR' was not declared in this scope

  pinMode(dir1PinR, OUTPUT);

          ^

smartcar-lesson1:69:11: error: 'dir2PinR' was not declared in this scope

   pinMode(dir2PinR, OUTPUT);

           ^

smartcar-lesson1:70:11: error: 'speedPinR' was not declared in this scope

   pinMode(speedPinR, OUTPUT);

           ^

exit status 1
'dir1PinL' was not declared in this scope

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

is that the whole error message?

It doesn't look like you've created any variable with that name in your code.  That's what that error message usually means.  You must create a variable and give it a value before you can use it elsewhere.  Go find any good C++ tutorial and go through the first bit of it and you will learn these sorts of basics pretty quick.
Your code would need a line at the top that looks something like:
int dir1PinL = 2

or whatever number value you want that variable to have depending on what pin you're actually talking about there.  Similar for the other variables you are trying to use.


text:
ESP8266 12-E can't connect to any Access Point with converted variables from strings to char arrays
I'm using an esp8266 12-E nodemcu
I wrote a code that scans the available WiFi networks, print them through serial communication,ask the user which network he wants to connect to and then the password for that network. The problem is that the nodemcu won't connect to that network. I think that the problem is when I convert the strings buffer_pw and buffer_ssid to the char arrays password and ssid. Why does it give problems to connect?
#include <ESP8266WiFi.h>

int num_ap; //number of access points
String buffer_ssid = "empty"; //temporary stores the ssid in here because then it has to be converted in a char array
String buffer_pw = "empty"; //temporary stores password and same thing as^^
bool askPW = false; //"Did I already ask the password?"
bool connesso = false; //"Did I already connect?"

void setup()
{
  Serial.begin(9600);
  WiFi.mode(WIFI_STA); //put the nodemcu in sta mode so that it can connect to access points
  WiFi.disconnect();   //it disconnects from any access point it was connected to
  Serial.println("Setup completo");
  num_ap = WiFi.scanNetworks(); //scans for access points
  if (num_ap == 0)   //if there aren't any access points available
  {
    Serial.println("Nessun Access Point rilevato");
  }
  else //if there are some access points available
  {
    Serial.println("Access Point rilevati:");
    delay(200);
    for (int i = 0; i < num_ap; i++)
    {
      Serial.println(" ");
      Serial.print(i + 1);
      Serial.print(") ");
      Serial.print(WiFi.SSID(i)); //print access point's ssid
      Serial.print(" ");
      Serial.print("(Potenza segnale: ");
      Serial.print(WiFi.RSSI(i)); //prints access point's rssi(strength of signal)
      Serial.print(")");
      delay(50);
    }
    delay(500);
    Serial.println(" ");
    Serial.println(" ");
    Serial.println("A quale Access Point ti vuoi connettere?");

  }
}

void loop()
{
  if (buffer_ssid == "empty") //if the variable has the standard value "empty" so if the user has already given an ssid. I need this to execute  this piece of code once
   {
    if (Serial.available() > 0)
     {
      buffer_ssid = Serial.readString();  //stores user input(the ssid) in buffer_ssid
      if (buffer_ssid != "empty") //if the variable isn't empty(if the code has successfully saved the ssid) prints the ssid
       {
        Serial.println(buffer_ssid);
       }
     }
   }

  if(buffer_ssid != "empty") //if the user has given an ssid
  {
   if(askPW == false) //if the code has asked the password(I need this in order to execute this piece of code once)
    {
     Serial.println("Inserire la password per connettersi all'Access Point, se non serve premere spazio e invio"); //"insert the password"
     askPW = true;
    }
    if (Serial.available() > 0)
    {
      buffer_pw = Serial.readString(); //saves user input(the password) in the variable buffer_pw
      if(buffer_pw != "empty") //if the code has successfully saved the password so it hasn't the standard value "empty"
      {
        Serial.println(buffer_pw);
      }
    }
  }

  if (buffer_pw != "empty" && buffer_ssid != "empty") //if buffer_ssid and buffer_pw aren't "empty", so if the user inserted them
  {
    if(connesso == false) //in order to execute this piece of code once
    {
     //converts the strings buffer_ssid and buffer_pw in char arrays(I have to do this because WiFi.begin() doesn't accept strings)
     char ssid[buffer_ssid.length()];
     buffer_ssid.toCharArray(ssid,buffer_ssid.length());
     char password[buffer_pw.length()];
     buffer_pw.toCharArray(password,buffer_pw.length());
     //start connecting
     Serial.println("Connessione in corso");
     Serial.println(ssid); //prints ssid
     Serial.println(password);//prints password so I know that they were converted succesffully
     WiFi.begin(ssid,password);//start connecting
     while(WiFi.status() != WL_CONNECTED) //while it's not connected
     {
      Serial.print(".");
      delay(500);
     }
      Serial.println("Connesso!"); //"Connected!"
      Serial.println("Il mio ip locale: ");
      Serial.print(WiFi.localIP()); //nodemcu's local IP

    }
    connesso = true;  //set connesso to true so that this piece of code doesn't loop
  }
}

Don't cross post. You already asked this on SO.

Ok thanks, I won't do that anymore. I did this because a guy in the comment suggested me to ask this question in this Stack Exchange

Problem is that you set to toCharArray the length of the String. But the second parameter is the maximum allowed length of the output and there is then no space for the terminating zero and string is cut at last character.
The function toCharArray knows the size of the String. The second parameter should be the size of the char array buffer_ssid.toCharArray(ssid, sizeof(ssid));
And next problem could be that you copy the CR/LF characters from input into ssid and password. You can see it in debug printouts.

Thank you very much! One thing is that I had to add "- 1" to the char length, so now it is:                                                                                char ssid[buffer_ssid.length() - 1];
char password[buffer_pw.length()  - 1];

because you left the CR/LF there. this cuts it out. but it is not the right solution. set None or only CR or LF in Serial Monitor and it will be wrong again

@MyAlexro  You're better off avoiding the arrays altogether. You don't need to copy the String contents into them - just use the c_str() String method. You'd call WiFi.begin(buffer_ssid.c_str(), buffer_pw.c_str()) and skip the copies and char[]s. c_str() is very efficient; it just returns a pointer to the String's internal character buffer. Of course, after you trim the CRLF from the end of your Strings.

@JohnRomkey Ok thanks, I didn't know that function


text:
Arduino Uno won't upload code and overheats
We are using an Arduino Uno R3 connected via USB to a computer. The main problem is that we can't upload any code to the board. We get this error in the Arduino IDE console:

avrdude: ser_open(): can't open device ".\COM1": The system cannot find the file specified
  Problem uploading to board. Visit http://www.arduino.cc/en/Guide/Troubleshooting#upload

My computer may not recognize the board, the IDE won't find any port (COM) and on the board I got the three LEDs turned on, they don't even blink, they stay turned on as long as I have connected the Arduino to the computer. Apart from that, the Arduino heats too much and too fast. I don't have anything connected to it yet. I've tried resetting the board with its built-in button, I've also tried changing the USB cable, even the computer, different system architecture and OS. I don't to want to mess up the board even more, so I don't know what to do. Could you point out what's the problem with my board?
If you need more information, I will try to post as much as you need to help me out.

The fact that it doesn't blink the LED when plugged in or reset indicates that the bootloader of the main microcontroller no longer works.
The fact that the computer no longer recognizes the board as a serial port means that the USB-to-Serial interface doesn't work.
The fact that it heats up tells you that at least one of the chips on the board is dead.
I'm afraid that you'll have to get yourself a new Arduino.

Yeah, I'm afraid of that too. Anyway I got an Arduino Mega2560 to work with, but I wanted to know if I could do something to save the UNO.

Probably not in a cost-effective way.

See Have I bricked my Arduino Uno? Problems with uploading to board

First of all (with unplugged Uno) visually (and maybe with help of some magnifying glass) check, that really there is nothing stuck there, what should not be (tin ball, pice or wire or such) and that all copper lines on PCB are OK (and not shorted or broken). Also check all chips, resistors etc. are visually clean, good soldered and undamaged. If something looks damaged or burned, the it is probably damaged and should be replaced anyway.
If you connect it (I suggest USB charger, to be sure to not damage computer) and the main chip (MCU) is hot, I think, that it is dead.
If some other chip is hot and MCU not so much, then maybe the MCU is not dead, but something else is broken. (probably the hot part, but maybe also some resistor/capacitor shortcuted)
The way it is now makes it is dead for you anyway, so there is not much to came worse.
I would try to connect it only to USB charger (to not damage expensive computer by bad luck) and measure voltage on various points of the board (from ground). There should be 5V straight at 5V pin, also on the same 5V on ISP head, one pin of USB connector and on all power pins on MCU and the other chip between it and USB (new R3 have some atmega there too).
Take schema for that and try to measure on the right places. Be carefull to not shortcut anything with your voltmeter rod (it is easy to connect two legs with it and it may damage something not damaged yet). You can try to check voltage anywhere safely, on some places there should be 0V, on some 5V, but in default setup (no program working yet) the i/o pins are INPUT on boot, so just High resisteance and no strong voltage on them (you should get probably weak 0V until there is some interference).
If you identify (or thing so) wrong part, you can try to replace it with new one - good training even if you botch it and you risc youst price of the new part. Even the MCU can be changed with good soldering pen and some effort. The schema is simple, but the legs are tiny and many of them.
As it is effectively dead for you now, the worse what can happen is, that you burn the new part too and throw it all away (as you would anyway). The best what can happen is that you repair it and it will work flawlessly.
I build some "arduinos" from the SMD chip and other parts on home made PCBs - all worked well. So If you want some entertainment and practise, it is not bad think to try.
If you do not want risc the price of new MCU, but want the practise, yout take away and thyen resolder the (already broken) MCU - it would not repair it, but you can see for yourself, if you think you are able do similar experiments and if you enjoy it.

I found, that some chineese cheap clones have voltage stabilisers, that can break on shortcut and then do anything (usually the output is then shortcuted to input, so the power goes full where only stabilised 5V should be, but also can shortcut to ground, burn to total resistance, or something random between)
It is usually not good idea have arduino connected to two powersources (like external power source for servos AND USB for programming it) at the same time, as there may be different voltage on both and big currents between in some cases. If you need more power for servos (or something) and USB for serial/programming, then better there should be no direct connection between the external source power and Arduino +5V/+3.3V or any pin - just common ground, everything other separated by at least transistor (base on pin, collector on external source) or so.


text:
How to connect Mg995 and arduino nano since nano can only output 40mA at max?
Datasheet for Mg995 shows:
Current draw at idle 10MA
No load operating current draw 170MA
Stall current draw 1200MA

Maximum current that an arduino nano can output is 40mA.
So, what intermediary component should I use to make the connection between the two work?

The servo has 3 Pins to connect: Vcc, GND and PWM. The power, which actually drives the servo is drawn through the power lines Vcc and GND. The PWM pin, which is connected to an Arduino output pin, does not draw mich current. It is only for the PWM (-like pulsed) signal, which tells the servos driver, which angle is requested. But you should not power the servo through the Arduino. You have to connect it directly to a power supply with the correct voltage, because some parts of the Arduino can get fried, when drawing too much current through it.
So all in all: Connect the PWM pin directly to an Arduino output pin and supply the power from the source directly to the servo, not going through the Arduino.


text:
Extra "zero" displayed on LCD when integer sent from PC to Arduino through serial port
Every time I send an integer from computer to Arduino an extra zero is displayed on the LCD connected to Arduino. I don't know the reason. Why?
Here is the code:
#include <LiquidCrystal.h>

int en = 2, rs = 3, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
int a;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);

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

}

void loop() {
    Serial.println("Enter a number");
    while(Serial.available()==0){}
    a=Serial.parseInt();
    lcd.print(a);
}

The result is as follows:

Enter a number
When I enter the number 1
The result 10 is displayed instead of 1

and what you get if you print a back to Serial Monitor?

It is a typical problem when reading the serial input. The more experienced arduino users do not use such a while-statement to wait for input and do not use the Serial.parseInt functions. You might send a linefeed as well, and the Serial.parseInt can not make a number from the linefeed and returns zero or perhaps it has a timeout and returns zero. https://www.arduino.cc/en/Reference/StreamParseInt

Is there any alternate command/function instead of using Serial.available() and Serial.ParseInt()???

@Jot, not true. parseInt has no problem with LF or any other character. we still don't know what is the value of a

@Juraj there could be a linefeed and there could be a timeout. I'm pretty sure the parseInt returns a normal number the first time and a zero with the next call to parseInt. In my opinion it is very obvious (even without actually testing it).

@Jot, true. Rizwan, add while (Serial.read() != -1)' after parseInt();

It is display related problem. You need to clear display field(s) before printing number.

The Serial.parseInt returns zero when it can not find a number within a timeout. That timeout is default one second.
When a number is typed in the serial monitor, often a linefeed is added to it. That linefeed is read by Serial.parseInt. It can not make a number out of that and waits until the timeout and returns zero.
There is no way to tell if the Serial.parseInt returns zero because the number was zero, or if it returns zero because there was a timout.
You can try the next sketch to show the problem. Set the line ending in the serial monitor to linefeed or carriage return or both or nothing and see what happens.
int a;

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

void loop() {
  Serial.println("Enter a number");
  while(Serial.available()==0){}
  a=Serial.parseInt();   // it returns zero with a linefeed !
  Serial.println(a);
}

The easiest way to fix this, is to use a number that is only a single digit. The function isdigit is used to check the incoming characters.
void setup() {
  Serial.begin(9600);

  Serial.println("Enter a number (a single digit)");
}

void loop() {
  if (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isdigit(inChar)) {
      int value = inChar - '0';
      Serial.println(value);
    }
  }
}

The Serial.parseInt is not completely useless, but the number zero can not be used. The next sketch ignores the input when Serial.parseInt returns zero.
void setup() {
  Serial.begin(9600);

  Serial.println("Enter a integer, but not zero, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    int value = Serial.parseInt();
    if (value != 0) {
      Serial.println(value);
      Serial.println("Enter a integer, but not zero, with a linefeed at the end");
    }
  }
}

To be able to allow to type the number 0, the Serial.parseInt can no longer be used. To avoid waiting and delays, every character is immediately put into a buffer. The sketch becomes larger, but there is no other way. Either use Serial.parseInt or do it right.
#define BUFFER_SIZE 40
char buffer[BUFFER_SIZE];
int index;

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

  Serial.println("Enter a integer, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    bool ready = false;

    int inChar = Serial.read();
    buffer[index] = (char) inChar;
    index++;
    if (index >= BUFFER_SIZE) {
      index = BUFFER_SIZE - 1;
      ready = true;
    }

    if (inChar == '\n' || inChar == '\r') {
      ready = true;
    }

    if (ready) {
      if (isdigit(buffer[0]) || buffer[0] == '-') {
        buffer[BUFFER_SIZE - 1] = '\0';
        int value = atoi(buffer);
        Serial.println(value);
        Serial.println("Enter a integer, with a linefeed at the end");
      }
      index = 0;
    }
  }
}

thank you so much..@Jot..                                                                                Thank to all of you..

2 things:

use lcd.println() instead of lcd.print().

Once you open the serial monitor, set it to "No line ending" instead of "newline".

if you do step 1 but miss step 2 the 0 will print on the next line.


text:
NodeMCU minimum supply voltage)
I have read several articles an datasheets, but I couldn't find an affordable answer...
This is my problem: I need to power a NodeMCU (on Vin pin) with 3xAA batteries. Which is the minimum operating voltage at Vin accepted by NodeMCU? In other words, which voltage drop from 4.5 will let NodeMCU still working?
thanks.

i run several simple devices on 2xAA batteries connected to VCC. Only uses about 2/3rds of the battery, but for me, that's years of operation before they drop down to under 2.5v...

If you have 2xAA why don't you connect them directly to 3V3 pin?

good idea. so good in fact, that's what i did (VCC == 3.3v)

The NodeMCU uses the SPX3819 3.3v voltage regulator.
That regulator, according to the datasheet has a dropout of maximum 700mV, but much less at lower currents.
Taking the maximum, that means that you need to supply 3.3 + 0.7 = 4V to the board for the regulator to regulate properly. However, it is doubtful you will be using that much current, so probably nearer a 350mA dropout - which means 3.3 + 0.35 = 3.65V.
However, the ESP8266 itself will work down to 2.5V - so if you operate the board with the regulator out of regulation (not recommended, but it should work fine), you could probably go as low as 2.8 to 3V without problems.

But I can't connect 4.5v to 3.3 pin, correct?

No. That's why I say 2.8 to 3v because the regulator will drop an unknown amount.

In other words: my 3xAA battery pack could work until it supplies at least 3.5-3.6v?

Sounds about right.