text:
Convert byte* to int in Arduino
I am trying to convert byte* value to int here is how I have it.
void mqttCallback(char* topic, byte* payload, unsigned int length) {

  String topicStr = topic;
  int* payload_value;
  int updates_cal;

    payload_value = (int*)payload;
    //updates_cal = *payload_value;

    Serial.print((int)payload_value);

  delay(1);

  Serial.println();
  Serial.println("-----------------------");

}

I am getting MQTT payload as Integer value. Which I want to receive in my NodeMCU (ESP8266).
Is there any way to do this?
Thank you!

If you want to convert a byte * to int, then you already have it, assuming that int is large enough to store an address on your platform. But what would be the point of this? Your payload_value is an address.

@AnT I just want integer (without pointer). How can I Serial.print it?

What specific integer do you want? Taken from where?

@AnT the integer is published by MQTT as a message.

The description of the format of MQQT message suggest that the second part of my answer (as well as Duncan C's) answer is the proper way to do it.

I tried that but its throwing error. Here is how the error looks like:

Exception (9):
epc1=0x40202430 epc2=0x00000000 epc3=0x00000000 excvaddr=0x3ffeeb79 depc=0x00000000

stack>>>

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

Considering the lengthy comments in the accepted answer, please consider editing this questions and / or title to reflect a more clear statement of what was desired.

Judging by the comments, you are actually receiving your integer data as text, as a sequence of ASCII characters. This is what you send yourself using mosquitto_pub. The buffer is apparently not zero-terminated.
If these characters represent an integer value, then the way to retrieve it as an integer value would be
char buffer[128];

// Make sure here that `length` is smaller than the above buffer size.
// Otherwise, you'd need a bigger buffer

// Form a C-string from the payload
memcpy(buffer, payload, length);
buffer[length] = '\0';

// Convert it to integer
char *end = nullptr;
long value = strtol(buffer, &end, 10);

// Check for conversion errors
if (end == buffer || errno == ERANGE)
  ; // Conversion error occurred
else
  Sterial.println(value);

Another approach, which avoids using a separate large[ish] buffer just for the purposes of zero-termination, would be
// Build a `scanf` format string that will read no more than `length`
// characters without relying on zero-termination of the payload
char format[16];
snprintf(format, sizeof format, "%%%ud", length);

// Convert the payload
int payload_value = 0;
if (sscanf((const char *) payload, format, &payload_value) == 1)
  Serial.println(payload_value);
else
  ; // Conversion error occurred

However, this approach is less protected from integer overflow than the previous one.

Note that most of the above "jumping through the hoops" is dedicated to adding a zero-terminator to the input buffer. If instead you opt for ensuring zero-termination on the sender's side, then it would all reduce to a simple
// Convert C-string to integer
char *end = nullptr;
long value = strtol((const char *) payload, &end, 10);

// Check for conversion errors
if (end == buffer || errno == ERANGE)
  ; // Conversion error occurred
else
  Sterial.println(value);

No extra buffers required.

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

Don't know if you found an answer yet, but I had the exact same issue and eventually came up with this:
   payload[length] = '\0'; // Add a NULL to the end of the char* to make it a string.
   int aNumber = atoi((char *)payload);

Pretty simple in the end!

Keep in mind that payload[length] is not part of the memory dedicated to the payload variable. The last item in the memory space of an array always is length-1. Your approach may work most of the time, but you could potentialy overwrite other variables located at that place in memory.

byte* means "pointer to byte(s). It is usually used to point to a byte buffer, and usually will also have a length value so you know how many bytes are in the buffer. It looks like your function does have a length value.
If you're certain that the data in the payload parameter is a single int, and the length is correct for an int (2 bytes on Arduino I believe) then you should be able to cast the pointer to int* type and then fetch the value from the buffer:
void mqttCallback(char* topic, byte* payload, unsigned int length) {
  String topicStr = topic;
  int payload_value;
  int updates_cal;

  if (length >= 2) {
    //Cast payload to an int pointer and fetch the value
    intValue = *((int*)payload);
  }
}

I tried this, but there is some error. Its resetting my NodeMCU. Exception number is 9 is througing.


text:
AttachInterrupt - fail to initiate inside a class
I'm trying to create a class that uses attachInterrupt, but get this error msg:
 In member function 'void ledDoor::attach()':
ClosetLedStrip:31:82: error: invalid use of non-static member function
         attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
                                                                                ^
exit status 1
invalid use of non-static member function

I found few answers regarding static member, but it was not clear for my needs.
Appreciate help,
#define USE_SLEEP true

#if USE_SLEEP
#include <avr/sleep.h>
#endif

#define sensorPin_1 2
#define sensorPin_2 3
#define RelayON HIGH
#define doorOpen HIGH

#define pwrdown_timeOut 10*(1000*60) // mins to powerdown

// volatile boolean detectDoor_1_Open = false;
//volatile boolean detectDoor_2_Open = false;
const int relayPin1 = 4;
const int relayPin2 = 5;

class ledDoor {

private:
int _sensorPin;
int _interruptPin;
int _relPin;

void  attach(){
        attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
}

void detection_door(){
    #if USE_SLEEP
        sleep_disable();
    #endif

        detachInterrupt(digitalPinToInterrupt(_sensorPin));
        if (digitalRead(_sensorPin) == doorOpen) {
                _doorOpen = true;
        }
        else {// trun off
                _doorOpen = false;
        }
        attach();
}

public:
bool volatile _doorOpen;
ledDoor(int sensorPin, int relPin){
        _sensorPin=sensorPin;
        _relPin=relPin;

        pinMode(_relPin, OUTPUT);
        pinMode(_sensorPin, INPUT); // sensor io
        attach();
}
void go2sleep() {
  #if USE_SLEEP
        sleep_enable();
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_cpu();
  #endif

}
void switchLeds(){
        if (_doorOpen == true) {
                digitalWrite(_relPin, RelayON);
        }
        else{
                digitalWrite(_relPin, !RelayON);
        }
}

};

ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void setup() {
        Serial.begin(9600);
        Serial.println("UP");
}

void loop() {
        door1.switchLeds();
        door2.switchLeds();

  #if USE_SLEEP
        door1.go2sleep();
        door2.go2sleep();
  #endif
}

perhaps the reason that you cannot find a satisfactory answer is because you do not ask a question

Firstly, if detection_door is a non-static member function, then C++ simply has no such expression syntax as just detection_door. Such functions have to either be called (with () operator) or be taken address of (with & operator). You can't just say detection_door. That's meaningless, which is what the compiler is telling you.
Secondly, as you already realized, regardless of the syntax a non-static class member function cannot be used as an interrupt handler. You need a freestanding ("ordinary") function as a handler or a static class member. Non-static class methods are beasts of completely different and incompatible nature.
I see that you have multiple ledDoor objects that you want to attach to interrupts independently.
At the level of attachInterrupt and void (void) handlers you will not be able to use a single interrupt handler function and then properly dispatch the handling to multiple individual objects. The high-level attachInterrupt mechanism is insufficient to work around this limitation in a proper way. (At ISR level you can do that, the same way Servo.h handles multiple servos, but it is more complicated.)
For this reason, in your case, as long as you want to stay at attachInterrupt level, it is better to just implement two separate interrupt handlers as external functions that will call your class methods for your existing global objects
ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void handler_door1()
{
  door1.detection_door();
}

void handler_door2()
{
  door2.detection_door();
}

and then just attach these handlers to your desired pins in a regular way.
static in this case can only change things in a purely cosmetic way.

On the second thought one can wrap the above into a quasi-elegant implementation that might look as follows
constexpr unsigned N_PINS = 16; // Range of attachable pin numbers

class ledDoor
{
  // ...

  static ledDoor *self[N_PINS];
  static void (*const HANDLERS[N_PINS])();

  template <unsigned PIN> static void handler()
  { // This is the actual interrupt handler that will dispatch the call to
    // the `detection_door` method of the proper class object
    self[PIN]->detection_door();
  }

  // ...

  void attach()
  {
    self[_sensorPin] = this;
    attachInterrupt(digitalPinToInterrupt(_sensorPin), HANDLERS[_sensorPin], CHANGE);
  }

  void detection_door()
  {
    // Your code
  }
};

And somewhere in one of the .cpp files
// Definitions and initializers for static members

ledDoor *ledDoor::self[N_PINS] = {};

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  ledDoor::handler<0>,
  ledDoor::handler<1>,
  // ...and so on...
  ledDoor::handler<15>
};

This uses a dedicated callback for each pin. Maybe a better idea would be to use interrupt number (i.e. the result of digitalPinToInterrupt) for indexing instead of pin number.
The same thing can be rewritten through lambdas instead of a template. I.e. one can get rid of ledDoor::handler<> template and instead initialize the HANDLERS array as
void (*const ledDoor::HANDLERS[N_PINS])() =
{
  [](){ ledDoor::self[0]->detection_door(); },
  [](){ ledDoor::self[1]->detection_door(); },
  // ...and so on...
  [](){ ledDoor::self[15]->detection_door(); }
};

Note that this approach is a bit more memory wasteful that it could have been, since it uses a number of static tables of pre-determined size. In essense this is a slightly different implementation of the same "gluing" approach as described here.

Where do you write ‘AttachInterrupt’?

@Guy . D: Wherever you are ready to do that. In setup(), for example.

source: Stack Exchange

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

sort: votes


text:
Make one button print different sentences on LCD
I am very new to arduino and I've been scratching my brain on how to make one button print out three different sentences. When I press it the first time, a " I am " is suppose to appear, when I press it the second time " very" and then the third time " late". I can't have three different buttons because a tone follows this button as well.

You can start with the https://www.arduino.cc/en/Tutorial/StateChangeDetection and try to count to three and use the count to display different messages.

but how do I do that with a text?

When the counter is incremented, then you can do a few if-statements to show text according to the value of the counter.

@chase if you want me to break it down more in the answer, post a follow up note under my answer below.  But regardless of what you call it, you will eventually create a state machine.  If the code is nice an clean it will be easy to maintain and add to.  If you go about it piecemeal then it might turn out to be difficult to manage.  Remember to start simple, test then add more features.  Don't try and do it all at once.  Hence why I said make a 3 state machine w/o the messages the 1st go around.

I have no idea where to start.

Consider using what is commonly called in programming as a Finite-state machine.  Advance to the next state each time the button is pressed.  Start out with 3 states and advance to the next after pressing the button.  You many need to double the number of states after adding your message to the program.  This is because you will want to press the button and only print the message once then advance to a new state where all you do is wait for the next button press.
Note, a mechanical device such as a button will need to be de-bounced either in hardware or in software.  This is because the processor may see individual makes and breaks as the button is closed and opened causing it to advance to the next state in unexpected ways.

Put more simply: Make sure your code to respond to button presses "debounces" the button presses. Then add a global variable pressCount, initialized to 0. In the code that handles button presses, increment pressCount and use it to display the appropriate message. (Then you need to decide what to do on the 4th button press. Do you reset to 0 and start over? Do you ignore button presses after the 3rd?)

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


text:
Arduino-IDE "while (!Serial)"
I have a Question regarding Arduino IDE:
Many old Arduino setup examples states that the Serial.begin() function always should begin with :
Serial.begin(9600); // (or 115200)

while (!Serial)
 {
   ; // Wait for serial to connect
 }

Now I have read a lot of comments saying that this "Wait-function" is no longer necessary ??
Is this an old routine, that's no longer necessary, or is it still important ???

That function is not obsolete. However, there is gratuitous use of it where it's not really needed.
The usage of the function that you alude to grew from the desire to make ATMega32U4-based boards (such as the Leonardo) which have a native USB interface act similar to the ATMega328P etc boards.
When you open the serial port on an Uno, for example, the main MCU is reset and the sketch runs from the start.  When you do the same on a Leonardo that doesn't happen. So by adding that code snippet to the beginning the sketch is paused until the serial port is opened.  This makes it appear that the board has been reset and the sketch is running afresh, like an Uno - but it isn't.
Placing that while loop at the start of your sketch without thinking about the consequences means that your sketch may never run. If a serial connection is required for your program then that's not such a problem. However, if all you're using the serial for is debugging, then as soon as you try and use your sketch without the computer opening the serial port it will fail.
So I would recommend not using that while loop unless you know that you want the effects that it provides.  That is, stalling the sketch until the serial port is opened by the computer.

Microcontrolers with native USB interface create an USB connection. It takes a little time. The serial prints right after begin() would be lost without waiting or the connection.
For Uno, Mega, Nano, esp8266/32 boards and other boards with a MCU without native USB support, an external USB-to-TTL-Serial converter chip handles the USB connection.
Leonardo, Micro, MKR have an MCU with built-in USB port. Some boards with Zero or M0 in name have only the native USB port, some have a debugger chip which can serve as USB-to-TTL-Serial converter too.
!Serial is a C++ construct using bool() operator. Then implementation is a function which checks if the USB connection is ready.
The waiting for native USB Serial (called SerialUSB for some boards) is used in examples to see the debug prints from setup(). But if USB is not connected, it waits and the sketch doesn't continue. It can be very confusing. So I rather use a delay(500) after Serial.begin() on boards with native USB.

You could explain some more. What if a Leonardo has that code but then is used with a power supply without usb connector.

I am working on it :-)

I have a timeout of one minute in my Leonardo and then the code continues, Serial or not.

I'm still chuckling about your Majenko comment @Juraj.  :-)

"!Serial" works due to overloading of operator "!" (logical not), not bool()

@iPathツ, what is the parameter of this overloaded operator? Where in class of Serial do you see ! overloaded?

@Juraj you're right. I haven't looked at the source code.

This is for the Arduino boards that have native USB to ensure that the serial port is ready before progressing. The while loop is not needed for Arduino boards where the USB is not native to the processor (such as the Arduino Uno).

Indicates if the specified Serial port is ready.
On the boards with native USB, if (Serial) (or if(SerialUSB) on the Due) indicates whether or not the USB CDC serial connection is open. For all other boards, and the non-USB CDC ports, this will always return true.
Ref: Arduino Reference > communication > serial > if(serial)

How  about Wemos D1 Mini and Wemos D32 Pro ?? Is it the same as for Arduino Uno ??

yeah, it's only "needed" for a few less-common ardunio boards. every ESP board should be fine without.


text:
Port 0x6F problem
When I disassemble an Arduino IDE created pjoject I see in the created code ("disassembled code actually"), the it uses IN / OUT instruction on port 0X6F.
Like this (part of disassembled list):
00E3     4FFF                SBCI      R31,0XFF                 ; .O
00E4     91A5                LPM       R26,Z+                   ; ..
00E5     91B4                LPM       R27,Z                    ; ..
00E6     B79F                IN        R25,0X6F                 ; ..
00E7     94F8                CLI                                ; ..
00E8     1161                CPSE      R22,R1                   ; a.
00E9     C004                RJMP      L00EE                    ; ..

00EA     918C                LD        R24,X                    ; ..
00EB     9530                COM       R19                      ; 0.
00EC     2338                AND       R19,R24                  ; 8#
00ED     C002                RJMP      L00F0                    ; ..

00EE     91EC      L00EE:    LD        R30,X                    ; ..
00EF     2B3E                OR        R19,R30                  ; >+
00F0     933C      L00F0:    ST        X,R19                    ; <.
00F1     BF9F                OUT       0X6F,R25                 ; ..
00F2     9508      L00F2:    RET

Anyway the ATMEGA328 Datasheet says that port 0x6F is memorymapped and as such should be accessed through LDS/STS instructions.  This problem really confuses me.  Can anyone give me an explanation ??  Thanks !

What is the original C/C++ code?

avr-objdump disassembles those bytes to in r25, 0x3f and out 0x3f, r25, which is consistent with Mikael Patel's answer. It looks like your disassembler is broken.

The AVR operation code for the IN instruction is:
Loads data from the I/O Space (Ports, Timers, Configuration Registers, etc.) into register Rd in the Register File.

Operation:
(i) Rd ← I/O(A)
Syntax: Operands: Program Counter:
(i) IN Rd,A 0 ≤ d ≤ 31, 0 ≤ A ≤ 63, PC ← PC + 1
16-bit Opcode: 1011 0AAd dddd AAAA

The disassemble of the operation code B79F (hex) = 1011 0111 1001 1111 (bin) is IN R25,$3F which is actually SREG.
The block of code with the IN, CLI and OUT instruction is a critical section where the flags in SREG are saved, interrupts are turned off, and later the SREG is restored.
Cheers!

Thansk a lot . I'll check with the Disasm creator, tell him the problem and recompile when I get a new version.. Hope that solves the problem.   Anyway many, many thanks for the constructive answers.

HI: (time 22:23 European  time):   Called him, told him about the error. He examined. Corrected it. Returned a new version. I ran it. Disassembled the file (which give the above list), io-ports are now correct (all in range 0x00 - 0x6F) Thank for a valuable help.  KSH


text:
Scanned RFID data is not appearing in the serial monitor
I am attempting to use this code to receive data from 2 ports, alternating between them:
/*
  Software serial multple serial test

  Receives from the two software serial ports,
  sends to the hardware serial port.

  In order to listen on a software port, you call port.listen().
  When using two software serial ports, you have to switch ports
  by listen()ing on each one in turn. Pick a logical time to switch
  ports, like the end of an expected transmission, or when the
  buffer is empty. This example switches ports when there is nothing
  more to read from a port

  The circuit:
  Two devices which communicate serially are needed.
   First serial device's TX attached to digital pin 10(RX), RX to pin 11(TX)
   Second serial device's TX attached to digital pin 8(RX), RX to pin 9(TX)

  Note:
  Not all pins on the Mega and Mega 2560 support change interrupts,
  so only the following can be used for RX:
  10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

  Not all pins on the Leonardo support change interrupts,
  so only the following can be used for RX:
  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

  created 18 Apr. 2011
  modified 19 March 2016
  by Tom Igoe
  based on Mikal Hart's twoPortRXExample

  This example code is in the public domain.

*/

#include <SoftwareSerial.h>
// software serial #1: RX = digital pin 10, TX = digital pin 11
SoftwareSerial portOne(10, 11);

// software serial #2: RX = digital pin 8, TX = digital pin 9
// on the Mega, use other pins instead, since 8 and 9 don't work on the Mega
SoftwareSerial portTwo(50, 51);

int RFIDResetPin = 13;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // Start each software serial port
  portOne.begin(9600);
  portTwo.begin(9600);
}

void loop() {
  // By default, the last intialized port is listening.
  // when you want to listen on a port, explicitly select it:
  portOne.listen();
  Serial.println("Data from port one:");
  // while there is data coming in, read it
  // and send to the hardware serial port:
  while (portOne.available() > 0) {
    char inByte = portOne.read();
    Serial.write(inByte);
  }

  // blank line to separate data from the two ports:
  Serial.println();

  // Now listen on the second port
  portTwo.listen();
  // while there is data coming in, read it
  // and send to the hardware serial port:
  Serial.println("Data from port two:");
  while (portTwo.available() > 0) {
    char inByte = portTwo.read();
    Serial.write(inByte);
  }

  // blank line to separate data from the two ports:
  Serial.println();
}

I am using a mega2560, and have the pins placed in the 10 and 51 port. any help is appreciated.

Does it work, if you only use one Software serial interface? Why are you using Software Serial anyway? The Mega has 4 hardware serial interfaces. Currently I don't see, why your program should work reliably, since you are listening on the individual interfaces only for very short time intervals. Definitely not enough to receive much data at 9600 baud

@chrisl Im going to try to set a higher baud rate, maybe that will help.

This is still not a good way to read the two software serials. You could try to first read a full message from one software serial and then change to the second software serial and read a full message there. This would ensure, that you always read a valid message from each interface.

But again: Why SoftwareSerial? Why not hardware Serial interfaces?

@chrisl Yeah, I realized I was being dumb about it. I'm now using the hardware serial ports. I succesfully got serial1 to send to the serial monitor, now I a trying to set up serial2, so arduino will run through them sequentially. Any idea how to do that?

@chrisl If you are interested, the question is here


text:
code error- Real Time Clock program-DS3231 RTC module
I'am a NEW-B with an ELEGOO mega 2560 starter kit.The program code came from their disc.The verifying error message for the declaration: RTCDateTime dt; is
RTCDateTime' does mot name a type
exit status 1
'RTCDateTime'does not name a type
I can not determine what this means or how to correct.
HELP,Dick

I downloaded the tutorial code for ELEGOO Mega Most Complete Starter Kit from here: http://www.elegoo.com/tutorial/ (their web site is a mess of broken links). The RTC example (Lesson 19) does indeed use RTCDateTime type. However, the accompanying DS3231 library does properly define that type in DS3231.h. So, in that package the problem you are reporting does not exist. Maybe the version on the disc has some kind of typo? And your sure you are using their libraries?

My bet would be that you simply included a third-party DS3231.h, which has nothing to do with the proper DS3231.h. Hence the error.


text:
Read the value of a register in arduino
I want to read the value of the register (8-bit). In particular I want to read the values of:

The Timer/Counter - TCNT0 ( Adress 0x26 (0x46) )
The output compare registers - OCR0A and OCR0B.

Is there a way to read them with the Arduino program?

How about just using them in your program? You can use the register names directly

@chrisl So is the output of Serial.print(TCNT0, BIN) the current value (in binary) of the register?

Yes, that should work. You see much code on the web, where timers are configured by directly writing to the registers. You can try it. Write a value to a register and read it back. Though, if you are using the Arduino core, the timer0 counter will change, because it is used for millis() and siblings. You can try it with a currently disabled timer.

To convert my comments to an answer:
You can use the register names directly. They are defined in the boards/chips core. To read them, simply use the names in your calculations. Write to the registers by setting the value of the registers name (like a variable: TCNT0 = 0;). Be sure to look into the datasheet, to check the behavior of that register.

As noted, do check the datasheet -- some register flags are cleared (zeroed) by writing a 1 to them.


text:
Send data to API from Arduino with ESP8285 Strange Error
I have an Arduino with few sensors, and I want to send all of data to my API over ESP8285 what is connected to the wifi.
Its almost working fine, except one thing.
I have these AT commands:
String postRequest =
    "POST /hello HTTP/1.1" + String("\r\n") +
    "Host: 192.168.88.186" + "\r\n" +
    "Cache-Control: no-cache" + "\r\n" +
    "Content-Type: application/x-www-form-urlencoded" + "\r\n" +
    "Content-Length: " + String(data.length()) + "\r\n\r\n" +
    String(data) + "\r\n";

void connectWifi()
{
  espclient.println("AT+CWMODE=1");
  String connectcmd = "AT+CWJAP=\"" + ssid + "\",\"" + w_password + "\"";
  espclient.println(connectcmd);

  delay(3000);
  if (espclient.find("OK"))
  {
    Serial.println("Connected!");
  }
  else
  {
    connectWifi();
    Serial.println("Cannot connect to wifi");
  }
}

void espStatus()
{
    String tmpResp = espclient.readString();
    Serial.print("ESPLOG:");
    Serial.println(tmpResp);
}

void httppost()
{
  espclient.println("AT+CIPMUX=0");
  espclient.println("AT+CIPSTART=\"TCP\",\"" + server + "\",5000"); //start a TCP connection.
  if (espclient.find("OK"))
  {
    Serial.println("TCP connection ready");
  } else {
    espStatus();
  }
  espclient.println("AT+CIPSTATUS");
  espStatus();

  Serial.println("PRINT REQUEST ==================================");
  Serial.println(postRequest);
  Serial.println("PRINT REQUEST ==================================");

  espclient.println("AT+CIPSEND="+String(postRequest.length()));
  do {
    delay(1000);
    if (espclient.find(">"))
    {
      break;
    }
  }
  while(true);
  espclient.print(postRequest);
  delay(500);
  espStatus();
  espclient.println("AT+CIPCLOSE");
}

SETUP:
void setup() {
  Serial.begin(9600);
  Serial.println("Starting the modules....");

  espclient.begin(9600);
  connectWifi();
  Serial.println("ESP Module is ready");
}

LOOP:
void loop() {
    httppost();
    delay(5000);
}

And I get this error(?) message:
TCP connection ready
ESPLOG:
AT+CIPSTATUS

STATUS:2

OK

PRINT REQUEST ==================================
POST /hello HTTP/1.1
Host: 192.168.88.186
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
name=ESPModul

PRINT REQUEST ==================================
ESPLOG: Q�J5U�S�!*HZYlo QQA��HV�^\��
H��銒)       �&�C��y \�R
�r�+����H�

TCP connection ready
ESPLOG:
AT+CIPSTATUS

STATUS:2

OK

PRINT REQUEST ==================================
POST /hello HTTP/1.1
Host: 192.168.88.186
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
name=ESPModul

PRINT REQUEST ==================================
ESPLOG: Q�J5U�S�!*HZYlo QQA��HV�^\��
H����)      �&AC��y \�R
�r�+����H�

UPDATE The new /error/ message:
ESPLOG:Q�J5U�SS�CT��he���EE))���H��
����    )�H��HK�
Ca����E�K�V,YCCb

UPDATE2 I restarted the arduino, and now I am getting this:
TCP connection ready
PRINT REQUEST ==================================
POST /hello HTTP/1.1
Host: 192.168.88.186
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

name=ESPModul

PRINT REQUEST ==================================
ESPLOG:
AT+CIPSTATUS

STATUS:2

OK
AT+CIPSEND=155

link is not vAT+CIPCLOSE

ERROR

UPDATE3: This method is working
void testHTTP()
{
  Serial.println("Establishing TCP connection");
  espclient.println("AT+CIPSTART=\"TCP\",\"" + server + "\",5000");
  delay(1000);
  Serial.println("Sending out data…");
  espclient.println("AT+CIPSEND=16");
  espclient.println("GET / HTTP/1.1");
  espclient.println();
  espclient.println("AT+CIPCLOSE");
}

If I connect the ESP to my PC with TTL adapter, and I write the commends manually, then its working fine. And yes, the ESP is connecting correctly to the wifi, I tested it.
The main solution was to put "delay(1000);" after "CIPSEND=".
I hope my fumbling can help to someone in the future.

add one more \r\n for mandatory empty line after HTTP request header. "Content-Length: " + String(data.length()) + "\r\n\r\n" +.

Serial.println("ESPLOG: "+tmpResp), prints some random memory content at address calculated by the +. use Serial.print("ESPLOG:"); Serial.println(tmpResp);

wait for > after CIPSEND

@Juraj: No, why? Overload resolution for "ESPLOG: "+tmpResp will interpret it as String("ESPLOG: ") + tmpResp, which uses overloaded binary + for String type. Everything is correct in that expression: it does concatenate two Strings into a new String. It is unnecessarily "heavy", but otherwise perfectly correct.

@Juraj Thanks for the advice, I tried what you said, but I have the same issue. The new error message is a bit different. I added the new message to the post.

you still print wrong and you still don't wait for >

@Juraj No, I just didn't updated in the code. But now I updated those parts.

try not to request status between connection and data sending

@AnT, "ESPLOG" is const char*. what does a + do for pointer type?

There's no "+ for a pointer type" here. This is a binary +, which has two equally important operands. One operand is const char[7], another is String. This launches a process called overload resolution. And overload resolution will conclude that the best match in this case is overloaded operator + for two String operands. It will let const char[7] to decay to const char * and then it will implicitly convert it to a temporary String object. Then it will add (concatenate) two String objects forming a String result.

To put it shorter, if just one operand of binary + is a String (no matter which), the other operand will typically be implicitly converted to a String as well. And you end up with concatenation and a new String.

@AnT, yes, you are right

@G3ph4z, did you set the baud rate of AT firmware to 9600 baud?

@Juraj Sorry, I was AFK. Yea, I changed the baud in the ESP's firmware. I will test the code without ESPStatus, as you said before.

So I tried, but nothing. It doesn't send me any packet, also I can ping the ESP modul.

maybe the esp8266 crashed on connecting because of insufficient powering


text:
Esp8266 Web based code and real button
0
I wrote a code in the Arduino IDE. With this code, i can control 4 leds on and off from the web page. In the web page 9 buttons.
2 buttons for led-1 on and off. 2 buttons for led-2 on and off. 2 buttons for led-3 on and off. 2 buttons for led-4 on and off. 1 button for toggle all leds on and off.
I want also add a real button to the circuit. When i press this button, i want to run that toggle code. How can i do that?
This is my code;
#include <ESP8266WiFi.h>

const char* ssid = "UnderSpeed";
const char* password = "q1w2e3r4t5__";
const char* host = "192.168.1.185"; //it will tell you the IP once it starts up
                                        //just write it here afterwards and upload
int r0 = D0;
int r1 = D1;
int r2 = D2;
int r3 = D3;
int btn0 = D5;

WiFiServer server(301); //just pick any port number you like

void setup() {
  Serial.begin(115200);
  delay(10);
Serial.println(WiFi.localIP());
  // prepare GPIO2
  pinMode(r0, OUTPUT);
  pinMode(r1, OUTPUT);
  pinMode(r2, OUTPUT);
  pinMode(r3, OUTPUT);
  pinMode(btn0, INPUT_PULLUP);
  digitalWrite(r0, HIGH);
  digitalWrite(r1, HIGH);
  digitalWrite(r2, HIGH);
  digitalWrite(r3, HIGH);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected

  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  while (!client.available()) {
    delay(1);
  }

  // Read the first line of the request
  String req = client.readStringUntil('\r');
  client.flush();

  // Match the request
  if (req.indexOf("") != -10) {  //checks if you're on the main page

    if (req.indexOf("/r0-OFF") != -1) { //checks if you clicked OFF
      digitalWrite(r0, HIGH);
      Serial.println("Relay-0 OFF");
    }
    if (req.indexOf("/r0-ON") != -1) { //checks if you clicked ON
      digitalWrite(r0, LOW);
      Serial.println("Relay-0 ON");
    }

    if (req.indexOf("/r1-OFF") != -1) { //checks if you clicked OFF
      digitalWrite(r1, HIGH);
      Serial.println("Relay-1 OFF");
    }
    if (req.indexOf("/r1-ON") != -1) { //checks if you clicked ON
      digitalWrite(r1, LOW);
      Serial.println("Relay-1 ON");
    }

    if (req.indexOf("/r2-OFF") != -1) { //checks if you clicked OFF
      digitalWrite(r2, HIGH);
      Serial.println("Relay-2 OFF");
    }
    if (req.indexOf("/r2-ON") != -1) { //checks if you clicked ON
      digitalWrite(r2, LOW);
      Serial.println("Relay-2 ON");
    }

    if (req.indexOf("/r3-OFF") != -1) { //checks if you clicked OFF
      digitalWrite(r3, HIGH);
      Serial.println("Relay-3 OFF");
    }
    if (req.indexOf("/r3-ON") != -1) { //checks if you clicked ON
      digitalWrite(r3, LOW);
      Serial.println("Relay-3 ON");
    }

    if (req.indexOf("/btn0") != -1) { //checks if you clicked OFF
      buton_islemi();
    }

  }

  else {
    Serial.println("invalid request");
   client.stop();
    return;
  }

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\n";
  s += "Content-Type: text/html\r\n\r\n";
  s += "<!DOCTYPE HTML>\r\n\r\n";

  s += "
<input type=\"button\" name=\"rly0-on\" value=\"Relay-0 ON \" onclick=\"location.href='/r0-ON'\">";
  s += "
";
  s += "
<input type=\"button\" name=\"rly0-off\" value=\"Relay-0 OFF\" onclick=\"location.href='/r0-OFF'\">";

  s += "

";

  s += "
<input type=\"button\" name=\"rly1-on\" value=\"Relay-1 ON \" onclick=\"location.href='/r1-ON'\">";
  s += "
";
  s += "
<input type=\"button\" name=\"rly1-off\" value=\"Relay-1 OFF\" onclick=\"location.href='/r1-OFF'\">";

  s += "

";

  s += "
<input type=\"button\" name=\"rly2-on\" value=\"Relay-2 ON \" onclick=\"location.href='/r2-ON'\">";
  s += "
";
  s += "
<input type=\"button\" name=\"rly2-off\" value=\"Relay-2 OFF\" onclick=\"location.href='/r2-OFF'\">";

  s += "

";

  s += "
<input type=\"button\" name=\"rly3-on\" value=\"Relay-3 ON \" onclick=\"location.href='/r3-ON'\">";
  s += "
";
  s += "
<input type=\"button\" name=\"rly3-off\" value=\"Relay-3 OFF\" onclick=\"location.href='/r3-OFF'\">";

  s += "

";

  s += "
<input type=\"button\" name=\"btn0\" value=\"Button-0 \" onclick=\"location.href='/btn0'\">";
  s += "
";

  s += "\n";

  client.flush();

  // Send the response to the client
  client.print(s);
  delay(1);
}

void buton_islemi() {
  digitalWrite(r0, !digitalRead(r0));
  delay(500);
  digitalWrite(r1, !digitalRead(r1));
  delay(500);
  digitalWrite(r2, !digitalRead(r2));
  delay(500);
  digitalWrite(r3, !digitalRead(r3));
  Serial.println("Button Pressed");
}

you really should use the built-in http lib to make it simpler, more readable, and more flexible, like turning on and off many pins per request, like if(server.arg("r1")=="OFF")

@dandavis could you write simple example? I’m newbie.

i can't do it much better than the examples at File > Examples > ESP8266WebServer >

Just add your button check into the section where you're not handling a client. For example:
static uint8_t buttonState = LOW;
if (!client) {

  uint8_t bs = digitalRead(BUTTON_PIN);
  if (bs != buttonState) {
    buttonState = bs;
    if (buttonState == HIGH) {
      buton_islemi();
    }
  }

  return;
}

Thank you so much, it's working!!


text:
HMAC SHA256 in Arduino use case?
I am doing a school project and wanted to implement HMAC on a arduino UNO like board. I have been testing the Cryptosuite, but none of the examples work for me. Such as this one: https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde
This one https://github.com/simonratner/Arduino-SHA-256, a trimmed-down version, which sounds good but there's none working example.
Can any one point me to the right direction? Thanks a lot!!

When you are asking a question, here or on a forum, then please tell what you did and what the result was. When you say that it is not working, then we have not enough information and your question might not get answered.
I have tested the first link that you gave to Cryptosuite. It is outdated and needs to be fixed.
I renamed "hmacsha256test.pde" to "hmacsha256test.ino".
The compiler errors and warnings are in the lower part of the Arduino IDE. Scroll up to find the first problem and fix that. Repeat it until it works.
The PROGMEM requires that the 'const' keyword is used. For example in "sha256.cpp":
const uint32_t sha256K[] PROGMEM = {

The 'write' function should return a size_t value.
In sha256.h:
// virtual void write(uint8_t);
virtual size_t write(uint8_t);

In sha256.cpp:
size_t Sha256Class::write(uint8_t data) {
  ++byteCount;
  addUncounted(data);
  return 1;
}

Then it compiles and runs on a Arduino Uno, although there is a warning for low memory because 75% of the sram is used.
The second link is a changed version of the same Cryptosuite. It should be able to use the examples of the Cryptosuite, but it does not.
I can make that work as well.
Using the same example of the Cryptosuite "hmacsha256test.pde" (I renamed it to "hmacsha256test.ino"), create a object 'sha' after including the "sha256.h":
#include "sha256.h"
Sha256 sha;

In the example, replace all "Sha256" function calls with "sha" function calls:
sha.initHmac(hmacKey1,20);
sha.print("Hi There");

Then it works as well.

Thank you very much!! You are a great teacher! I have Arduino IDE 1.8.9 downloaded and installed. And added a SHA folder inside "C:\Program Files (x86)\Arduino\libraries" to install the libraries (sha256.cpp and sha256.h) adopted from the second link and use the example (hmacsha256test.pde) from the first link, and made changes as you suggested. It works well!! Although I am getting "Low memory available, stability problems may occur" due to the sketch is taking up 22% of the storage space. But that is fine for a test of the HMAC for arduino. Thanks again! Merci! Gracias! Vielen Dank! 谢谢!

I have used the https://github.com/Cathedrow/Cryptosuite/ on ESP8266. For that in addition to the changes desribed by Jot it is enough to remove
#include <avr/io.h>
#include <avr/pgmspace.h>

from the header files. Then it is working fine.


text:
HUZZAH ESP-8266 (by ADAFRUIT): How to use with the ARDUINO R3
I have recently purchased a ESP-8266 HUZZAH by adafruit. I'm kind of new to the whole arduino concept. I would like to know how I would be able to utilise this breakout board with my Arduino to do anything. I have searched on the internet and I know about flashing the board. However, I have no idea how to flash this device. Some help would be appreciated.
I also have no idea where to put my pins. I know that there are RX and TX pins on the UNO, but those are at 0 and 1. Most online guides are using something like 11/12 or 2/3.
Here is the link to the product website
Thanks,
Vraj

You wouldn't typically use it with an Uno. You program the ESP8266 directly with your own code and interface it to your devices of choice.

Oh ok. But would I still be able to use it with an arduino. I'm asking because I don't want to immediately go out and buy a new board if the old one works.

You can use it "with" an Arduino if you want to use it with an Arduino. You need some form of USB to UART device to program it, and the Arduino can do that. Just connect RESET to GND on the Arduino to disable the Arduino, then pins 0/1 can link your computer to the Huzzah.

Thanks, one other thing. I have a working MFRC522, I want to send the data from the RFID Card to the WiFi board to put it onto a website/server. If I connect it to the arduino and shut the arduino down. Would this still be possible?

No. You would connect the MFRC522 directly to the Huzzah. The Arudino is just the equivalent of an FT232 board. It's a dumb pipe. If you want to connect the MFRC522 to the Arduino then you will also have to write software for bothe the Arduino and the Huzzah to communicate between them (probably over serial).

Woah. That's weird. So I found this thing on the MFRC522 github post. It states that it is compatible with the ESP8266. So now that I have some info on that, what's the deal about the flashing thing. Would I still have to perform the flash? And how would I do that? Sorry, just very confused...

"Flashing" is the act of uploading your software to the ESP8266 from the Arduino IDE. It's how you get your code into the chip to make it do what you want it to do.

Oh yes. I see thank you. So that's what the posts meant. I think I have a deeper knowledge of the topic. Once I can fully get the solution, I'll post it as an answer. Thanks for the advice!

Ok, I'll keep this post open for anyone who got this board and the Arduino and wanted to use them together (it's probably only me, but who cares). Anyway, when looking at this board it's basically it's own controller. The front pins are what you need to communicate with the board itself. It's meant to be used with a FTDI cable to the computer. Anyway, looking further into it we see many pins behind the first 6 or so. To connect it to the computer using the Arduino you need to use this config.
Arduino | HUZZAH ESP8266
RX | RX (In the front)
TX | TX (In the front)
5V | V+ (In the front)
GND | GND (In the front)

Also, you need to create a thing where the Arduino won't be able to function, making it a communicator port for the HUZZAH itself. To do this simply take one of the GND pins on the Arduino and connect it to the RESET pin on the Arduino. After doing this you need to set up your ESP8266. This is a link to a basic guide on how to do this by ADAFRUIT. Instead of the USB cable, you are using your arduino as a cable essentially (a pretty expensive one). Anyway, the port number should be the port that your arduino is connected to (to the computer). This is if you want to use the ARDUINO IDE.
To use NODEMCU LUA which it comes preloaded with, you need to refer to this guide.
The other thing I wanted to mention was how to utilise a basic board with the controller. I had to use a MFRC522 RFID board with the Arduino, and I wanted to send the info to the internet. Sadly, it seemed as if I couldn't use the arduino itself. To use this board I used many sources. First, was the library github (this one).
The next step was to get the pin layout (from here). However, if you look at it it's in the pin format of a WESMOS D1 MINI board. The final source was to look at the product page (here) and convert the pin format to fit the HUZZAH Board (It's in the PIN section). That took a long time, but now you're done. That's a basic guide on how I used the HUZZAH Board with my arduino.


text:
How would I give an Arduino-based product WiFi credentials?
Let's imagine I create this cool little Arduino-based (replace Arduino with any embedded system that's not a Raspberry Pi) object that does some interesting things but it needs an internet connection to retrieve some information. The object doesn't have an input interface for the user because it would be meaningless if not for the WiFi credentials insertion procedure. In my testing instance, I can just hardcode the credentials before flashing the firmware, but what if I wanted to make it a product and have every user set it up on his own network?
How was such a task handled in some commercial products with similar challenges? Or what would the best way of handling it be?

I have a security camera that gets wifi creds from an app.  You enter the wifi info in the app, it generates a qr code, and you stick that in front of the camera, which scans it. Pretty clever.

You could use WPS on boot, but then you would have to press the WPS button on your AP on every boot. Another option is to have some external media plugged into the device (e.g. USB flash drive) with the passcode stored on that.

@Minijack doesn't WPS only work after you select the network you want to connect to?

@memememe Yes. The way I read your question, I thought you needed the password, not the SSID as well. you could try and connect to every WiFi network with WPS (not ideal, and may take a lot of time depending on number of networks around)

Most WiFi chips/modules these days worth paying for can function both as a WiFi client or as an AP.
So, what you would do is when the device is unconfigured, put your WiFi module into AP mode, and serve up a lightweight webpage hosted from your device. The owner connects to the devices WiFi network, and accessing the device through that webpage, they can setup their wifi information. Once configured, you switch the WiFi back to client mode, and connect to the provided Wi-Fi network.


text:
Motor code for the "Pirate: 4WD Arduino Mobile Robot Kit with Bluetooth 4.0", will not work
The board is the RoMeo BLE V 1.0 and I have set the board to Arduino UNO on the board part of the arduino IDE, as I cannot find the RoMeo Board.
This is the code for the motors.
``int speedPin_M1 = 5;     //M1 Speed Control
int speedPin_M2 = 6;     //M2 Speed Control
int directionPin_M1 = 4;     //M1 Direction Control
int directionPin_M2 = 7;     //M1 Direction Control

void setup(){

}

void loop(){
    carAdvance(150,150);
    delay(1000);
    carBack(150,150);
    delay(1000);
    carTurnLeft(150,150);
    delay(1000);
    carTurnRight(150,150);
    delay(1000);
}

void carStop(){                 //  Motor Stop
  digitalWrite(speedPin_M2,0);
  digitalWrite(directionPin_M1,LOW);
  digitalWrite(speedPin_M1,0);
  digitalWrite(directionPin_M2,LOW);
}

void carTurnLeft(int leftSpeed,int rightSpeed){         //Turn Left
  analogWrite (speedPin_M2,leftSpeed);              //PWM Speed Control
  digitalWrite(directionPin_M1,LOW);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,HIGH);
}

void carTurnRight(int leftSpeed,int rightSpeed){        //Turn Right
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,HIGH);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,LOW);
}

void carBack(int leftSpeed,int rightSpeed){             //Move backward
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,LOW);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,LOW);
}
void carAdvance(int leftSpeed,int rightSpeed){          //Move forward
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,HIGH);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,HIGH);
}

After I upload the code, nothing happens. The boards light blinks and then after that nothing occurs. How do I get the Motors moving according to the code in the loop?

As I read the documentation I found this: "Please turn OFF the Motor Power Switch, when you debug the motor with USB port." Meaning, that the motors cannot run from USB, since it cannot provide enough current. Upload your code with the Motor Power switch in OFF state. Then take the board out of your USB port and connect the external power supply to Vin. Then turn on the Motor Power Switch.

Please try that, and if it is working, I will write a formal answer to your question

So these are the specific steps that I took. Plugged the usb in with the battery supply off. Uploaded the code, unplugged the usb then turned the battery supply for the motors on. After that, nothing occurs.

Okay, so I have got this code working which prints hello when pressing the "z" key BUT the motors do not respond when I send "w, a, s, d" keys through the serial monitor.

Your code does not read any data from serial, so it cannot react to anything. The motors should start running directly, since thats what your code says. 2. Have you used the motor power switch and the motor control jumper set to the right position, as described in the documentation, that I linked?

And in your code you don't set the pinmode for the direction pin. They have to been set to OUTPUT

So the power switch is on of the motor controls. 2. The wires from the motors are placed accordingly in the motor controls. 3. I have not at all utilised the motor control terminal jumpers as I don't know how to use them. Iam  a begginner so sorry for the confusion

The motor control terminal jumpers are marked on the image on the linked documentation with "Motor Control Terminal Jumpers". Please insert the jumper headers on all 4 jumper pin pairs, as shown in the image

thank you so much... The car now works, the problem was the the board on the instructions had the terminal jumpers already soldered together, and your comment saved the day. I am estatic... Thank you once again...

Thats great. I have formulated my comments as a proper answer. If you think, that it answers your question sufficiently, then please accept it. That you

To formulate my comments as answer:
Your board has some features involving the motors/servos:

Since the PCs USB port cannot provide enough current for the motors, they can be switched off wit the Motor Power Switch. It has to be set to OFF, when you connect the board to an USB port. For operating the motors the board needs it's own power supply (a battery in your case), which can provide enough current. So in this case, you have to switch the Motor Power Switch to ON, to enable the motor drivers. Attention: If you turn on the motors while being connected to the USB port, you can damage your board and also your USB port.
The motors are connected to the pins 4, 5, 6 and 7. If you don't need the motors, you can use these pins for other purposes. For this, the board let's you disconnect the motor driver from these pins. If the jumpers, that are marked with "Motor Control Terminal Jumpers" in the image on this documentation page, are inserted onto the jumper pin pairs (in the image they are already inserted), the motor drivers will be connected to the mentioned pins. If the jumpers are not inserted there, the motors will not work, since they are not connected to the controlling pins.

Note, that you need to use pinMode(pin_number, OUTPUT); in the setup() function for all pins, that you want to use digitalWrite() on, because only this way, the corresponding pin will be set to an output (can only then output a digital signal on digitalWrite()). analogWrite() will configure the corresponding pin for you, but it is a good practice to set it as OUTPUT in setup anyway, to make it clear for readers, that this pin is an output.


text:
ESP8266 Bootloader Firmware (on the ESP8266)
It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.  If that firmware is corrupted, the ESP8266 is dead.  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.  Does anybody know how to do that?  Thank you.

what has SPI to do with bootloader (or application) flashing? classic AVR used the same pins for ISP (in system programming), but even new AVR MCU models don't use SPI pins to flash the bootloader (or application)

Possible duplicate of Wiring when burning the bootloader of esp8266

It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.

Indeed there is.

If that firmware is corrupted, the ESP8266 is dead.

Well, if that firmware gets corrupted, then yes indeed the chip is dead. That's because the firmware is in ROM, not flash - and the only way it can get corrupted is for the chip to be physically damaged internally.

I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.

No. They are SPI. SPI has nothing to do with flashing firmware. It just happens that AVR chips share the same pins as SPI for their debug protocol.
You cannot replace the bootloader on an ESP8266. It is in ROM. It's unchangeable - except as mentioned earlier by physical trauma to the silicon itself.


text:
I've gotten an error telling me, "expected initializer before 'digitalWrite'"
I should mention that I didn't write this code but got it from HERE.
#include<Servo.h>
Servo myservo; // create a servo object
int redled=13; // declare the pins
int greenled=12;

int servopin=9;
int trigpin=6;
int echopin=5;
float distance;
float duration;
int datapin=7;
int clockpin=8;
int latchpin=3;

void setup(){
  Serial.begin(9600);
  pinMode(redled,OUTPUT); // declare the pinmode
  pinMode(greenled,OUTPUT);

  pinMode(servopin,OUTPUT);
  pinMode(trigpin,OUTPUT);
  pinMode(echopin,INPUT);
  pinMode(datapin,OUTPUT);
  pinMode(clockpin,OUTPUT);
  pinMode(latchpin,OUTPUT);
  myservo.attach(servopin); // declare servo object is connected to servo pin

}

int ping() // create a function {
  digitalWrite(trigpin,LOW);
  delayMicroseconds(10);

  digitalWrite(trigpin,HIGH);
  delayMicroseconds(20);
  digitalWrite(trigpin,LOW);

  duration= pulseIn(echopin,HIGH);
  distance= duration*0.034/2; // distance is in cm
  return(distance);
  }

void loop() {
  myservo.write(90); // set servo at 90 degree angle
  float value;
  value=ping(); // call the ping function
  Serial.println(value);
  delay(100);
  if(value>20) {
      digitalWrite(redled,LOW);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000); // move the car in forward direction
      digitalWrite(latchpin,HIGH);
  }
  if(value<20&& value>15) {
      digitalWrite(redled,HIGH);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000);
      digitalWrite(latchpin,HIGH);
  }
    if(value<15) {
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // stop the car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // then again stop
      digitalWrite(latchpin,HIGH);
      delay(100);

      go(); // call go function
      delay(2000);
  }

  myservo.write(90);

}

void go() {
  int a;
  int b;
  myservo.write(0);
  delay(1000);
  a=ping();
  myservo.write(180);
  delay(1000);
  b=ping();

  if(a>b) {
   digitalWrite(redled,HIGH);
   digitalWrite(greenled,LOW);

   digitalWrite(latchpin,LOW);
   shiftOut(datapin,clockpin,LSBFIRST,B00010000); // move to the right side
   digitalWrite(latchpin,HIGH);
} else if(a<b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // move to the left side
    digitalWrite(latchpin,HIGH);
} else if(a=b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
    digitalWrite(latchpin,HIGH);
    delay(4000); // wait for 4 seconds
    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // then move to right direction
    digitalWrite(latchpin,HIGH);
    delay(2000);
  }
}

The error in full is:
sketch_may02a:31:3: error: expected initializer before 'digitalWrite'

   digitalWrite(trigpin,LOW);

   ^

sketch_may02a:32:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(10);

                    ^

sketch_may02a:34:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,HIGH);

               ^

sketch_may02a:35:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(20);

                    ^

sketch_may02a:36:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,LOW);

               ^

sketch_may02a:38:3: error: 'duration' does not name a type

   duration= pulseIn(echopin,HIGH);

   ^

sketch_may02a:39:3: error: 'distance' does not name a type

   distance= duration*0.034/2; // distance is in cm

   ^

sketch_may02a:40:3: error: expected unqualified-id before 'return'

   return(distance);

   ^

sketch_may02a:41:3: error: expected declaration before '}' token

   }

   ^

exit status 1
expected initializer before 'digitalWrite'

In addition to that, why is your ping function declared with int return type? It looks like you intended to return float value. Although in your code you are constantly going back and forth on that.

note: you have repeating code in the if blocks in the go() function ..... the first three lines of each if block are same .... move the three lines to before the first if statement and delete them  from inside the three if blocks

Your function definition starts:
int ping() // create a function {

Notice that the comment is inserted before the open curly brace. That means the curly brace is commented out. Move the comment to the end of the line, or move the curly brace to a line on it's own.

Good catch. I looked at that code and saw what I expected to see, not what's there. (voted)


text:
MD5 hash for Arduino Uno [-Wshift-count-overflow]?
I tried to test out this MD5 library (https://github.com/tzikis/ArduinoMD5 ) as a hash function on arduino uno.
What I have done is that I placed the MD5.cpp and MD5.h to the folder below:
C:\Program Files (x86)\Arduino\libraries\MD5
And launched arduino IDE 1.8.9 to test the example provided (https://github.com/tzikis/ArduinoMD5/blob/master/examples/MD5_Hash/MD5_Hash.ino):
#include <MD5.h>
/*
This is en example of how to use my MD5 library. It provides two
easy-to-use methods, one for generating the MD5 hash, and the second
one to generate the hex encoding of the hash, which is frequently used.
*/
void setup()
{
  //initialize serial
  Serial.begin(9600);
  //give it a second
  delay(1000);
  //generate the MD5 hash for our string
  unsigned char* hash=MD5::make_hash("hello world");
  //generate the digest (hex encoding) of our hash
  char *md5str = MD5::make_digest(hash, 16);
  free(hash);
  //print it on our serial monitor
  Serial.println(md5str);
  //Give the Memory back to the System if you run the md5 Hash generation in a loop
  free(md5str);
}

void loop()
{
}

However when run verify and compile, it works but got the warnings below:
...\sketch_may02a_MD5_test.ino.ino: In function 'void setup()':

sketch_may02a_MD5_test.ino.ino:15:51:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

   unsigned char* hash=MD5::make_hash("hello world");

                                                   ^

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:
In static member function 'static void MD5::MD5Update(void*, const void*, size_t)':

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21:
warning: right shift count >= width of type [-Wshift-count-overflow]

  ctx->hi += size >> 29;

                     ^

I know little of c++, can anyone help to fix this? Thanks a lot!!

size is of type size_t, which seems to be an unsigned int on the Uno, meaning 16 bits. Shifting it by 29 bits would always result in zero, I think. And that seems a complicated way to write 0.

@chrisl: Shifting by too much does not result in 0. It results in undefined behavior.

You better don't mess with the arduino system files at C:\Program Files (x86)\Arduino. Can you uninstall arduino, delete C:\Program Files (x86)\Arduino and reinstall it? Are your sketches located at Documents\Arduino? There is a libraries folder in that folder alongside the folders of your projects. That libraries folder is meant to put libraries into that you have downloaded. When using the arduino library manager and a library is downloaded, it will be put there as well.

@Jot Thanks for the tips. I noticed that it will also grab the libraries from the Document\Arduino\libraries which I thought it was only used with the arduino installed from windows app store. As you suggest, I should just use it for all the libraries to be deployed in the future.

....\sketch_may02a_MD5_test.ino\sketch_may02a_MD5_test.ino.ino:15:51: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

That is a flaw in the library. The author defined the function as taking a char * instead of a const char *.  You can ignore it, it's just a warning - however maybe raising the issue with the author could be a good idea.

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21: warning: right shift count >= width of type [-Wshift-count-overflow]

This one is a little more awkward.  The size variable is defined as type size_t.  That varies in length depending on the architecture the software is compiled on.  On the 8-bit Arduinos that's a 16 bit variable. On 32-bit Arduinos, like the Due, it's a 32-bit variable.
It is probable that the author developed the library using a 32-bit Arudino (or Arduino-compatible) device - in which case he would never see that warning (since 29 is less than 32).  However anyone that then uses an 8-bit Arduino gets the warning, and probably a corrupt hash.
However, it looks like it should only be a problem if size is too big - and it can't be on an 8-bit Arduino. So again you can ignore it, but the author should really be made aware of the issue.

OK, before I consider this is answered. Can it be fixed by a couple lines such as replacing the size_t with something else from the .cpp file? If so, I would perhaps give it a try and push it to a public github project.

Shifting past bitwidth is undefined behavior. It should not be ignored.

@EdgarBonet While I agree it shouldn't be ignored in general terms, but in this situation it will be shifting nothing anyway, so with nothing to shift it doesn't really matter. Raising an issue with the author should still be done, of course.

@Harry You could do a search and replace of size_t to uint32_t, and change the parameter of make_hash() to const char *.


text:
How to increase the serial port's data throughput
I have an array of numbers that will be subtracted from the ADC readings
of a 50 Hz sine wave. Using Serial.begin(57600);, I can only
output 25 samples per sine wave cycle, or about 1,250 samples per
second. my questions are:

how fast the increent of array number moves with y++ in my int sinus[]? because when i see on serial monitor with 52700 baudrate it can only show about 25 numbers per cycle (50Hz)
how to increase the speed the increment of y++ in my array?

int sinus[] = {
    70, 72, 83, 92, 108, 132, 157, 182, 207, 230, 243, 255, 255,
    255, 250, 238, 217, 193, 169, 143, 118, 98, 88, 77, 72, 80
};
int dataSensor;
int hasil[26];
int datasensor2;
int dataBaru;
int x;
int y;
int intPin = 2;
int output;
int output2;
int toggle;
int toggle2;
int z;

void setup() {
    TCCR1A = 0b00000010;
    TCCR1B = 0b00011100;
    TCCR0A = 0;  //disable millis, delay and mciros
    TCCR0B = 0;
    ICR1 = 3200;

    Serial.begin(57600);

    pinMode(A1, INPUT);
    pinMode(A0, INPUT);
    pinMode(A2, INPUT);
    pinMode(intPin, INPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);

    attachInterrupt(0, genJeah, RISING);
}

void genJeah() {  //intrupsi rising
    y = 5;
}

void loop() {
    dataSensor = analogRead(A0);
    toggle     = digitalRead(A1);
    toggle2    = digitalRead(A2);
    dataBaru = map(dataSensor, 0, 1023, 0, 255);

    for (x = 0; x < 25; x++) {
        hasil[x] = sinus[x];
    }
    // for (x=0; x<100; x++){

    output = sinus[y] - dataBaru;
    Serial.println(output);
    y++;
    if (y > hasil[26]) {
        y = 0;
    }
}

what does move number mean?

would raising the serial speed to 230400 help? - 57600 outputs 5760 characters per second, so even if you output a single character as fast as possible, you wont make 5760 "data points" per second (the reason you only get about 2500 per second is that you output an average of 2.3 digits per "output"

Another possibility of raising speed is sending byte data instead of ASCII data. Would that be acceptable?

I edited the title and the body of your question to make it clearer. I believe my rewriting faithfully reflects what you intended to write, but feel free to re-edit if I misinterpreted something. Note that, for the purpose of your question, the fact that you are subtracting values from an array is completely irrelevant. Ideally you should remove this part (and the corresponding code) from the question in order to keep it focused on one single problem. Unless the question is about a compile error, you should also make sure, before posting some code, that it does at least compile.

Your code doesn't compile, therefore it cannot run at one speed or another speed. For example, where is y declared? And intPin? And toggle? We can't be expected to help speed up code that won't even compile.

Arduino @ 16Mhz with AVR MCU can at most perform 8.9 K ADC sample/s (10-bits, 112 us). This assumes the same channel (pin). Changing analog pin takes additional time. The upper limit for the sketch is approx. 1 K sample/s just for the ADC (10-bits). The conversion from integer to string to print takes additional time but ADC can be run in parallel. Also the ADC can be initiated for 8-bit conversion instead.

Don't use analogRead, as analogRead is blocking, while the conversion is taking place. Better to read the ADC result value, and then immediately start a new conversion (asynchronously), while run the rest of the code in the loop.

how to read adc without using analogread?  @Gerben

i have edited again my question @jsotola

i have edited again my question @EdgarBonet

i have edited again my question @NickGammon

how to read adc without using analogread? - this is another question, isn't it? However see this: http://www.gammon.com.au/adc

See Nick Gammons link; section "Read without blocking".

If you are looking for throughput then stop sending the ASCII conversion of numbers and just send the numbers.
In other words, use Serial.write() rather than Serial.print(): you can send ~25k integers per second with a 52k baudrate.
As you are actually remapping the ADC output to a single byte, that means you can easily achieve a 48k/s throughput with this simple change.
If you are also looking for low latency please consider the USB connection is actually packet based, not stream based, which means you will receive the data in chunks, no matter how frequently you write. You can speed it up a bit flushing the channel, at the cost of throughput.

will it work with Serial Plotter?

Do you mean the plotting view included in Sloeber?

Arduino IDE has Serial Plotter too

Sorry, wasn’t aware of that. For the Sloeber one I wrote a library (PlotPlus) which can probably achieve the 10k/s throughput considering the 2 additional protocol bytes used. I’m not sure it is compatible with the Arduino IDE one, never tried myself

doesn't Serial Plotter read numbers as text?

As I said, I cannot speak for the Arduino IDE implementation, but the Sloeber one uses a binary protocol

how fast the increment of array number moves with y++ in my int
  sinus[]?

Incrementing an int is fast enough. Even on a slowish Uno, y++ will
take less than one microsecond to execute, so you can do it a million
times per second if you want...

when i see on serial monitor with 52700 baudrate it can only show
  about 25 numbers per cycle (50Hz)

Your loop() is doing more than y++, no it's no wonder it takes
more time!
There are two slow functions there:

analogRead() takes about 110 µs
Serial.println() is initially fast, but once the output buffer is
full, it runs at the speed of the serial port.

The limiting factor here is Serial.println(). You are printing
4.6 bytes on average per sample (2.6 printable characters,
plus CR and LF). Each byte is worth 10 bits on the wire (one start
bit, 8 data bits and one stop bit). That is 46 bits per sample
at 57,600 bits per second. The ratio of these numbers gives the
1,250 samples per second you experienced.

how to increase the speed the increment of y++ in my array?

It's very hard to answer this question because you did not explain what
you are actually trying to achieve. If I naively take the question at
face value, the simplest option is to just repeat y++ several times
per loop iteration:
y++;
y++;
y++;
y++;

This can obviously be optimized into
y += 4;

and the compiler may even be able to figure out this optimization by
itself.
But maybe what you don't care so much about speeding up y++, and
instead you want to process more data samples per second? If this is the
case, then you can speed up the loop by speeding up the serial port:
Serial.begin(115200);

by printing only every other sample (or one sample every N):
static bool print_this_sample;
if (print_this_sample) {
    Serial.println(output);
}
print_this_sample = !print_this_sample;

by printing one sample every so often:
static uint32_t last_print_time;
if (millis() - last_print_time >= PRINT_PERIOD) {
    last_print_time += PRINT_PERIOD;
    Serial.println(output);
}

by printing the samples in binary (first make sure they fit in a byte):
Serial.write((byte) output);

Now, what I suspect, is that you actually want to get your processing
synchronized with the 50 Hz mains. If this is the case, you will
have to completely rethink your program, and reason about the timings:
at what specific time do you want to take each sample? The Arduino
timing functions (millis() and micros()) should help.
As you see, half of this answer is me making guesses about what you may
want to achieve. This is a sign of a very badly written question.
Normally it is your job to explain that in detail. Please, rewrite the
question and provide all the necessary background to help us understand
your project, and the difficulties you are facing.

Might want to add that the number conversion will take several hundred micro-seconds as it involves integer division.

thanks, again its very great explanation


text:
Mega code not compiling on Wemos Mega board
Hi I have some code that I'm trying to port from a Mega 2560 R3 to a Wemos Mega.
#include "SoftPWM.h"
#include ESP8266WiFi.h

// Outputs to PWM & H bridge direction
// PWMs:
// DC_pwm, left_pwm, right_pwm = 3, 4, 5
int pwm_out[] = {3, 4, 5};
const int num_pwm = sizeof(pwm_out) / sizeof(pwm_out[0]);

// H bridge direction control:
// dc_1, dc_2, left_1, left_2, right_1, right_2 = 6, 7, 8, 9, 10, 11
int dir_pins[] = {6, 7, 8, 9, 10, 11};
const int num_dir_pins = sizeof(dir_pins) / sizeof(dir_pins[0]);

// Variable for reading pin inputs
int from_r_pi_pwm = 0;
int from_r_pi_dir = 0;

void setup() {

  // Inputs from Raspberry Pi
  Serial.begin(38400);

  // Set up PWM pins
  SoftPWMBegin();
  for (int i = 0; i < num_pwm; i++)
  {
    SoftPWMSet(pwm_out[i], 0);
  }

  // Set up H bridge direction pins
  for (int i = 0; i < num_dir_pins; i++)
  {
    pinMode(dir_pins[i], OUTPUT);
    digitalWrite(dir_pins[i], LOW);
  }
}

void loop() {

  // Check input from R Pi & send it to the H bridges
  while (Serial.available() < 2){}

  if (Serial.available()) {
      // read the incoming bytes:
      from_r_pi_dir = Serial.read();
      from_r_pi_pwm = Serial.read();
      Serial.print("Serial in: directions - ");
      Serial.print(from_r_pi_dir);
      Serial.print(" PWM - ");
      Serial.print(from_r_pi_pwm);
      Serial.println();
  }

  // Set direcions on H bridges
  for (int i = 0; i < num_dir_pins; i++)
  {
    digitalWrite(dir_pins[i], bitRead(from_r_pi_dir, i));
    Serial.print("pin ");
    Serial.print(dir_pins[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(dir_pins[i]));
    Serial.println();
  }

  // PWM to motors
  for (int i = 0; i < num_pwm; i++)
  {
    analogWrite(pwm_out[i], from_r_pi_pwm);
    Serial.print("pin ");
    Serial.print(pwm_out[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(pwm_out[i]));
    Serial.println();
  }
}

This compiles and runs fine on a Mega & is my go to code for setting up pwm & h bridges.
So when I was playing with WiFi I selected the Wemos R1 board from the programmer & everything worked fine but if I try that with this code I get,
#include <avr/io.h>
                    ^
compilation terminated.

exit status 1 Error compiling for board WeMos D1 R1.

So after a bit of searching I found that I should be selecting Arduino/Genuino Mega 2560 but now the upload keeps timing out,
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
An error occurred while uploading the sketch

Anybody come across this before?
Edit #1:  As per the comment below I tried setting DIP switches 1 & 2 ON and all the rest OFF (I also tried 1, 2, 3 & 4 ON and the rest OFF) but still the same compliation error if I select Wemos board.
If I select the Mega 2560 I get ESP8266WiFi.h: No such file or directory which is a new error!

You cannot simply compile code for the Mega also for the WeMos. It is complete different hardware. The Arduino Mega uses an Atmega chip, while the WeMos is an ESP. You will have to go through the whole code, change the pins, check if the required hardware is available in this chip and check, if the used libraries are compatible with the ESP. Porting is mostly not an easy task.

the wemos board is a Mega & an eps on the same board. See here

switch the dip switches 1 and 2 ON all other OFF

@Juraj tried that but still the same compliation error if I select Wemos board & if I select the Mega 2560 I get ESP8266WiFi.h: No such file or directory

The Wemos/Mega board and IDE setup is complex and not for the faint hearted. Here is the table for the DIP switch setting:
1=ON  2=ON  3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (ATmega2560<->ESP8266)
1=OFF 2=OFF 3=ON  4=ON  5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=ON  8=OFF (USB<->ESP8266 (Update firmware or sketch))
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=OFF 8=OFF (USB<->ESP8266 (communication))
1=OFF 2=OFF 3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (All independent)

Table DIP switch Special Solution:
1=ON 2=ON 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <-> ATmega2560<-> ESP8266)
USB converter CH340G connect to RX0/TX0 of ATmega2560
ESP8266 connect to RX3/TX3 of ATmega25

https://arduino-esp8266.readthedocs.io/en/latest/index.html for ESP8266 documentation.
Set the Additional Boards URL to http://arduino.esp8266.com/stable/package_esp8266com_index.json in preferences
Under Tools select Board then Board Manager, then install the esp8266 by ESP8266 Community
The Arduino IDE setup requires understanding what board setting and communication setting to use to build and upload a sketch.
Under Tools select Board then select the "Arduino/Genuino Mega or Mega 2560"
Set the DIP switches on the actual board to 1=OFF 2=OFF 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
That was the DIP switch and USB setup.
Ref. https://forum.arduino.cc/index.php?topic=578430.0
The error ESP8266WiFi.h: No such file or directory is easy. The file name should be a string: #include "ESP8266WiFi.h".


text:
No headers (.h) found in Documents\Arduino\libraries\arduino_144469 with demo code
I followed this tutorial for a demo code for the SR04 ultrasonic distance sensor (without the LCD display). I've installed the Arduino IDE and wrote the code in it and saved it in some location. Compilation of the code is successful. However when I try to upload the code, I get the message:
Invalid library found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469: no headers files (.h) found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469

There are no header files in the directory and I'm wondering if I need to download additional header files or if I should configure something else.

Is there anything in that folder?

No. It is empty.

Then delete it. The Arduino IDE tries to find a library there, because it is a folder in the library folder.

It worked. Thanks. I can't believe all it took was deleting. I looked all over the internet for a solution.

Yes! Exactly the answer I was looking for. Worked perfectly. Thanks Guys. :)

If the folder is not needed then delete it.
The Arduino IDE uses the folders in the library folder to search for library header files (ie. .h files). It expects one library in each folder. When it see's a folder without any header files in it, it will count this as an invalid library.

i had similar problem and I Fix it by changing in preferences field Sketchbook location to different drive (from c:\ to d:).
This problem can ocure on system windows 10 (probably also 8) where you have sequred drive with system installed to protect you data (or system files) against some unwanted changes. Probably there is missing in Arduino some rights to make directory and save files in temporary directories, but i'm not an expert.


text:
How to get a list of IPs in a LAN using NodeMcu?
I'm going to create an IoT system. I use a Raspberry Pi as a MQTT broker and as a webserver. Every day, the Pi gets a new IP address, so I need to find its new IP address via ESP8266 to use this information in my code. I know that I can use a fixed IP, but I don't want to, so it is better if I can find a solution.

What is the question you are asking?

Welcome to the Arduino stackexchange. Please be sure to take the tour, to know, how things are working here: https://arduino.stackexchange.com/tour

You could use mDNS.

There was some problem in the libraries that i tried, i'm trying to solve it via Pinging now.

As @Gerben say use multicast DNS aka AVAHI, it is even supported on ESP's  ref.: https://tttapa.github.io/ESP8266/Chap08%20-%20mDNS.html

First of all, if your Raspberry Pi acts as webserver and mqtt broker, in my opinion you should assign a fixed ip-address, either via configuration in the access point/router or via static ip.
However, if you insist on your approach you could do some hands-on method of pinging all addresses in your LAN-subnet and checking for the MAC-address of the respondents.
If the MAC-address matches to that of your Pi, you have found it.
I have not tested it myself, but this library seems to have what you need for this purpose.
After finding a responsive ip-address via ping, it tries to resolve the corresponding MAC-address using the etharp_find_addr function.
This struct field is the reference to a 6 byte character array that you can use for comparing with the Raspberry Pi's MAC address:
response.DestMacAddress->addr

Update:
If you only want to find the IP address of the Raspberry Pi, using mDNS as suggested by @Majenko is the superior choice.
If you are looking for all devices in your LAN, as your title suggests, pinging makes more sense.

I had a Lib problem, now i fixed it and i really close to get the result. In the loop, i send all of the ip addresses that i want and the mac adresses are shown in
pinger.OnEnd([](const PingerResponse& response)
function. I wrote a function for convert response.DestMacAddress->addr to String.
mac = mac2String(response.DestMacAddress->addr); I would like to have it on my setup function for create a list. But i can't. Could you please help me?

I am sorry, but I cannot follow your explanation. I guess it would be best, if you ask a separate question on Stack Overflow for this programming issue. Then you can layout all your code, your results/error messages and what you expect from the program. Then feel free to link to this question.

You should use mDNS.  Install (if it isn't already) avahi-daemon on your Raspberry.
Then check out the ESP8266mDNS library and the examples it has. Especially the mDNS-SD_Extended example, which performs a query for a service on the network.

I need also some other devices' ips. That's why mDNS does't work.

Make those use mDNS as well, then. Either that or redefine your expectations and requirements and embrace the static IP address.


text:
nRF24L01 6TXA_1RXA network + 6TXB_1RXB network with arduino

How to build nRF24L01 network shown above with arduino ?
SPI pins are shared between RXA,RXB and separate pins for both CE, CSN, IRQ.
Which nRF24L01 library supports my requirements ?

You can share the SPI (MISO, MOSI and SCK) pins but need separate pins for IRQ, CE, CSN.

@Kwasmich This is all the information that the OP requires, but please write an answer too.

@MichaelT My comment was meant to be an obvious generality to let zastereo improve on his/her question. I don't think the raw pin connection is what was asked about. So I hope for more details on the actual problem.

@Kwasmich Off-course I need separate pins for IRQ, CE, CSN

Answer below is definitely correct, but just to be sure: are you aware you probably don’t actually NEED two masters? The 6 peers limitation of the nRF24 doesn’t apply unless you are using databurst protocol

You can use the RF24 library that you can install right away from the Arduino IDE. It provides you all you need. Just use two instances of RF24 with different CSN and CE pins assigned to get started.
RF24 radioA(7, 8); // CE, CSN
RF24 radioB(5, 6); // CE, CSN

Use the simple ping sketch as a starting point and add a second radio to it.


text:
ISR definition causing boot loop?
I am trying to compile and upload code to an Arduino Uno from the command-line, however I seem to be experiencing an odd issue.
When I compile this code:
#include <avr/interrupt.h>
#include <stdbool.h>

ISR(TIMER0_OVF_vect) {
}

int main() {
  while (true);
}

With these commands:
$ avr-gcc -mmcu=atmega328p -DF_CPU=16000000 -std=c17 -O3 -Wall -Wextra -c boot_loop.c -o boot_loop.o
$ avr-gcc boot_loop.o boot_loop.elf
$ avr-objcopy -j .text -j .data -O ihex boot_loop.elf boot_loop.hex
$ avrdude -p atmega328p -c arduino -P /dev/ttyUSB0 -U flash:w:boot_loop.hex

My Arduino ends up in a boot loop, flashing the LED 3 times every second or so (similarly to when you press the reset button or the device powers up).
I've tried it without an empty ISR and also with different interrupt vectors (e.g. TIMER0_COMPA_vect) but to no avail. Completely removing the ISR definition stops the boot loop.

just add a nop

Your problem is not with your code. It's with how you're linking your elf file.
You haven't specified the chip to link for.
$ avr-gcc -mmcu=atmega328p boot_loop.o -o boot_loop.elf

That's the ticket! Can't believe I missed that, thanks!

You know why I spotted it so readily? Because I did the exact same thing once :)


text:
Can't find exact Part type of Stepper Motor Driver
I have searched everywhere and can't seem to find the exact model/part number for this Stepper Motor Driver.

Neither can we. We can't read the number on the chip. Can you?

It may be an ULN2003, but thats pure speculation

@chrisl Looking at the pinout and wiring (what can be seen of it), you may be spot on there. Ground and + are in the right location, certainly.


text:
Using LDR and RGB Led to get R,G,B values
Has anyone tried using a setup of RGB LED directed to cuvette and the LDR on the opposite side? using arduino to and get the RGB values..
Currently having problems with calibration... I was able to get R,G,B values of colored papers... however with colored liquids inside a cuvette I'm not getting any good results (i.e the Red/Blue/Green values goes way up like 5000++)
Used white and black paper for callibration..
No idea for liquid...

You gave us nearly no information. Please show your circuit and your code. And what does "not getting any good results" mean? Explain what you expected and what you actually see.

Never tried with a cuvette, but that is exactly how (though with an array of photodiodes) modern cheap flatbed scanners work.

Also, what do you hope to achieve doing this? The results will be, from a spectrophotometric point of view, meaningless. You are only testing 3 wavelengths within a whole spectrum of colour.

As for the RGB values, I needed it for the computation of vector values at different concentration perentages

https://www.instructables.com/id/Using-an-RGB-LED-to-Detect-Colours/  Im using this exact circuit to get the RGB values

Your are probably doing the white calibration with some clear liquid,
like water. The LDR is then lit directly by the LEDs, and is getting too
much light. It's resistance is then very low compared to the pull-down
resistor in series with it. You end up measuring something very close to
5 V.
You should try to reduce the amount of light hitting the LDR. A neutral
density filter (the kind used in photography) would be ideal.
Alternatively, you could increase the distance between the LEDs and the
LDR, and put some translucent paper in between. You could also add a
diaphragm (a small hole). Then, you can also lower the resistance of the
pull-down in order to get lower voltage readings, but beware not to draw
too much current.
A comment about the instructable you linked to: owing to the highly
non-linear characteristic of the readings you get, it is quite likely
that you get unequal RGB vales from a neutral grey. Some kind of
linearization (estimating actual light fluxes) would be needed if you
want neutral greys to be measured as neutral greys.


text:
Can I program a factory fresh Atmega328P through UART pins without burning a bootloader?
Can I program a factory fresh ATMega328P using the UART pins without burning a bootloader? These pins are TX, RX, VCC, GND, and DTR pins in the schematic below. They are not the ISP/SPI pins 10-13.
Arduino Pro Mini schematic
For example, if you program an Arduino Pro Mini (which requires an ICSP programmer) with a programmer, you're not connected to the ISP pins (basically the SPI interface: MOSI, MISO, SCLK, SS), but rather to the serial i/o and reset pins.
My understanding is that a bootloader is required if you want to program through these pins, because the Arduino bootloader looks for UART traffic at these pins upon startup and hands off operation to the user's code if no attempt at programming happens during this time.
That said, I also understand burning a bootloader is done through the ISP/SPI pins, and my PCB is already manufactured, which makes burning a boatloader somewhat of a hassle. So...
Can I program an ATMega328P through the UART pins fresh off the reel, or will I need rig up a way to burn a bootloader through the ISP pins first?

"... using the ICSP pins without burning a bootloader? These pins are TX, RX, VCC, GND, and DTR pins ... They are not the ISP/SPI pins ..." - ICSP is commonly used as a synonym of ISP, so for the 328P, that means through the SPI pins. Yes, you can do this to a factory-fresh 328P, but not through the pins you have in mind.

"if you program an Arduino Pro Mini (which requires an ICSP programmer) with a programmer," no, for Mini Pro you need an USB to TTL Serial adapter for programming over UART and bootloader

No, the ATmega's ISP does not operate over the UART pins but only the ISP pins.
To program it via a UART, you need to first load a bootloader, unless your chip was pre-programmed by the vendor, something some offer as a value-added service (or even as an essential stock item, with an Arduino type bootloader)

Thanks for confirming.... Whenever I think I've done enough research, I find out that, nope, I don't know anything. It's good to have experts around.


text:
Arduino not responding to macbook pro
When I try to upload my code onto the Arduino it just gives me the error message: "avrdude: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions."
My Arduino used to function just fine. Now when a plug it in, the lights on the Arduino do not blink like they used to, and the only pins that do anything are the ones to power. It also said something like: Arduino is not optimized for mac os. It seems that the Arduino is taking in the power but not the code. here's the code:
int led = 13; // the pin the LED is connected to
void setup() {
  pinMode(led, OUTPUT); // Declare the LED as an output
}

void loop() {
  digitalWrite(led, HIGH); // Turn the LED on
}

Is there a power LED? Is that lit? The lights for the serial connection are only going to blink if there is a program on the board that is sending serial data. I would try it on a different computer and see if its the Mac or the arduino causing issues.

Genuine Arduino or cheap Chinese clone?

While having your Arduino connected try pushing the reset button and report us if there is anything blinking.

Make sure you have a USB cable with data lines - I spent a couple of hours trying to debug a similar problem  because of a "Charging Only" cable.

I had this issue and it was because the port was not set in my Arduino IDE.
I fixed it by going to Tools -> Port, and selecting my usb device.  In my case it was called /dev/cu.SLAB_USBtoUART

I fixed it by plugging it into my other USB port (which I had previously been using)
So possibly this is caused by switching USB ports

Whoever voted this down didn't bother to say why, so I'll take a guess: They probably saw it was short and what looks like a duplicate of an existing answer. You're new here, so sorry for the crappy reception, but I figured I'd at least be able to give you some insight on what the downvote may mean.

Thanks, I appreciate making you making up for it. I debated putting an answer since its short and not expert insight. But I figured I wish someone put it for me since its super fast to attempt and hints at a possible cause.

This sounds so silly, but honestly was the just the ticket that got me to be able to finally flash via UART to my device. I had this issue both in Arduino IDE as well as VSCode ESP-IDF extension. On a MacBook Pro, ls /dev/cu.* listed /dev/cu.Bluetooth-Incoming-Port /dev/cu.SLAB_USBtoUART  /dev/cu.usbserial-XXXX and I set the PORT /dev/cu.SLAB_USBtoUART, flash method to UART, and it didn't work. Unplugging the cable from the top USB near the MacBook screen to the one right below it did work.


text:
Connecting a push button to a stepper motor problem
I can't get this code to work. The button code and the step motor code works separately. However, when I code using an if statement saying when the button is pressed the motor will move or else it won't. PLEASE HELP.
const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30

int i = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IN_1, OUTPUT);
  pinMode(IN_2, OUTPUT);
  pinMode(IN_3, OUTPUT);
  pinMode(IN_4, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.print ("start");
}

void loop() {
  buttonState = digitalRead (buttonPin);
  if (buttonState == HIGH) {
    //delay(1000);
    for (i=0; i<4; i++)
      Serial.println ("pressed");
    switch (i) {
      case 3: // ASCII value for '1'
        digitalWrite(IN_1, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_1, LOW);
        break;
      case 1: // ASCII value for '2'
        digitalWrite(IN_2, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_2, LOW);
        break;
      case 0: // ASCII value for '3'
        digitalWrite(IN_3, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_3, LOW);
        break;
      case 2: // ASCII value for '4'
        digitalWrite(IN_4, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_4, LOW);
        break;
      default:
        Serial.println("Not a valid case");
        break;
    }
    if (i == 4) {
      i = 0;
    } else {
      i = 5;
    }
  }
}

What is that if supposed to achieve in your for loop that changes the i value to 5 all the time supposed to achieve?

will you please explain what you are trying to achieve?

Your code makes no sense at all.  Let's break it down. First we'll reformat the code using the auto-formatter (AStyle) in UECIDE:
const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30
int i = 0;

void setup()

{
    Serial.begin(9600);
    pinMode(IN_1, OUTPUT);
    pinMode(IN_2, OUTPUT);
    pinMode(IN_3, OUTPUT);
    pinMode(IN_4, OUTPUT);
    pinMode(buttonPin, INPUT);
    Serial.print("start");
}

void loop()

{
    buttonState = digitalRead(buttonPin);

    if (buttonState == HIGH) {
//delay(1000);
        for (i = 0; i < 4; i++) {
            Serial.println("pressed");
        }

        switch (i) {
            case 3: // ASCII  value for '1'
                digitalWrite(IN_1, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_1, LOW);
                break;

            case 1: // ASCII  value for '2'
                digitalWrite(IN_2, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_2, LOW);
                break;

            case 0: // ASCII  value for '3'
                digitalWrite(IN_3, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_3, LOW);
                break;

            case 2: // ASCII  value for '4'
                digitalWrite(IN_4, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_4, LOW);
                break;

            default:
                Serial.println("Not a valid case");
                break;
        }

        if (i == 4) {
            i = 0;
        } else {
            i = 5;
        }
    }
}

Now that we have fixed the formatting we can see some very strange things:
if (buttonState == HIGH) {

First we're doing this for every loop iteration where the button is pressed. That means we're doing it over and over again until you release the button.
    for (i = 0; i < 4; i++) {
        Serial.println("pressed");
    }

Now we're printing the word "pressed" four times.  After this i will be set to 4.
The switch will now take an input value of 4, which is "Not a valid case". So nothing will happen.
Then:
    if (i == 4) {
        i = 0;
    } else {
        i = 5;
    }

i is always 4, so it will always set it to 0.  Quite what this block is supposed to achieve I have no clue. If it were supposed to be inside the for loop above then it would just kill the loop on the first iteration, since i, when 0, would not be 4, so would be changed to 5, which is > 4. It makes no sense and can achieve nothing of value.
As for the switch: if it were inside the for loop and able to get some varying values of i, it would just make each output briefly activate in turn. If that's what you need to drive your motor, then fine. However, it's never going to run since the rest of the program is just nonsense.


text:
Receive Signal from different circuit
I am an mid experienced Programmer but I have no clue about electronic circuits. I want my Arduino to do sth if he gets a signal from an external source. The external source has 5V and is 0V or 5V and when it has 5V I want my Arduino to send me a Message, the Code for the Message is no problem, but please help me with the circuit:
The external source is independent and runs on battery and the device has a 2.5mm jack, normally there is an LED attached that lights up, but I want my Arduino to receive the signal. Are there any opportunities for realising this?
Thank you for your help

its ground to the uno's ground, it's 5v to one of the uno's GPIO pin.

You may need an optocoupler if for whatever reason you cannot safely share grounds.

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

what is "the external source"?

the external source is an indicator that sends a 5V signal via a 2.5mm mono jack, I think this just has +&- so no ground. But I only need to measure if it is on or of, not the intensity

Unless there are exceptional circumstances you can just connect the two ground connections together. Then the 5V of your other circuit will be the same voltage as the 5V of the Arduino and you can just connect your signal direct to an input.
However, if there are exceptional circumstances (ground isn't really ground, for example) then you can use an opto-coupler to act like an optically-controlled button:

simulate this circuit – Schematic created using CircuitLab
R1 can be replaced by the internal pullup resistor of the Arduino by setting the pinMode to INPUT_PULLUP.
Note that this inverts the logic of the input: a HIGH input signal is detected on the Arduino as a LOW logic level, and vice versa.

the external source is an indicator that sends a 5V signal via a 2.5mm mono jack, I think this just has +&- so no ground. But I only need to measure if it is on or off, not the intensity