text:
Arduino does not boot when SPI lines are loaded
i connected an Arduino Nano to an external SPI Flash using THIS tutorial (russian) and the SPIMemory library. While accessing the Flash works well, i have encountered the following issue:
The Problem: When the SPI MISO line is pulled high by the flash while the Arduino boots, it does not start, for example because it was rebooted while accessing the flash. I have to power down the Flash before it boots again. But even then, it takes unusually long to boot.
I know that the Atmega328p allows reprogramming via SPI, but to my knowledge this should not cause this behavior since the SPI lines do not change (starting the programming mode would require a command to be sent immediately after restart). Is there any way to prevent this behavior? (Except disabling SPI programming via fuse bits, this would be my last choice)
EDIT
Programming the Arduino via ISP does work, however i added some series resistors to the flash to prevent accidentally driving the SPI lines from multiple sources.
The problem seems to come from the MISO line, when it is pulled to VCC the Arduino does not start. This is not mentioned in the data sheets anywhere and i am not sure how to prevent this (sketch below to show the wiring).

Is it possible for you to burn the bootloader/flash a sketch via ISP? If you erase the bootloader you can find out if thats where it hangs.

@SimSon I made a few tests, i will add the results to the post, too: writing via ISP does work, however i added some series resistors to the flash to prevent multiple drivers on the same line. Writing the firmware without bootloader greatly speeds up the startup of the arduino, but does not prevent it from freezing when the SPI lines are pulled by the flash. The MISO line seems to be the main problem, when it is pulled to VCC the Arduino does not start.

how do you actually know that it "freezes"? If it still happens without a bootloader, then it looks like it's caused by your sketch. you might also want to include a wiring diagram

@SimSon i edited the program so that it enables the status led of the nano right at the beginning. The LED remains dark until i pull the MISO line from the nano, then it immediately lights up

I honestly can't imagine why a sketch like that would hang in this scenario. But I'm confident that my answer can solve the issue.
My guess is that the following happens:
The flash is selected (CS pulled low by atmega) at the moment at which the reset happens. At this moment, the master will stop generating a clock signal and CS will be floating.
Thus, the flash will not be deselected reliably due to the floating CS and MISO will remain in the state it was before the reset occured (HIGH if it was transmitting a logic 1, LOW for 0). Basically, the SPI communication of the flash will be stuck with MISO being actively pulled to logic high or low.
IDK why this causes the sketch to freeze, but if you add a pullup resistor to the flash's CS, it should be deactivated by default (and also after a reset of the atmega as pins will be inputs/floating by default). As a result, the flash can not actively pull MISO and should therefore barely affect the atmega at all.
I suggest you add the mentioned pullup and see if that makes any difference. If it doesn't I'm going to delete this answer, but it was a bit too long for a comment ;).
Edit: I also just saw that you are missing the pullup resistor on the reset pin. That could well be the actual problem.

Thank you, this actually works! I've also added a weak pull down on the MISO line to be sure, but this does not seem to be really necessary.

@Sabulanis I just saw that you also don't have a pullup on the reset pin. That could have been the problem behind it


text:
How to get 2 loop functions to cooperate?
I have a OLED SSD1306 & DS3231 RTC, 2 buttons to set the time & date. My project is to display a scrolling text at the top of the OLED, the RTC time in the middle, the day & date on the last line. My issue is I can't get the scrolling text & the time to run right when in the loop together, individually they work normal. When they are together, the scrolling text is fine, but the time is static, its not displaying the current RTC. Then after 1 loop cycle the time seconds text become jumbled, then after a 2nd cycle the minutes & seconds become jumbled. I have tried putting display.clearDisplay(); display.display(); at the end of the loop, doing this fixes the time from becoming jumbled by clearing the buffer before the next cycle, but does not fix the time from being static. How can I get the time to not be static anymore? Any help would be greatly appreciated. Here is my sketch:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

#define OLED_RESET 4
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define button1    9                       // Button B1 is connected to Arduino pin 9
#define button2    8                       // Button B2 is connected to Arduino pin 8

void setup(void) {
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  delay(1000);

  // by default, the high voltage from the 3.3v line
  display.begin(SSD1306_SWITCHCAPVCC, 0x3c);  // initialize with the I2C address
  // init done

  // Clear the display buffer.
  display.clearDisplay();
  display.display();

  display.setTextColor(WHITE, BLACK);
}

char Time[]     = "  :  :  ";
char Calendar[] = "  /  /20  ";
byte i, second, minute, hour, day, month, date, year;

void display_day(){
  switch(day){
    case 1:  draw_text(0, 50, " SUNDAY  ", 1); break; //(Column,Row,Data to be displayed,Font size)
    case 2:  draw_text(0, 50, " MONDAY  ", 1); break; //(Column,Row,Data to be displayed,Font size)
    case 3:  draw_text(0, 50, " TUESDAY ", 1); break; //(Column,Row,Data to be displayed,Font size)
    case 4:  draw_text(0, 50, "WEDNESDAY", 1); break; //(Column,Row,Data to be displayed,Font size)
    case 5:  draw_text(0, 50, "THURSDAY ", 1); break; //(Column,Row,Data to be displayed,Font size)
    case 6:  draw_text(0, 50, " FRIDAY  ", 1); break; //(Column,Row,Data to be displayed,Font size)
    default: draw_text(0, 50, "SATURDAY ", 1); //(Column,Row,Data to be displayed,Font size)
  }
}

void DS3231_display(){
  // Convert BCD to decimal
  second = (second >> 4) * 10 + (second & 0x0F);
  minute = (minute >> 4) * 10 + (minute & 0x0F);
  hour   = (hour >> 4)   * 10 + (hour & 0x0F);
  month  = (month >> 4)  * 10 + (month & 0x0F);
  date   = (date >> 4)   * 10 + (date & 0x0F);
  year   = (year >> 4)   * 10 + (year & 0x0F);
  // End conversion

  Time[7]     = second % 10 + 48;
  Time[6]     = second / 10 + 48;
  Time[4]     = minute % 10 + 48;
  Time[3]     = minute / 10 + 48;
  Time[1]     = hour   % 10 + 48;
  Time[0]     = hour   / 10 + 48;
  Calendar[9] = year   % 10 + 48;
  Calendar[8] = year   / 10 + 48;
  Calendar[4] = date   % 10 + 48;
  Calendar[3] = date   / 10 + 48;
  Calendar[1] = month  % 10 + 48;
  Calendar[0] = month  / 10 + 48;

//Print text
  draw_text(60, 50, Calendar, 1); // Display the date (format: mm/dd/yyyy)
  draw_text(15, 25, Time, 2); // Display the time
}

void blink_parameter(){
  byte j = 0;
  while(j < 10 && digitalRead(button1) && digitalRead(button2)){
    j++;
    delay(25);
  }
}

byte edit(byte x_pos, byte y_pos, byte parameter){
  char text[3];
  sprintf(text,"%02u", parameter);
  while(!digitalRead(button1));                      // Wait until button B1 released
  while(true){
    while(!digitalRead(button2)){                    // If button B2 is pressed
      parameter++;
      if(i == 0 && parameter > 12)                   // If month > 12 ==> month = 1
        parameter = 1;
      if(i == 1 && parameter > 31)                   // If date > 31 ==> date = 1
        parameter = 1;
      if(i == 2 && parameter > 99)                   // If year > 99 ==> year = 0
        parameter = 0;
      if(i == 3 && parameter > 23)                   // If hours > 23 ==> hours = 0
        parameter = 0;
      if(i == 4 && parameter > 59)                   // If minutes > 59 ==> minutes = 0
        parameter = 0;
      sprintf(text,"%02u", parameter);
      draw_text(x_pos, y_pos, text, 1);
      delay(200);                                    // Wait 200ms
    }
    draw_text(x_pos, y_pos, "  ", 1);
    blink_parameter();
    draw_text(x_pos, y_pos, text, 1);
    blink_parameter();
    if(!digitalRead(button1)){                       // If button B1 is pressed
      i++;                                           // Increment 'i' for the next parameter
      return parameter;                              // Return parameter value and exit
    }
  }
}

void draw_text(byte x_pos, byte y_pos, char *text, byte text_size) {
  display.setCursor(x_pos, y_pos);
  display.setTextSize(text_size);
  display.print(text);
  display.display();
}

void scroll_text(){
  draw_text(0, 0, "The Pumpkin Express", 1);
  display.display();
  display.startscrollright(0x00, 0x00);
  delay(8500);
  display.stopscroll();
  delay(4000);
  }

void loop() {

  if(!digitalRead(button1)){                         // If button B1 is pressed
    i = 0;
    while(!digitalRead(button1));                    // Wait for button B1 release
    while(true){
      while(!digitalRead(button2)){                  // While button B2 pressed
        day++;                                       // Increment day
        if(day > 7) day = 1;
        display_day();                               // Call display_day function
        delay(200);                                  // Wait 200 ms
      }
      draw_text(0, 50, "         ", 1);
      blink_parameter();                             // Call blink_parameter function
      display_day();                                 // Call display_day function
      blink_parameter();                             // Call blink_parameter function
      if(!digitalRead(button1))                      // If button B1 is pressed
        break;
    }
    //set position of text when editing on button press
    month  = edit(60, 50, month);                    // Edit month
    date   = edit(80, 50, date);                      // Edit date
    year   = edit(110,50, year);                    // Edit year
    hour   = edit(14, 25, hour);                     // Edit hours
    minute = edit(50, 25, minute);                   // Edit minutes

    // Convert decimal to BCD
    minute = ((minute / 10) << 4) + (minute % 10);
    hour = ((hour / 10)  << 4) + (hour % 10);
    date = ((date / 10) <<  4) + (date % 10);
    month = ((month / 10)  << 4) + (month % 10);
    year = ((year / 10)  << 4) + (year % 10);
    // End conversion

    // Write data to DS3231 RTC
    Wire.beginTransmission(0x68);               // Start I2C protocol with DS3231 address
    Wire.write(0);                              // Send register address
    Wire.write(0);                              // Reset seconds and start oscillator
    Wire.write(minute);                         // Write minute
    Wire.write(hour);                           // Write hour
    Wire.write(day);                            // Write day
    Wire.write(month);                          // Write month
    Wire.write(date);                           // Write date
    Wire.write(year);                           // Write year
    Wire.endTransmission();                     // Stop transmission and release the I2C bus
    delay(200);                                 // Wait 200ms
  }

  Wire.beginTransmission(0x68);                 // Start I2C protocol with DS3231 address
  Wire.write(0);                                // Send register address
  Wire.endTransmission(false);                  // I2C restart
  Wire.requestFrom(0x68, 7);                    // Request 7 bytes from DS3231 and release I2C bus at end of reading
  second = Wire.read();                         // Read seconds from register 0
  minute = Wire.read();                         // Read minutes from register 1
  hour   = Wire.read();                         // Read hour from register 2
  day    = Wire.read();                         // Read day from register 3
  month  = Wire.read();                         // Read month from register 4
  date   = Wire.read();                         // Read date from register 5
  year   = Wire.read();                         // Read year from register 6
  Wire.beginTransmission(0x68);                 // Start I2C protocol with DS3231 address
  Wire.write(0x11);                             // Send register address
  Wire.endTransmission(false);                  // I2C restart
  Wire.requestFrom(0x68, 2);                    // Request 2 bytes from DS3231 and release I2C bus at end of reading

  DS3231_display();                             // Display time & calendar
  display_day();                                // Display date

  scroll_text();                                // Display scrolling text
              // If i dont use the clear buffers(next 2 line codes), on the
             //next loop cycle the seconds & minute text becomes jumbled
  //display.clearDisplay();
  //display.display();

  delay(50);                                    // Wait 50ms
}

it is not surprising, your scroll_text() function stops the program execution for 12.5 seconds

Thx for the suggestions, I changed the title to my post, & I tried commented out the delays and start & stop in my void scrolling_text(); the text is not scrolling, but is glitching, & the time is all jumbled

The reason for the delays in the void scrolling_text(); is because I want the text to scroll 1 lap around, pause to display the text, then the scrolling starts back up again. Just like the LCD screen on a train when it is displaying the next train stop

maybe what you need is a unified display function ... the scroll function does not do any displaying .. it only sets a character buffer ... the time function also does no displaying ... it sets the value of a time variable ... the display function uses the values in the character buffer, and in the time variable, and puts them on the screen

So are you saying I should create a new void called void display_text(); & in it put: draw_text(60, 50, Calendar, 1);  draw_text(15, 25, Time, 2); draw_text(0, 0, "The Pumpkin Express", 1); ?

possibly something like that ... it does not have to be in its own function .. it can be part of loop() ... whatever way you like to organize your code

"is there a way to isolate those delays...?" The processor can only do one thing at a time so if is delaying(), everything else it has to do is being held up, not just the contents of the function containing the delay(). [Responding here in anticipation of you editing your "answer" into the question.

So I tried creating a new void with all 3 draw_text’s, both the calendar & time would not work outside the void DS3231_display(). So I figured out my problem is the delays in the void scrolling_text() is some how being read as part of the whole sketch. I thought creating a void would prevent that & only run it when it is called. Is there a way of coding to prevent one void delays from effecting the whole program, like is there a way to isolate those delays, or have the program only read the delays only when it is executing the display.scrollleft(0x00,0x00);?

JRobert, are you saying I cant have the scrolling text in my sketch, because the Arduino cant handle it while executing the rest of the sketch? The reason for the delay's, is because I want the OLED to scroll the text, then pause the text to show it fully on the display, then scroll again, rinse & repeat. The reason the first delay is 8500, is because that is how long it takes the text to completely scroll out of view.

@Stiglitz Unclear what's meant by "the delays in the void scrolling_text() is somehow being read as part of the whole sketch." A delay delays: it stops the world (except for interrupts)--nothing else will happen during a delay, it's delaying (except interrupts). If you don't want the sketch to delay in a way that stops the world then you'll need to delay differently. The Blink Without Delay may be what you're ultimately asking for.

The answer to your title question, "How to get 2 loop functions to cooperate?" is: You can't, because your program can't have two functions with the same name. What you'd need to do instead is redesign your program, keeping in mind the MCU can only do one thing at a time, although you could break up each of several jobs into pieces and interleave them fast enough that we slow humans won't notice.
My approach, when I have a question like this, is to temporarily put aside what I know about coding and about MCUs, and just focus on how to do the job. I list the sub-tasks my code needs to do but without thinking too much about how to do them. Write them down, in the order they required doing, in any note-taking style that suits you.
Now break down each one of those sub-tasks into its sub-tasks. Repeat, until you understand how to code each one. Then you'll know enough to start writing the code.
Update:
@NathanJiang is correct. The solution is not to make two loop() functions (because the language doesn't support that), but to decide how to interleave pieces of each job within 1 function, in such a way that they each appear to operate smoothly and don't interfere with each other. Especially, neither one must call delay(), which stops your code doing anything for the duration. If some piece isn't ready to be done yet, your code must move on to other pieces and do which ever of those is ready. This keeps it checking each piece over and over again, rapidly, doing what is ready and skipping what is not.

What do you mean I have 2 functions with the same name? All 3 functions have different names, scroll_text(), display_day(), & DS3231_display(). the reason for my title, is because I am having an issue with scroll_text() & DS3231_display() making my program glitch when both are running in the sketch. I can get them to run fine individually.

I believe that @JRobert means that you cannot have two functions both with the name loop.

The way to get functions to cooperate with each other is to re-code them so they don't waste time and pass control back and forth as quickly as possible.  You do this by using the BlinkWithoutDelay trick to re-write the "blocking" code to be non-blocking and trust in loop() to hand back control to your function in a reasonable amount of time.
For instance take this function that @jsotola identified as a performance killer:
void scroll_text(){
  draw_text(0, 0, "The Pumpkin Express", 1);
  display.display();
  display.startscrollright(0x00, 0x00);
  delay(8500);
  display.stopscroll();
  delay(4000);
  }

It really doesn't need to monopolize the processor for 12500 microseconds--Instead it could just check the time and turn scrolling on and off every so often, and quickly pass control back to the loop() for reading and updating the clock.
I don't have your hardware or setup, so here's some untested code:
void scroll_text(){
  // some local state variables to remember where we are
  static bool isInitialized = false; // maybe a global if re-initializing is needed.
  static bool isScrolling = false;
  static unsigned long interval = 1;
  static unsigned long last = -interval;
  unsigned long now = millis();
  if (now - last >= interval ) { // time to do something
    last = now;
    if( !isInitialized ){
      draw_text(0, 0, "The Pumpkin Express", 1);
      display.display();
      isIinitialized = true;
    }
    if ( !isScrolling ) {
        isScrolling = true;
        display.startscrollright(0x00, 0x00);
        // delay(8500);  // use BWOD trick instead
        interval = 8500;
     } else { // isScrolling
       isScrolling = false;
       display.stopscroll();
       //delay(4000);
       interval = 4000;
     }
  }

This drop-in scroll_text() function can be called many time times per millisecond and will mostly do nothing and return control immediately.  But when it realizes the time is right, it will update its own state variables and the output states.
By replacing the scroll_text() function with a non-blocking form, it speeds up loop() by 12.5 seconds per loop.  Doing similar replacement of processor-sapping delay()s could further improve responsiveness.  However it is a big mind shift to stop using serial, blocking code and shift to events.  Every time you see a delay(), a while(...), or a for() loop, think about whether you really need to trap the processor inside of that loop, or what data you would need in order to skip it for now and come back to it next time through the main event loop().
I think the next step would be to wrap the reading of the reading the the DS3231 with the BWOD trick -- you only need to read the clock once per 1000ms and you could save hundreds of instructions per loop().

source: Stack Exchange

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

sort: votes


text:
How to test custom cables?
I'm trying to make a cable checker to help me make custom cables for my computer. I'm thinking I plug the cable ends into sockets on the device, then the Arduino checks between different pins to make sure that no wires are in the wrong spot or unplugged.
So I'm thinking it runs through like this:
I plug the cable into connectors on the device. The Arduino has the PSU pinouts saved. Pin 1 represents one end of the cable, pin 2 represents the opposite end. Same with 3-4/5-6 etc. If the cable is assembled correctly, it should act as a connection between pins 1-2, pins 3-4, 5-6 etc.
tests pin 1 - 2 to see if they're connected, if yes, light up a green LED, if not, light up a red LED
tests pin 3 - 4, does the same thing
Repeats this  for every wire in the cable
Am I on the right track? How would I do this? I've seen people talking about pullup resistors but I'm also seeing people say that shorting can damage the board

Am I on the right track? ... that depends on whether pins 1 and 2 are supposed to be shorted together

write down the exact step-by-step procedure in great detail ... the resulting description will translate to code almost directly, if you include enough detail

@jsotola yes, done

if that is the most detailed description that you can write down, then you have a lot of thinking to do ... tests pin 1 - 2 to see if they're connected is not anywhere near one line of code  ......... a cable has two ends ... call them left and right ... I am talking about a description something like, set each pin on left as inputs, set each pin on right as inputs, set left pin 1 to output, output LOW on left pin 1, check state of right pin 1 ......

Do you consider shortcuts as an error? Then you need to check for them, too. -- At least in the history of computer cables, there are a several variants that have connections between two (or more) pins on the same side, without being connected to the other side. -- Other cables might connect one pin of one side to multiple pins on the other side, for example for ground. -- Some USB charger cables have resistors between pins that must fall into a certain range. -- You see, this task is not trivial, if you like to check non-trivial cables.

connectivity, resistance, cross-talk, capacitance, insulation integrity... check what matters for your uses.  There's no end to what you can check; arduino on its own may not be the best way to check everything though.

The scope of your question is too wide for a simple answer so let us constrain it to slow signals (audio frequencies or less) over short cables (not more than several meters) in a electrically clean environment (such as found in most homes).
That said, it is likely most looking for similar solutions reading your question will have different specific requirements.  So to make this question and answer useful to others let us consider the most generic, economical and Arduino based solution.

Most cables worth automatically testing will have far more individual connections than common Arduino boards, such as the Arduino Uno, have GPIO pins.  Consider using a GPIO expander or multiple Arduinos which communicate with each other to coordinate efforts.
When testing a cable that will be used for low frequencies, short distance and low immunity to noise it is likely the only faults that are of concern are OPENS and SHORTS.
As this design uses GPIO pins we have the following options at any given GPIO pin: Drive High, Drive Low and Input With Pull Ups.
Build a cable test rig where one end (the near end) of the cable under test is connected to GPIO pins designated as the driver side and the other end of the cable under test (the far end) is connected to GPIO pins designated as the sensing side.
For a SHORTS and OPENS test set all the sensing  and driving GPIO pins to Input With Pull Ups.  Verify that all sensing GPIO pins report a 1.  Next change one and only one of the driver GPIO pins to an output and send a 0.  Record that state of all sensing GPIO pins.  Return the driver GPIO pin to Input with NO PULL UPS and repeat these steps for the next GPIO driver pin.
If this is a STRAIGHT THROUGH cable only 1 sensing GPIO pin should report a 0 in each testing pattern recorded.  If more than 1 sensing GPIO pin reports a 0 then there is a short between the 0 reporting pins.  If none of the GPIO pins reports a 0 then there is an open for that GPIO pin.
Use the same test for cables containing intentional SHORTS (perhaps multiple ground pins are shorted together) expecting to see the associated GPIO pins to all change to 0 at the same time.
For even more complex cables containing loop backs at both ends consider only the "GPIO pin set to an output sending 0" as the driver and record the state of ALL OTHER GPIO pins as they are now all possible outputs.

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


text:
Trouble interfacing PN5180 RFID Module with Arduino Uno
I bought the PN5180 module a few weeks back and I am having quite a bit of trouble interfacing it with my Arduino Uno. The library that I am using is ATrappmann PN5180 Library. The link of which is here https://github.com/ATrappmann/PN5180-Library. I have followed his connections to the letter and have tested each component individually.
The Uno is fine since I have used it extensively for other testing. The Level Shifter is also working fine. The one I am using is similar to this. The jumper wires are also fine. I have tried working with both examples given in the library and the code gets stuck during the looping. I have attached a screenshot here.

I can't seem to figure out where is it going wrong. Is there any way I can use the RC522 Library for setting up the PN5180 reader? I have successfully integrated both RC522 and PN532 NFC readers with Uno but they don't have the required range. I plan on using the reader for localization. It will read the cards and compare it with an array of UID characters to figure out where it is. Any suggestion would be greatly appreciated honestly!
Edit:
Adding the circuit diagram and code so that It is easier to understand

Code:
// NAME: PN5180-Library.ino
//
// DESC: Example usage of the PN5180 library for the PN5180-NFC Module
//       from NXP Semiconductors.
//
// Copyright (c) 2018 by Andreas Trappmann. All rights reserved.
//
// This file is part of the PN5180 library for the Arduino environment.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// BEWARE: SPI with an Arduino to a PN5180 module has to be at a level of 3.3V
// use of logic-level converters from 5V->3.3V is absolutely necessary
// on most Arduinos for all input pins of PN5180!
// If used with an ESP-32, there is no need for a logic-level converter, since
// it operates on 3.3V already.
//
// Arduino <-> Level Converter <-> PN5180 pin mapping:
// 5V             <-->             5V
// 3.3V           <-->             3.3V
// GND            <-->             GND
// 5V      <-> HV
// GND     <-> GND (HV)
//             LV              <-> 3.3V
//             GND (LV)        <-> GND
// SCLK,13 <-> HV1 - LV1       --> SCLK
// MISO,12        <---         <-- MISO
// MOSI,11 <-> HV3 - LV3       --> MOSI
// SS,10   <-> HV4 - LV4       --> NSS (=Not SS -> active LOW)
// BUSY,9         <---             BUSY
// Reset,7 <-> HV2 - LV2       --> RST
//
// ESP-32    <--> PN5180 pin mapping:
// 3.3V      <--> 3.3V
// GND       <--> GND
// SCLK, 18   --> SCLK
// MISO, 19  <--  MISO
// MOSI, 23   --> MOSI
// SS, 16     --> NSS (=Not SS -> active LOW)
// BUSY, 5   <--  BUSY
// Reset, 17  --> RST
//

/*
 * Pins on ICODE2 Reader Writer:
 *
 *   ICODE2   |     PN5180
 * pin  label | pin  I/O  name
 * 1    +5V
 * 2    +3,3V
 * 3    RST     10   I    RESET_N (low active)
 * 4    NSS     1    I    SPI NSS
 * 5    MOSI    3    I    SPI MOSI
 * 6    MISO    5    O    SPI MISO
 * 7    SCK     7    I    SPI Clock
 * 8    BUSY    8    O    Busy Signal
 * 9    GND     9  Supply VSS - Ground
 * 10   GPIO    38   O    GPO1 - Control for external DC/DC
 * 11   IRQ     39   O    IRQ
 * 12   AUX     40   O    AUX1 - Analog/Digital test signal
 * 13   REQ     2?  I/O   AUX2 - Analog test bus or download
 *
 */

//#define WRITE_ENABLED 1

#include <PN5180.h>
#include <PN5180ISO15693.h>

#if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA2560) || defined(ARDUINO_AVR_NANO)

#define PN5180_NSS  10
#define PN5180_BUSY 9
#define PN5180_RST  7

#elif defined(ARDUINO_ARCH_ESP32)

#define PN5180_NSS  16
#define PN5180_BUSY 5
#define PN5180_RST  17

#else
#error Please define your pinout here!
#endif

PN5180ISO15693 nfc(PN5180_NSS, PN5180_BUSY, PN5180_RST);

void setup() {
  Serial.begin(115200);
  Serial.println(F("=================================="));
  Serial.println(F("Uploaded: " __DATE__ " " __TIME__));
  Serial.println(F("PN5180 ISO15693 Demo Sketch"));

  nfc.begin();

  Serial.println(F("----------------------------------"));
  Serial.println(F("PN5180 Hard-Reset..."));
  nfc.reset();

  Serial.println(F("----------------------------------"));
  Serial.println(F("Reading product version..."));
  uint8_t productVersion[2];
  nfc.readEEprom(PRODUCT_VERSION, productVersion, sizeof(productVersion));
  Serial.print(F("Product version="));
  Serial.print(productVersion[1]);
  Serial.print(".");
  Serial.println(productVersion[0]);

  if (0xff == productVersion[1]) { // if product version 255, the initialization failed
    Serial.println(F("Initialization failed!?"));
    Serial.println(F("Press reset to restart..."));
    Serial.flush();
    exit(-1); // halt
  }

  Serial.println(F("----------------------------------"));
  Serial.println(F("Reading firmware version..."));
  uint8_t firmwareVersion[2];
  nfc.readEEprom(FIRMWARE_VERSION, firmwareVersion, sizeof(firmwareVersion));
  Serial.print(F("Firmware version="));
  Serial.print(firmwareVersion[1]);
  Serial.print(".");
  Serial.println(firmwareVersion[0]);

  Serial.println(F("----------------------------------"));
  Serial.println(F("Reading EEPROM version..."));
  uint8_t eepromVersion[2];
  nfc.readEEprom(EEPROM_VERSION, eepromVersion, sizeof(eepromVersion));
  Serial.print(F("EEPROM version="));
  Serial.print(eepromVersion[1]);
  Serial.print(".");
  Serial.println(eepromVersion[0]);

  /*
  Serial.println(F("----------------------------------"));
  Serial.println(F("Reading IRQ pin config..."));
  uint8_t irqConfig;
  nfc.readEEprom(IRQ_PIN_CONFIG, &irqConfig, 1));
  Serial.print(F("IRQ_PIN_CONFIG=0x"));
  Serial.println(irqConfig, HEX);

  Serial.println(F("----------------------------------"));
  Serial.println(F("Reading IRQ_ENABLE register..."));
  uint32_t irqEnable;
  nfc.readRegister(IRQ_ENABLE, &irqEnable));
  Serial.print(F("IRQ_ENABLE=0x"));
  Serial.println(irqConfig, HEX);
  */

  Serial.println(F("----------------------------------"));
  Serial.println(F("Enable RF field..."));
  nfc.setupRF();
}

uint32_t loopCnt = 0;
bool errorFlag = false;

void loop() {
  if (errorFlag) {
    uint32_t irqStatus = nfc.getIRQStatus();
    showIRQStatus(irqStatus);

    if (0 == (RX_SOF_DET_IRQ_STAT & irqStatus)) { // no card detected
      Serial.println(F("*** No card detected!"));
    }

    nfc.reset();
    nfc.setupRF();

    errorFlag = false;
  }

  Serial.println(F("----------------------------------"));
  Serial.print(F("Loop #"));
  Serial.println(loopCnt++);

/*
  // code for unlocking an ICODE SLIX2 protected tag
  uint8_t password[] = {0x01, 0x02, 0x03, 0x04}; // put your privacy password here
  ISO15693ErrorCode myrc = nfc.unlockICODESLIX2(password);
  if (ISO15693_EC_OK == myrc) {
    Serial.println("unlockICODESLIX2 successful");
  }
*/

  uint8_t uid[8];
  ISO15693ErrorCode rc = nfc.getInventory(uid);
  if (ISO15693_EC_OK != rc) {
    Serial.print(F("Error in getInventory: "));
    Serial.println(nfc.strerror(rc));
    errorFlag = true;
    return;
  }
  Serial.print(F("Inventory successful, UID="));
  for (int i=0; i<8; i++) {
    Serial.print(uid[7-i], HEX); // LSB is first
    if (i < 2) Serial.print(":");
  }
  Serial.println();

  Serial.println(F("----------------------------------"));
  uint8_t blockSize, numBlocks;
  rc = nfc.getSystemInfo(uid, &blockSize, &numBlocks);
  if (ISO15693_EC_OK != rc) {
    Serial.print(F("Error in getSystemInfo: "));
    Serial.println(nfc.strerror(rc));
    errorFlag = true;
    return;
  }
  Serial.print(F("System Info retrieved: blockSize="));
  Serial.print(blockSize);
  Serial.print(F(", numBlocks="));
  Serial.println(numBlocks);

  Serial.println(F("----------------------------------"));
  uint8_t readBuffer[blockSize];
  for (int no=0; no<numBlocks; no++) {
    rc = nfc.readSingleBlock(uid, no, readBuffer, blockSize);
    if (ISO15693_EC_OK != rc) {
      Serial.print(F("Error in readSingleBlock #"));
      Serial.print(no);
      Serial.print(": ");
      Serial.println(nfc.strerror(rc));
      errorFlag = true;
      return;
    }
    Serial.print(F("Read block #"));
    Serial.print(no);
    Serial.print(": ");
    for (int i=0; i<blockSize; i++) {
      if (readBuffer[i] < 16) Serial.print("0");
      Serial.print(readBuffer[i], HEX);
      Serial.print(" ");
    }
    Serial.print(" ");
    for (int i=0; i<blockSize; i++) {
      if (isprint(readBuffer[i])) {
        Serial.print((char)readBuffer[i]);
      }
      else Serial.print(".");
    }
    Serial.println();
  }

#ifdef WRITE_ENABLED
  Serial.println(F("----------------------------------"));
  uint8_t *writeBuffer = malloc(blockSize);
  for (int i=0; i<blockSize; i++) {
    writeBuffer[i] = 0x80 + i;
  }
  for (int no=0; no<numBlocks; no++) {
    rc = nfc.writeSingleBlock(uid, no, writeBuffer, blockSize);
    if (ISO15693_EC_OK == rc) {
      Serial.print(F("Wrote block #"));
      Serial.println(no);
    }
    else {
      Serial.print(F("Error in writeSingleBlock #"));
      Serial.print(no);
      Serial.print(": ");
      Serial.println(nfc.strerror(rc));
      errorFlag = true;
      return;
    }
  }
#endif /* WRITE_ENABLED */

/*
  // code for locking an ICODE SLIX2 protected tag
  ISO15693ErrorCode myrc = nfc.lockICODESLIX2(password);
  if (ISO15693_EC_OK == myrc) {
    Serial.println("lockICODESLIX2 successful");
    delay(5000);
*/
  delay(1000);
}

void showIRQStatus(uint32_t irqStatus) {
  Serial.print(F("IRQ-Status 0x"));
  Serial.print(irqStatus, HEX);
  Serial.print(": [ ");
  if (irqStatus & (1<< 0)) Serial.print(F("RQ "));
  if (irqStatus & (1<< 1)) Serial.print(F("TX "));
  if (irqStatus & (1<< 2)) Serial.print(F("IDLE "));
  if (irqStatus & (1<< 3)) Serial.print(F("MODE_DETECTED "));
  if (irqStatus & (1<< 4)) Serial.print(F("CARD_ACTIVATED "));
  if (irqStatus & (1<< 5)) Serial.print(F("STATE_CHANGE "));
  if (irqStatus & (1<< 6)) Serial.print(F("RFOFF_DET "));
  if (irqStatus & (1<< 7)) Serial.print(F("RFON_DET "));
  if (irqStatus & (1<< 8)) Serial.print(F("TX_RFOFF "));
  if (irqStatus & (1<< 9)) Serial.print(F("TX_RFON "));
  if (irqStatus & (1<<10)) Serial.print(F("RF_ACTIVE_ERROR "));
  if (irqStatus & (1<<11)) Serial.print(F("TIMER0 "));
  if (irqStatus & (1<<12)) Serial.print(F("TIMER1 "));
  if (irqStatus & (1<<13)) Serial.print(F("TIMER2 "));
  if (irqStatus & (1<<14)) Serial.print(F("RX_SOF_DET "));
  if (irqStatus & (1<<15)) Serial.print(F("RX_SC_DET "));
  if (irqStatus & (1<<16)) Serial.print(F("TEMPSENS_ERROR "));
  if (irqStatus & (1<<17)) Serial.print(F("GENERAL_ERROR "));
  if (irqStatus & (1<<18)) Serial.print(F("HV_ERROR "));
  if (irqStatus & (1<<19)) Serial.print(F("LPCD "));
  Serial.println("]");
}

Edit 2:
So i tried one of the forks of ATrappmann library. the link is https://github.com/tueddy/PN5180-Library, and the problem of the code stalling at loops have been resolved. But now, the reader won't read any of my cards :(

I have the same problem as you, have you solved it ????.


text:
Error on Uploading Program to ESP8266 via Foca v2.2 (USB to TTL Adapter)
BACKGROUND
To test the capability of uploading program to ESP8266,  I use an empty program with only a blank setup function and a blank loop function. The result showed me that there are a espcomm_sync error and a espcomm_open error. Any idea to solve this problem?

HARDWARE

PIN CONNECTION
  Foca v2.2 <-> ESP8266
        TXD <-> RXD
        RXD <-> TXD
        DTR <-> RST

Arduino UNO <-> ESP8266
        GND <-> GND
       3.3V <-> Vcc

PIN DIAGRAMS
Foca v2.2

ESP8266

ON LINUX UBUNTU 15.04

ON WINDOWS 10

REFERENCE

Bring IoT to Arduino, together [Getting Started] - http://www.arduinesp.com/getting-started

The link you provide describes 3 possible scenarios. None of them corresponds to your pin connections on foca. If problem persists after correcting the DTR and RST connections try to use the manual setup first.

@Personagem - Now I removed the connection RST <-> GPIO0 and got the same result in both windows and ubuntu but the uploading problem is still not solved.

by the comments I think you are not understanding correctly how to connect Reset and GPIO_0 of ESP. To set esp-01 into flash mode (to program) you need to set GPIO_0 Low (GND) and then also apply Low on RST ESP pin.
To debug the things and be certain that there is no hardware problem let just start by doing these connections:
Foca v2.2 <-> ESP =1
      TXD <-> RXD
      RXD <-> TXD
      GND <-> GND
  Arduino <-> ESP 01
     3.3V <-> 3.3V
     3.3V <-> CH_PD
     GND  <-> GND

Now, with a wire, connect GPIO_0 to ground. With another wire, briefly connect RST of the ground to make ESP reset. You should be now in flash mode. Remove the connection on GPIO_0 and make it float. Now upload the code.
Note: this is basically the option C on the link you provide. If you have some buttons you can make it too:

(source: arduinesp.com)
Now, does the code upload in Arduino IDE?
If the answer is still no, try to add a small capacitor between 3.3v and ground.
If the answer is yes, now you can move on and try the other options described in the link you provide. I recommend using the option A:

(source: arduinesp.com)
Any generic npn transistor should work

I had the same problem. I solved connecting GPIO0 to GND and connecting RST to GND a while after uploading and then leave it floating while uploading

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


text:
Wifi module for arduino shield
Recently I bought a B006RATC2E wireless shield for my Arduino One, but didn't notice that I had to buy a wifi module as well to let it work (bad surprise as the shield already cost me $30 + travel expenses to CR). Could someone be so kind to suggest me some compatible wifi modules for the shield?
I'm kind of newbie in this and when I search specs for Adafruit and XBee modules, the documentation is not explicit about the compatibility with Arduino shields, so I'm stuck.
I don't want to buy components that would't work together (my budget is limited). Is XBee XB24 a good module for the shield? Any other alternative?
Thanks in advance for any help!

Wireless doesn't necessarily mean it's WiFi.
You should get an XBee module that explicitly states that it's a WiFi module.
For a cheaper alternative you can check ESP8266 WiFi modules, which you can get for $5.

That definitely helped me, along with this tutorial: http://www.cse.dmu.ac.uk/~sexton/ESP8266, thanks gre_gor! And the best, I don't need a wireless shield to get WiFi

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


text:
DHT11 with Mysql
I need help to record databаse from dht11 sensor to mysql server.
this is my code:
#include <DHT.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
EthernetClient client;

IPAddress server(192,168,0,102); // IP Adres (or name) of server to dump data to

#define DHTPIN 2 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

float temperature = 0;  // TEMPERATURE VAR
float humidity = 0; // HUMIDITY VAR
String data;

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

    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
    }

    dht.begin();
    delay(10000); // GIVE THE SENSOR SOME TIME TO START

       temperature = (float) dht.readTemperature();
       humidity = (float) dht.readHumidity();

}

void loop(){

    currentMillis = millis();
    if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
        previousMillis = currentMillis;
        temperature = (float) dht.readTemperature();
                humidity = (float) dht.readHumidity();
    }

    if (client.connect(server, 3306)) {
          Serial.print("temperature=" );
          Serial.println( temperature );
          Serial.print("humidity=" );
          Serial.println( humidity );
          Serial.println("-> Connected");
            if(client.connected()){
            // Make a HTTP request:
            client.print( "GET /add_data.php?");
            client.print("temperature=");
            client.print( temperature);
            client.print("humidity=");
            client.print( humidity);
            client.println( " HTTP/1.1");
            client.println( "Host: 192.168.0.102" );
            //client.println(server);
            client.println( "Connection: close" );
            client.println();
            client.println();
            client.stop();
          }
        }
    if (client.connected()) {
        client.stop();  // DISCONNECT FROM THE SERVER
    }

    delay(30000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

I connected to database but can't make records. this is output on serial monitor:
temperature=21.00
humidity=73.00
-> Connected
this is my php:add_data.php
<?php
    // Connect to MySQL
    include("dbconnect.php");

    // Prepare the SQL statement
    $SQL = "INSERT INTO test.test.temperature (temperature ,humidity) VALUES ('".$_GET["temperature"]."', '".$_GET["humidity="]."')";

    // Execute SQL statement
    mysql_query($SQL);

    // Go to the review_data.php (optional)
    header("Location: review_data.php");
?>

dbconnect.php=>
<?php
$MyUsername = "root";  // enter your username for mysql
$MyPassword = "fifa2005";  // enter your password for mysql
$MyHostname = "localhost";      // this is usually "localhost" unless your database resides on a different server

$dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
$selected = mysql_select_db("test",$dbh);
?>

review_data.php=>

    <title>Arduino Temperature Log</title>

Arduino Temperature Log

        ID
        Date and Time
        Temperature
        Humidity

    <?php
    // Retrieve all records and display them
    $result = mysql_query("SELECT * FROM temperature ORDER BY id ASC");

    // Used for row color toggle
    $oddrow = true;

    // process every record
    while( $row = mysql_fetch_array($result) )
    {
        if ($oddrow)
        {
            $css_class=' class="table_cells_odd"';
        }
        else
        {
            $css_class=' class="table_cells_even"';
        }

        $oddrow = !$oddrow;

        echo '
';
        echo '   '.$row["id"].'	';
        echo '   '.$row["timestamp"].'	';
        echo '   '.$row["temperature"].'	';
        echo '   '.$row["humidity"].'	';
        echo '
';
    }
    ?>

You should compare the result client.connect against 1 to make sure it's really connected. (The result might be negative, indicating an error.) Do you see the connection in the server log? If so, it's not really an Arduino problem.

I compare the result of client.connect and everything is ok. :) Maybe i should try in stackoverflow for php :)

I meant if (client.connect(server, 3306) == 1). And yes, if that is the part where you have problems with, then do so.

Hey!  Let's all inject some SQL into that incredibly insecure query!!! :)

i'm not sure why my old code doesn't work, but this is my new one and it is working fine. Maybe it will help someone.
#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>
EthernetClient client;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192.168.0.101";
dht DHT;
int interval = 5000; // Wait between dumps
#define DHT11_PIN 2
void setup()
{
  Ethernet.begin(mac);
  Serial.begin(115200);

  //Serial.println("Humidity (%),\tTemperature (C)");
}
void loop()
{
  Serial.print("Temperature2 = ");
    Serial.print(DHT.temperature);
    Serial.println(" *C");

    Serial.print("Humidity = ");
    Serial.print(DHT.humidity);
    Serial.println(" ");

  // READ DATA
  //Serial.print("DHT11, \t");
  int chk = DHT.read11(DHT11_PIN);

  if (client.connect(server, 80)) {

    client.print( "GET /diplomna/Arduino/add_data.php?");
    client.print("temperature=");;
    client.print( DHT.temperature );
    client.print("&&");
    client.print("humidity=");
    client.println( DHT.humidity );
    client.println( "HTTP/1.1");
    client.println( "Connection: close" );
    client.stop();
    Serial.println("CONNECTED");
  }
  else {
    // you didn’t get a connection to the server:
    Serial.println("–> connection failed/n");
  }
  delay(interval);
}

You have one problem in the construction of your HTTP GET request on Arduino side:
        // Make a HTTP request:
        client.print( "GET /add_data.php?");
        client.print("temperature=");
        client.print( temperature);
        client.print("humidity=");
        client.print( humidity);

You forgot to separate both request arguments with an ampersand. It should be:
        // Make a HTTP request:
        client.print( "GET /add_data.php?");
        client.print("temperature=");
        client.print( temperature);
        client.print("&humidity=");
        client.print( humidity);

Note the "&humidity" instead of just "humidity".

I fixed my mistake and made several checks, but still there is something wrong.I'm not sure that add_data.php receive data or my mysql query is wrong.

You can break down testing in steps.
Call your PHP page from the browser with some dummy parameters and see if it saves them in the DB.
If that part works use a network sniffer, like WireShark to sniff the TCP connection and make sure the correct data is sent to the PHP server from the Arduino.
Depending on which part is not working you can ask the question in the appropriate stack exchange.


text:
Connecting Arduino ethernet shield (ip address - 0.0.0.0)
I need some help to connect my arduino uno R3 and ethernet shield. I don't have a mac address with my shield so I'm using this one: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
The Ethernet controller on the Ethernet shield is W5100 and I don't use SD card.
I have receiver module wich receives data from transmitter and I want to save it in database, but there is issue related to the connection. When I print the Ethernet.localIP i observed only 0.0.0.0.
This is the IP address of my local network - char server[] = "192.168.0.106"
You can find my code below:
  #include <Wire.h> // use Wire library for protocol i2c (A4 = SDA & A5 = SCL)
  #include <VirtualWire.h> // use Virtual library for decode signal from Rx module
  #include <SPI.h>
  #include <Ethernet.h>

  EthernetClient client;
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  char server[] = "192.168.0.106";

  int humidity=0;
  int temp=0;
  int pressure=0;
  char MsgReceived[21];

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

     Serial.println(Ethernet.localIP());

    // Bits per sec
    vw_setup(2000);
    // set pin for connect receiver module
    vw_set_rx_pin(3);
    // Start the receiver PLL running
    vw_rx_start();

  }
  void loop()
  {
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  //Taking the data from the control base
  if (vw_get_message(buf, &buflen))
  {
    int i;
    // Message with a good checksum received, dump it.
    for (i = 0; i < buflen; i++)
    {
      // Fill Msg Char array with corresponding
      // chars from buffer.
      MsgReceived[i] = char(buf[i]);
      //Serial.print(MsgReceived[i]);
    }

    sscanf(MsgReceived, "%d,%d,%d",&humidity, &temp,&pressure); // Converts a string to an array
    lcd_display();
    memset( MsgReceived, 0, sizeof(MsgReceived));// This line is for reset the StringReceived

    Serial.print("Temperature = ");
    Serial.print(temp);
    Serial.println(" *C");
    Serial.print("Pressure = ");
    Serial.print(pressure);
    Serial.println(" Pa");
    Serial.print("humidity = ");
    Serial.print(humidity);
    Serial.println(" %");

if (client.connect(server, 80)) {
   Serial.println("CONNECTED");
   client.print( "GET /diplomna/Arduino/add_data.php?");
   client.print("temperature=");;
   client.print( temp);
   client.print("&&");
   client.print("humidity=");
// change this to a print rather than println
   client.print( humidity );
// add a leading space in this println
   client.println( " HTTP/1.1");
// add a second cr/lf here to denote end of header
   client.println();
   client.println( "Connection: close\r\n" );

   while(client.connected()) {
      while(client.available()) {
        char ch = client.read();
        Serial.write(ch);
      }
    }
   client.stop();
   Serial.println("DISCONNECTED");
   }
 else {
   // you didn't get a connection to the server:
   Serial.println("-> connection failed/n");
 }
   delay(10000);
  }
  }

You can find the serial monitor output below:
0.0.0.0
Temperature = 26 *C
Pressure = 997 Pa
humidity = 57 %
-> connection failed/n
I also tried to execute the following example code (DhcpAddressPrinter)  and the results are the same - 0.0.0.0
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for (;;)
      ;
  }
  // print your local IP address:
  printIPAddress();
}

void loop() {

  switch (Ethernet.maintain())
  {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");

      //print your local IP address:
      printIPAddress();
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");

      //print your local IP address:
      printIPAddress();
      break;

    default:
      //nothing happened
      break;

  }
}

void printIPAddress()
{
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }

  Serial.println();
}

Serial monitor output:
Failed to configure Ethernet using DHCP
I also tried to set the ip address of the shield to be 192.168.137.1 and made the following update:
  Ethernet.begin(mac);  ===>  Ethernet.begin(mac,ip);
The results are the same.
Could you please help me to debug this issue.
Thanks in advance!
Regards,
SK

If you're not using one of the peripherals in your program, you'll need to explicitly deselect it. To do this with the SD card, set pin 4 as an output and write a high to it. https://store.arduino.cc/arduino-ethernet-shield-2

what research have you done? .... did you try the example sketch?

How is your Ethernet shield wired to your network? What does your network consist of?

Hi Juraj,
thank you for the feedback. I will try this today.

Hi jstola,
Yes I made reasearch. I read many thames and reviwed a lot of videos regarding the issues related to the connections. Did you have a chance to read about my issue before to comment? There I explain that I have tried an example sketch, but the results are not as expected.

Hi Majenko,
I use straight connection cable to connect the ethernet shield to my laptop and I use wifi network. I also use xampp to create a virtual host with port 80.

Also asked at: http://forum.arduino.cc/index.php?topic=552471 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

Hi per, you are right. Thank you for the comment.

in my case was the SS pin, it was disconnected.

from comments:
  " I use straight connection cable to connect the ethernet shield to my
  laptop and I use wifi network. "

This is the problem. Connect to router.
The direct Ethernet connection may require the use of a cross-over cable and the PC probably doesn't have a DHCP server for the Ethernet interface, so you should set an IP address for the network interface and in the Arduino sketch.
see this SO question

Hi Juraj, you are right. I have connected the ethernet with the router and now the example scratch works.

The first thing you should do is disconnect or disable all devices from the Arduino except the network card then run your tests again, if they work (which I doubt) then the problem is a hardware resource clash, for which you will need to read the datasheets.
I suspect the problem you have is more fundamental, do you have a DHCP server on your network?
The first example doesn't specifically mention DHCP, but the second example makes the same call top Ethernet.begin() and seems to expect the call to have configured the NIC via DHCP.
So my advice would be to look at the API for the NIC and see what you need to do to statically configure you IPv4 settings.  Also you might need to bone up on IPv4 addresses and net masks, because the addresses you mentioned won't be able to communicate unless you have some special routing gear (it could be I read the question wrong).
Hope that helps.


text:
SMD Voltage Regulator 662k very hot, how to repair it?
I think I made a mistake. Now, the 662k on my Arduino Uno very hot about 90°C.
I test it, it can be programmed and can run blink program normally.
There is a switch for voltage choose. Now, run in 3.3v mode get 2.8v and in 5v mode get 4.8v.
What should I do?
If 662k be replaced, can I use that Arduino normally in the future.

From the picture I guess it is a roboduino. The only voltage regulator is the 662k, it is too small compared to other voltage regulators!!! (have a look at the size and sink of the official arduino), so it is normal that the temperature is high. (arduino uno can get up to 1A and the regulator is bigger)
To reduce temperature just use the lowest input source (for instance, for arduino 5 volts, use 7 volts source, not 12 volts source). The bigger input voltage, the higher temperature in the regulator.
Solutions.

replace the 662K with another 662K one.
use a bigger voltage regulator. Since 66K space is tight (SOT-23) and no sink space I suggest to solder a TO-92 like voltage regulator. Not nice solution, but handy.

I thought you are right. Lucky they just sent me another board.


text:
Multiple external power sources and one Arduino
really noob question..
I am thinking of using a 12v power source and a 5v power source as an external power supply for my 5v relay (and some other stuff that I might add up to my project that will need 5V) and the 12v is for my 12V solenoids.
Is it right to connect all ground wires to the ground of the Arduino?
I am really sorry that I have to ask this question cause all tutorials I see online are only connecting one external power supply to their Arduino.
Any form of correction is highly appreciated. Thank you so much

First make sure the voltages are stable enough even under any and all expected changes in current load - solenoids take quite a bit of juice and have interesting magnetic field effects.  No sense subjecting your arduino to potential overvoltage in AC from an accidentally bucking inductor.

Yes, in general all grounds need to be connected

Besides connecting all the grounds, a "good idea" whenever working with solenoids or magnetic (as opposed to solid state) relays is to add protection against inductive kickback, which can create really high voltages (hundreds of volts) when the current through an inductor changes suddenly. (The voltage is the product of the inductance and the rate-of-change of the current.)  The protection is simple:  Put a rectifier diode across each coil, with the arrow pointing to positive (reverse-biased).  The rectifier has to handle a big spike of current as well as the high voltage, so use something like 1N4004.
This protection will reduce the likelihood of spikes causing mysterious state changes in your circuits.

Hi, correct me, but a snubber diode is like a safety precaution to avoid frying your relays right? so it should work for DC Motors too cause its an inductive load right? thanks

Correct.  Google for "snubber diode on DC motor"

thanks a lot! I wish you a happy day :)


text:
Float switch is not detected

Good day everyone, forgive me for the shabby drawing I am just panicking, why my float switches are suddenly undetected by my Arduino mega. I've tested all the float switches one by one to confirm if everything is working just before installing it..
i have 18 sets of float switches, 5 pumps being controlled by the relay, my main PSU is 12V 20A.
The yellow rectangle stands for the float switch, the purple line is connected to digital pins from between and 10k ohm resistor and the switch. the green line is a common ground connection from the 5.2V buck (psu for devices that need 5 to 5.5v) to the Arduino mega's gnd.
here's my code, and its not the project code, just a simple test sketch because my float switches are suddenly acting weird:
#include <OneWire.h>
#include "OneButton.h"
#include <DallasTemperature.h>
#include "GravityTDS.h"
#include <EEPROM.h>
#include "Wire.h" // Include the I2C Wire Library
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4);

#define bp1 (uint8_t) 10 /*Button 1*/
#define bp2 (uint8_t) 11 /*Button 2*/
#define bp3 (uint8_t) 12 /*Button 3*/

OneButton btn1 = OneButton(bp1,false,false); uint8_t bx1 = 0;
OneButton btn2 = OneButton(bp2,false,false); uint8_t bx2 = 0;
OneButton btn3 = OneButton(bp3,false,false); uint8_t bx3 = 0;

//Float Switches...........
/*Collector Float Switch*/
#define CT_Fs2 (uint8_t) 9

/*Sieve & Cloth*/
#define SC_Fs1 (uint8_t) 8

/*Primary Test Tank*/
#define PT_Fs1 (uint8_t) 7
#define PT_Fs2 (uint8_t) 6

/*Grease Trap*/
#define GT_Fs1 (uint8_t) 5

/*First Filtration*/
#define FFP_Fs1 (uint8_t) 4
#define FFP_Fs2 (uint8_t) 3

/*Sediment Filter*/
#define SD_Fs1 (uint8_t) 2

/*Second Filtration Passed*/
#define SP_Fs1 (uint8_t) 24
#define SP_Fs2 (uint8_t) 25

/*Final Test Tank*/
#define FT_Fs1 (uint8_t) A7
#define FT_Fs2 (uint8_t) A8

/*Tank A*/
#define TA_Fs1 (uint8_t) 45
#define TA_Fs2 (uint8_t) 47

/*Tank B*/
#define TB_Fs1 (uint8_t) 42
#define TB_Fs2 (uint8_t) 43

/*Tank C*/
#define TC_Fs1 (uint8_t) 40
#define TC_Fs2 (uint8_t) 41

void setup()
{
  Serial.begin(9600); /* Show Serial Monitor */
  lcd.begin(); /* LCD Screen Set Up */

//---------------------------------------------------------------------dont forget to set up the pins
//ALL DIGITAL PINS ARE INPUT AS DEFAULT, DECLARE ONLY IF MODE IS OUTPUT:
  pinMode(FT_Fs1,INPUT);
  pinMode(FT_Fs2,INPUT);

//----------------------------------------------------------------------One Button Single Click event attachment
  btn1.attachClick(handleClick1);
  btn2.attachClick(handleClick2);
  btn3.attachClick(handleClick3);

}

//simple show txt on LCD Screen
void lcd_print(String txt ,uint8_t a, uint8_t b)
{ lcd.setCursor(a,b); lcd.print(txt);}

void loop()
{
  FSTester();
}

void FSTester() // to check FLOAT SWITCH
{
  if (digitalRead(CT_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("CT_Fs2 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(SC_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("SC_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(PT_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("PT_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(PT_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("PT_Fs2 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(GT_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("GT_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(FFP_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("FFP_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(FFP_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("FFP_Fs2 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(SD_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("SD_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(SP_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("SP_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(SP_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("SP_Fs2 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(FT_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("FT_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(FT_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("FT_Fs2 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(TA_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("TA_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(TA_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("TA_Fs2 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(TB_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("TB_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(TB_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("TB_Fs2 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(TC_Fs1) == 1)
  {
    lcd.clear();
    lcd_print("TC_Fs1 Detected",0,1);
    delay(5000);
  }
  else if (digitalRead(TC_Fs2) == 1)
  {
    lcd.clear();
    lcd_print("TC_Fs2 Detected",0,1);
    delay(5000);
  }
  else
  {
    lcd.clear();
    lcd_print("NOTHING",0,1);
  }
}

I've checked for continuity and everything is fine. why is it weird?
somebody please correct my mistakes

"suddenly acting weird" doesn't give us much to go on. I'd suggest trying a small fragment of your code that only uses one float switch and get that working. Then add in the rest of them (with any modifications you might have had to make for the first one). Is it possible that the switches work in the opposite sense from which your testing them? You're testing for HIGH - are they in fact switching to LOW? Otherwise, we'll need to know what you expected your code to do, and what it is doing instead. And it will still be helpful to reduce it to just one relay - i.e. the simplest case that fails.

What is the yellow component in your drawing and what are the green/purple connection?

What is the reason, that you are using an additional buck power supply for - what I assume from your drawing - are just simple switches? Why not just directly using the Arduinos 5V pin for that?

Your diagram is almost impossible to follow. Can you sketch out the actual wiring without using coloured boxes, etc? In particular the part about the switch. We assume you are supplying power to the various devices, you don't need to show that. Possibly the inputs to your switch are "floating" (that is, indeterminate) in either the open or closed position.

See my page about switches and if that helps I can make an answer along those lines (if there isn't one already which there probably is).

It is difficult to determine from the diagram if the green wire is at the same voltage as the black wire supplying power to the Arduino board. Even if they are connected, it is difficult to say if the current is nominal. As there is a power supply of unknown design involved for both the Arduino and the float switch.
This could cause unexpected results and may even permanently damage sensitive parts.  Consider using a design with only one power supply thereby mitigating the risk of unexpected results.

The assumption is that your code, sensors and pump all worked together at one point ("on the test bench").  So the code probably works.  And only after you installed it and ran it for a while did you notice that it fails.  Is that correct?

You're new @princessbubbles15. If the above answers your question select it as the correct answer. If you want to wait and try it fist to see if it works that's ok too. Or write a comment/question here if something is not clear and I'll edit the answer. Feel free to edit your question too if you find you forgot to ask something in particular.


text:
#Ardunio Send Float values with bluetooth.print in arduino
I have been creating the example for bluetooth communication with arduino with hc_05  Problem I am facing are below.
String statuss= "1.00,2.00,3.00";
bluetooth.print(statuss);
Serial.print(statuss);

This is the code where is get only last 2 digits i.e 00 in android while its showing me complete string in serial monitor.
String statuss= "Hello";
bluetooth.print(statuss);
Serial.print(statuss);

Then I get the output as ello in Android n in Serial monitor it show Hello
Can Anybody suggest the whats the problem

Do you use the Softwareserial lib? Do you set a speed higher than 19200 bauds? If you answer YES to these two questions, you'll have problem. SoftwareSerial is bugged and lost byte when speed is higher than 19200.

I suspect (at first sight) a speed problem. Android runs Bluetooth at 115200 Bauds. So you must set your HC-05 o HC-06 at this speed to get proper result.
But as you perform "bluetooth.print(statuss);" and also "Serial.print(statuss);" this mean you have created a virtual port, probably using the Software Serial lib.
Unfortunatly, this lib is not very efective. At speed higher than 19200 Bauds, you lost data (I've had a lot of problem with that before understanding!!)
The only right way is to use directly the RX and TX port of the Arduino (pin 0 and 1) and use (eg) a LCD Display to display data and help you debugging your Arduino code (as when you plug the HC on Pin 0 and 1 you lost the access to the serial monitor).
A trick: with the HC on pin 0 and 1, each time you send the sketck to the Ardino, you must unplug RX as it's used for sending the code.
Hope this will help.

It is difficult to know your exact problem since you have not provided your code. However, I believe that you don't have a clear starting bit and a clear end bit, so that the modules don't know when to Start and End.


text:
How does Arduino UNO deal with bit shifting?
Explanatory comment: I'm a beginner. I'm examining the feasibly of bit shifting to the right 6 places to divide up the range of the Arduino ADC (has a range of 0 to 1023) to something much smaller. Such that any number in the ADC registers, between 0 and 63 produces a value of 0, a number between 64 and 127 a 1, between 128 and 191 a 2, between 192 and 255 a 3, etc. There is a change every 64 increase in the initial number.
I think this is possible to do. But some doubt has been expressed I think.
As far as I have determined, after right shifting 6 places to the right the following values of numbers are resident in the ADC registers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.
I wish you to consider, is there anything in the way Arduino's IDE works, or with the nature of the initial number in the register (signed/unsigned) that makes the results I have indicated false.  I think, that the initial number will be unsigned, just guessing.

analogRead(pin_number) >> 6 will give you wat you want, as a signed integer in the range 0 – 15.

There are two types of right-shift in C - logical and arithmetic.
GCC (which is the compiler the Arduino IDE uses) selects which one to use depending on whether the type you are shifting is signed or not:

If it's signed then use an arithmetic shift
If it's unsigned then use a logical shift

In a logical shift, the value is literally shifted to the right padding the left side with zeros. An arithmetic shift, however, shifts and extends the sign. I.e., it performs an arithmetical "divide by 2".  That means if you right shift a negative value to still have a negative value (Note: this behaviour is implementation specific, so is only applicable to GCC. For other compilers in other situations you will have to check the documentation of that compiler).
So if you store the results of analogRead() in an unsigned integer variable >> N will right shift the value N times. If you store it in a signed integer it will divide the value by 2 N times.
For a positive value, which the results of analogRead() will be, the end result is the same - divide by 2 N times.
So if you right-shift 6 times you reduce a 10-bit value down to (10-6) 4 bits. 24 is 16, so you get 16 possible values.  24-1 is 15, so you get values 0-15 in your final value.

Why should it make a difference in terms of efficiency? On the AVR at least, both lsr (logical shift right) and asr (arithmetic shift right) are one-cycle instructions.

I was not aware of asr.


text:
Does analogueRead() change the way a number is represented etc?
Explanatory Comment: The ADC conversion result is a 10 bit number and is placed in two 8 bit registers: ADCH & ADCL. AnalogueRead() reads the output of the ADC. This, I believe is an unsigned number. But, generally taken as only a positive number.
I'm interested in what changes, if any, take place to the number (in it's representation, interpretation, or construction or whatever) when analogueRead() reads the number and presumably makes something of it, or sends it or stores it somewhere.

In other variants, like Mega, there is a possibility to configure ADC to measure differential value between two channels. In this case, the values insife of ADC are from -512 to 511. But It's not possible (supported) by analogRead() (note: there is no analogueRead).

There is no change in representation. analogRead() reads two I/O
registers, ADCL and ADCH, which on the Uno are memory-mapped to
addresses 0x0078 and 0x0079 respectively. It returns the result in a
register pair, r24 and r25, which per the AVR C calling
conventions is the
standard way of returning a 16-bit number. Thus, r24 holds the value
read from ADCL, and r25 the value read from ADCH. That's it. No
conversion whatsoever.
There is a change in interpretation... of sorts. The function is
declared as returning an int, which on the AVR is a 16-bit signed
integer, whereas it could be argued that the I/O registers contain an
unsigned number. However, since the sign bit will always be zero, the
signed/unsigned distinction is moot: either way the result will be
interpreted as a number between 0 and 1023.

Edit: As a clarification: the ADC register (which is another
name for the ADCL/ADCH register pair) is a 16-bit I/O register. At
the end of a conversion, it holds the 10-bit result right-adjusted into
this 16-bit space, zero-padded on the left, as follows:
-------- ADCH --------- --------- ADCL --------
0  0  0  0  0  0  r9 r8 r7 r6 r5 r4 r3 r2 r1 r0
----------------- ADC (16 bits) ---------------

where the bits r9..r0 represent the 10-bit conversion result. Since the
MSB is zero, it is irrelevant whether you interpret it as a sign bit or
as a regular unsigned bit.
Just for completeness, it could be noted that it is possible (though not
through the Arduino core library) to configure the ADC to left-adjust
the result, as follows:
-------- ADCH --------- --------- ADCL --------
r9 r8 r7 r6 r5 r4 r3 r2 r1 r0 0  0  0  0  0  0
----------------- ADC (16 bits) ---------------

In this case, the MSB could be one, at it would obviously be incorrect
to interpret it as a sign bit.
As a side note, the avr-libc defines ADC as
(*(volatile uint16_t *)(0x78)), which is unsigned. And it makes sense
considering that, unlike the users of Arduino core, the users of
avr-libc are supposed to know they have the choice to get a
left-adjusted result.

What I am understanding, is that the number in ADCH & ADCL (put together) is a 10 bit number. Unless it's held to be a 16 bit number because the register is 16 bits. Although that does not sound convincing to me. There is no sign bit in the ADC result register. But, an int store is 16 bit number. And the MSB is signed. That change from 10 bit to 16 bit, and unsigned to signed, seems to represent a change of some nature.  Maybe on a practical level, no difference, but on the level of theory - a change.

As I understand, it is nicely convenient that analogueRead() returns a 16 bit number, when reading a 10 bit conversion result, because there is then space for the sign bit. And I'm pretty sure whether the conversion result is left or right adjusted the MSB in int, will be a sign bit. A zero.

@RR.: You wrote: “I'm pretty sure whether the conversion result is left or right adjusted the MSB in int, will be a sign bit. A zero.” Not necessarily a zero if left-adjusted. Try this: Serial.begin(9600); PORTC|=_BV(PC0); ADMUX=_BV(REFS0)|_BV(ADLAR); ADCSRA=_BV(ADEN)|_BV(ADSC)|7; loop_until_bit_is_clear(ADCSRA,ADSC); Serial.println((int)ADC);.

It doesn't change anything, it just combines the two 8-bit register values to one 16-bit integer.
You can just look it up in the source code for analogRead.
int analogRead(uint8_t pin)
{
    uint8_t low, high;

[...]

    // we have to read ADCL first; doing so locks both ADCL
    // and ADCH until ADCH is read.  reading ADCL second would
    // cause the results of each conversion to be discarded,
    // as ADCL and ADCH would be locked when it completed.
    low  = ADCL;
    high = ADCH;

[...]

    // combine the two bytes
    return (high << 8) | low;
}

It is worth noting that this part of the code could be written more succinctly as return ADC;. The way it is actually written is inspired by the Atmel datasheets, which were probably written in ancient times, when gcc did not know how to properly handle 16-bit I/O registers.

I assume you mean AnalogRead, see AnalogRead.
What it effectively does is mapping 0 to 5V to values 0 to 1,023.
The unit is thus 5/1,024 V.
What this number means depend on the ADC used.
Probably the two bytes (ADCH as most significant bits and ADCL as least significant bits) contain this 0-1,023 value.

But, analogueRead() returns an int. Which is a 16 bit number, and the first bit is signed. Is that not a change in the original unsigned number?

It is indeed a 16 bit (signed) number. But according to the documentation it only returns values from 0 to 1,023. AnalogRead could also be have an uint(32) or uint(16) as return variable, but probably for novice users a 'simple' int is chosen.
So there is no need to change the original unsigned number. an unsigned 16 bit value perfectly fits in an integer type.

The way I am looking at things, as a novice, is that analogueRead() has taken an unsigned 10 bit number, and stored it (by way of default action) as a 16 bit signed number. And so, my answer to the question I posed (short form) would be yes.

Oh, I see that folks see the number is ADCH & ADCL, as a 16 bit number, even though it's only holding a 10 bit result.  So, it's not as if a 10 bit number is being turned into a 16 bit number.

True ... like e.g. the max value 1,023 is in binary 0000 0011 1111 1111 (16 bits) where ADCH is probably the first 8 bits and ADCL the last 8 bits.


text:
A small problem that I cannot detect, My steppers are not moving for some reason ...?
I'm working on a similar project that can be found in this link
https://howtomechatronics.com/projects/arduino-mecanum-wheels-robot/
It's the same build.
To control the 4 steppers (via the NRF24L01), I have built a remote control ( and you can find the project on the same website).
I have modified a few things and kept on testing on each step that I go through.
For now: my remote control sends X, Y from 1 joystick module and X1, Y1 from a second joystick module, besides mapped value from a potentiometer.
Back to the car, I'm receiving the exact same data and all works fine.
I have tested my circuit,
the power supply is fine and all good.
But I'm facing a problem that I could not detect when it comes to making the steppers move after receiving the data from the transmitter.
This is the code I m using for the receiver:
I'm not familiar with this Library and I feel like I'm only missing a small detail.
(As I said the same circuit was tested with a different code and steppers are running just fine).
Hopefully, you can help me out and spot what's wrong.
Thanks a lot guys.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <AccelStepper.h>
 RF24 radio(7, 8);   // nRF24L01 (CE, CSN)
const byte address[6] = "00001";
//unsigned long lastReceiveTime = 0;
//unsigned long currentTime = 0;
// Define the stepper motors and the pins the will use
AccelStepper LeftBackWheel(1, 2, 3);   // (Type:driver, STEP, DIR) - Stepper1
AccelStepper LeftFrontWheel(1, 4, 5);  // Stepper2
AccelStepper RightBackWheel(1, 9, 10);  // Stepper3
AccelStepper RightFrontWheel(1, 41, 40); // Stepper4
int wheelSpeed = 1500;
// Max size of this struct is 32 bytes - NRF24L01 buffer limit
struct Data_Package {
  byte j1PotX;
  byte j1PotY;
  byte j2PotX;
  byte j2PotY;
  byte pot1;

};
Data_Package data; //Create a variable with the above structure
void setup() {
  // Set initial seed values for the steppers
  LeftFrontWheel.setMaxSpeed(3000);
  LeftBackWheel.setMaxSpeed(3000);
   RightFrontWheel.setMaxSpeed(3000);
  RightBackWheel.setMaxSpeed(3000);
  radio.begin();
  radio.openReadingPipe(0, address);
  //radio.setAutoAck(false);
  //radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_LOW);
  radio.startListening(); //  Set the module as receiver
  Serial.begin(9600);
}
void loop() {
  // Check whether we keep receving data, or we have a connection between the two modules
  /*currentTime = millis();
    if ( currentTime - lastReceiveTime > 1000 ) { // If current time is more then 1 second since we have recived the last data, that means we have lost connection
    resetData(); // If connection is lost, reset the data. It prevents unwanted behavior, for example if a drone jas a throttle up, if we lose connection it can keep flying away if we dont reset the function
    }*/
  // Check whether there is data to be received
  if (radio.available()) {
    radio.read(&data, sizeof(Data_Package)); // Read the whole data and store it into the 'data' structure
    //lastReceiveTime = millis(); // At this moment we have received the data
  }

  Serial.print("X1= ");
  Serial.print(data.j1PotX);
  Serial.print("  Y1= ");
  Serial.println(data.j1PotY);
  Serial.println();
  Serial.print("X2= ");
  Serial.print(data.j2PotX);
  Serial.print("  Y2= ");
  Serial.println(data.j2PotY);
  Serial.println(" POT1=  ");
  Serial.println(data.pot1);
  Serial.println();
  delay(1000);
  // Set speed - left potentiometer
  wheelSpeed = map(data.pot1, 0, 255, 100, 3000);

  if (data.j1PotX > 150) {
    moveSidewaysLeft();
  }
  else if (data.j1PotX < 100) {
    moveSidewaysRight();
  }
  else if (data.j1PotY > 160) {
    moveForward();
  }
  else if (data.j1PotY < 100) {
    moveBackward();
  }
  else if (data.j2PotX < 100 & data.j2PotY > 160) {
    moveRightForward();
  }
  else if (data.j2PotX > 160 & data.j2PotY > 160) {
    moveLeftForward();
  }
  else if (data.j2PotX < 100 & data.j2PotY < 100) {
    moveRightBackward();
  }
  else if (data.j2PotX > 160 & data.j2PotY < 100) {
    moveLeftBackward();
  }
  else if (data.j2PotX < 100) {
    rotateRight();
  }
  else if (data.j2PotX > 150) {
    rotateLeft();
  }
  else {
    stopMoving();
  }
  // Execute the steps
  LeftFrontWheel.runSpeed();
  LeftBackWheel.runSpeed();
  RightFrontWheel.runSpeed();
  RightBackWheel.runSpeed();
}
void moveForward() {
  LeftFrontWheel.setSpeed(wheelSpeed);
  LeftBackWheel.setSpeed(wheelSpeed);
  RightFrontWheel.setSpeed(wheelSpeed);
  RightBackWheel.setSpeed(wheelSpeed);
}
void moveBackward() {
  LeftFrontWheel.setSpeed(-wheelSpeed);
  LeftBackWheel.setSpeed(-wheelSpeed);
  RightFrontWheel.setSpeed(-wheelSpeed);
  RightBackWheel.setSpeed(-wheelSpeed);
}
void moveSidewaysRight() {
  LeftFrontWheel.setSpeed(wheelSpeed);
  LeftBackWheel.setSpeed(-wheelSpeed);
   RightFrontWheel.setSpeed(-wheelSpeed);
  RightBackWheel.setSpeed(wheelSpeed);
}
void moveSidewaysLeft() {
  LeftFrontWheel.setSpeed(-wheelSpeed);
  LeftBackWheel.setSpeed(wheelSpeed);
  RightFrontWheel.setSpeed(wheelSpeed);
  RightBackWheel.setSpeed(-wheelSpeed);
}
void rotateLeft() {
  LeftFrontWheel.setSpeed(-wheelSpeed);
  LeftBackWheel.setSpeed(-wheelSpeed);
   RightFrontWheel.setSpeed(wheelSpeed);
  RightBackWheel.setSpeed(wheelSpeed);
}
void rotateRight() {
  LeftFrontWheel.setSpeed(wheelSpeed);

  LeftBackWheel.setSpeed(wheelSpeed);
   RightFrontWheel.setSpeed(-wheelSpeed);
  RightBackWheel.setSpeed(-wheelSpeed);
}
void moveRightForward() {
  LeftFrontWheel.setSpeed(wheelSpeed);
  LeftBackWheel.setSpeed(0);
  RightFrontWheel.setSpeed(0);
  RightBackWheel.setSpeed(wheelSpeed);
}
void moveRightBackward() {
  LeftFrontWheel.setSpeed(0);
  LeftBackWheel.setSpeed(-wheelSpeed);
  RightFrontWheel.setSpeed(-wheelSpeed);
  RightBackWheel.setSpeed(0);
}
void moveLeftForward() {
  LeftFrontWheel.setSpeed(0);
  LeftBackWheel.setSpeed(wheelSpeed);
   RightFrontWheel.setSpeed(wheelSpeed);
  RightBackWheel.setSpeed(0);
}
void moveLeftBackward() {
  LeftFrontWheel.setSpeed(-wheelSpeed);
  LeftBackWheel.setSpeed(0);
  RightFrontWheel.setSpeed(0);
  RightBackWheel.setSpeed(-wheelSpeed);
}
void stopMoving() {
  LeftFrontWheel.setSpeed(0);
  LeftBackWheel.setSpeed(0);
   RightFrontWheel.setSpeed(0);
  RightBackWheel.setSpeed(0);
}
void resetData() {
  // Reset the values when there is no radio connection - Set initial default values
  data.j1PotX = 127;
  data.j1PotY = 127;
  data.j2PotX = 127;
  data.j2PotY = 127;
  data.pot1 = 1;
}

I think you should not use delay here. Ditch that delay call. You can time the LCD display like in the BlinkWithoutDelay example

I will try that for sure


text:
How to find the index of the maximum value in an array?
Say we have an array named myMeasurements
int myMeasurements[9]={3,4,8,12,7,2,1,67,8};

How can I find the index of the maximum element of this array?
For example the MATLAB code would be:
myMeasurements = [3,4,8,12,7,2,1,67,8];
[maxValue,Index] = max(myMeasurements);

where maxValue is returned as 67 whereas the Index is returned as 8.
For the record, I am using Teensy 3.2 and I program it with the Arduino IDE using the Teensyduino add-on.

Arduino libraries have no special function to find the element in array

Duplicate of https://stackoverflow.com/a/2953498/5296568

I have an Average library that does all this kind of thing for you. Here is how it finds the maximum value's index: https://github.com/MajenkoLibraries/Average/blob/master/Average.h#L194

First of all, do you really need int values for the measurements or not? If not, and you have numbers between 0 and 255, switch the values to byte, your microcontroller will thank you.
Then, there is a problem with the other answers, which is... The variables cannot be left uninitialized!!! You can use this code to get the info you need:
(I also put the size of myMeasurements in a const variable.. You can thank me later for this)
const byte maxMeasurements = 9;
int myMeasurements[maxMeasurements ]={3,4,8,12,7,2,1,67,8};

byte maxIndex = 0;
int maxValue = myMeasurements[maxIndex];

for(byte i = 1; i < maxMeasurements; i++)
{
    if(myMeasurements[i] > maxValue) {
        maxValue = myMeasurements[i];
        maxIndex = i;
    }
}

The content of the myMeasurements array is coming from the ADC (analogRead) and hence it is 10 bits (0-1023). Unless the map function is used, they cannot be declared as a byte. I refrained from doing this because the map function reduces the resolution and it is likely that the values stored in the myMeasurements array are close to each other, i.e. the resolution plays an important role when finding the maximum element. I can define it as unsigned int Instead of int.

As a matter of fact, I am going to use the analogReadResolution(16) command to increase the ADC precision to 16-bits, which is also supported by the unsigned int data type.

@canberk_gurel you don't need a map (which is slow), you can just do something like (uint8_t)(readAnalog(channel) >> 4) (I don't remember the function, so forgive if readAnalog is not correct). In any case yes, if you need more than 8-bit measurement you need a more-than-8-bit variable, and so uint16_t is perfect

int myMeasurements[9] = {3,4,8,12,7,2,1,67,8};
int maxI = 0;
for(int i = 1;i < 9;i++)
    if(myMeasurements[i] > myMeasurements[maxI])
       maxI = i;

Put >= for last found max

Beaten by a few seconds... Even if a little of explanation why this is better than the previous answers would not have hurt...

You don't use variable for current number, you don't use  variable for max value, only for max index. You can assign 0 to maxI before for loop and so skip 1 iteration so it's faster a little bit and takes less ram

The code given by Jakub Krnáč gets a slight change which will give the index of the max value. Here is the changed code:
int myMeasurements[9]={3,4,8,12,7,2,1,67,8};
int max,current, maxI;
for(int i = 0;i < 9;i++){
    current = myMeasurements[i];
    if(current > max){
        max = current;
        maxI = i;
    }
}

Oh, those wonderful uninitialized variables....

Arduino forum has discussed finding the index once you know which value's index you want. Solution was arrived at by traversing the array by value you were looking for.
For your requirement, you will have to
(1) find the maxValue first and then
(2) find the position(index) of that maxValue using the code they have discussed here :
https://forum.arduino.cc/index.php?topic=121116.0

So two passes in the array to get the max index? Uhm...


text:
Communication between 3.3 V and 5 V system
I am using an ESP8266-01S that only works with 3.3 V power. I want to control a 5 V relay.
I gave each component its own power source and got an NPN transistor and wired it like in the diagram, but for some reason, it's not working when I power the transistor from the GPIO2 pin.
When I plug the middle pin of the transistor to the 3.3 V the relay works fine. I don't want to use a logic convertor and I want the solution to be small and simple.

Electronics circuits between two boards need to have common GND to operate properly.

Keep the GPIO2 pin high. Then measure the voltage of this pin with a multimeter. See if it is 3.3V or lower.

Connect the grounds of the two boards (maybe you already have).
Also, the maximum GPIO pin current of the RSP8266 is 12 mA. Connecting a transistor without a base resistor will send a large current through the BE of the transistor, which can damage the GPIO (and some transistors).
You have 3.3 V, minus the BE diode drop, say 0.6 V, leaves 2.7 V. Staying well within the GPIO's max. current, you can go for 9 mA base current. R = V/I = 2.7/0.009 = 300 Ω for the base resistor.

1- I tried to connect the ground together but the ESP just turns off for some reason
2- I put a 1k resistor between gpio and the transistor but nothing happened I don't know if I should connect a lower resistance or not

@Samyashraf, if your picture shown exactly the Relay module you had, it already has a resistor and a transistor (and a diode) on board, so you can directly connect to the board from GPIO2 directly to the relay board without extra transistor. You do need the common GND.

@hcheung ok, that works thanks, but I am also trying to make a custom PCB so what I need to make this connection work as I think I need a 5v relay without the module NPN transistor, and a 300-ohm resistance is that right, or is there is more to it?

You also need a flyback diode to prevent in-rush current. See how to use a relay for more explanation.

@hcheung I just got the parts and tried what like the schematics but the relay makes like a buzz sound and don't work I even tried a potinchiometer and star loring the ohm until it works but still noting


text:
LM7805 gets very hot with four servo motors
I'm making a robotic arm using three SG90s and one Futaba s3003 servo motors and an ESP32 dev_kit_V4.
The problem is when I am controlling the arm, the voltage regulator gets so hot that I can't touch it. After a minute or so the servos stop rotating and I have to restart the ESP32 to control the servos and the cylce continues.
I tried to connect the ESP32 to a power bank alone but the issue isn't solved. Can you help me?
The schematic for wiring:

Depending on load, your servos can draw 250ma of current or more when actuated. This means that your 7805 may need to supply >1 amp of current at 5V.
In order to get 5V from a 12V adapter the 7805 will need to drop 7V (The LM7805 is a linear regulator, essentially a variable resistor). 7V at 1 amp (peak) is 7 watts, which is what your regulator will dissipate during peak current draw.
With effective heat sinking your circuit will work. According to the datasheet, if you are running at room temperature with no heat sink you are limited to ~2.5 watts of dissipation.
If the 7805 chip temperature exceeds 150 degrees C it will go into thermal shutdown, which is probably what you're seeing.
Solutions would be to install an appropriate heat sink on the 7805, use a 7.5 volt power adapter (brings 7805 power dissipation down to ~2.5 watts), use multiple 7805 chips, or power everything with a 5V power adapter.

thanks , I will add a heatsink and see if it fixes the problem

I've added a heatsink and it works , thank you

Linear regulators especially the older ones like to go into oscillation at a relative high frequency. This may be load dependent.  The data sheet will recommend the appropriate capacitors to connect to it to prevent that. You would typically use a scope to see this. That oscillation will cause them to get hot rapidly even if they do not have a large load. You can look at the data sheet and determine the temperature rise of the die per watt of power. That you can determine by multiplying the drop across the regulator by the current. You can also apply this to heatsinks and pick one accordingly. There are conditions on this to be sure you have adequate ventilation to get rid of the heat on a air cooled heatsink. Liquid are similar but the numbers are much different.
In your case I would recommend you go to a switch mode regulator, commonly known as a buck or SEPIC regulator. The buck will drop the voltage from a higher voltage. The SEPIC does the same thing but if the input voltage goes below the output setpoint within its range it will boost the voltage keeping it at setpoint. As BobT explained the excess voltage is dropped through the regulator, it sort of acts like a variable resistor. This is dissipated as heat. The current on the input is about the same as the output. A switch mode regulator will operate in the efficiency range of maybe 80% - 95% efficiency, dissipating much less heat. They actually turn on and off very rapidly but the output is filtered so you do not see it.

I would recommend you to go with lm2596. That will solve your problem. Its output is adjustable. So set the output voltage first before connecting anything to it.

thanks for your reply,but I can't get it now because there is no electrical stores near to me