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

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

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

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

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

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

#define ledpin 13

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

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

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


text:
Trying to power 100 Arduino's from single power line
I'm trying to power up to 100 Arduinos that will be spread across a 25m wall using a single power line.
The idea is each Arduino will have a few a few buttons, leds & an oled screen and will all communicate to a master server using rs485.
====[A0]====[A1]====[A2]====[A3]====[A4]== ... ==[A99]

I've already followed this brilliant post http://www.gammon.com.au/forum/?id=11428 to implement the data connection using an rs485 bus.
However I'm struggling to understand how I could power multiple Arduino's from the one line and not introduce surges/ground loops from the difference in group potential caused by the long power line.
Would I have to isolate each Arduino and rs485 driver? Or is there a simpler solution?

Try electronics.stackexchange. It might be better to have a higher voltage power rail, and have a buck-converter on each Arduino, but I don’t have any experience with this.

Sam's question on Electronics Stack Exchange: https://electronics.stackexchange.com/q/392642

please define single power line .... it means more than one thing

You are already using a differential signalling system that doesn't care about ground levels, so you don't need to worry about that side of things.
As for power distribution - a strategy known as point of load regulation is what you want. That is where you supply a higher voltage (but lower current) power feed to one, or in this scenario more likely a group of, boards and regulate that power down using a switching regulator to a lower voltage (5V) and higher current.
This has the advantage that:

You are only worrying about small groups of Arduinos, not the whole lot
You can use thinner wires to feed in the power to a group
You get less losses from wire resistance at high currents

For 100 Ardunos you may want to have maybe 10 to a group with a 3A switching regulator for each group, giving an average of 300mA per board (depending on your current needs, of course - you may want less per group and more groups to give more average current per board).
In that example you'd have a total output current limit of 30A in 10 sections at 5V. That equates to (P=V×I) 150W. So a 200W 24V power supply would be adequate.
At 24V, 150W would demand 6.25A (plus some more to account for the efficiency of the regulators, so call it 8A - hence the desire for a 200W supply).
For 3A you need at least 24AWG wire - but preferably considerably thicker - maybe 18AWG.  The 8A for the 24V would need minimum 15AWG, preferably bigger - although you don't need that size all the way to the end of your chain of regulators. If you had each regulator wired directly back to the power supply individually that would only need thin wires (absolute minimum 30AWG, which is tiny - though to keep losses to a minimum you'd want more like 20AWG).
So for simplicity and to reduce your wire costs, just stick to one size all the way through so you're buying only one gauge of wire (so you get a bigger discount for buying more).  You could quite easily use:

18AWG direct from the PSU to each POL regulator (24V, 0.8A)
18AWG from each POL regulator to all Arduinos in a group (5V, 3A)

Of course, this is all using numbers plucked out of thin air, and you'd need to adjust it to fit your specific project, but you get the idea - higher voltage to a group, regulate to 5V, then 5V to each Arduino in the group. You don't need to care about grounding etc because you're using RS-485.

Despite being differential, RS485 does care about ground levels, to the point of not saturating the receiver(s).  Given enough amplitude, ground bounce will introduce bit errors.

@AaronD You'd need pretty massive ground bounce...  One of the advantages of RS-485 is that you don't need to care about ground voltage differences at the different nodes. Hell, you don't even need a separate ground connection if you have a common ground somewhere around the system. The spec of RS-485 is -7V to +12V, and since this is working at +5V, it would be very hard for any ground bounce to get anywhere near that kind of level...

I second @AaronD on this. This is not necessarily a ground bounce, as you call it, but a DC offset between the grounds that may or may not be there depending on the power distribution strategy. Such an offset could possibly saturate the RS485 transceivers, so the point remains. RS485 does care about ground levels.

With this much power I’d also add some fuses to the system. Shorting a 200W supply isn’t fun. It will also prevent the whole system from going down if only a single Arduino fails.

Indeed. Although one per Arduino may be overkill. One per POL regulator may be a more realistic proposition...

source: Stack Exchange

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

sort: votes


text:
Using RST pin as external power switch
I have Arduino Nano with powered over USB. I have the request for external (physical) slide switch acting as power on/off for Arduino even if USB is always connected.
Looking at documentation and various posts, it seems the RST button could do just that. So when the "power" switch is on, RST is disconnected (= pulled high) and everything runs like normal. When the "power" switch is switched, it will pull RST low. As long as RST is pulled low, the board is stopped (the PWR led is lit, which is true and okay). Once released, the board will boot again.
Even though I agree this is not terribly elegant, is it going to work? I tried manually with the reset switch. Any side-effects I am overlooking?

That is a perfectly legitimate use of the RESET pin. Holding the chip in reset perfectly valid. Everything in the chip will be stopped.
Releasing it will start your sketch from the start again perfectly fine.
The only negative point is that your switch will be pulling power through the reset pin's pullup resistor, so will waste a little power.

Thanks! The power is fine, I guess.

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


text:
Load Adafruit GFX bitmap fonts on desktop for pixel-level design
I am designing UI for 160x128 ST7735-based TFT display which will be displayed using Adafruit's GFX library (and the driver in Adafruit_ST7735.h). I am using the default bitmap font (custom fonts don't provide the white-out functionality, causing flicker) and would like to load it in some desktop pixel editor (like Gimp or some pixel-art editor) so that I can work the design out on desktop.
There are many posts about converting regular (TFT, OTF) fonts to the c-style array, I need to do the opposite. If possible, including the scaled variants, so that I have 1:1 corespondence :)
Any tips on this?

As explained here and here the font format in the GFX-library is GFXglyph, you can use the free tool from the second link adafonteditor v1.0.3 on the desktop.EDITOk so its actually decompile the gfx header file to something on the desktop. Take a look at the Adafruit GFX Font Customiser Source can be used as basis for own projects or compiled to the designated OS.

Thanks, but that's the opposite direction. I don't have a problem parsing the GFXGlyph format, but would like to convert it to standard (BDF, PCF) raster font formats desktop programs can use, without writing the converter myself. Adafonteditor is mac-only. I think I will just use standard 5x7 font shipped with x11.

Thanks, the font customiser might be a useful reference.


text:
Can a DHT11+ESP8266 be powered by a Adafruit USB LiPo charger directly?
I have rigged up a small DHT11+ESP8266 combo which I'm currently powering from the 3.3v from an Ardruino. I've ordered a 3.7v LiPo battery and have a Adafruit usb micro LiPo charger, however, the battery will take two weeks to come.
Can I plug the usb charger directly into the DH11 while my battery arrives?

What kind of module is the ESP8266? Wemos? NodeMCU? AIThinker module only? Bare chip?

DHT11s use next to nothing, you can power it from a GPIO set to output HIGH...

It's an ESP-01S. "DHT11s use next to nothing" I'm more worried that the charger will fry it. Is the voltage the only thing I should be worried about?

No, you can't.
The charger circuit will only operate properly with a battery attached.
It is not designed to provide power to a system. It is designed for charging the battery and nothing else.  You are supposed to remove the battery from the charger and then attach it to your circuit.  Even with a battery attached you can't use it to power your circuit - the voltage will be too high, and your target circuit will confuse the charger and it will fail to charge the battery properly (or it may end up over-charging the battery).
To do what it sounds like you want to do you need:

A LiPo charge circuit
A 3.3V regulator (ideally a Buck/Boost combined regulator)
Bypass circuitry to power the 3.3V regulator directly from the incoming power when present or from the battery when no external power is present.

ok, - what is the difference between the power supply coming from the charger and the supply after the steps you've mentioned here? I Don't want to use the two in conjunction - when I have the battery I'll just be using that, as you suggest. So it looks like the only difference is the 3.3V regulator - is the only concern that the charger will not give out a steady 3.3V voltage?

The charger press out special voltages and currents depending on the state of the battery connected. With no battery it won't know what to do.


text:
Project: Relay is ticking, but not actually switching
I'm trying to make an automatic planter for herbs etc. I finally got everything 3D printed and wired together. But for some reason, the relay I'm using refuses to switch or enable certain connections. I'm confused because it worked perfectly - continuity-wise - during my initial testing or installation.
The relay model HERE. The relay is to be controlling the ground connection of both an 12v indoor grow light and 12v small water pump. I was a bit confused with the relay's wiring itself. First time using this type of relay. Anyway, I got it working; well previously.
Here are some video to help explain the issue:
https://www.youtube.com/watch?v=GUiHs28bvK8
https://www.youtube.com/watch?v=-xaj8q537x4
(After uploading, I hear that my phone's mic stops the tone of the multimeter a few seconds into each video. But trust me, the tone is constant throughout the duration of both videos. You may be able to hear it?)

remove the relay board from the enclosure and check again

Tearing it all apart is the very last thing I'd want to do. It's all held together with hot glue lol. Will do if it gets to that point ... But if that was the situation, I'd just buy another relay module I'm familiar with instead of dealing with this one.

Listening to the sound of the relay, it does turn on and off. Therefor your 12v has enough power. Could there be a shortcut between the pins in the circuit? Remove the wires from the screw terminals. After that, remove the relay board. Is the multimeter okay? I often measure 0.1 or 0.2 instead of 0.0 ohm.

The first video indicates there is a short between the NO and the NC terminal.

I tried messing with it again today and got it working to some degree... So I moved the VCC on the relay to the other VCC, furthest from the JD-VCC pin. Afterwards, I was able to get the expected behavior from the first two terminals of each relay. The pump and lights are working great even at the same time. However, the first and third of each relay isn't working right. They only activate if both relays are on at the same time.... Obviously some sort of wiring issue here I'll have to figure out. Thanks for the advice everyone.


text:
7-12V Power supply + USB
Im connecting a servo to my Arduino Uno Rev.3. The general recommendation is to put a 7V -12V power supply for servos as far as I understand. However I’d like to combine it with an USB to a computer since I use it to flush data from a different probe on the Arduino to my PC.

Will it be safe to use both a AC/DC adapter and serial bus?
Will it use the USB for power draw even if adapter is connected?

Arduino Uno supports external power supply and USB at the same time. There is automatic switch will re-direct the power feed.
so, your answer to your first question is YES.
and the second, if you connected the external power supply, USB part won't be used for power feeding through your servo motor. But, this won't still guarantee you can feed you servo motor safe and sound. Because, you are again limited to some current around 1A. It is still up to the specs of your motor.

You will see that the Servos have 3 wires [GND, Power, and Data/Signal]. You can connect your external power supply to GND and Power of the servos, and connect the GND and Signal wires from the Servos to the Arduino.
By connecting the Grounds of the Arduino and Servos together, they share the same 0V reference and you will not damage either by powering the Servos from a higher voltage and the Arduino from USB.
It is not necessary to connect the Arduino Vin or barrel jack to the external power supply. Look at the Servos+power supply as one independent unit, and the Arduino+USB/Computer as a separate independent unit, and the only things connected between them should be GND and the servo signal/data wire.


text:
Vacuum pressure sensor for Arduino
I have an application that is being controlled by an Arduino. At one point in the process, it needs to determine the level of vacuum in a chamber and adjust it to within a range of values.
I can control the vacuum pumps easily enough, but it is hard to find a vacuum sensor for the Arduino. I need a sensor that can be reasonably accurate down to roughly 28 inches mercury and would connect by a tube. I can't put the sensor directly into the chamber.
Does anyone know of an Arduino sensor that would work? If not, could someone suggest a sensor component that may work with an Arduino. I would prefer to not have to engineer a solution from the sensor component up but I can if I need to.

Is that 94.8 kPa? So it is just a slightly below the normal baromic pressure?

A bmp280 can measure 300...1100 hPa.

@Jot Inches of mercury are a negative scale. The greater the number the closer to a perfect vacuum. 28 inches Hg is just short of the level of vacuum created by a good commercial vacuum pump you would use for fiberglass infusion.

Then how many absolute hPa is it?

I would need to check this, but roughly 29.8 inHg is close to max mechanically achievable vacuum. Basicly the pressure difference between normal atmouspheric perssure and an empty volume of space.

I just did a conversion and 28 inches mercury came out to aprox 950 hPa. I am unfamiliar with that scale so I don't know if I made a mistake. I need to be able to measure the level of vacuum in a very evacuated cylinder. This is for degassing epoxy resin mixtures

It is not an absolute value then, but a differential value? That is a little weird for me, for very low pressures a absolute value makes more sense. The "normal" pressure or vacuum sensors are 3V or 5V sensor with amplifier and temperature compensation from nxp.com. Search for vacuum sensors. For example the MPXV6115V. For more sensors search at mouse.com for pressure sensor, and then select one of the vacuum types. I see some Honeywell sensors, but they are 15V.

Ok, a quick check on my vacuum gauges and I can see that I need to measure down to roughly -92 kPa. The MPXV6115V seems to handle this range fine and works over a 5v range. That may be the solution. I was really hoping there would be a mass-produced Arduino shield for this, but worst case I can work with that sensor. Thanks @Jot

That sensor is ratiometric, you should power it with the 5v pin of the arduino. A arduino uno has 10-bits adc, that is good enough for the 1.5% error of the MPXV6115V. Take a few samples and calculate the average. I think that will work. The biggest problem is soldering something to the small pins. Never connect something to the unused pins of the sensor. The unused pins can be connected to something inside.

10 bits resolution with an error of +/- 1.5% would be more than enough for what I will be doing. My bigger concern would be hysteresis in the sensor but I am guessing that shouldn't be an issue. I still wish this was in an off the shelf shield, but I can't have everything. Looks like I will need to hone my SMD soldering skills.

Most industrial vacuum/pressure sensors do not specify which sensor is inside. I suppose this sensor is used in a metal case with a price of about 100 dollars. Perhaps with extra electronics for a voltage of 24v and a current loop output. I have never noticed any hysteresis with these kind of sensors. Just a little noise, that's all.

@Jot If you want to add this as an answer I will accept it. I have ordered the parts and it looks like it will do what I need. Thank you.

Industrial pressure/vacuum sensors are sturdy and rigid. They have extra protection, for example to use it submersible. The manufacturer often make them for certain voltages (for example 24v) and with different outputs (0..5v output, or 5-20ma output, and so on).
There are cheap versions of those sensors. They are between 5 and 20 dollars on Ebay and Aliexpress.
The manufacturers do not tell which sensor they use inside, and it can be hard to find a sensor that is exactly the one that you need.
The bare sensor is often a piezoresistive sensor in a wheatstone bride configuration. The output voltage span of those sensors is very low and not suitable to connect directly to an arduino board.
The advantage can be that they do not have a operating voltage. Only a maximum voltage.
The ideal pressure/vacuum sensor has a temperature compensation and a gain and a output span that is near 5v. You find most of them at nxp.com.
Luckely they have also a vacuum sensor with a large range, for example the MPXV6115V.
Those sensors are ratiometric. Power them with the arduino 5v and use the arduino 5v as analog reference (that is the Arduino default setting). When the 5v changes, the resulting measured pressure does not change and is still accurate.
Never solder something to the unused pins. Those pins can be connected to something inside.
There are a few ways to calculate the pressure. One way is to use the formula from the datasheet, the other way is to map the output voltage span to the pressure span and correct for the offset of the output voltage.

Thanks for the information. I have 4 of these sensors on order and will be testing them out. They look spot on for my application. I wish they were a shield, but I can't get everything.


text:
Problem I²C Communication between Arduinos
My Problem seems to be that my I²C slave randomly disconnects.
I have an Arduino Due communicating with a Arduino Chestnut board (bought hardware).
I now measure data with the Due and then send the data via an I²C interface to the Chestnut. No other devices are on the I²C bus.
The problem is that I randomly receive the error code "2" from the endTransmission method which seems to imply that the slave device disapeared from the bus. The connection sometimes works fine, and then sometimes right after startup or some time later this error occurs. I measured the signals with an oscilloscope and the clock signal then is always low.
Has someone an Idea what could be the problem?

lack of, or incorrect, pullup resistors?

Standard Arduino pullups, 4k7

The Arduino Due has sometimes troubles with the i2c bus. Lately I see more people having problems with the Due and the i2c bus. The Due has onboard pullup resistors of 1k5 (sometimes 1k), that is very low. Some add 100 ohm resistors in the signal path of sda and scl to reduce the slew rate. Can you replace the Due with a samd21 (zero, m0, mkr boards)? Add a delay of 1ms between Wire.endTransmission and Wire.requestFrom. Show us the sketch of the master and the slave please. The slave is not allowed to turn off interrupts. How long are the wires? Do you use a cable? Are the GND connected?

I can't switch boards, I got the circuit, hardware and the code from my supervisor with the task to fix the i2c problem. But I will tell him about the problems of the Due with the i2c interface and how to fix it and the we'll see what I am allowed to do.

The master (Due) just sends data to the slave (actuator) because my actuator is hardwired to be a slave device. The GND are connected (same power source) and the cable is a standart, shielded three wire cable (just SDA and SCL used, one is connected to GND).
What do you mean the slave is not allowed to turn off interrupts? I use a simple protocoll, master sends data, slave waits to receive data (gets interrupt when data is reveiced) and then moves some motors according to the data. I guess  the slave can only turn off interrupts because of a library error, but how can I check this?


text:
Sending the data for temperature and soil using esp8266-01 through software serial
The code I used was from online and I tried using it to send data to firebase through web server. But the ouput I get from serial monitor was just "ATE0" which means there's something wrong. Hence, I can't proceed in solving this issue.
I tried several resources online to match my current problem.
I hope someone can help me
Thank you :)
#include <SoftwareSerial.h>;
SoftwareSerial Serial1(10, 11);
#include "DHT.h"
#define Terra "terra1"
#define DHTPIN 2

#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

//const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; eyagagana soy

int j=0;
int prev=0;
int pres=0;
String status="";
String buff(64);
String getStr(128);

void setup() {

  Serial.begin(9600);
  Serial1.begin(9600);
//  Serial.println(F("Humiture and Soil Moisture Sensors"));
  delay(2000);
  Serial1.setTimeout(5000);
  dht.begin();

   if (!connectWiFi()) {
    Serial.println("Can not connect to the WiFi.");
    while (true)
      ; // do nothing
  }
  Serial.println("OK, Connected to WiFi.");
  sendCommand("AT+CIPSTA?");
  sendCommand("AT+CIPDNS_CUR?");
  sendCommand("AT+CIPSTAMAC?");

}

void loop() {
 j=analogRead(A0);
  j=map(j,0,982,148,0);
  pres=j;
  if(j>100)
  j=100;
  else if(j<0)
  j=0;

  prev=j;
  delay(1000);

  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
//  if (isnan(h) || isnan(t) || isnan(f)) {
//    Serial.println(F("Failed to read from DHT sensor!"));
//    return;
//  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

//  Serial.print(F("Humidity: "));
//  Serial.print(h);
//  Serial.print(F("%  Temperature: "));
//  Serial.print(t);
//  Serial.print(F("°C "));
//  Serial.print(("Soil Moisture: "));
//  Serial.print(j);
// Serial.println("%");

// connect to server
  if (sendCommand("AT+CIPSTART=\"TCP\",\"https://terraduino.000webhostapp.com\",80")) {
    Serial.println("connected to Cloud");
    // build HTTP request
    getStr = "GET /upload.php?terra=";
    getStr += Terra;
    getStr += "&j=";
    getStr += j;
    getStr += "&t=";
    getStr += t;
    getStr += "&h=";
    getStr += h;
    getStr += " HTTP/1.1\r\n";
    //WEBSERVER
    getStr += "Host: https://terraduino.000webhostapp.com\r\n\r\n";
    // open send buffer
    buff = "AT+CIPSEND=";
    buff += getStr.length();
    if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data
      // send HTTP request
      Serial.println(getStr);
      Serial1.print(getStr);
      // print HTTP response
      if (Serial1.find("+IPD,")) { // response received
        int l = Serial1.parseInt();
        while (l > 0) {
          if (Serial1.available()) {
            Serial.write(Serial1.read());
          }
        }
        Serial.println("--------------");
      } else {
        Serial.println("no response");
      }
    } else {
      Serial.println("send error");
    }
    sendCommand("AT+CIPCLOSE");
  } else {
    Serial.println("Error connecting");
  }
}
bool connectWiFi() {
  if (!sendCommand("ATE0")) // echo off
    return false;
  if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
    return false;
  if (!sendCommand("AT+CWMODE=1")) // set STA mode
    return false;

  return sendCommand("AT+CWJAP=\"I Pronounce you Man and Wifi\",\"-PX?*z3A_1x@.exe\"");
}
bool sendCommand(const char* cmd) {
  Serial.println(cmd);
  Serial1.println(cmd);
  while (true) {
    buff = Serial1.readStringUntil('\n');
    buff.trim();
    if (buff.length() > 0) {
      Serial.println(buff);
      if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
        return true;
      if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
        return false;
    }
  }
}

ESP boards are definitely nothing for beginners. The problem with them is that they might have very different Firmware versions on them. You can for example not be sure what baud rate they are using. So, you have to find out which baud rate the Serial interface uses. You configured 9600 Bit/sec but most of the boards need 115200. Event ESP Gurus do flushing the ESP with a well define firmware: e.g.  https://medium.com/@aallan/getting-started-with-the-esp8266-270e30feb4d1

It would be a good idea to also add the complete output of the arduino to the question. The output helps us to follow the program and how it executes.

thank you sir, the output was just "ATE0"

did you set the baud rate of AT firmware to 9600 baud? (btw, I wrote this version of sendCommand function)

not yet sir, awsome!

It doesn't work

after I uploaded the bareminimum to separate ESP-01 to arduino, then I got this output Both NL & CR 115200 baud set in the serial monitor, ets Jan  8 2013,rst cause:4, boot mode:(3,0)
wdt reset
load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79
2nd boot version : 1.5
SPI Speed      : 40MHz
SPI Mode       : DOUT
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

@Juraj need help sir

I connected RX and TX of arduino and esp-01 accordingly while uploading the bareminimum and set BL & NR and baud rate of 115200, still not work

https://chat.stackexchange.com/transcript/85432/2018/11/7

short version https://arduino.stackexchange.com/questions/57496/arduino-uno-with-esp8266-01-with-at

Possible duplicate of Arduino Uno with ESP8266-01 with AT

I already read those articles

I would say you are trapped in the sendCommand function. You print the cmd (cmd="ATE0") variable to the terminal and then send the command to the ESP over Serial1 = software serial. Serial1 is configured with a baud rate of 9600 (Serial1.begin(9600))  it depends on your ESP but that might be wrong. A common value is 115200 (Serial1.begin(115200)). But because that can vary from board to board, it could also be wrong.
If I'm right and you configured a wrong baud rate, the command can not be understood by the ESP and even the newline after the command might be missing for it.
So the ESP send nothing back and the 'buff.length()' equals to 0. Then the while(true) runs and runs and runs ... .

yes, this was the idea. But I can't go back with the AT Commands, I checked all the wires and process done well. output are just some internal information and unknown  random symbols printed in serial monitor


text:
uint8_t to Text
I am trying to use a Protocentral_MAX30102 Pulse Ox sensor to get SpO2 and serial write it to an SD logger. However, my serial write is a mess and I need is in a text form not what it is in now. I would live to write a CSV for to my SD card logger.
This is the stock code.
#include "Protocentral_MAX30102.h"
#include <Wire.h>

MAX30100 sensor;  //attach sensor
uint8_t data_len=8;
uint8_t DataPacketHeader[15];
volatile unsigned int IRR,REDD;

void setup() {
  Wire.begin();
  Serial.begin(57600);
  while(!Serial);
  sensor.begin(pw1600, i50, sr100 );
}

void loop() {
    sensor.readSensor();        //read sensor
    IRR=sensor.IR;
    REDD=sensor.RED;
    DataPacketHeader[0] = 0x0A;
    DataPacketHeader[1] = 0xFA;Uni
    DataPacketHeader[2] = (uint8_t) (data_len);
    DataPacketHeader[3] = (uint8_t) (data_len>>8);
    DataPacketHeader[4] = 0x02;

    DataPacketHeader[5] = REDD;
    DataPacketHeader[6] = REDD>>8;
    DataPacketHeader[7] = REDD>>16;
    DataPacketHeader[8] = REDD>>24;

    DataPacketHeader[9] = IRR;
    DataPacketHeader[10] = IRR>>8;
    DataPacketHeader[11] = IRR>>16;
    DataPacketHeader[12] = IRR>>24;

    DataPacketHeader[13] = 0x00;
    DataPacketHeader[14] = 0x0b;

    for(int i=0; i<15; i++) // transmit the data
    {

       Serial.write(DataPacketHeader[i]);
     }

  delay(10);
}

You first need to define how your string looks like, and than convert each value to a string (or text characters you place/append in a character array).

You currently create binary data. Why? You want text, so just Serial.print() the data directly.


text:
Arduino Uno R3 and ESP8266(ESP-01) serial connection
I have done everything i found but just nothing works, or maybe i just dont understand why it wont work. Im only trying to pass data(String) from Arduino to Esp through serial comms. Please I need your help, I'm as dead as my deadlines.
Note: What I am trying to do is send data from arduino to esp and make esp send the data on a raspberry pi server through sockets. The rasp part is fine, i just need the data passed from arduino to esp.
Original Arduino code
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");
   }
}

ESP
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>

SoftwareSerial  ESPlease(3,1);

const char* ssid  = "sendhelp";
const char* password =  "ple4seH3lpm3";

uint16_t port = 8090;
const char* host = "192.168.1.3";

void setup()
{

  Serial.begin(9600);
  ESPlease.begin(9600);
  pinMode(3,INPUT);
  pinMode(1,OUTPUT);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("...");
  }

  Serial.print("WiFi connected with IP: ");
  Serial.println(WiFi.localIP());

}

void loop()
{
    WiFiClient client;

    if (!client.connect(host, port)) {

        Serial.println("Connection to host failed");

        delay(1000);
        return;
    }
    String message = "";

    Serial.println("Connected to server successful!");
    while(Serial.available()) {
      message = Serial.readString();
     // messageReady = true;
    }
    String sensorValue = message;
    String sname = "flowRate-";
    String stringThree = sname + sensorValue;

    if(sensorValue != 0){
      client.print(stringThree);
    }

    Serial.println("Disconnecting...");
    client.stop();

    delay(10000);
}

please help me anyone :(

SoftwareSerial on hardware Serial pins? pin mode of RX/TX changed after Serial.begin()? where do you output data in Uno? I see only a simple print to Serial

that's it, i dont know where i output code anymore. some say all i had to do was print it to serial. I know the code is full of useless stuff its because I have tried so many times already

but the useless code is in the way. clean it up


text:
Speed control of BLDC with an integrated controller (Hall out, PWM in)
I am aiming at precise speed control of this BLDC motor: it has an integrated controller, outputting digital Hall signal (period 20.8ms on oscilloscope, w/o load) and taking PWM as input for speed regulation.
As far as my knowledge goes, this is a task for PID: measure Hall pulses at input, adjust duty cycle of the PWM based on target period/frequency of the Hall output.
The speed should be controlled with <1% error (even less is better).

Is this goal realistic with this particular motor?
How should I measure pulse duration?
Is pulseIn (with interrupts disabled) going to be sufficiently precise? Should I measure lows or highs?
Should I measure several pulses instead (and how)? Or should I accept imprecision in the pulse period and compensate (smooth) it using integral/derivative terms?
Do I need more than 8-bit PWM resolution for this task? (I will use Nano at first, but might switch to Nano Every, which has 10-bit PWM).

Any other comments/suggestions are welcome.

you can have 16bit PWM with Timer1 (library) on Nano

This is only a partial answer, about measuring pulse period or duration.
For best accuracy, I would recommend using the “input capture” feature
of a 16-bit timer. This is not as easy as using pulseIn() or timing
the signal with micros(): you will have to carefully study the MCU's
datasheet and manually configure the bits of some I/O registers. You
will be rewarded with high accuracy (single-cycle if the timer runs at
the MCU clock speed) and without the jitter inherent to any
software-based approach.
Beware that the Nano and Nano Every use different MCUs, with very
different timers. Both have input capture capability, but if you switch
from one to the other you will have to redo most of the work. Note that
the Nano is capable of 10-bit PWM if you program it low-level.
A software-based approach (pulseIn() or attachInterrupt() +
micros()) has the advantage of portability.

To expand a little on Edgar's answer:
There are two main ways of measuring frequency, and both require different resources and are better for different situations.
The method Edgar describes using the Input Capture method, is good for rapidly changing low frequency signals where you want to respond very quickly to changes in the frequency. It works by measuring the time between two pulses using a free-running timer. Of course you can only measure frequencies as fast as the timer can run, which is pretty fast anyway, and if configured right it can run almost entirely asynchronously so you can just query the current recorded time whenever you need to.
The other option is to count the number of pulses within a given time period. This can also be done in hardware but using a different set of peripherals.
For this you have two timers. Timer 1 has the ability to us an external signal on pin D5 as its clock. This basically turns it into a pulse counter, and every time a pulse arrives on the timer pin it increments the count by one.
Then you have a second timer which triggers an interrupt at a predefined period. What that period is depends on the responsiveness you want and the frequency range you want to measure.  You can also use the "prescaler" of Timer 1 to increase the frequency measurement range by only counting every 2nd or 4th or 8th etc edge.
Of course, all that timer use would interfere with PWM generation on the Nano, but should be better on the Nano Every, but you'd want to check the datasheet for timer usages.
So in summary:
Input capture

Fast response
Limited frequency range

Pulse counting with timer 1

Slower response
Naturally smoothed output
Greater frequency range
Understands the concept of zero Hz
Interferes with PWM generation

Whichever method you choose, sure, feed it through PID to create a stable output RPM.


text:
How to make BLE data accessible to a particular app?
I used the BLE example from here.
But any device can read and write to the advertised characteristic. Is there a way to make the data inaccessible to other devices except for my app somehow. What I would really like to do is something like SDP and then connect and exchange data over RFCOMM but it seems impossible to do so in esp32. I have done it using bluez library on Linux but in case of esp32 I found only one library btstack that is impossible to use with esp-idf because of lack of CMakeLists.txt. Is there some way I can achieve what I want?

In general terms, you could simply require a client to authenticate first. This would require a bit of a deviation from the example you linked to (which actually only handles reading of the characteristic) to handle multiple connections and their state, but it should be pretty straightforward.
The Arduino BLE library seems to lack sending quite a bit of information via the callbacks, so you just know there's a connect or disconnect or a write to a characteristic, and not which devices did. This means you won't be able to handle multiple connections at the same time, but making sure you reset your authentication state whenever you receive a connect or disconnect should be enough to prevent anyone but your own client from "talking" to your device.

thanks, I'll try implementing this flow and update you as soon as I can.


text:
SIM800l is not Avalible
I am using :
-arduino uno r3
-SIM800L
connection:
Arduino   SIM800L
5v     -->  vcc
gnd    -->  gnd
pin10  --> TX
pin11  --> RX
the led on the module blinks once each 3~5 seconds
but when i use the function sim.available() i got 0;
thus as i guess there is a problem .
the code :
#include <SoftwareSerial.h>
SoftwareSerial sim(10, 11);
int _timeout;
String _buffer;
String number = "000000000000"; //-> change with your number
void setup() {
  delay(7000); //delay for 7 seconds to make sure the modules get the signal
  Serial.begin(9600);
  _buffer.reserve(50);
  Serial.println("Sistem Started...");
  sim.begin(9600);
  delay(1000);
  Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
}
void loop() {
  Serial.print(Serial.available());
  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        RecieveMessage();
        break;
      case 'c':
        callNumber();
        break;
    }
  if (sim.available() > 0)
    Serial.write(sim.read());
}

i looked the internet they say the voltage should be 3.7~4.2 itriedgivving 3.55 and it didn't work

it didn't work or maybe the command i wrote was wrong : "ATD" then enter then the phone then enter then ; but no response @jsotola

and about the putty i need the sim800L and arduino or what? @jsotola

still i am having the zeros from the sim.avalible() @jsotola

yup i tried AT no response @jsotola

in my previous code Serial.print(Serial.available()); i wanted to check that @jsotola

then the sim800L is not communicating ... incorrect wiring or insufficient power supply voltage

Try to connect your module with the power supply useing wires as short as are is possible. I was fight with this module for few months and now I know that almost all of issue with it are regarding power supply.
For short test you can connect module directly to LiPo 3,7V.
You have to be sure that your power supplay can handle 2A current. The voltage never can drop below 3,4V.

The power IC and the bypass capacitor should be placed to the module
as close as possible.

SimCom, SIM800_Hardware Design_V1.09, available 27.11.2020


text:
Maximum frequency that can be converted with Arduino Uno?
Arduino Uno Board use successive approach ADC of 12 bits and 16 MHz frequency clock. What is the maximum voice frequency can be converted using arduino uno board? I want the step by step solution with calculations.

you are not going to get a step by step solution with calculations .... please provide the code that you have written explain how you expect it to function and explain where it fails

First of all, the ADC on the Uno is 10 bits, not 12.
The naive approach of having analogRead() in a tight loop can give you
up to 8.9 kS/s (112 µs per sample), but you won't be able to
do much else, as the CPU spends most of it's time just waiting for the
ADC to do its job. If you configure the ADC manually, then you can set
it into the so called “free running mode”. You then get about
9.6 kS/s (104 µs/S), but then the CPU is free to process one
sample while the next one is being converted.
If you need to go faster, you can tweak the frequency of the internal
ADC's clock. Then it's a compromise between speed and accuracy: the
faster you go the less accurate. You may get rough but kind of usable
samples at up to 77 kS/s (13 µs/S).
For a detailed comparison of the different clocking options, with speed
and accuracy estimation, see the article ADC conversion on the Arduino
(analogRead), by Nick Gammon.

Note that thanks to the Nyquist-Shannon theorem the sample frequency is twice that of the maximum content frequency - so 8.9kS/s would equate to a 4.45kHz maximum audio frequency.


text:
Why does my circuit work only when I do not use the Serial port?
I am a newcomer to working with Arduinos (and circuits in general) so when I was tasked with making a simple push-button circuit to control an LED's state, and to send a message back using Serial.println() to show the button had been pressed, I noticed that the LED is dimly lit when I press the button to give it power. However, when I do not use the Serial port at all in my code, then it works perfectly as expected.
My code:
const int ledPort = 8;
const int detPort = 7;
void setup() {
  pinMode(ledPort, OUTPUT);
  pinMode(detPort, INPUT);
  digitalWrite(ledPort, HIGH);
  Serial.begin(9600);
}

void loop() {

  if (digitalRead(detPort) == HIGH) {
    digitalWrite(ledPort, LOW);
    Serial.println("9");
    delay(500);
  }
  else {
    digitalWrite(ledPort, HIGH);

My circuit:
https://i.sstatic.net/mYUYf.jpg
My Board: MEGA2560

Your circuit makes no sense whatsoever. Can you draw out how it is actually all connected together as a proper schematic rather than photos that make it hard to see what goes where?

Please [edit] your question so that the image can be seen, without the need to follow a link.

Your circuit is wired improperly.
It will be easiest for you to simply follow this official tutorial that will show you how to use a push button to turn on an LED. Even though you have a mega, it will work fine for you.
You will see a wiring picture there that is simplified:

Plus, the correct code is there:
/* Basic Digital Read
 * ------------------
 *
 * turns on and off a light emitting diode(LED) connected to digital
 * pin 13, when pressing a pushbutton attached to pin 7. It illustrates the
 * concept of Active-Low, which consists in connecting buttons using a
 * 1K to 10K pull-up resistor.
 *
 * Created 1 December 2005
 * copyleft 2005 DojoDave <http://www.0j0.org>
 * http://arduino.berlios.de
 *
 */

int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){
  val = digitalRead(inPin);  // read input value
  if (val == HIGH) {         // check if the input is HIGH (button released)
    digitalWrite(ledPin, LOW);  // turn LED OFF
  } else {
    digitalWrite(ledPin, HIGH);  // turn LED ON
  }
}

Schematic Is Quite Important
also, as you attempt to look at the picture and build the circuit you discover how difficult it is to see how things are connected.
That leads you to understand how important a simple schematic can be.
I've attempted to turn the pic from the arduino site into a schematic and my interpretation may be wrong or the actual circuit that the Arduino site has built may be wrong.  If anyone has comments I will take them into account.
Trying to build from a picture of a circuit is terribly difficult and trying to debug your circuit from a picture is also. That's why when you submit a question you should submit a drawn schematic of how you have wired it up.

simulate this circuit – Schematic created using CircuitLab

There‘s no series resistor for the led...

@SimSon Yeah, it's a bit odd that the circuit from the Arduino site doesn't add one.  It's because they simply pushed one LED pin into GND and the other into PIN13 on the Arduino header.

Oh, I see. They use a green/blue led, so it might be fine in this case. Not your fault...

Your circuit doesn't make sense to me, either :) I can't see where the LED is getting its ground from, in particular.
Try starting with the circuit shown here and report back!
Good luck!


text:
Ethernet shield connected to local network, not to internet
Using the WebServer example file I have been able to confirm that my arduino is connected to my local network and I can open the page in my browser. However any attempt at contacting addresses outside my own network fails. For example this simple script:

    #include <SPI.h>
    #include <Ethernet.h>

    EthernetClient client;

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 25);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress dns(8, 8, 8, 8);
    byte server[] = { 64, 233, 187, 99 }; // Google

    void setup() {
      Ethernet.begin(mac, ip, dns, gateway);
      Serial.begin(9600);
      delay(1000);
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      if (client.connect(server, 80)) {
        Serial.println("connected");
        client.println("GET /search?q=arduino HTTP/1.0");
        client.println();
      } else {
        Serial.println("connection failed");
      }
    }

This consistently returns connection failed. The ethernet cable in the arduino has an active internet connection, albeit via a switch. My board is an arduino uno.

Find a server that doesn't automatically switch modes to https as google does.  If you put 64.233.187.99/search?q=arduino%20HTTP/1.0   in your browser you'll see that it switches to https.
If make the same request via the wget terminal app it fails.
--2020-01-17 11:42:26--  http://64.233.187.99/search?q=arduino%20HTTP/1.0
Connecting to 64.233.187.99:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: http://www.google.com/search?q=arduino%20HTTP/1.0 [following]
--2020-01-17 11:42:26--  http://www.google.com/search?q=arduino%20HTTP/1.0
Resolving www.google.com... 172.217.4.132, 2607:f8b0:4007:80c::2004
Connecting to www.google.com|172.217.4.132|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2020-01-17 11:42:28 ERROR 403: Forbidden.

There should also be an error returned to the client object which you can print out for debugging the conection.
Change your code to print out the return value of the client.connect call like so
void loop() {
      int result = client.connect(server, 80);
      if (x) {
        Serial.println("connected");
        client.println("GET /search?q=arduino HTTP/1.0");
        client.println();
      } else {
        Serial.println("connection failed");
        Serial.println(x);  // print out the error
      }
    }

One last thing, you set your dns server to 8.8.8.8 which should generally be set to your gateway / router of 192.168.1.1.


text:
using PN532 chip on arduino
I've recently purchased an NFC-PN532 module online, which I connected to my arduino board and tried to get working. After connecting the pins and using the PN532 adafruit lib I encountered and error where the board was not being picked up. I was using the 'readMifareClassic' example from the lib and uploaded the example to the board and it resulted in the image below where I would receive a '?' or the first print output which is 'hello' in the code.
I'm not that experienced with NFC atm and so im seeking some guidance on what may be the issue. If you need more information please leave a comment.
Thank you

the example has 115200 baud for Serial. your Serial Monitor is set to 9600 baud

thanks Juraj, but the chip is not being picked up now and feel as though it might be due to the wiring though i connected the pins according to the code, yet its not picking it up

but that is a different Question

A very common error when PN532 module is not recognized, is that you are not using the right bus (I2C, SPI, UART).
Make sure:
In Arduino sketch make sure to follow carefully the lines that need to be commented out.
On the PN532 make sure that DIP switches match your bus configuration


text:
Connecting NFC reader and fingerprint scanner to arduino
Im new to NFC and am currently working on a project dealing with NFC and security, where I use biometrics to authenticate NFC cards, when being used during payments. I've been able to get both the reader and fingerprint scanner working seperately (connected when the other isn't), although when trying to connect both i came across some issues. I've redifined the digital pin locations for the fingerprint scanner assuming it would work, though it didn't work and so im now not sure what the issues maybe. On top of this i think that my fingerprint scanner maybe broken, which might also be the issue, but if someone could guide me on connecting these two types of devices to the board it would be very appreciated.
Code used for the fingerprint scanner from adafruit fringerprint scanner lib (incase anyone wanted to check it out)

#include <Adafruit_Fingerprint.h>

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
// #define mySerial Serial1

// For UNO and others without hardware serial, we must use software serial...
// pin #2 (switch to 8) is IN from sensor (GREEN wire)
// pin #3 (switch to 9) is OUT from arduino  (WHITE wire)
// comment these two lines if using hardware serial
SoftwareSerial mySerial(8, 9);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

uint8_t id;

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }
  }
}

uint8_t readnumber(void) {
  uint8_t num = 0;

  while (num == 0) {
    while (! Serial.available());
    num = Serial.parseInt();
  }
  return num;
}

void loop()                     // run over and over again
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
  id = readnumber();
  if (id == 0) {// ID #0 not allowed, try again!
     return;
  }
  Serial.print("Enrolling ID #");
  Serial.println(id);

  while (!  getFingerprintEnroll() );
}

uint8_t getFingerprintEnroll() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

And code for the NFC reader from adafruit pn532 lib
   #include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>

// If using the breakout with SPI, define the pins for SPI communication.
#define PN532_SCK  (2)
#define PN532_MOSI (3)
#define PN532_SS   (4)
#define PN532_MISO (5)

// If using the breakout or shield with I2C, define just the pins connected
// to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
#define PN532_IRQ   (2)
#define PN532_RESET (3)  // Not connected by default on the NFC Shield

// Uncomment just _one_ line below depending on how your breakout or shield
// is connected to the Arduino:

// Use this line for a breakout with a software SPI connection (recommended):
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

// Use this line for a breakout with a hardware SPI connection.  Note that
// the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
// hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
// SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
//Adafruit_PN532 nfc(PN532_SS);

// Or use this line for a breakout or shield with an I2C connection:
//Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void) {
  Serial.begin(115200);
  while (!Serial) delay(10); // for Leonardo/Micro/Zero

  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A Card ...");
}

void loop(void) {
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {
    // Display some basic information about the card
    Serial.println("Found an ISO14443A card");
    Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("  UID Value: ");
    nfc.PrintHex(uid, uidLength);
    Serial.println("");

    if (uidLength == 4)
    {
      // We probably have a Mifare Classic card ...
      Serial.println("Seems to be a Mifare Classic card (4 byte UID)");

      // Now we need to try to authenticate it for read/write access
      // Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
      Serial.println("Trying to authenticate block 4 with default KEYA value");
      uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

      // Start with block 4 (the first block of sector 1) since sector 0
      // contains the manufacturer data and it's probably better just
      // to leave it alone unless you know what you're doing
      success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);

      if (success)
      {
        Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
        uint8_t data[16];

        // If you want to write something to block 4 to test with, uncomment
        // the following line and this text should be read back in a minute
        //memcpy(data, (const uint8_t[]){ 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0 }, sizeof data);
        // success = nfc.mifareclassic_WriteDataBlock (4, data);

        // Try to read the contents of block 4
        success = nfc.mifareclassic_ReadDataBlock(4, data);

        if (success)
        {
          // Data seems to have been read ... spit it out
          Serial.println("Reading Block 4:");
          nfc.PrintHexChar(data, 16);
          Serial.println("");

          // Wait a bit before reading the card again
          delay(1000);
        }
        else
        {
          Serial.println("Ooops ... unable to read the requested block.  Try another key?");
        }
      }
      else
      {
        Serial.println("Ooops ... authentication failed: Try another key?");
      }
    }

    if (uidLength == 7)
    {
      // We probably have a Mifare Ultralight card ...
      Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");

      // Try to read the first general-purpose user page (#4)
      Serial.println("Reading page 4");
      uint8_t data[32];
      success = nfc.mifareultralight_ReadPage (4, data);
      if (success)
      {
        // Data seems to have been read ... spit it out
        nfc.PrintHexChar(data, 4);
        Serial.println("");

        // Wait a bit before reading the card again
        delay(1000);
      }
      else
      {
        Serial.println("Ooops ... unable to read the requested page!?");
      }
    }
  }
}

use hardware SPI for NFC reader

I believe that i am using SPI communication with the NFC reader, but what do you mean by using hardware SPI, cause i've connected the reader using the defined pins for SPI connection

All the information is actually available in the comments of your sample code, Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS); is for software SPI. Hardware SPI is available at SCK = 13, MOSI = 11, MISO = 12 and all you need to do is to instantiate it with Adafruit_PN532 nfc(SS); to specify the SS pin you want to use. Also, when you use SPI, you don't need #include <Wire.h>, and #define PN532_IRQ 2 in your code.


text:
guidance on Mikrobus NFC tag and connecting to arduino
I've recently purchased an NFC tag reader from MikroE and ive been a little lost on connecting the reader to my arduino board.
I've also been looking online for a library that i could use for this device, and have found little to nothing, though i maybe looking in the wrong place. If you could provide any guidance to the matter please respond.
any help would be much appreciated.
link to the tag: https://www.mikroe.com/nfc-tag-click

There is link on the mikroe.com website to a PDF that describes your circuit board: https://download.mikroe.com/documents/add-on-boards/click/nfc-tag/nfc-tag-click-manual-v100.pdf  The PDF tells you to go to https://libstock.mikroe.com for code samples.

To find an Arduino library for a device, you can search for the term combination
Arduino github <devicename>

because most libraries are hosted on github. The devicename here means the chip on the product, not the product itself. You won't find much for "Mikrobus NFC", but when you search for the chip on it - the  M24SR64 - you can find some promising results.
For example this library, which looks good to me. It was used for this blog article, which is where I found it (though that is a german site. I just wanted to link as reference for the german speakers). It has some examples, that show the usage of the library.

In general: Sometimes there might be no ready to use library for a chip or product to use with Arduino. In that case you need to write that code yourself. Let's take this product as example. It uses the I2C interface and the seller also links to the datasheet of the used chip. In the datasheet you can read, how the chip is used, including the communication protocol, that is imposes on the I2C interface. You could then write the corresponding I2C code using the Wire library.
Fortunate for you there already is a library, so you can first try that.


text:
Arduino Due ADC negative voltage
I’m trying to sample an AC signal on the Arduino Due. The AC signal will never exceed +-80mv across a frequency range of 6-833Hz. Current is negligible.
I believe there are clamping diodes to protect from this but cannot find any datasheets for the Due.
I understand that the Due cannot read negative voltage but can a negative voltage damage the ADC or it’s accuracy?

Add a DC offset to your signal. Make it all positive.

or add a diode to cut away the negative part

Can’t use a diode because I’ll lose 0.7v. I could add a DC offset but I need high accuracy, I’d like to avoid adding any extra noise.

It's not a datasheet for the Due you need, but a datasheet for the ATSAM3X8E microcontroller on the Due, which you can download here: https://www.microchip.com/wwwproducts/en/ATSAM3X8E

The best thing you can do is to simply add a DC offset to your signal.  Instead of having it be 0V ±80mV, have it 1.65V ±80mv.  All you need is a capacitor and two resistors:

simulate this circuit – Schematic created using CircuitLab
However, 80mV is not going to have much resolution unless you reduce your reference voltage considerably, and in that case you'd need to reduce the 3.3 down to the same (or around) the reference voltage you use.
But, just feeding your signal directly into the ADC will give you the positive 80mV signal which you can use a smaller reference voltage with directly with no problem - after all, the datasheet shows:

Voltage on Input Pins
  with Respect to Ground (except VBUS)...............-0.3V to +4.0V

So you can provide down to -300mV on an analog input before it potentially becomes a problem.
This is because all the IO pins have ESD protection diodes, which look like this:

simulate this circuit
Those diodes have a forward voltage of about 300mV, and so anything below -300mV will cause the lower diode to start conducting. When that happens too much current can flow and the diode risks burning out.  But you can add further protection by simply adding a small resistor (1kΩ is good) in series with the IO pin to limit the current in the case that the voltage goes below -300mV and protect the internal circuitry.

Probably leaving the scope of this question but is the 3v3 pin noise free? Obviously any noise on the DC offset voltage will add noise to the AD conversion. Also, If I use say 1v as Vref, where is the best source for a noise free voltage... the DAC? Or external?

The 3.3V can be noisy, yes, since the main MCU is being powered from it.  For low-noise operation you need a low noise "precision voltage reference" chip.


text:
Arduino UNO LED half brightness when connected to digital GND but not analog
I am using an Arduino UNO. When lighting an LED with the switch button on a joystick module, I have two situations:

If the LED's cathode is connected to GND on the digital pin side of the Uno, the LED only dimly lights up on button press.
If the LED's cathode is connected to GND on the analog pin side of the Uno, the LED fully lights up on button press.

The device is receiving power from my laptop, and I am writing a digital HIGH/LOW to the LED pin (on press/release).
Is this a fault in my board, or is there a (perhaps more enlightening) reason why this is happening?

Despite double checking my cables before asking this question, it seems I had connected the LED's cathode to digital pin 13, and not GND. The issue is now resolved. Takeaway: Triple check your cables :)


text:
Stack smashing protect failure ESP32 with Modbus RTU
I'm doing a project using an ESP32 TTGO with LoRa, the Max485 and a WELLPRO ADAM 8082 for Modbus communication. I'm trying to use the ESP32 as a master to and the ADAM as a slave.
I'm also using Node-RED to send the input signals (reading the digital inputs on the ADAM or sending signals to the digital outputs).
Whenever I send a signal there's no problem, the ADAM receives it correctly and sends the answer. But when my ESP32 receives the answer, I get the following error:
Stack smashing protect failure!

abort() was called at PC 0x400dc860 on core 1

I tried debugging my program and the error happens when my program comes back from the function that has my reading modbus loop.
I'm pretty new to Arduino, so I don't really understand what could be causing this stack overflow.
Here's my code.
My global variables:
unsigned char ucSt[N_MAX];
int delayTime;

HardwareSerial modbusData(2);

WiFiClientSecure espClient;
PubSubClient client(espClient);
boolean bWifiConnected = false;

const byte button = PRG_BUTTON;

Modbus reading with loop:
void vReadingModBus()
{
  int i, nCmpt = 0;
  unsigned int uiCRC;

  while (modbusData.available() > 0)
  {
    Serial.print("nCmpt: ");
    Serial.println(nCmpt);
    ucSt[nCmpt] = (unsigned char)modbusData.read();
    nCmpt++;
    delay(delayTime - 2);
  }
  if (nCmpt)
  {
    Serial.print("He llegit aquests ");
    Serial.print(nCmpt);
    Serial.println(" bytes: ");
    char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "%02X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
    client.publish(TEMA_RESPOSTA_MODBUS, szResposta);
    uiCRC = uiModRTU_CRC(ucSt, nCmpt - 2);
    if ((byte)(uiCRC >> 8) == ucSt[nCmpt - 1] && (byte)(uiCRC & 0xFF) == ucSt[nCmpt - 2])
    {
      Serial.println("Trama amb CRC correcte");
    }
    else
    {
      Serial.println("Trama amb CRC incorrecte");
    }
  }
  nCmpt = 0;
}

Modbus transmission:
void vModbusTx(unsigned char *uc, int nLen)
{
  int i;

  Serial.print("Enviat: ");
  for (i = 0; i < nLen; i++)
  {
    Serial.print(uc[i], HEX);
    Serial.print(" ");
  }
  Serial.println();

  vModeTxRxRS485(RS485Transmit);
  delay(1);
  for (i = 0; i < nLen; i++)
  {
    modbusData.write(uc[i]);
  }
  delay(delayTime);

  vModeTxRxRS485(RS485Receive);
}

My setup:
void setup() {
  Serial.begin(115200);    // U0_RXD:GPIO3, U0_TXD:GPIO1 (UART0)
  modbusData.begin(9600); // U2_RXD:GPIO16, U2_TXD:GPIO17 (UART2)

  pinMode(PRG_BUTTON, INPUT_PULLUP);
  pinMode(GPIO_R2, INPUT); // 39
  pinMode(SSerialTxControl, OUTPUT); // hardwired to GPIO_R2
  pinMode(LED, OUTPUT);

  vModeTxRxRS485(RS485Receive); // RS485Receive is a 0, and vModeTxRxRS485 controls the DE/RE bits for the Max485

  delayTime = 0;

  //Wire.begin(I2C_SCL_OLED);

  delay(1000); // give me time to bring up serial monitor
}

My loop:
void loop() {
  boolean bButtonState = !digitalRead(button);
  static boolean bLastButtonState = bButtonState;

  // MODBUS READING LOOP
  vReadingModBus();

  if (!client.connected())
  {
    reconnect();
  }

  // BUTTON STATE CHECK
  if (bButtonState != bLastButtonState)
  {
    bLastButtonState = bButtonState;
    vDelayESP(50);
    if (!bButtonState)
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "UNPRESSED");
    else
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "PRESSED");
  }

  client.loop();
}

And finally here's an example of my program running and giving the error mentioned:
Connecting to WiFi network
Waiting for WIFI connection...
..............................................
Attempting MQTTS connection...connected
Message arrived [/clot/dam/biel/esp32/escriuModbus] 010F000000080111
Petició a ModBus:
010F000000080111
Mida: 8
ucSt[0] = 1
ucSt[1] = F
ucSt[2] = 0
ucSt[3] = 0
ucSt[4] = 0
ucSt[5] = 8
ucSt[6] = 1
ucSt[7] = 11
Enviat: 1 F 0 0 0 8 1 11 3E 99
He llegit aquests 8 bytes:
1 F 0 0 0 8 54 D
Trama amb CRC correcte

Stack smashing protect failure!

abort() was called at PC 0x400dc7d8 on core 1

Backtrace: 0x4008c800:0x3ffb1ef0 0x4008ca31:0x3ffb1f10 0x400dc7d8:0x3ffb1f30 0x400d1eed:0x3ffb1f50 0x400d23c0:0x3ffb1f90 0x400d513d:0x3ffb1fb0 0x4008879d:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x17 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:928
ho 0 tail 12 room 4
load:0x40078000,len:8424
ho 0 tail 12 room 4
load:0x40080400,len:5868
entry 0x4008069c

tl;dr: The message probably means your function is overwriting its array:
A stack overflow is caused by a stack that grows downward into the allocated heap space, either causing damage to data within the heap, or code using that heap space causing damage to the contents of the stack.
But "stack smashing" refers to damage caused by function code writing past the bounds of an automatic local variable and damaging the stack contents, typically including the function's return address.
[Feel free to skip rather long explanation:]
A function's stack-frame begins with the return address - the address following the instruction that calls the function, i.e., the address of the next instruction to be executed after the function returns. Then, building downwards, the call parameters are put on the stack and become local variables. Then any variables allocated during the function execution are allocated, still building downward.
Assume one of those allocated variables is an array. Its zero-th element is in the lowest address of the allocated space, and subsequent elements are at successively higher addresses. If I start writing into the array, and continue past its length, I'll eventually overwrite other automatic locals, my parameters, and and my return address. Then, when the function tries to return, instead of jumping to the code that called the function, the MCU uses the damaged return address and jumps to ... ????
To catch this error, the compiler can insert code that 1) allocates and writes a "canary" - a known value - just after the return address, and 2), checks the canary for damage just before the function returns. If the canary has been altered, you get the message you saw, because it's likely that the return address will have been altered also. But regardless, the canary isn't part of your code and isn't accessible to it. Thus, it detects writing-out-of-bounds errors.
[End of wordy explanation]
Check the code in your function 'void vReadingModBus()' - my money is on the loop that writes into szResposta[]:
  char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "%02X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }

Update:

If I understood correctly, it means szResposta must be overwriting the
  function's return address? How should I avoid this?

The short answer is make your array big enough for what you're going to put in it. But that's probably not a satisfying answer though, so let's take a closer look. I'm not sure exactly what your intent is in that loop, but since you print the strcat() result at every iteration and you don't seem to use szResposta after that, perhaps you meant to call strcpy() (replace the contents of the array) instead of strcat() (extend the contents of the array). If so, strcat() would quite likely write past the array bounds.

Thank you so much for this fantastic explanation! It certainly was the loop. The line giving the error is strcat(szResposta, szByte). If I understood correctly, it means szResposta must be overwriting the function's return address? How should I avoid this? Thank you, again!


text:
MCP2515 CAN bus with Arduino
I'm using MCP2515 CAN controller and TJA1050 transceiver. I want to send some square waves to TJA1050 with digital write and delay instruction of Arduino. How can I do that? I also read the MCP2515's datasheet. It has 5 GPIOs. Can I use these pins to send square waves to the transceiver?
Here is the library I used:https://github.com/Seeed-Studio/CAN_BUS_Shield
The examples of this library contains a sample code as gpioread and gpiowrite but when I compile them I got error:
exit status 1
'class MCP_CAN' has no member named 'pinMode'
Thanks in advance.

Why would you want to "send some square waves" to a CAN transceiver?

This is not really a general Arduino question but...
The compiler is telling you that the member function 'pinMode' is not available. A closer look at the commit history for the library reveals that they have recently rolled back to a "working version". There is a commit with the member functions 'pinMode', 'digitalRead' and 'digitalWrite' included.
Please see:
https://github.com/Seeed-Studio/CAN_BUS_Shield/commit/15c6bfb80a50c924a9c708117a66a66b54af5370


text:
How do you use the plastic cover/case that came with Arduino?
They have holes for screw on, on top of the holes on the Arduino itself. Where can I find parts that are compatible with this case/cover? What was the intended use of this case/cover? Thanks.

Looks like there are some taps on the sides, so it should just snap in. USB side at the top (in your image). (PS this case goes on the bottom of the UNO)

just match up the shape of the board to the shape of the case .... the shape is not completely rectangular

What is the point of matching it? I bought a stand from amazon and that just screws to the board itself. Same with the stand that came from the starter kit. I'm probably going to throw this away, if there is no use...

What was the intended use of this case/cover? .... this question is unclear .... only you can answer what you intend to use the cover for

I bought Arduino uno and it came with it... I guess they just don't want the wires that stick out touch metal, like laptop covers? they probably thought leaving the back side naked was a bad idea...

The cover was developed for Arduinos with on-board Ethernet with POE and similar cover has the Ethernet shield with POE. POE - power over Ethernet is 48 V, so it is better to not to touch a soldering point with this voltage.
The arduino.org boards were sold with this cover. Some of them had on-board esp8266 and soldering points leading to esp8266 sensitive pins. Again, better not to touch.
I used the cover to attach the Arduino to a DIN rail over a DIN rail clip.


text:
NodeMcu pins and an RGB LED
I'm using a NodeMcu for my project and am running out of pins to use. I have a MFRC522 Module, IR Receiver, Buzzer and RGB LED connected. I am facing the problem that whenever I start scanning for RFID tags with the MFRC522 module, the onboard LED starts flashing very fast and the RGB LED changes to an undefined color.
I looked up the pin definitions of the NodeMcu, but couldn't quite find information on what pins I can use for this and which I can't, and why this only happens once I start up the RFID reader.
This is my wiring sketch:

I found this pin layout image, as well as the datasheet.
The code shouldn't be really relevant since it works before starting the RFID reader, but here is the setup of the reader, just in case:
#define SS_PIN D4   // SPI - Slave Select Pin
#define RST_PIN D2  // SPI - Reset Pin - not actually connected

MFRC522 mfrc522(SS_PIN, RST_PIN);

// Initial setup for SPI and MFRC522
bool rfidSetupCompleted = false;
void setupReader()
{
  SPI.begin();
  mfrc522.PCD_Init();
  rfidSetupCompleted = true;
}

These are the pin definitions of the RGB LED:
#define LED_BLUE D8
#define LED_GREEN D3
#define LED_RED D2

Any help is highly appreciated! I'm assuming I am using a pin that is used for other purposes (such as maybe D8), but I can't figure out which, and why. I did try to change up the pins and switched D0 and D8 (buzzer and one LED pin), but without luck. I also tried disconnecting each LED pin separately, but didn't learn anything from that either.

what library for MFRC522  you use? I think you should set all SPI pins for the library, to set the correct SPI interface. Or if the library doesn't initialize SPI library, you should do it in setup()

@Juraj I'm using this: https://github.com/miguelbalboa/rfid
The library only takes those two parameters so I'm not sure if that is needed. And I do initialize the SPI library in my setup code.

@Juraj I have it in the setup method that I posted above. This is executed before I start using the MFRC522. I have it that way because I split up the code into several files.

then SPI looks OK, because D5, D6 and D7 are default SPI pins in SPI library

@Juraj yeah exactly. I do have one wire attached to D8, which is "HCS" according to this image: https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=616
I'm not sure if this might cause issues

D8 is Slave Select if esp8266 is slave. in your case esp8266 is master so you can choose Slave/Cable Select pins for devices on SPI bus. it is common to use SS pin as CS pin for the first device, but it is not mandatory.

the problem could be powering of the board

Is the MFRC522 module 3.3 V?

Meaning I can't use the pin for something else when I want to use the MFRC522? That does make sense that it's doing weird things once I start using it. And yes, the MFRC522 is 3.3V, and so is the NodeMcu. So that shouldn't be a problem.

I switched D4 and D8 around now, don't know why I didn't have it like that in the first place. The onboard LED doesn't flash anymore, but the RGB LED still changes it's color. Could this be because D4 is TXD1 and D8 TXD2? It shows me a connection between the two when I wire it in Fritzing. Can I use any other pins on the NodeMcu for this?

@Juraj I found out that the colors work correctly when I start scanning with the MFRC522 a second time. It's supposed to be blue during the scan, but is purple during the first scan. When pressing the button to start it again, it works correctly. So I'm assuming I have to set up the reader at the very start of the program or something similar.

@Juraj I fixed it by setting up the MFRC522 at the very start of the program now. Thank you for your help!

I fixed the issue by swapping pin D4 and D8, and then setting up the MFRC522 at the very start of the program. I originally set it up before I started using it, which caused the color to change during the first scan.

SPI.begin sets io15 (D8) mode even it is not used as SS pin for your device. It is better to use io15 (D8) as slave select pin for one of the slave devices. In your case for the one device you have on SPI bus.
Pins io 0 (D3) and io 2 (D4) have on-board pull-up, because they are boot configuration pins. Set them LOW right after setting pinMode for them, to not let current to LED RGB legs.


text:
Decreasing a functions programming size
I have Arduino Code that utilizes the I2CDev library to control an MPU-6050. I am pretty new to coding and copied and pasted most of the code from examples I have found around. I am starting to run out of programming space on my Arduino, and I have found that one line of the code takes up 21%, or 6000 bytes of the programming memory. I found the function that the line related to and I have it shown below.
The link to the I2CDev libarary can be found on Github here as well:
https://github.com/jrowberg/i2cdevlib
Is there a way to decrease it? Ot can someone explain to me why it is taking up so much space? Thanks!
uint8_t MPU6050::dmpInitialize() {
// reset device
DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
reset();
delay(30); // wait after reset

// enable sleep mode and wake cycle
/*Serial.println(F("Enabling sleep mode..."));
setSleepEnabled(true);
Serial.println(F("Enabling wake cycle..."));
setWakeCycleEnabled(true);*/

// disable sleep mode
DEBUG_PRINTLN(F("Disabling sleep mode..."));
setSleepEnabled(false);

// get MPU hardware revision
DEBUG_PRINTLN(F("Selecting user bank 16..."));
setMemoryBank(0x10, true, true);
DEBUG_PRINTLN(F("Selecting memory byte 6..."));
setMemoryStartAddress(0x06);
DEBUG_PRINTLN(F("Checking hardware revision..."));
DEBUG_PRINT(F("Revision @ user[16][6] = "));
DEBUG_PRINTLNF(readMemoryByte(), HEX);
DEBUG_PRINTLN(F("Resetting memory bank selection to 0..."));
setMemoryBank(0, false, false);

// check OTP bank valid
DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
DEBUG_PRINT(F("OTP bank is "));
DEBUG_PRINTLN(getOTPBankValid() ? F("valid!") : F("invalid!"));

// get X/Y/Z gyro offsets
DEBUG_PRINTLN(F("Reading gyro offset TC values..."));
int8_t xgOffsetTC = getXGyroOffsetTC();
int8_t ygOffsetTC = getYGyroOffsetTC();
int8_t zgOffsetTC = getZGyroOffsetTC();
DEBUG_PRINT(F("X gyro offset = "));
DEBUG_PRINTLN(xgOffsetTC);
DEBUG_PRINT(F("Y gyro offset = "));
DEBUG_PRINTLN(ygOffsetTC);
DEBUG_PRINT(F("Z gyro offset = "));
DEBUG_PRINTLN(zgOffsetTC);

// setup weird slave stuff (?)
DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
setSlaveAddress(0, 0x7F);
DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
setI2CMasterModeEnabled(false);
DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
setSlaveAddress(0, 0x68);
DEBUG_PRINTLN(F("Resetting I2C Master control..."));
resetI2CMaster();
delay(20);

// load DMP code into memory banks
DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
DEBUG_PRINTLN(F(" bytes)"));
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
    DEBUG_PRINTLN(F("Success! DMP code written and verified."));

    // write DMP configuration
    DEBUG_PRINT(F("Writing DMP configuration to MPU memory banks ("));
    DEBUG_PRINT(MPU6050_DMP_CONFIG_SIZE);
    DEBUG_PRINTLN(F(" bytes in config def)"));
    if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
        DEBUG_PRINTLN(F("Success! DMP configuration written and verified."));

        DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
        setClockSource(MPU6050_CLOCK_PLL_ZGYRO);

        DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
        setIntEnabled(0x12);

        DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
        setRate(4); // 1khz / (1 + 4) = 200 Hz

        DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
        setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);

        DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
        setDLPFMode(MPU6050_DLPF_BW_42);

        DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
        setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

        DEBUG_PRINTLN(F("Setting DMP programm start address"));
        //write start address MSB into register
        setDMPConfig1(0x03);
        //write start address LSB into register
        setDMPConfig2(0x00);

        DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
        setOTPBankValid(false);

        DEBUG_PRINTLN(F("Setting X/Y/Z gyro offset TCs to previous values..."));
        setXGyroOffsetTC(xgOffsetTC);
        setYGyroOffsetTC(ygOffsetTC);
        setZGyroOffsetTC(zgOffsetTC);

        DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero..."));
        //setXGyroOffset(0);
        //setYGyroOffset(0);
        //setZGyroOffset(0);

        DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)..."));
        uint8_t dmpUpdate[16], j;
        uint16_t pos = 0;
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Resetting FIFO..."));
        resetFIFO();

        DEBUG_PRINTLN(F("Reading FIFO count..."));
        uint16_t fifoCount = getFIFOCount();
        uint8_t fifoBuffer[128];

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
        setMotionDetectionThreshold(2);

        DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
        setZeroMotionDetectionThreshold(156);

        DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
        setMotionDetectionDuration(80);

        DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
        setZeroMotionDetectionDuration(0);

        DEBUG_PRINTLN(F("Resetting FIFO..."));
        resetFIFO();

        DEBUG_PRINTLN(F("Enabling FIFO..."));
        setFIFOEnabled(true);

        DEBUG_PRINTLN(F("Enabling DMP..."));
        setDMPEnabled(true);

        DEBUG_PRINTLN(F("Resetting DMP..."));
        resetDMP();

        DEBUG_PRINTLN(F("Writing final memory update 3/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 4/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 5/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
        while ((fifoCount = getFIFOCount()) < 3);

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);
        DEBUG_PRINTLN(F("Reading FIFO data..."));
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Reading interrupt status..."));

        DEBUG_PRINT(F("Current interrupt status="));
        DEBUG_PRINTLNF(getIntStatus(), HEX);

        DEBUG_PRINTLN(F("Reading final memory update 6/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
        while ((fifoCount = getFIFOCount()) < 3);

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);

        DEBUG_PRINTLN(F("Reading FIFO data..."));
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Reading interrupt status..."));

        DEBUG_PRINT(F("Current interrupt status="));
        DEBUG_PRINTLNF(getIntStatus(), HEX);

        DEBUG_PRINTLN(F("Writing final memory update 7/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("DMP is good to go! Finally."));

        DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
        setDMPEnabled(false);

        DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
        dmpPacketSize = 42;
        /*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) {
            return 3; // TODO: proper error code for no memory
        }*/

        DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
        resetFIFO();
        getIntStatus();
    } else {
        DEBUG_PRINTLN(F("ERROR! DMP configuration verification failed."));
        return 2; // configuration block loading failed
    }
} else {
    DEBUG_PRINTLN(F("ERROR! DMP code verification failed."));
    return 1; // main binary block loading failed
}
return 0; // success

}

Which line? Put a marker on it and refer to it in your question.

A lot of PLINTLN lines aren’t very useful. Most of them are just comments. Removing them or converting them to regular comments would reduce the size.

There is no magic recipe for reducing the code size. The only general rule is: “remove everything that is not strictly needed”, but you cannot make use of that rule unless you really understand what the program is doing. You can start nevertheless by looking at which functions take up the most space. C.f. Determining which section of code uses the most flash.

i know that you are new to coding ... i am just wondering why it did not occur to you to remove the DEBUG_PRINTLN( commands

@jsotola, that was the first thing I tried but it didn't change the size of the code at all.

It doesn't matter if you use 90% of your program memory, provided your code does all you want it to. Are you in fact likely to run out of program memory?

One line of code doesn't use 6000 bytes of memory. However if it calls a function, which otherwise would not be called, then the compiler has to include the function.
So, for example, if you have a function that takes 6000 bytes, but don't call it, then the compiler can omit the function itself.

Assuming DEBUG_PRINTLN does something, then I count 2480 bytes of string literals there. Therefore your function would at the very least take up 2480 bytes. And that is called 71 times, so if DEBUG_PRINTLN takes (say) 10 bytes to call each time, that is another 710 bytes. We are already up to 3190 bytes. Other stuff (unrelated to debugging) also probably takes quite a few bytes.

I am starting to run out of programming space on my Arduino

That's not a problem until you actually run out of space. Who cares if you use 99% of available memory?

The fact that something causes a jump in memory usage is not, in itself, cause for worry. For example this sketch:
void setup() {
  Serial.begin(115200);
  int a;
  Serial.println (a);
}

void loop() {  }

Compiled for a Uno using IDE 1.6.9 I get:
Sketch uses 2,122 bytes (6%) of program storage space. Maximum is 32,256 bytes.

So, 2,122 bytes. Now change a to be float:
void setup() {
  Serial.begin(115200);
  float a;
  Serial.println (a);
}

void loop() {  }

Now it uses 3,668 bytes:
Sketch uses 3,668 bytes (11%) of program storage space. Maximum is 32,256 bytes. That's another 1,546 bytes just by changing one variable's type.

However it doesn't take another 1,546 bytes if you add a second such variable.
void setup() {
  Serial.begin(115200);
  float a;
  float b;
  Serial.println (a);
  Serial.println (b);
}

void loop() {  }

That only uses another 18 bytes:
Sketch uses 3,686 bytes (11%) of program storage space. Maximum is 32,256 bytes.

In other words, the floating-point library has now been included by the compiler. This is a once-off jump in usage. Of course, if I now do something with I2C there will be another jump as that additional library is loaded.

Yeah sorry for the misconfusion. The single line was in the arduino code. I then opened up the function that that line was referring to and pasted it above. My question is what in this function is taking up so much space?

What in what function? Can you please be more explicit?

What does DEBUG_PRINTLN do? Try to post enough information to enable us to answer your question.

See my amended answer.

You could save a lot of memory by replacing those rather wordy debugging message with something like DEBUG_PRINTLN(F("1")) (and then 2 and so on) and have a spreadsheet that tells you which one each one means. You are working on a microcontroller, not a PC with 20 gigabytes of RAM.

So I tried removing the DEBUG_PRINT lines and it did not change the size of the code at all. Do DEBUG_PRINT have to be enabled somewhere else in the code to work?

It would help to show the code/macro for DEBUG_PRINT so then that could be answered. Quite possibly it is a macro that does nothing unless something (like DEBUG) is defined.

See amended answer about library code only needed to be included once.