text:
Cannot mount NodeMCU with MicroPython on Mac OS X
I've recently bought a NodeMCU board and flashed MicroPython in it. I've read about the boot.py and main.py scripts, but I can't understand how to access them...
I have succesfully connected to the Python REPL with the screen command and everything works fine. Is there a way to mount it as an external drive on Mac OS X? Because I haven't found a way till now.
Thanks in advance!

this is not an arduino question, it's a micropython question.

The typical NodeMCU board uses a fixed function CP-210x USB-Serial chip.  This cannot appear to a host operating system as any ordinary sort of storage device, so it is not "mountable" via conventional storage drivers.
Access would need to be through some client program - or else, at a bit of a stretch, some highly specialized driver that created something fitting the host operating system's idea of filesystem, but proxying the actions through operatings the CP-210x and software running in the ESP8266 can support.

You have a NodeMCU; not a pyboard. I'm not sure that the USB Drive option is available in the NodeMCU.
I flashed microPython in a NodeMCU and Linux doesn't recognize it as a external drive or any other media type, but REPL thru serial monitor works fine.

meanwhile I've discovered ampy, which does what I need!

Adafruit MicroPython Tool (ampy) - Utility to interact with a MicroPython board over a serial connection. Ampy is meant to be a simple command line tool to manipulate files and run code on a MicroPython board over its serial connection. With ampy you can send files from your computer to a MicroPython board's file system, download files from a board to your computer, and even send a Python script to a board to be executed.


text:
I2C Temperature Sensor Communication Issue
I'm currently learning I2C and having some issues displaying the correct temperature in the serial monitor.
I am using an Arduino Uno and an SI7021 temperature sensor from Sparkfun; here's the datasheet I'm looking at.
The datasheet says that its device address is 0x40 and the temperature register is 0xF3 (maybe I am looking at this wrong?). However when I print the result to the screen it reads -1 degrees F.
Here's my code:
// SparkFun Si7021 Humidity and Temperature Sensor
#include <SparkFun_Si7021_Breakout_Library.h>
#include <Wire.h>

//Weather sensor slave address
int WeatherAddress = 0x40;

#define Temperature_Register_DATA 0xF3

//initialize humidity and temperature variables
float humidity = 0;
float tempf = 0;

//create a sensor from the Weather library
Weather temp_rh_sensor;

void setup() {
  Serial.begin(9600);
  //create wire object
  Wire.begin();
  //begin weather sensor
  temp_rh_sensor.begin();
}

void loop() {
  //begin transmission to weather sensor
  Wire.beginTransmission(WeatherAddress);
  //ask particular register for data (temperature register)
  Wire.write(Temperature_Register_DATA);
  Wire.endTransmission();
  //request the transmitted single byte from the register
  Wire.requestFrom(Temperature_Register_DATA, 1);
  if(Wire.available() <= 1) {
    tempf = Wire.read();
  }
  Serial.print("Temp: ");
  Serial.print(tempf);
  Serial.println("F, ");
  delay(1000);
}

You have connected a 3.3V sensor to a 5V Arduino Uno via the sda and scl lines ? Did you use a i2c voltage level shifter ? Did you connect 5V or 3.3V to the + connection of the module ? The sensor could be broken by now.

Reading this sensor is a little more involved. You don't just select a register and then read the value from it. Instead you send it a command to begin a read of a parameter (e.g., temperature) and then you need to wait for it to perform that command before you can read the result.
You need to use command 0xF3 for read with no hold master mode which will return NACK from a read request if the command isn't completed (which you are doing) - you then need to keep retrying the read until you don't get a NACK.
Also you need to read two bytes, not one:
//begin transmission to weather sensor
Wire.beginTransmission(WeatherAddress);

//ask particular register for data (temperature register)
Wire.write(Temperature_Register_DATA);

Wire.endTransmission();

// Keep retrying the read until it succeeds, or times out
uint32_t start = millis();
while (Wire.requestFrom(WeatherAddress, 2) < 2) {
    if (millis() - start > 2000) { // 2 second timeout
        break;
    }
}

if (Wire.available() < 2) { // It timed out
    Serial.println("Timeout");
} else {
    // Read the two bytes
    uint8_t hi = Wire.read();
    uint8_t lo = Wire.read();

    // and combine them into a 16 bit value
    uint16_t temp = (hi << 8) | lo;

    // Now convert the returned value into a real temperature:
    tempf = ((175.25 * temp) / 65536.0) - 46.85
    Serial.print("Temperature: ");
    Serial.println(tempf);
}

Wire.requestFrom(Temperature_Register_DATA, 1);

This should have the WeatherAddress as parameter instead of the register.
Wire.requestFrom(WeatherAddress, 1);

Hi thanks for the response, I just gave this a shot but it is still spitting out a -1 for the temperature. Does this mean I'm just accessing the wrong register inside the sensor?

The datasheet says that its device address is: 0x40

there is no standard notation on how to code i2c addresses - it all depends on how the particular library is coded. In this case, try 0x80 and 0x40 and see which one works.

The datasheet is quite clear... "The 7-bit base slave address is
0x40". It even goes so far as to depict it in an entire byte showing the bits of the address (1000000) and the RW bit.

source: Stack Exchange

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

sort: votes


text:
Arduino & NodeMCU, one server and multiple clients
I have seen another similar question and I followed the answer, but I cannot get my code to work for a single client properly.
In short, one NodeMCU provides AP and a WiFi server to multiple clients. The clients are supposed to stay connected. I am testing just a single client and it succeeds to connect and server reads just the first message, whereas all the subsequent messages are not received.
The server code:
#include <ESP8266WiFi.h>

#define MAX_CLIENTS 10

IPAddress    apIP(42, 42, 42, 42);
const char *ssid = "ESP8266";
const char *password = "ESP8266Test";
WiFiServer server(80);
WiFiClient *clients[MAX_CLIENTS] = { NULL };

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.begin();
}

void loop () {
  WiFiClient newClient = server.available();
  if (newClient) {
    Serial.println("new client");
    // Find the first unused space
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
      if (NULL == clients[i]) {
        clients[i] = new WiFiClient(newClient);
        break;
      }
    }
  } else {
    // Check whether each client has some data
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
      if (NULL != clients[i]) //ako ima taj client {
        if (clients[i]->available()) {
          Serial.print("client "); Serial.print(i);
          Serial.println("data received");
          digitalWrite(ledPin, LOW);
          String request = clients[i]->readStringUntil('\r');
          Serial.println(request);
        }
      }
    }
  }
}

As one can see, I'm checking incoming connections with server.available(), whereas I check if there is some data over the existing connection with clients[i]->available.
What happens is that I get only the first message from the client. The client code follows:
#include <ESP8266WiFi.h>

char ssid[] = "ESP8266";
char pass[] = "ESP8266Test";
WiFiClient client;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("W");
    delay(500);
  }
  client.connect(WiFi.gatewayIP(), 80); // Connection to the server
}

void loop () {
  client.println("0.00"");
  Serial.println("0.00"");
  delay(3000);
}

I suspect that I do not understand well the Server and Client classes from ESP8266WiFi Library, but it seems poorly documented.
Please advise.

i would just use the http examples if you only need 1/3Hz updates.

I believe it should work this way somehow, as http is more complex, and introduces unnecessary data and processing overhead. Maybe the problem is because the server node is also an AP?

I tried the both server and client nodeMCU's to be stations on another router's wireless network. Surprisingly, it works now.
Is this an issue with the library? Thank you

I presume you are not flushing the first data that's why only the first time your communication is happening but not after the subsequent time

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


text:
How to send data from an Arduino GPRS module to a Django application hosted on Heroku?
I have a Django web application hosted on a Heroku server. Currently I am using the free package for hosting. I want to send data from an Arduino using a SIM900L GPRS module to the web application. I want to know if it is possible. I have searched for a solution but couldn't find a proper guide or example for it. My web application accepts get requests and updates values in the database when url is entered. However if the Arduino sends data using the same url I get the following error:

AT+CIPSTART="TipCP","https://.herokuapp.com",80
  ERROR

Any tested example or suggestions about what I am doing wrong or what I should be doing instead?
     void gprs(float *value1, float *value2, float *value3, float *AFR, float *value5, float *value6)
{

  String APN = "";
  String UNAME = "";
  String PWD = "";
  char fid[] = "";
  char nid[] = "";
  char s_ip[] = "https://<appname>.herokuapp.com";
  char apikey[] = "";

  wdt_reset();
  digitalWrite(A4, HIGH);
  Serial.println(F("GPRS-1 Function"));
  delay(5000);
  wdt_reset();
  delay(5000);
  wdt_reset();

  char buffer1[10];

  uint8_t GSMTries = 0;
  String res;

  //wdt_reset();
  // the below code establishes connection and if not successful
  // tries three times in total
  do {
    sendData(F("AT\r\n"), 1000, DEBUG);
    sendData(F("AT+CIPSHUT\r\n"), 2000, DEBUG);
    sendData(F("AT+CIPMUX=0\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    sendData("AT+CSTT= \"" + APN + "\", \"" + UNAME + "\", \"" + PWD + "\"\r\n", 2000, DEBUG);

    sendData(F("AT+CIICR\r\n"), 2000, DEBUG);
    sendData(F("AT+CIFSR\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
    scnt += s_ip ;
    scnt += "\",80\r\n" ;

    res = sendData(scnt, 10000, DEBUG);
    GSMTries++;

    wdt_reset();

  } while (((res.indexOf("ERROR") != -1) || (res.indexOf("CONNECT") == -1)) && (GSMTries < 3));
  /*
    if(res.indexOf("ERROR") != -1){
    delay(200);
    sendData(scnt, 10000, DEBUG);
    }
  */

  String api = "GET /value?apkey=" ;
  api += apikey;
  api += "&&fid=";
  api += fid;
  api += "&&nid=";
  api += nid;

  Serial.println(F("API......."));
  Serial.flush();
  Serial.println(F("here-1"));

  String Data1 = "";

  //wdt_reset();
  //Co ordinator data is compiled along with html commands
  //and sent through GPRS
  String sensor = dtostrf(*value1, 4, 2, buffer1);
  Data1.concat(api);
  Data1.concat(F("&field1="));
  Data1.concat(sensor);

  sensor = dtostrf(*value2, 4, 2, buffer1);
  Data1.concat(F("&field2="));
  Data1.concat(sensor);

  sensor = dtostrf(*value3, 4, 2, buffer1);
  Data1.concat(F("&field3="));
  Data1.concat(sensor);

  sensor = dtostrf(*AFR, 4, 2, buffer1);
  Data1.concat(F("&field4="));
  Data1.concat(sensor);

  sensor = dtostrf(*value4, 4, 2, buffer1);
  Data1.concat(F("&field5="));
  Data1.concat(sensor);

  sensor = dtostrf(*value6, 4, 2, buffer1);
  Data1.concat(F("&field6="));
  Data1.concat(sensor);

  Data1.concat(F("\r\n"));

  delay(1000);

  String cipSend = "AT+CIPSEND=";
  cipSend.concat(Data1.length());
  cipSend.concat("\r\n");
  sendData(cipSend, 8000, DEBUG);
  sendData(Data1, 8000, DEBUG);
  sendData(F("AT+CIPCLOSE\r\n"), 5000, DEBUG);
  digitalWrite(A4, LOW);

  wdt_reset();

}

The above is a part of code used in arduino to upload data to website. This code was being used before to upload data to thingspeak through its IP address and worked fine.

Why is this tagged as python?

There's a number of errors in your program regarding your understanding of basic networking:
Let's start with this bit:
String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
scnt += s_ip ;
scnt += "\",80\r\n" ;

That constructs a string:
AT+CIPSTART="TipCP","https://<appname>.herokuapp.com",80

and sends it to the modem.  Now:

There is no such protocol as "TipCP" - I think you meant "TCP"
You need to provide an FQDN (Fully Qualified Domain Name), not a URL.  FQDNs don't start with "https://".  I think you meant to use "foobar.herokuapp.com" where "foobar" is the name of your application.

You then go on to form a GET request and send it.
Now: the URL you used instead of an FQDN starts with https:// - that tells me you want to be using SSL for your communications. I don't know if that is required for Heroku or not, but if it is then you cannot use AT+CIPSTART with it unless you feel like trying to implement the entirety of SSL in your program. Also you would be connecting to port 443 not port 80.
Assuming you don't need SSL fixing your protocol and FQDN may be enough. However using the AT+HTTP... commands instead of manual manipulation of a raw TCP socket may be an easier option.
If you do need SSL (and it is advisable that you do if you can) then you will have to use the SIM900's AT+HTTPS... command set (detailed here).


text:
What good designs are available for Geiger counters using an Arduino?
Are there any good circuit designs for Geiger-counter projects using an Arduino?
If so, what Geiger-Muller tubes should I choose to detect different types of radiation?

There are a few good, open-source, designs for Geiger counters using cheap G-M tubes and Arduino boards out there. Which one is best for you depends on what you want to achieve, so let's start by taking a look at what you might want to detect.

What are these "types" of radiation?

(source: Wikipedia)
Alpha radiation: basically consists of helium-4 nuclei (i.e. two protons and two neutrons). These interact with matter strongly because they are relatively heavy and carry a positive charge. However, because of their mass they will normally only penetrate a few centimetres of air. Alpha particles can be stopped in their tracks by a single sheet of paper.
You may not realise it, but the sensor in most smoke detectors uses a very small amount (~0.2μg) of Americium -  241Am.

Beta radiation: consists of highly energetic electrons. Because these particles are relatively light, they can penetrate somewhat further than Alpha particles. Even so, beta radiation can be stopped by a thin sheet of aluminium.
The big risk to human health from alpha- and beta-emitters is when they are ingested or inhaled. In these cases, the particles are brought into close contact with sensitive live tissue where the ionising radiation has the potential to cause various types of cancers.
Gamma radiation: is electromagnetic radiation having a higher frequency and shorter wavelength than X-rays.

One way to think of gamma-radiation is like a kind of "super X-ray". Gamma rays can pass through virtually anything. To build an effective shield, you need to have either very thick walls or a shield made from something with a high atomic weight, such as lead.
Gamma rays are produced naturally by the sun and stars - this is the source of what we call "cosmic radiation".

So which tubes should you choose?
Once you have decided what types of radiation you want your Geiger counter to detect the next step is choosing the tube. In general, they are all high-voltage tubes, typically operating at ~ 400V.
At the moment, the cheapest available tubes are probably the Russian SI-3BG Geiger Muller tubes, which can be picked up on eBay for about £5 GB. These are not very sensitive, but I've found they do work OK for beta and gamma radiation. However, it doesn't detect alpha radiation (which, as mentioned earlier, is what is emitted by the source in the sensor in many smoke detectors!)
One thing to watch out for is that these tubes are all different sizes, ranging from about 20mm long to more than 200mm. This matters. If you are going to design or buy a PCB for your project, just check that it has been designed to fit the sensor that you intend to use.
The following table lists the most popular G-M tubes, together with their main characteristics:

Follow the links below for further data on each tube:

SBM-20
SBM-21
SI-1G
SBT-9
SI-3BG
LND-712
LND-7124
LND-7224
J408γ
J305β
J306β

Your choice of tube is going to be determined by your budget, the types of radiation you want to detect and the sensitivity you want to achieve with your G-M counter.

Circuit designs
OK, so now we understand the radiation types, and we've chosen our tube, what Geiger counter designs are out there that use the Arduino.
(disclaimer: I have no connection with any of the companies mentioned in this answer)
Well, it turns out there are a few good designs out there (Google is your friend here), but one that does stand out from the pack (IMHO) is the Geiger Counter - Radiation Sensor Board for Arduino and Raspberry Pi from Cooking Hacks.
This is an open hardware design, and the code can be downloaded on a GPL licence.
It's a relatively simple design, and has a kit available pretty much off-the-shelf. Software can be downloaded for the Arduino and/or the Raspberry Pi. If you decide to buy the kit, they assure us that the shield/hat has been tested with the Arduino Uno and all models of the R-Pi.
Alternatively, you can just download the circuit diagram on the link above and design your own PCB (I don't think they offer the Gerber or Eagle files to download).
It is worth mentioning that the tutorial page also includes all the lovely useful background theory you'll need to understand how Geiger counters work, and how to get the most out of it.

Final thoughts. If you were thinking of building a Geiger counter without using an Arduino (Yes, yes, I know. But there may be some strange people out there who want to go this route!), there are still some nice designs out there you can play with.
The Geiger counter from MightyOhm is also open-source and uses the SBM-20 Geiger-Muller tube. Again, it is available as a kit, but if you prefer the DIY route, the design files are available to download.
Having looked at it, adapting this design to interface with an Arduino would probably also be relatively straightforward ...
If you are on a really tight budget there is a $15 Geiger counter on Hackaday. This uses the Russian SI-3BG G-M tube (discussed above) and a modified power-supply from a disposable camera.
I built one of these with a friend who was just starting out studying electronics and wanted to have a go at this project. I can confirm that it works, but that $15 price-tag is very optimistic.
(Having built this one, my friend decided that her next project would be to design a better one with greater sensitivity and which could detect alpha-, beta- and gamma-radiation and which incorporated an Arduino Uno. In hindsight, I should probably have mentioned the design from Cooking Hacks ..!).

Nice answer! A lot of good detail there. :)


text:
Force Sensitive Resistor OverLoad
I've got just a simple question. What happens when I overload Force Sensitive Resistor (FSR). Example Here.

Let's say that it's got force sensitive range between 100g and 10 000g. What would happen if I'd create pressure about 100kg? I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance? If so, can this FSR survive this overload? Has somebody test that?
Thank you for any answer.

It depends a lot on how it is mechanically set under pressure. The backside has to be against a very flat surface and the pressure has to be applied evenly spread over the whole sensor. That is hard to achieve, so the mechanical stress damages it. I did not test it, but I suppose it can handle a lot more than the 10kg, but it will get damaged. I think that it is impossible to get to almost zero ohms. There are other materials, for example conductive rubber, that can handle someone standing on it.

Also asked at http://forum.arduino.cc/index.php?topic=499102

I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance?

The harder the force, the lower the resistance. Sparkfun has a datasheet attached that shows the following graph:

Notice how both axis of the graph are logrithmic. This means that the resistance will never reach 0 ohms. However it will get close. At 10 Kg (22 lb) the resistance is about 250 ohms.

What would happen if I'd create pressure about 100kg?

The datasheet has the following to say for weight above the 10 Kg mark:

At the high force end of the dynamic range, the response deviates from the power-law behavior, and eventually saturates to a point where increases in force yield little or no decrease in resistance. Under these conditions of Figure 2 [ie. the graph above], this saturation force is beyond 10 kg. The saturation point is more a function of pressure than force. The saturation pressure of a typical FSR is on the order of 100 to 200 psi. For the data shown in Figures 2, 3 and 4, the actual measured pressure range is 0 to 175 psi (0 to 22 lbs applied over 0.125 in^2). Forces higher than the saturation force can be measured by spreading the force over a greater area; the overall pressure is then kept below the saturation point, and dynamic response is maintained. However, the converse of this effect is also true, smaller actuators will saturate FSRs earlier in the dynamic range, since the saturation point is reached at a lower force.

In summary, the weight applied can go over 10 Kg providing that weight is spread over the sensing area. The larger FSRs (such as this one) are better suited for this purpose as they have a larger area for which to spread the pressure.
Note: It is quite possible that with 100 Kg you could irreversibly damage the FSR, particularly if the weight isn't spread over the sensor area.
Measuring an analog voltage from the sensor is possible so that it can be fed into one of the analog pins of the Arduino. This Adafruit page has a nice table at the bottom showing the analog voltage that you get when you put the sensor in a voltage divider network (ie. in series) with a 10K ohm resistor.


text:
Arduino ESP8266 direct/fast control of the digital pins
How does one control a digital pin directly avoiding the slow digitalWrite or digitalRead?

One reads the datasheet.

in what manner is it slow? you know the clock speed of an ESP right?

digitalWrite and digitalRead have a lot of overhead since the input pin is a variable. I just tried the following code
void loop() {
digitalWrite(D3,HIGH);
digitalWrite(D3,LOW);
}    and it runs with 160kHz on a Wemos D1 mini. This is very slow for a micro controller running at 80MHz

Your question needs more detail.

@sa_leinad - no, it really doesn't need more detail - it's perfectly clear as is.  This is a pretty basic, and ordinary question.  It's quite well known how to do the analogous thing on an ATmega, and it makes perfect sense to have a question about doing it on the ESP8266, if that chip is going to be considered on-topic as an Arduino target at all.

After a weekend of searching and trying, here is what I was looking for:
It is slightly different than for the AVR chips. There is one register for setting the pins to HIGH and another one to set the pins to low.
Setting the pin HIGH:
GPOS = (1 << PIN_OUT);

Setting the pin LOW:
GPOC = (1 << PIN_OUT);

using this, I managed to speed up my code by a factor of three. It is not as dramatic as for the AVR chips, since the digitalWrite function is much more simple for the ESP8266.
Edit Further experiments show it is 10x faster: 910nsec for digitalWrite vs. 88nsec using GPOC or GPOS!

Unfortunately, Ratchet Freak's answer is specific to AVR, and isn't how the ESP8266 works.
It looks like the ESP8266 does indeed have registers for doing exactly this, which would let you set all 16 GPIO pins (GPIO0 through GPIO15, 16 is a different thing entirely) with a single operation. There's also a SET register, which sets the pins corresponding to 1 bits, and ignores pins corresponding to 0 bits, and a CLEAR register, which is the other way around.
Something I found on a forum said a user went from ~800KHz to ~5.7MHz toggling pins using these direct registers, that sounds about right.
One version of this is found in eagle_soc.h. The relevant bits from the header to get you started:
#define GPIO_REG_READ(reg)                         READ_PERI_REG(PERIPHS_GPIO_BASEADDR + reg)
#define GPIO_REG_WRITE(reg, val)                 WRITE_PERI_REG(PERIPHS_GPIO_BASEADDR + reg, val)
#define GPIO_OUT_ADDRESS                         0x00
#define GPIO_OUT_W1TS_ADDRESS             0x04
#define GPIO_OUT_W1TC_ADDRESS             0x08

So, if I've understood this correctly (and I haven't done any real testing, just going off the spec sheet and the header and posts elsewhere):
GPIO_REG_WRITE(GPIO_OUT_ADDRESS, 0xF0F0);

would set GPIO 4-7 and 12-15 to high, and 0-3 and 8-11 to low. In one operation. But there's more! Look at those W1TS and W1TC names. Those are set and clear registers. Which means you don't have to mask things. Instead of grabbing the current value, masking a bit in or out, and then writing it back, you can use those:
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, 0x1);

This will set GPIO0 high, and not affect any other bits.
This is also offered in a cleaner/simpler (??) form in esp8266_peri.h, which simplifies it to:
GPOS = 0x1;

for setting a bit. This is what's actually called by the arduino library's digitalWrite (for pins other than GPIO16):
extern void ICACHE_RAM_ATTR __digitalWrite(uint8_t pin, uint8_t val) {
  pwm_stop_pin(pin);
  if(pin < 16){
    if(val) GPOS = (1 << pin);
    else GPOC = (1 << pin);
[...]

But definitely be aware of this if you're doing anything fast, because writing multiple pins with a single operation is going to be way faster than multiple function calls. Without this, this chip can't even toggle bits as fast as a 16MHz Arduino.

In the spec sheet you will find the details for your device but most of the time it's pretty simple.
There will be global variables to control them, each will control various aspects of the pins.
For example you will have a register to control whether it's input or output, a register to control the output state, ... Again read the spec for your device to know what is what.
After the pin has been set up the instruction to set a pin high is:
PORTA |= PINx_MASK;

where Pinx_MASK is a bit mask with a single bit set according to the pin it represents.
To set the pin low it's similar:
PORTA &= ~PINx_MASK;

To set multiple pins on the port to different values you can do the following:
PORTA = (PORTA & ~pinsMask) | pinValues;

where pinsMask is a bitmask where all the pins you want to change are set and pinValues is the bitmask of which pins should be set high.
It pays to know how to manipulate bits in bitmasks but that's out of scope for this answer.
The SDK will be doing direct port manipulation itself, if you follow the definitions you should be able to figure it out.

this looks like AVR code, did you test it on the ESP?

This works for a platform with Atmel AVR chips like the Arduino Uno, Nano,..., but it does not not work for ESP8266. I am fully aware of exactly this trick and want to know if it exists for the ESP8266.

"There will be global variables to control them". This are not global variables, these are registers. When you did this to a variable no pin will change.

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


text:
What are these wires called?
I'm currently developing a quad copter for my school project and I am coming to the part where I am collecting all the parts before I assemble everything.
I have recently encountered a roadblock. I am going to solder an Arduino nano onto a strip board, but the problem is I cannot seem to find cables/wires to connect the nano to the module.
Excuse my ignorance, but where can I find these cables for soldering and what are they called?

Just wires? make sure they are copper and a smallish gauge and you'll be fine

"magnet wire" or "wrapping wire" is cheap and works well for bodging. ~30awg. old solid-core phone cables are another good source when on a budget.

If they are an intentional part of the design they are jumper wires. If they are to correct a mistake in the design they are bodge wires.
They aren't anything special, just wire. They look to be in the range of 24 to 30 AWG and PVC jacketed.
You can buy it in any electronic store.
You can also salvage it from things like old SCART cables and similar things.

If you want to wire your board with stranded wire, you can ask for NYAF and solder the edges with the tip. Otherwise you can ask for hook-up wires.
But if you are using breadboard, which i recommend you to use solid wire, you can ask it as wire wrap.
You can find them at an electronic store.

Read this tutorial about working with wires.
Sorry for the link-only answer, but I can't copy the article in full.

but where can I find these cables for soldering and what are they called?

hook-up wires.
pretty much any hardware stores should have it.


text:
Atmega328p screen + midi, possible?
I'm trying to build this Midi2CV (control voltage for analog synths) using a Arduino Nano:
https://photos.app.goo.gl/3IhhFL3PrLELLODB3
I was hoping to use this Nokia screen too for settings and debugging purposes, but I just realized there's only one hardware serial port on 328p and software serial seemed to be doomed for MIDI:
SoftwareSerial too slow for MIDI?
So I have three peripherals:

DAC (MCP4822)
Nokia 5110 screen
MIDI

I've gotten both the DAC and screen to work fine on normal pins so I'm thinking I'm good with just using the hardware serial for MIDI and the DAC and screen can use software. Or am I in for a world of pain without getting a more powerful chip with more hardware serial ports? And if so, what's the recommendation? (shoestring budget)

Neither the MCP4822 nor the 5110 screen use UART. You only have 1 UART, and you only have 1 "peripheral" that uses UART - so where is your problem? The DAC and screen are both SPI devices.

I guess I have no problem then? I'm noob. I've gotten both to screen and DAC to work over SPI on normal D-pins. So the hardware serial thing on RX/TX is only (needed?) for UART?

For SPI you should be using pins 10-13 plus extras for other CS pins as and when you need them. Pins 0/1 are connected to the USB port through an adaptor chip, but if you don't use USB you can use them for hardware UART (and are the only pins on the Uno that can do hardware UART).

Of your three functions (DAC, screen and MIDI) only one (MIDI) actually uses UART.
The other two devices are SPI devices which, while it is a serial protocol isn't UART (serial is a concept not a protocol).
Connect the DAC and screen to the SPI port (you can share SCK, MOSI and MISO, but select different CS pins) and you have the UART pins (0/1) available for MIDI use - as long as you don't want to use the USB connection which is linked directly to those pins.


text:
LCD is not showing any text
I'm using LCD QC1602A with a 10k potentiometer and changing contrast. It works well but the problem is that no text is appearing.
I'm using the LCD hello world examples and a few other examples. I tried reconnecting wires at least 5 times but every time it's the same problem. I connected it like this but the screen is not displaying any text at any contrast.
PS: It was showing white squares only in the top row, and now it's in both rows.

Two rows of white squares means that the driver chip has been successfully initialised to run in a 2x16 mode (it defaults to 1x16 which was the 1 row of squares you had originally).
So that means that you are configuring the display at least partially correctly.
You should adjust the pot so that you can just about see the squares. The squares are the background and the text would appear over them. If they are too bright you won't see the text. So adjust the contrast until you can just see that there are squares there.
If the wiring is correct and the code is correct then you should be able to see the text.

It works well but the problem is that no text is appearing.

it works well and yet no text is appearing?
so there is or there isn't a problem?

PS: It was showing white squares only in the top row, and now it's in both rows.

when correctly initialized, it should one row of blocks in the first row.
if it shows two rows of blocks, either it is not correctly initialized or the contrast is too much.

Actually, correctly initialised is 2 rows of blocks (it's set it up to be a 2 row display) and 1 row is not initialised (it defaults to a 1 row display). Two rows of blocks usually means the contrast is too high but communication is (at least to a certain extent) working.


text:
Fade sketch stuck in mathematical loop
I tried to edit the Fade sketch such that the max intensity the PWM reaches is controlled by a potentiometer. I used analogRead() on the potentiometer and converted the 10bit value to 8bit equivalent(by dividing by 4 and rounding) to feed into analogWrite. I am new to arduino and I dont know a more elegant way to do this, sorry!
It worked generally but sometimes while turning the potentiometer, the LED would be stuck at a fixed level of brightness. I have to reset the Arduino or turn the pot to the extremes to remove this "loop". I set up serial monitor to look at the values of brightness. It does not always happen at the same position of the potentiometer.
I deduce that it is a mathematical error causing this loop, likely due to my poor use of the if() function. Can anyone offer me a reason for this?
*I tested with both the Uno and Nano, as well as TinkerCad simulator with similar results.

-----------------------------Fade sketch edited by me----------------------
/*
 Fade, edited with maximum intensity controlled by potentiometer reading
 */

int led = 11;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
int potPin = A0;    // set the pin that reads the potentiometer voltage
int potValue = 0;   // declare and initialize potValue
int potValueConverted = 0; // 10bit potValue converted to 8bit equivalent

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  //read the voltage at the pot
  potValue = analogRead(potPin);

  //convert 10bit input into 8bit output by dividing by 4, rounding to avoid need for float variable
  potValueConverted = round(potValue/4);

  // set the brightness of pin 11:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

Serial.println(brightness);

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= potValueConverted) {
    fadeAmount = -fadeAmount;
  }

  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

Dividing an integer by an integer yields an integer. There is no need to round.

Interesting! Thanks for pointing that out.

It seems like the problem occurs when brightness is a lot higher than potValueConverted.
For example, lets say our brightness=100, potValueConverted=50, this triggers the latter "if" condition, i.e.

brightness >= potValueConverted

and at the next iteration, brightness = 105 (or 95), both of which will satisfy the condition for fadeAmount to flip its polarity, thus resulting in the brightness value oscillating between 105 and 100 (or 100 and 95).
This results in the LED getting stuck at the same level of brightness.
a quick hack fixes this problem (as far as I can tell)
 if (brightness <= 0 ) {
    fadeAmount = 5;
  }
 if (brightness >= potValueConverted +5 ) {
    fadeAmount = -5;
  }

**note the +5 for the second if statement is to ensure that the brightness value does not become negative.

if (brightness >= potValueConverted +5 )

the LED would be stuck at a fixed level of brightness.

that's by design: think about what happens when potValueConverted is very small.
edit:
to change the brighness, I would do this:
  brightness += fading; //change brightness;
  if ((brightness < BRIGHTNESS_MIN) || (brightness > BRIGHTNESS_MAX)) {fading = -fading; brightness += fading;} //bound brightness to _MIN and _MAX

if potValueConverted is very small then the LED will cycle very quickly with output like 0,5,0,5,0,5... causing a very dimly lit LED.
However, when the LED gets stuck, the brightness can be 80, 100, or 250, it doesnt always stay dimly lit, it simply gets stuck.


text:
Can you use an input pin instead of ground in Arduino circuitry?

Beginner here: Would the circuit in the picture work or do input pins not absorb the energy as ground does? I know setting the pin as an input makes the direct 5V connection safe but maybe I'm mistaken. I'm trying to understand the nature of how these connections are made. Thank you in advance!

An input pin can only sense the voltage that is applied to it - whether it is above or below a pair of thresholds.
In your existing circuit when the button is not pressed the voltage sensed by the pin is 0V because it is connected to 0V (also known as Ground) through the resistor. When you press the button the input pin is connected directly to +5V, so the pin senses 5V.
If you remove the resistor or the connection to ground the pin can still sense 5V on it when the button connects it to 5V, but when you release the button the input pin then isn't connected to anything at all. It's not connected to 0V, so it can't sense what voltage is there - there simply isn't any voltage connected to it (no voltage isn't the same as 0V).
In this case the pin is said to be "floating". It's neither HIGH (5V) nor LOW (0V), it's just dangling around not knowing what it's doing.
If you want to get more technical and look at the mechanics of it, it's helpful to know that the gate of a MOSFET (which is what the input pin actually is) looks to all intents and purposes like a small capacitor.  When you connect the input pin to +5V the capacitor is charged up (current flows into it from 5V to charge it). When you connect the input pin to 0V it discharges (current flows out of the capacitor down to 0V). When charged you have a HIGH and when discharged you have a LOW.
However when a charged capacitor has no connection it (for a certain amount of time, due to self discharge) keeps hold of its charge. So if you charge it with +5V and then disconnect it you will still get +5V on the capacitor. That is until it discharges through internal leakage currents.
Those leakage currents though are so small and the capacitor is so sensitive that the input pin acts like a radio antenna. It picks up noise from the surrounding area (electromagnetic waves) which can charge and discharge the capacitor pretty much at random. So at times you may see the input as HIGH and at other times as LOW, purely depending on chance. And the longer your wires the more noise it will pick up.
The worst source of noise is the 50/60Hz mains hum that is all around you. You can see this in reality if you graph the voltage on a disconnected ADC pin and bring your hand close to it - you act like a capacitively coupled antenna and you can see the mains waveform on your graph.
It's the same on a digital input pin, except that it converts it to a square wave as it passes the thresholds (you might like to look at schmitt triggers for more detail about how it does that).
So adding the pull down (or pull up if you prefer) resistor is critical to making the input pin see what you want it to see, and not just random noise.
Since the input is like a capacitor selecting the right value of resistor can be quite important in some situations. For a simple button like this there's nothing to worry about, but for something like a rotary encoder where the input signal may change more rapidly the resistor value does become more of a concern.  Have too high a value and the gate will take too long to discharge (or charge if it's a pull up resistor). Too low and too much current could be wasted through the resistor when the button (or encoder) is active (potentially damaging the button if it's a low current sensitive device).

If you remove the ground wire, digital pin 2 will be left "floating" until the button is pressed, and this is not a good thing to do:
https://electronics.stackexchange.com/questions/83133/arduino-digitalread-reading-wrong
There is a way to eliminate the pull-down resistor and simplify the wiring by using pinMode(BUTTON_PIN, INPUT_PULLUP); in setup(). You would connect one "leg" of the N.O. momentary push button switch to ground and the other "leg" to Pin 2. You will still need to "debounce" the switch, and for that I recommend a library.
There is a link to a good library here: https://playground.arduino.cc/Code/Bounce.
The example sketch called bounce.ino is a good place to start.


text:
How do I make the HC-05 bluetooth module take data from the HC-SRO4, and then send it to my Android app?
Currently, I have an Arduino Uno set up, with a HC-SRO4 ultrasonic sensor printing distances of objects in front of it on a scale from 1-15 to the serial monitor. I want to attach the HC-05 bluetooth module and do the following:
First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.
I understand the Android part may be out of scope of this forum, but please try to help me with taking data from the serial monitor and have it transmit the data.
Here is the code I have for the ultrasonic sensor:
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}
void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

You don't have to take data from serial monitor. Just use the same data and send it via HC-05. You only have to add instructions to your current sketch. For debugging purposes, keep sending data to serial monitor while you work on the Android part of it.

What is the actual code used to get the HC-05 to transmit the data so that my Android app can pick it up?

You're using an uno so you'll need to use the software serial library. Get the hc05 working with software serial. Run a Bluetooth terminal monitor on your Android and make sure you can see the hc05 output.

First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

No. What you do is you connect your Bluetooth module to two digital pins, which you'll use, along with the SoftwareSerial library, just the way you are using currently the Serial object. Look at the SoftwareSerial examples in the IDE.
Before you use the HC-05 module, and transmit data, you'll have to make sure it is set up properly (baud rate, name, PIN code, etc). Plenty of code and tutorials on Google about that.

Use software serial library and connect your HC-05 TX RX pins accordingly, to transmit/recieve the ultrasonic data using bluetooth. From playstore you will get bluetooth terminal software. Install it in your smart phone. Now connect your phone's bluetooth to HC-05 using that software. Now you can see in that app, all data you are receiving via bluetooth. you can also transmit data using that app. If you want to develop your own app, maybe you can check out MIT app inventor. Simple and fast.


text:
Can you connect more sensors of the same type to a single board while not using up more pins than if you were to use a single sensor?
I'm as new as you can be at Arduino programming and specific electronics, so I don't even know if I'm asking the correct question.
I've ordered an Arduino a breadboard and some PCBs and now I'm looking for a few parts that I should buy in order to get some basic projects done.
I'd like to start with a garden automation project, a fairly simple one.
Humidity sensors, temperature sensors and a water pump.
Can I connect all (4) of the humidity sensors to a single local circuit and then connect that to the board so I can limit the number of input pins used? I'd still need to get independent readings from the sensors. Or would I need to use another board incorporating RF/Wireless/Bluetooth modules to receive the information and then send it to the board for further processing?
I'm sorry if what I just said makes no sense and I thank you for your time.
All I have is low-mid level electronic related experience. Battery checkers, Power supplies, basic light sensors, PCB making ETC.

Did any of the answers help? If so, please accept the answer that helped. If not, please post your own answer and mark it as accepted in 48 hours time. Thank you.

If the connection is a digital sense pin then you can use a parallel-in serial-out IC to read them all simultaneously and then shift it in. Takes up 3 pins on the arduino a latch a clock and a data pin.
If the connection is SPI then you can connect the clocks and MISO pins together and then need a slave select for each. you can control many of them with a serial in parallel out IC or a decoder.
If the connection is with the I2C protocol and each device has a different address then you can simply connect them all in parallel.
If the sensor has an analog output then you can use an analog to digital converter (ADC) which can have multiple inputs and often have a serial interface.

It all depends on the interface between the Arduino and the sensor.
For example the DS18B20 uses the 1-Wire bus. That requires one digital pin and a number of DS18B20 can be connected to the same 1-Wire bus. Every DS18B20 has an unique identifier that makes that possible.
Humidity sensors like DHT11 or DHT22 require a pin for each sensors. They are not accurate anyway.
Sensors like the BME280 use the I2C bus. The I2C bus allows that many sensors can be connected. Each I2C sensor has an I2C address. Sometimes a sensor can have just one I2C address and therefor only one of such a sensor can be connected to the I2C bus. But sometimes a trick is possible to have more.
This list goes on and on and on. A lot is possible without extra hardware.
Because you are going to use sensors and many sensors are 3.3V, did you buy a 3.3V Arduino board ?

If you do not need them to run simultaneously, you can use a multiplexer such as this one from Sparkfun:
https://www.sparkfun.com/products/9056

This doesn't look like a question, it looks like an answer.


text:
Cannot create a PWM with 20% duty cycle using micro() timer
I have been working with Arduino for almost a year, because I found it easy for beginners in electronics. But now, I have a major problem, I'm trying to get rid of my delay() function because I want my Arduino Nano to handle to tasks at once:
1-Read MIDI data and transfert it into a pwm signal, as well as monitoring the on and off of the signal (which are bytes). This part works correctly, but i'm not using the mirco(), i'm using a library called Timer1.
2-Generate a PWM signal of 20% dutycycle with a frequency ranging from 1 to 103 Hz using a potentiometer to adjust the frequency.
So, what happens is that the signal I measure on my oscilloscope is a PWM at 50% duty cycle and with frequencies that don't match my calculations at all. Also, It doesn't change smoothly, the frequency goes from 159Hz to let's say 180Hz only at one particular point on the potentiometer, just like if all the rest of it was useless. I decided to monitor all my values with Serial and everything was good, the values were OK and nothing was wrong. Then I decided to change all my variables to floats so I could maybe get more precision... Didn't work as well. So now I'm kind of desesperate.
//MANUAL MODE TEST WITH MICROS()
//VARIABLES ASSIGNEMENT
unsigned long current=0.0;
unsigned long previous=0.0;

float TimeOn = 0.0;
float TimeOff = 0.0;
float manuelF = 0.0;
float sensor = 0.0;

int pin = 11;

byte state = LOW;

//SETUP AND PIN ASSIGNEMENT
void setup() {
  pinMode(9, OUTPUT);//MUSIC SIGNAL OUTPUT
  pinMode(11, OUTPUT);//MANUAL SIGNAL OUTPUT
  pinMode(A5, INPUT);//POTENTIOMETER MANUAL
  pinMode(A6, INPUT);//POTENTIOMETER MUSIC
  Serial.begin(9600);
}

void loop() {

  sensor = analogRead(A5);
  manuelF=((sensor+10.0)/10.0); //Capture la fréquence sur A5
  TimeOn=1000000.0*(0.2*(1.0/manuelF));
  TimeOff=1000000.0*(0.8*(1.0/manuelF));
  current = micros();

  Serial.println(TimeOn);

  //Serial.print("A5 read:");
  //Serial.println(analogRead(A5),8);
  //Serial.println("-----------");
  //Serial.print("Fréquence: ");
  //Serial.println(manuelF,8);
  //Serial.print("timeon:");
  //Serial.println(TimeOn,8);
  //Serial.print("timeoff:");
  //Serial.println(TimeOff,8);

  if ((state == LOW)&&(current - previous >= TimeOff)){
      state = HIGH;
      digitalWrite(pin,state);
      previous = current;
    }
  else{
    if (current - previous >= TimeOn){
      state = LOW;
      digitalWrite(pin,state);
      previous =current;
    }

  }
 }

As you can see I'm still monitoring the TimeOn variable. Well, It shows exactly (to 4 micro seconds precise) the time that it is supposed to be ON.
My output at that moment is a 50% duty cycle with a frequency of 53Hz when I pass the 7k on the potentiometer (it is a 10k). Before that, it doesn't even outputs a signal.
What is going on?
EDIT#1:
I have done the modifications that @Edgar Bonet suggested me. It partially worked. What i'm left with now is a PWM that can go from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

I have found the problem. Part of it was the code, thank you @Edgar Bonet. The other part was the pin I was using to generate the PWM signal. Throughout my reasearch, I found that on the arduino nano, the timer pins are the same than those on the arduino Uno. Thus:
Timer0 :pins 5-6
Timer1 :pins 9-10
Timer2 :pins 3-11
Since I was using the function micros() which uses the timer0, I had to send the signal to the right pin. I cannot describe why it did send a certain PWM to discrete frequencies, but the important is that it now works.
In parallel, because the other part of my program is using timer1, the two data transmission won't interfere with each other!
Time inversted in researches: 4hours
Hope this helps someone! Thanks.

You wrote:
if ((state == LOW)&&(current - previous >= TimeOff)){
    state = HIGH;
    digitalWrite(pin,state);
    previous = current;
  }
else{
  if (current - previous >= TimeOn){
    state = LOW;
    digitalWrite(pin,state);
    previous =current;
  }

While you probably mean:
if (state == LOW && current - previous >= TimeOff) {
    state = HIGH;
    digitalWrite(pin, state);
    previous = current;
}
else if (state == HIGH && current - previous >= TimeOn) {
    state = LOW;
    digitalWrite(pin, state);
    previous =current;
}

Thank you! It solved a good part of the problem. Now, I can control a PWM from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

changed current=micros() to current=millis(), gives even worse results...


text:
How to read the busy flag on LCD?
I have a standard 16x2 LCD screen and I have it hooked up to my Arduino UNO via a I2C backpack (4-bit mode).
Since I want to learn about the lcd at a lower level I’ve decided not to use the LCD library and instead use the Wire library.
I have writing to the LCD working fine so now I want to understand how to read from it. I thought trying to read the busy flag was a good start.  (I currently delay() after to the LCD which seems to be the most popular solution).
According to the LCD documentation it requires that the RS bit be set to 0 and RW bit to 1. I have a attached the code below.  For some reason it always reads 0x2.
I also read the busy flag right after writing to the screen and it always screws up every other letter.  E.g. if I write 'k' twice to the screen, the first 'k' shows up fine, but the second time it becomes a 'f'.  I am suspecting writing to the LCD before reading is screwing up the data processing.  If I don't attempt to read the flag, all the characters show up correctly.
Here is the code.  Any help would be appreciated.  Thank you!
#define ENABLE (1 << 2)
#define BACKLIGHT (1 << 3)

#define READ (1 << 1)

byte readReq = BACKLIGHT | ENABLE | READ;
Wire.beginTransmission(0x3F);
Wire.write(readReq);
Wire.write(readReq & ~ENABLE);// write 1st nibble
Wire.write(readReq);
Wire.write(readReq & ~ENABLE); //write 2nd nibble

Wire.endTransmission();

Wire.requestFrom(0x3F, 2);

while (Wire.available() < 2) {}

byte firstNibble = Wire.read(); //always reads 0x2
byte secondNibble = Wire.read(); //always reads 0x2
Serial.println(firstNibble, HEX);
Serial.println(secondNibble, HEX);

What is this I2C backpack thing you are using?

Not the exact model, but something like this: https://goo.gl/images/ftHFNx

Does it have the same chip on it?

It is a PCF8574AT


text:
Trying to flash ESP8266 with Arduino UNO
This is my first project other than some of the starter projects. I am trying to flash the firmware onto an ESP8266 wifi module using and arduino uno. It would be nice to know if anything is wrong/redundant in the picture below (I was looking at a few different diagrams to try and figure out what was right). I have found some tutorials saying that TX should go to RX instead of TX to TX so that is what I am doing. I am trying to use the level shifter to go from 5v to 3.3v because I wasn't sure if I had enough current going to the ESP8266 when just directly hooked up to 3.3v on arduino (I read in a few places that the arduino doesn't have a strong enough current to operate the wifi module). I found some tutorials which use a voltage regulator, I tried doing that but had the same results I am getting now. I have also read that you don't need a level shifter or voltage regulator but it might harm the components so I haven't tried that way yet.
I am the point where I plug it into my computer via USB, open the Arduino IDE > Tools > Serial Monitor.
I type the command 'AT' and there is no response - I tried every baud setting. Sometimes it randomly outputs a question mark or two.
Other things of note: When I plug it in, the ESP8266 blue light flashes once. When I was modding the header pins of the ESP8266 I kind of fumbled it a lot - could that have broken some aspect of the chip? Also while modding the header pins, I pushed them all in to make them longer and bent them on the other side, so it would work with the breadboard - I'm wondering if the soldering connections need to be stronger (you can kind of see in the picture).

This is the schematic for what I was trying to achieve basically, while also using the level shifter:

Any advice with regards to anything you see here would be great, I am new to the world of circuits.
Note: there is a ground wire that is not in the frame of the picture connecting one side of the breadboard to the other, that part of this is one thing I was wondering about.

Ohhh... That solder! That is NOT ok!

You do not need the level shifter. The input pins of the ESP8266 contain over-voltage (though not over-current) protection. All you need to do is limit the current that can flow through the over-voltage protection circuit, and all that needs is a series resistor in the region of 100Ω or so.
And the Arduino already has that protection between the ATMega16U2 and the TX/RX pins anyway in the form of 100Ω resistors that it uses to prevent short circuits between the two MCUs on the board, so you don't need to add it in this instance (you do if you want to communicate between the ATMega328P and the ESP8266, but only between the Arduino's TX and the ESP8266's RX pins).
When it comes to actively running the ESP8266 it can be beneficial to power it from a more powerful 3.3V regulator than the 150mA one on the Arduino since when transmitting the ESP8266 wants more than that, but for simple flashing of it the Arduino's 150mA regulator should do the job fine.
One thing to note though: I don't like the look of the soldering on your ESP8266 pins. I would be inclined to re-solder those joints. Add a bit of flux to help the solder flow properly.

Thanks @Majenko, I'm gonna solder those joints. from your comments at the bottom: I don't have a regulator on hand and I was wondering if I could use the equation here https://learn.sparkfun.com/tutorials/voltage-dividers to use as sort of a rough regulator...would that be unsafe...I guess i'll solder and then try again just to make sure it wasnt a connection

Definitely not. https://hackingmajenkoblog.wordpress.com/2016/08/30/why-you-cant-use-resistors-as-a-voltage-regulator/

great that explained it, communication not power, thanks for link.

but I can still try with 3.3v on arduino as power source, u said that should be enough for flashing

would my level shifter help for 5v to 3.3v?

Not for power, no. Logic signals only.

What I have done was connecting ESP8266 and UNO as the schematic described.
But instead of using the default program in ESP8266, I programmed ESP8266 via UNO using the ESP8266 Library on Arduino IDE
If your way still did not work you can maybe try this method.

I think I may be able to help clarify things a bit here:
You are not trying to "flash" the ESP01 (the kind you have) board, but you are trying to talk to the AT command firmware it came installed with.
Also, there's a sort of pingback sketch (I forget the name and can't find it, but it basically uses a SoftwareSerial and copies characters from one to the other and vice versa) that is used to configure the ESP01 that's normally used, but you don't seem to be using it here (it may not be worth the effort, either, since it's tricky to get working sometimes).
In this case, it seems that you are trying to do one of two things:
If you are trying to talk to the ESP01 module from the computer connect the TX to the TX pin and the RX to the RX pin. This is because the Arduino board's serial adapter is already connected in the mirrored direction, and you are using that to talk to the ESP01. Do note that you should, before connecting the ESP01, upload the Blink sketch or similar to the Arduino so that it's not trying to use the Serial connection too.
See http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/ for more information on that use case.
On the other hand, if you are trying to talk to the device from the Arduino itself (as in, the Arduino has a program that needs WiFi access), you'd want to connect it RX to TX and TX to RX. Of course, when doing this, the Arduino should already have its program uploaded since the ESP01 would cause issues uploading firmware via Serial afterward (they both talk at once).
Lastly, these things are REALLY finicky, so make sure you set the baud rate and use NLCR end-of-line signaling.


text:
Stability issue with webserver and smartmeter logging
In the past few months I have successfully logged the data from the power and gas meter in my house to a remote web server.
Now I try to add the ability to enable and disable my doorbell over the internet.
Although it seems to work, I experience 2 problems.
Problems

Arduino freezes after a few hours
When the meter reading is transmitted, the doorbell can not be
switched.

Questions

Is there a way to give priority to control the doorbell?

and ..

is there a way to find out why the Arduino freezes after a while?

Setup:

Arduino Mega 2560 board
Ethernet shield
LCD display
Relay
light sensor(for backlight control)
serial connection to smart power/gas meter

//V1.1: Cleaned up messy code
#include <LiquidCrystal_I2C.h>
#include <Wire.h>  // Comes with Arduino IDE
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#include <AltSoftSerial.h>
#include <SPI.h>
#include <Ethernet.h>

//setup ethernet server
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //assign arduino mac address
byte ip[] = { 192, 168,  178, 95}; // ip in lan assigned to arduino
byte gateway[] = { 192,  168, 178,  1}; // internet access via router
byte subnet[] = {  255,  255,  255,  0}; //subnet mask
EthernetServer server(84); //server port arduino server will use
char thingSpeakAddress[] = "";
IPAddress myDns(8, 8, 8, 8);
EthernetClient client;
String writeAPIKey = "XXXMX2WYYR0EVZZZ";
String tsData = "hello"; //dummy data
String readString; //used by server to capture POST request
const int updateThingSpeakInterval = 20 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
unsigned long int updateCounter = 0; //set refresh counter to 0
//////////////////////
//slimme meter////////
/////////////////////
char c;
AltSoftSerial altSerial;
const int requestPin = 48; //data pin connected to smartmeter
char input; // incoming serial data (byte)
bool readnextLine = false;
#define BUFSIZE 75
char buffer[BUFSIZE]; //Buffer for serial data to find \n .
int bufpos = 0;
long mEVLT = 0; //Meter reading Electrics - consumption low tariff
long mEVHT = 0; //Meter reading Electrics - consumption low tariff
long mEAV = 0; //Meter reading Electrics - Actual consumption
long mG = 0; //Meter reading Gas
//unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

//const unsigned long postingInterval = 10 L * 1000 L; // delay between updates, in milliseconds, the "L" is needed to use long type numbers
/////////////////////////////////////////
//photcel////////controls lcd backlight//
////////////////////////////////////////
int photocellPin = 5; // the cell and 10K pulldown are connected to a0
int photocellReading; // the analog reading from the analog resistor divider
//boolean doorbell = true;

int creset = 43; //Telling arduino that you are connecting pin 43 with reset

//////////
//setup///
//////////
void setup() {
  Wire.begin();
  digitalWrite(22, LOW);
  digitalWrite(creset, HIGH);
  pinMode(creset, OUTPUT);
  pinMode(22, OUTPUT); //pin selected to control
  pinMode(6, OUTPUT); //pin selected to control
  pinMode(7, OUTPUT); //pin selected to control
  pinMode(8, OUTPUT); //pin selected to control
  //pinMode(5, OUTPUT); //pin 5 selected to control
  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  server.begin();
  Serial.begin(9600);
  altSerial.begin(9600);
  Serial.println(F("Smarthome controller")); // keep track of what is loaded
  Serial.println(F("Send a g in serial monitor to test client")); // what to do to test client
  lcd.begin(20, 4); // initialize the lcd for 16 chars 2 lines, turn on backlight
  // sensorValue = analogRead(sensorPin);
  lcd.backlight(); // finish with backlight on
  //-------- Write characters on the display ------------------
  // NOTE: Cursor Position: Lines and Characters start at 0
  lcd.setCursor(0, 0); //Start at character 4 on line 0
  lcd.print("Smarthome controller");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("powerd by arduino");
  delay(1000);
  lcd.print("                  ");
  lcd.setCursor(0, 2);
  lcd.print("");
  lcd.setCursor(0, 3);
  delay(1000);
  lcd.print("Slimmemeter:     ");
  //lcd.backlight(); // turn on backlight.
  lcd.setCursor(0, 2);
  lcd.print("Doorbell: onn      ");
}
void loop() {
  if (updateCounter > 400) {
    digitalWrite(creset, LOW);  // Reset arduino
  }
  // Update ThingSpeak
  if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {
    decodeTelegram();
  }
  // Check if Arduino Ethernet needs to be restarted
  if (failedCounter > 3) {
    startEthernet();
  }
  lastConnected = client.connected();
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char cl = client.read();
        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += cl;
          //Serial.print(c);
        }
        //if HTTP request has ended
        if (cl == '\n') {
          ///////////////
          Serial.print(readString); //print to serial monitor for debuging
          //now output HTML data header
          if (readString.indexOf('?') >= 0) { //don't send new page
            client.println("HTTP/1.1 204 Zoomkat");
            client.println();
            client.println();
          } else {
            client.println(F("HTTP/1.1 200 OK")); //send new page on browser request
            client.println(F("Content-Type: text/html"));
            client.println();
            client.println(F(""));
            client.println(F(""));
            client.println(F("<TITLE>Smarthome</TITLE>"));
            client.println(F(""));
            client.println(F(""));
            client.println(F("
Smarthome control page
"));
            // DIY buttons
            client.println(F("Deurbel"));
            client.println(F("ON"));
            client.println(F("OFF

"));

            client.println(F("Pins"));
            client.println(F(" ALL ON"));
            client.println(F(" ALL OFF"));
            client.println(F(""));
            client.println(F(""));
            client.println(F(""));
            client.println(F(""));
          }
          delay(1);
          //stopping client
          client.stop();
          if (readString.indexOf("**secretcode**") > 0) //checks for secretkey
          {
            ///////////////////// control arduino pin
            if (readString.indexOf("on2") > 0) //checks for 2
            {
              digitalWrite(22, LOW); // set pin 5 high
              //Serial.println(F("Led 5 On"));
              //Serial.println();
              lcd.setCursor(0, 2);
              lcd.print("Doorbell: on      ");
              //doorbell = true;
            }
            if (readString.indexOf("off3") > 0) //checks for 3
            {
              digitalWrite(22, HIGH); // set pin 5 low
              //Serial.println(F("Led 5 Off"));
              //Serial.println();
              lcd.setCursor(0, 2);
              lcd.print("Doorbell: off      ");
              //doorbell = false;
            }

            //clearing string for next read
            readString = "";
          }
        }
      }
    }
  }

  //lcd.setCursor(0, 0); //Start at character 4 on line 0
  //lcd.print("SMARTHOME CONTROLLER;.");
  //String analogValue = String(analogRead(A5), DEC);
  photocellReading = analogRead(photocellPin);

  //lcd.setCursor(0, 1);
  //lcd.print(photocellReading);
  if (photocellReading < 800) {
    lcd.backlight(); // turn on backlight.
  } else {
    lcd.noBacklight(); // turn on backlight.
  }

}

////////////////////////////////////////////////////////////////////////////
//////////////////////////FUNCTIONS/////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
void updateThingSpeak(String tsData)
//void sendGET() //client function to send and receive GET data from external server.
{
  //lcd.setCursor(0, 2);
  // lcd.print("                   ");
  lcd.setCursor(13, 3);
  lcd.print("verstur");
  // delay(1000);
  if (client.connect(thingSpeakAddress, 80)) {
    client.print("GET /smarthome/log.php?stroomLaag=");
    client.print(mEVLT);
    client.print("&stroomHoog=");
    client.print(mEVHT);
    client.print("&stroomVerbruik=");
    client.print(mEAV);
    client.print("&gasStand=");
    client.print(mG);
    client.println(" HTTP/1.1");
    client.println("Host: .nl");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();
    lastConnectionTime = millis();
    updateCounter++;
    Serial.print("Connecting to log server...");
    Serial.println(updateCounter);
    //x=x+1; //page upload counter
    // lcd.setCursor(0,3);
    // lcd.print("Data send           ");
    //delay(1000);
    lcd.setCursor(13, 3);
    //lcd.print("                    ");
    lcd.print("ok        ");
    lcd.setCursor(16, 3);
    lcd.print(updateCounter);
    if (client.connected()) {
      Serial.println("Connecting to suscesfull...");
      //Serial.println();
      failedCounter = 0;
    } else {
      failedCounter++;
      Serial.println("Connection to failed (" + String(failedCounter, DEC) + ")");
      Serial.println("connection failed");
      Serial.println();
      lcd.setCursor(13, 3);
      lcd.print("fout");
      lcd.setCursor(16, 3);
      lcd.print(String(failedCounter, DEC));
    }
  } else {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
    Serial.println();
    lastConnectionTime = millis();
  }
  while (client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char cl = client.read(); //gets byte from ethernet buffer
    //readString += c; //places captured byte in readString
    //Serial.print(c); //print raw data
  }
  client.stop(); //stop client
  readString = ""; //clear readString variable
}

////////////////////////////////////////////////////

void startEthernet() {
  client.stop();
  Serial.println("Connecting Arduino to network...");
  Serial.println();
  delay(1000);
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0) {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  } else {
    Ethernet.begin(mac, ip, gateway, gateway, subnet);
    server.begin();
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
  }
  delay(1000);
}

////////////////////////////////////////////////////

void decodeTelegram() {
  long tl = 0;
  long tld = 0;
  if (altSerial.available()) {
    //input = altSerial.read();
    c = altSerial.read();
    // --- 7 bits instelling ---
    c &= ~(1 << 7);
    char inChar = (char) c;
    //Serial.print(c);
    input = c;
    //Serial.println(input);
    //char inChar = (char)input;
    // Fill buffer up to and including a new line (\n)
    buffer[bufpos] = input & 127;
    bufpos++;
    if (input == '\n') { // We received a new line (data up to \n)
      if (sscanf(buffer, "1-0:1.8.1(%ld.%ld", & tl, & tld) == 2) {
        tl *= 1000;
        tl += tld;
        mEVLT = tl;
      }
      // 1-0:1.8.2 = Elektra verbruik hoog tarief (DSMR v4.0)
      if (sscanf(buffer, "1-0:1.8.2(%ld.%ld", & tl, & tld) == 2) {
        tl *= 1000;
        tl += tld;
        mEVHT = tl;
      }
      // 1-0:1.7.0 = Electricity consumption actual usage (DSMR v4.0)
      if (sscanf(buffer, "1-0:1.7.0(%ld.%ld", & tl, & tld) == 2) {
        mEAV = tl + tld;
      }
      // 0-1:24.2.1 = Gas (DSMR v4.0) on Kaifa MA105 meter
      //if (strncmp(buffer, "0-1:24.2.0", strlen("0-1:24.2.1")) == 0) {
      if (sscanf(strrchr(buffer, '(') + 1, "%d.%d", & tl, & tld) == 2) {
        mG = (tl * 1000) + tld;
      }
      //}
      // Empty buffer again (whole array)
      for (int i = 0; i < 75; i++) {
        buffer[i] = 0;
      }
      bufpos = 0;
    }
    if (input == '!') { //uitroepteken geeft einde van telegram aan, dus we gaan data versturen
      // if (millis() - lastConnectionTime > postingInterval) {
      // httpRequest();
      updateThingSpeak("field1=0");
      // httpRequest();
      mEVLT = 0;
      mEVHT = 0;
      mEAV = 0;
      mG = 0;
      client.stop();
      //}
    } //Einde vraagteken detectie
    //Serial.print(c);
  } //Einde 'if AltSerial.available'
} //Einde 'decodeTelegram()' functie

I already experienced an ATmega microcontroller freeze unexpectedly, but in my case it was because of fluctuations in the power source. As you have a full Arduino board here, it should have the necessary capacitors to filter things. Though insufficient power can still be an issue even with capacitors. So, unless you power it with insufficient batteries, it's probably a bug in your code. You could add more logging and last logged message is a clue ; this requires to constantly listen on the serial port with another machine.

power consumption of the relay coil could be the problem

The Arduino is powered with 1amp adapter on the power grid

Please see some comments that can help you.
Why do you use a software serial port?
This ATmega has 4 real serial ports!
delay() is dangerous in the main loop runtime. Try to use it only in setup.
Every time you call a task, be sure you will not stay there forever.
Get out of the task, if something seems to be too long time. Use millis() stamp time differences to measure time spent.
Print it if necessary on debug compiler option.
Printing on failure case do not spend MCU time if there are no errors.

I don't see any problem using delay() in program loops; if you are going to state that it is dangerous please explain why.  SoftSerial is handy  whenever you are using serial communications on the non-default serial pins, and for consistency in programming I find I tend to use it just so my code is very clear in naming pins.  millis() is great, however you must remember that adding any debugging statements like lcd.write() or Serial.write() will necessarily throw off the timing.  All that being said, can I ask what your main point is in this answer, please?

My recomendations are just to help you to find the two problems. The cpu freezes because there are ram buffer corruption. Serial hardware decreases time to process serial data and, a delay or a long loop means the system services for ethernet and serial tasks will stop

Im not sure why softserial is required, maby beqause the message from the smartpowermeter is inverted . I will try to add the buffer lenght protection and let you know te result.

buffer[bufpos] = input & 127;
bufpos++;

Never use a buffer without a length protection.
Flag if max buffer is reached, force to never write after last position.
Like this:
if ( bufpos > MaxBuff )
{
    Serial.print("errornumber");
    bufpos = MaxBuff;
    //And force \n to finish errored message
}


text:
What is causing this 'narrowing conversion' warning?
Because I'm still figuring out 'Arduino C' I leave all warnings on.
Recently I got this one:
narrowing conversion of '(int)(((unsigned char)bx_0) | ((unsigned char)bx_1))' from 'int' to 'const byte... etc.
...referring to this line:
const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

...pointing to the or symbol.
The code in question (much simplified to recreate this):
const int latch[2] = {2, 4};

const byte bx_0 = 1 << latch[0];
const byte bx_1 = 1 << latch[1];

const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

(This happens whether I use byte, uint8_t, or unsigned char everywhere.)
Without the or operator, no warning. If bx_0 and bx_1 are simple bytes, not shifted into existence, no warning. If I do this:
const byte pinMask[3] = {bx_0, bx_1, (byte)(bx_0 | bx_1)};

...again, no warning.
However, I get no complaints about this:
const byte notMask = !(bx_1 | bx_0);

...so a further condition is that the problem or has to be in an initializer list. Yikes.
I don't get it. There's no way an or of two bytes can force widening, so where did the (int) cast come from? It apparently has something to do with the 1 << latch[0] code, but the result of that is still a byte, by definition.
I have a solution -- the (byte) cast -- but in the real code it's ugly and feels unnecessary. Everything is already just bytes.

That warning message arises when a compiler complies with C/C++ specifications.
According to ISO/IEC 9899:2011 part 6.5.12.2 (“Bitwise inclusive OR operator”),

Each of the operands shall have integer type

Thus, in the evaluation of bx_0 | bx_1 within the statement const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};, the operands bx_0 and bx_1 are converted to int type before being OR'd together.  This produces an int result, which then must be narrowed to byte before it can be stored in the  byte array.
Knowing that the (byte) cast is necessary because of C/C++ specifications should convert your view of the cast from “ugly” and “unnecessary” to “necessary” and either “ok” or “oh well”.  :)

Thanks, I suspected that might be the issue, except that all the conditions are necessary for the warning: complex definition, bitwise operator, initializer list. Remove any one and it doesn't warn. And OK, I'll accept 'necessary' (-: but I'm keeping "ugly" because in the actual code there are 16 elements to pinMask[], some with three or's.


text:
Arduino UNO + Ethernet Shield + LCD + RFID but RFID doesn't work
I've been working to a project that uses arduino for RFID but when connected to ethernet shield, the RFID seems to not read any card tapped to sensor but the LCD seems to do fine. Here's the code I use from this page: http://www.instructables.com/id/RFID-CARD-READER-WITH-ARDUINORFID-RC522-and-LCD-16/
#include <EEPROM.h> //Library To read and write PICC's UIDs from/to EEPROM
#include <SPI.h> //Library  RC522 Module uses SPI protocol
#include <MFRC522.h> //Library  RC522 Module
#include <LiquidCrystal.h> //Library  for LCD Display
#include <Ethernet.h>

EthernetServer server(80);
boolean match = false; // initialize card match to false
boolean programMode = false; // initialize programming mode to false
int successRead; // Variable integer to keep if we have Successful Read from Reader
byte storedCard[4]; // Stores an ID read from EEPROM
byte readCard[4]; // Stores scanned ID read from RFID Module
byte masterCard[4]; // Stores master card's ID read from EEPROM
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
LiquidCrystal lcd(7, 6, 5, 4, 3, 2); //Initializing LCD PINS as (RS, EN, D4, D5, D6, D7)

void setup() {
  Serial.begin(9600); // Initialize serial communications with PC
  lcd.begin(16, 2); //Initializing LCD 16x2
  pinMode(8, OUTPUT); //LED and Buzzer PIN OUT
  SPI.begin(); // MFRC522 Hardware uses SPI protocol
  mfrc522.PCD_Init(); // Initialize MFRC522 Hardware
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
  if (EEPROM.read(1) != 1) {
    // Look EEPROM if Master Card defined, EEPROM address 1 holds if defined
    Serial.println("No Admin Card Defined");
    //When no Master Card in Your EEROM (Serial Display)
    Serial.println("Scan A card to Define as Admin Card");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.println("SET ADMIN CARD   ");
    //When no Master Card in Your EEROM (LCD Display)
    lcd.setCursor(0, 1);
    lcd.println("SCAN A CARD.....");
    //Scan any RFID CARD to set Your Master Card in Your EEROM (LCD Display)
    delay(1500);
    do {
      successRead = getID();
      // sets successRead to 1 when we get read from reader otherwise 0
    }
    while (!successRead);
    //the program will not go further while you not get a successful read
    for (int j = 0; j < 4; j++) {
      // Loop 4 times
      EEPROM.write(2 + j, readCard[j]);
      // Write scanned PICC's UID to EEPROM, start from address 3
    }
    EEPROM.write(1, 1); //Write to EEPROM we defined Master Card.
    Serial.println("Admin Card Defined");
  }
  Serial.println("Administrator Card's UID");
  for (int i = 0; i < 4; i++) { // Read Master Card's UID from EEPROM
    masterCard[i] = EEPROM.read(2 + i); // Write it to masterCard
    Serial.print(masterCard[i], HEX); //Master Card only view in serial
    Serial.println("Waiting PICCs to bo scanned :)");
  }
 //WAITING TO SCAN THE RFID CARDS:
  Serial.println("");
  Serial.println("Waiting cards to bo scanned :)");
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.println("WAITING     ");
  lcd.setCursor(3, 1);
  lcd.println("FOR CARD...  ");
  delay(1500);
}

int getID() {
 // Getting ready for Reading PICCs
  if (! mfrc522.PICC_IsNewCardPresent()) {
    //If a new PICC placed to RFID reader continue
    return 0;
  }
  if (! mfrc522.PICC_ReadCardSerial()) {
    //Since a PICC placed get Serial and continue
    return 0;
  }
 // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
 // I think we should assume every PICC as they have 4 byte UID
 // Until we support 7 byte PICCs
  Serial.println("Scanning card's UID....");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SCANNING");
  lcd.setCursor(0, 1);
  lcd.print("Card's UID.....");
  delay(2000);
  for (int i = 0; i < 4; i++) {
    readCard[i] = mfrc522.uid.uidByte[i];
    Serial.print(readCard[i], HEX);
  }
  Serial.println("");
  mfrc522.PICC_HaltA(); // Stop reading
  return 1;
}
boolean isMaster(byte test[]) {
  if (checkTwo(test, masterCard))
    return true;
  else
    return false;
}

boolean checkTwo (byte a[], byte b[]) {
  if (a[0] != NULL)
    // Make sure there is something in the array first
    match = true;
    // Assume they match at first
  for (int k = 0; k < 4; k++) {
    // Loop 4 times
    if (a[k] != b[k])
      // IF a != b then set match = false, one fails, all fail
      match = false;
  }
  if (match) {
    // Check to see if if match is still true
    return true;
  } else  {
    return false;
  }
}
boolean findID(byte find[]) {
  int count = EEPROM.read(0);
  // Read the first Byte of EEPROM that
  for (int i = 1; i <= count; i++) {
    // Loop once for each EEPROM entry
    readID(i);
    // Read an ID from EEPROM, it is stored in storedCard[4]
    if (checkTwo(find, storedCard)) {
      // Check to see if the storedCard read from EEPROM
      return true;
      break; // Stop looking we found it
    } else {
      // If not, return false
    }
  }
  return false;
}
void readID(int number) {
  int start = (number * 4) + 2;
  // Figure out starting position
  for (int i = 0; i < 4; i++) {
    // Loop 4 times to get the 4 Bytes
    storedCard[i] = EEPROM.read(start + i);
    // Assign values read from EEPROM to array
  }
}
void deleteID(byte a[]) {
  if (!findID(a)) {
    // Before we delete from the EEPROM, check to see if we have this card!
    failedWrite(); // If not
  } else {
    int num = EEPROM.read(0);
    // Get the numer of used spaces, position 0 stores the number of ID cards
    int slot;
    // Figure out the slot number of the card
    int start;
    // = (num * 4) + 6; // Figure out where the next slot starts
    int looping;
    // The number of times the loop repeats
    int j;
    int count = EEPROM.read(0);
    // Read the first Byte of EEPROM that stores number of cards
    slot = findIDSLOT(a);
    //Figure out the slot number of the card to delete
    start = (slot * 4) + 2;
    looping = ((num - slot) * 4);
    num--; // Decrement the counter by one
    EEPROM.write(0, num); // Write the new count to the counter
    for (j = 0; j < looping; j++) {
      // Loop the card shift times
      EEPROM.write(start + j, EEPROM.read(start + 4 + j));
      // Shift the array values to 4 places earlier in the EEPROM
    }
    for (int k = 0; k < 4; k++) {
      //Shifting loop
      EEPROM.write(start + j + k, 0);
    }
    successDelete();
  }
}
//For Failed to add the card:
void failedWrite() {
  Serial.println("something wrong with Card");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SOMETHING WRONG");
  lcd.setCursor(0, 1);
  lcd.print("WITH CARD");
  delay(2000);
}

//For Sucessfully Deleted:
void successDelete() {
  Serial.println("Succesfully removed");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SUCCESFULLY");
  lcd.setCursor(0, 1);
  lcd.print("REMOVED CARD");
  delay(2000);
}

int findIDSLOT(byte find[]) {
  int count = EEPROM.read(0);
  // Read the first Byte of EEPROM that
  for (int i = 1; i <= count; i++) {
    // Loop once for each EEPROM entry
    readID(i);
    // Read an ID from EEPROM, it is stored in storedCard[4]
    if (checkTwo(find, storedCard)) {
      // Check to see if the storedCard read from EEPROM
      // is the same as the find[] ID card passed
      return i;
      // The slot number of the card
      break;
      // Stop looking we found it
    }
  }
}
//For Sucessfully Added:
void successWrite() {
  Serial.println("Succesfully added");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SUCCESFULLY");
  lcd.setCursor(0, 1);
  lcd.print("ADDED");
  delay(2000);
}

//For Adding card to EEPROM:
void writeID(byte a[]) {
  if (!findID(a)) {
    // Before we write to the EEPROM, check to see if we have seen this card before!
    int num = EEPROM.read(0);
    // Get the numer of used spaces, position 0 stores the number of ID cards
    int start = (num * 4) + 6;
    // Figure out where the next slot starts
    num++;
    // Increment the counter by one
    EEPROM.write(0, num);
    // Write the new count to the counter
    for (int j = 0; j < 4; j++) {
      // Loop 4 times
      EEPROM.write(start + j, a[j]);
      // Write the array values to EEPROM in the right position
    }
    successWrite();
  } else {
    failedWrite();
  }
}
void loop() {
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("TAP YOUR");
  lcd.setCursor(4, 1);
  lcd.print("CARD HERE");
  do {
    successRead = getID(); // sets successRead to 1 when we get read from     reader otherwise 0
    if (programMode) {
      // Program Mode cycles through RGB waiting to read a new card
    } else {
    }
  }
  while (!successRead);
  //the program will not go further while you not get a successful read
  if (programMode) {
    if (isMaster(readCard)) {
      //If master card scanned again exit program mode
      Serial.println("This is ADMIN Card");
      Serial.println("Exiting ADMIN Mode");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("EXITING FROM");
      lcd.setCursor(0, 1);
      lcd.print("ADMINISTRATOR MODE");
      delay(2000);
      programMode = false;
      return;
    } else {
      if (findID(readCard)) {
        //If scanned card is known delete it
        Serial.println("I know this CARD, so removing");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("AVAILABLE!");
        lcd.setCursor(0, 1);
        lcd.print("SO DELETING.....");
        delay(5000);
        deleteID(readCard);
        Serial.println("-----------------------------");
      } else {
        // If scanned card is not known add it
        Serial.println("Adding this card...");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Card no:");
        lcd.setCursor(0, 1);
        lcd.print(readCard[0], HEX);
        lcd.print(readCard[1], HEX);
        lcd.print(readCard[2], HEX);
        lcd.print(readCard[3], HEX);
        lcd.print(readCard[4], HEX);
        delay(4000);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("NOT AVAILABLE");
        lcd.setCursor(0, 1);
        lcd.print("SO ADDING...");
        delay(5000);
        writeID(readCard);
        Serial.println("-----------------------------");
      }
    }
  } else {
    if (isMaster(readCard)) {
      // If scanned card's ID matches Master Card's ID enter program mode
      programMode = true;
      Serial.println("Welcome to Administrator Mode");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("WELCOME TO");
      lcd.setCursor(0, 1);
      lcd.print("ADMIN MODE");
      delay(3000);
      int count = EEPROM.read(0);
      // Read the first Byte of EEPROM that
      Serial.print("I have ");
      // stores the number of ID's in EEPROM
      Serial.print(count);
      Serial.print(" record(s) on EEPROM");
      Serial.println("");
      Serial.println("Scan a card to ADD or REMOVE");
      Serial.println("-----------------------------");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SCAN CARD TO");
      lcd.setCursor(0, 1);
      lcd.print("ADD OR REMOVE...");
      delay(2500);
    } else {
      if (findID(readCard)) {
        // If not, see if the card is in the EEPROM
        Serial.println("Acces Granted");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("ACCESS GRANTED");
        lcd.setCursor(0, 1);
        lcd.print("YOU MAY ENTER NOW");
        digitalWrite(8, HIGH);
        delay(1500);
        digitalWrite(8, LOW);
        lcd.clear();
      } else {
        // If not, show that the ID was not valid
        Serial.println("Access Denied");
        for (int abcd = 0; abcd < 3; abcd++) {
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("     SORRY");
          lcd.setCursor(0, 1);
          lcd.print("  ACCESS DENIED");
          digitalWrite(8, HIGH);
          delay(1000);
          digitalWrite(8, LOW);
          lcd.clear();
          lcd.print("   YOU'RE NOT  ");
          lcd.setCursor(0, 1);
          lcd.print("   AUTHORIZED   ");
          delay(1000);
        }
        lcd.clear();
      }
    }
  }
}

Any help would be appreciated!

Well, the Ethernet shield uses SPI as well, and pins 10-13.  Seems that would be a problem...

Thank you kind Sir, I'm fairly new to coding arduino and I just follow instructions so I don't know what to add in the code to add SPI device(Ethernet shield).

What @KCTucker is saying is that you can not use every optional feature with every other optional feature.

I recently made a similar project with a RFID reader and an SD card shield, and I had the same problem.
The explanation why it doesn't work is that some shields that use SPI communication don't really care about your slave select pin being pulled low, and interfere when Arduino is talking to another SPI device via the MISO pin.
The only way I got it to work is by using a tri-state buffer on the MISO pins of my SPI devices. You can find plenty of info about it on the internet, as well as how to use them in your project.
The idea is simple, it works kind of like a transistor. When you pull the enable pin of the buffer to ground using SS pin, you allow the MISO pin of that device to be connected to the corresponding Arduino input. Otherwise, the MISO pin will be on a state of high impedance and would not interfere on the communication anymore.
Good luck with your project.

It may not be possible to use every optional Arduino feature with every other optional Arduino feature. Some features use the same Arduino resources.  If there is actually a hardware contention problem, you need to dive deep into the software drivers and hardware to figure out if there is a possible work around.  But this is hardly the type of effort new developers would take on.  It might be easier for a new developer to use 2 different Arduino's to host the features desired and set up a communication link between them.

If you are "following instructions", please post a URL to the project that is using all the hardware you mentioned.


text:
Installing Arduino IDE on Linux
I downloaded arduino-1.8.4-linux32.tar.xz and ran install.sh as outlined (the very sketchy instructions) in https://www.arduino.cc/en/Guide/Linux
This seemed to work OK, so I removed 354M of what I thought was the installer, only to discover that I had deleted arduino.
The so-called install.sh on closer inspection seemed only to create links into the uncompressed download in my home directory.
The whole process seems very un-Linux like; I had assumed that it would be installed in /usr/share/ like most Linux programs.
I realise I could extract into /usr/share/ and set permissions for other users, but surely there must be others who have wanted to do the same. The macOS version seems to have a proper installer; does one exist for Linux?

There is a .deb package that properly installs everything. Alas, it's for the ancient Arduino 1.0.5.

Live with it. Many years ago I learnt the hard way not to mess with installed files. I will never fill my hard drive anyway, so, why take the risk?

I mentioned here about the flatpak versions (cross-distro)

I ran the following to Install the latest Arduino IDE on my Raspberry Pi3.
This should work all Pi models. This release enables you to run the Arduino Software (IDE) on many of the mini PC boards based on ARM6+ processors currently on the market, including Raspberry Pi
# Installing Arduino IDE
cd /usr/share/
sudo tar xf /home/pi/arduino-1.8.9-linuxarm.tar.xz
sudo chown root:root -R /usr/share/arduino-1.8.9/

# Adding desktop shortcut, menu item and file associations for Arduino IDE
# Each user needs to repeate this
cd
/usr/share/arduino-1.8.9/install.sh

There is a similar instruction in MagPi61 except they suggest installation in /opt

The problem here is that there are multiple flavours of linux each with their own installation and package management systems - Aptitude, Yum, EMerge, etc.
It is not easy for Arduino to keep up with creating packages for each and every system, so instead they create a single tarball that can be used on any of the systems.
At one point Arduino (or someone, anyway) used to create Debian packages for the IDE and upload them to the main Debian repository - however this has not been done for many years now and the packages in the Debian repositories are very much out of date (1.0.5 IIRC).
If you, as a system manager, choose to deploy the IDE system wide then it is your task to decide how best to do that.
One option is to just copy the contents of the archive to /usr/share/arduino and then run ./install.sh from within that directory.

There is some work being done for packaging a newer Arduino, but it seems there are some non trivial issues in the way: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=780706

I wrote an installation instruction for the Arduino 2.0.x IDE over at AskUbuntu.
I chose to install the files in the /opt directory, but opinions differ on that topic. The instruction also elaborates on adding desktop links and an icon for Ubuntu flavors.


text:
nRF24L01 not communicating
I have been using two nRF24L01 to communicate with each other using a simple Arduino Uno Board. It worked for 5 days and now all of a sudden it is now working. I tried to change the modules and the Arduino boards too, but even if trying a simple example the communication between them is not happening.
I googled everything and tried every option, it is not working.
I used printDetails() to check the config of the modules. It shows everything is ok but I am not able to understand if the transmitter or the receiver is the problem. Please guide me to solve this problem. Also how to make sure if both are working (any debugging technique)?
I have been trying it for 9 days now, and I badly want it to work.
The code I am using is very simple code. It doesn't have any errors.
Receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String response;
boolean done = false;

void setup() {
  delay(500);
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.openReadingPipe(0,0xF0F0F0F0AA);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&response, sizeof(response));
    done = true;
  }
  if (done) {
    Serial.println(response);
  }
  done = false;
  delay(1000);
}

Sender code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String request;

void setup() {
  delay(500);
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(0xF0F0F0F0AA);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  while (Serial.available() > 0) {
    request = Serial.readString();
    Serial.println(request);
    radio.write(&request, sizeof(request));
    delay(1000);
  }
}

You have to edit this question and include the printDetails() output here too, you saying "everything is ok" isn't enough.

You cannot use the String class here. You should use a char[ ] . The & operator and sizeof operator when used against a String object refer to the object handle.

Hello,
You need to set a channel to both NRF:
void setup() {
   delay(500);
   Serial.begin(9600);
   radio.begin();
   radio.setChannel(0x55); //set the channel
   radio.openWritingPipe(0xF0F0F0F0AA);
   radio.setPALevel(RF24_PA_MIN);
   radio.stopListening();
   radio.powerUp(); //Power up the radio
}

Change this.
void loop() {
    if (radio.available()) {
        radio.read(&response, sizeof(response));
        done = true;
    }
    if (done) {
        Serial.println(response);
        done = false;
    }
    //done = false;
    delay(1000);
}

Maybe you should check your power supply. If it worked for 5 days, then it should be ok with your boards and module. If it don't work anymore it could be broken board, broken module or power supply.


text:
Can't upload to Arduino Mini via Arduino USB 2 Serial Converter
I bought an Arduino Mini and also an Arduino USB 2 Serial Converter.
While trying to program the Arduino Mini, I get this error:
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00

After doing some research I tried many things like changing the settings, serial port, made sure I'm using the right Arduino etcetera.
Some points to consider:

I tried burning the bootloader using my Arduino Uno.
Uploading sketches to the Arduino Mini using my Arduino Uno works (so problem is not directly with the Mini).
I am pressing the Reset button before uploading. I also tried hooking a capacitor and the Reset wire directly. No change.

The wiring (I also tried connecting TX of Mini to RX of serial converter, and vice versa):

The Arduino USB 2 Serial converter was defect (even though brand new). I bought a cheaper (7 Euro) FTDI to USB and I can now upload.