text:
Button state issue
Let me preface this by saying I'm a beginner, and I know my code must have some logic errors. I need some fresh eyes on this, I have been messing with it a few days and am just running in circles at this point.
I'm trying to use buttons and button states to set hours and minutes of an alarm clock so I am trying to save the state of the buttons so after being pushed so it will remember the state rather than being changed on release.
I am trying to get it so pushing button A in my code goes into the alarm clock set procedure, then until button C is pressed it will loop to set hours then minutes (I havent added minutes procedure yet) So button A starts procedure and button C completes it, while button B increases the hours/minutes variable by one.
I have thoroughly confused myself. I have two "lastButtonState" variables which may be unnecessary but it was the only thing I could think of.
Right now with my code it goes into the button C while loop but doesn't come out of it on button press. My logic for that was that the while loop should exit when button C is pressed, so I don't think I need anything within the loop to break out of it.
I have the button B setting hours part working, it just isn't exiting the button C loop.
I'm eventually going to put this code in its respective function and add in the set minutes area after set hours area.
Here is my code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
//Constants
//const int buttonPin = 9;
const int buttonApin = 3;
const int buttonBpin = 2;
const int buttonCpin = 5;
int buttonState = 0;
int buttonState2 = 0;
int buttonState3 = 0;
//int flag = 0;
int alarmHoursInner = 1;
int lastButtonState = 0;
int lastButtonState3 = 0;
void setup() {
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  Serial.begin(9600);
  //Input or output?
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(buttonCpin, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  buttonState = digitalRead(buttonApin);
  buttonState2 = digitalRead(buttonBpin);
  buttonState3 = digitalRead(buttonCpin);

  if (buttonState == HIGH) {
    while (buttonState3 == LOW) {

      buttonState2 = digitalRead(buttonBpin);
      if (lastButtonState != buttonState2) { // last button state starts at 0 (or OFF) this line tests current state against last state
        if (buttonState2 == LOW) { // if buttonState is HIGH it went from OFF to ON
          // Serial.print("Button B works!");
          ++alarmHoursInner; // increments variable for hours
          Serial.print(alarmHoursInner); // prints hours
          Serial.println("  "); // blank line
          delay(50); // delay
        }
        else {

          Serial.print("Please push button B");
          Serial.println("  ");
        }
      }

      lastButtonState = buttonState2;
    }
      lastButtonState3 = buttonState3;
  }
}

start by renaming the buttons to some useful names that describe the function.... instead of buttonA, buttonB, buttonC call them something like mode, advance, exit .... modeButton, etc.

research Arduino state machine

Ok your input about renaming is noted, thanks! I have already looked at state changes pretty thoroughly. Could you point me in the direction of something specific about state machines that would help? I googled it and looked at a few links but what part of state machines should I focus on? So far, It looks like its what I have already known about states when I developed my code. What exactly is wrong with my code?

lastButtonState3 = buttonState3;  .... this line is indented too far, which makes it look like it is part of the if statement .... it is at the end of the while loop  ..... buttonState3 will always be LOW when this line executes


text:
Some Arduino components seem ridiculously cheap
My project is an Arduino-based device, packed into a box.
It will need to use Speed, Latitude, Longitude and Altitude data to log hills it detects on to an SD. On the press of a button, it will need to upload the hill data to the server via Wi-Fi.
I need the following items:

GPS Module + Antenna
WiFi Module
SD Module
Altimeter
microSD Card
Inline switch for my battery pack

The cost? Well on the Pi Hut it was £120 or so:

GPS =
  https://thepihut.com/products/sim808-gps-gprs-gsm-shield-for-arduino =
  £42
WiFi =
  https://thepihut.com/products/wifi-shield-v3-for-arduino-rpsma-802-11b-g-n
  = £54
SD = https://thepihut.com/products/microsd-card-module-for-arduino =
  £6
microSD Card = https://thepihut.com/products/blank-micro-sd-cards
  (4GB) = £5
Altimeter =
  https://thepihut.com/products/adafruit-bmp280-i2c-or-spi-barometric-pressure-altitude-sensor
  = £10
Switch =
  https://thepihut.com/products/adafruit-in-line-power-switch-for-2-1mm-barrel-jack
  = £2.50

On Bang Good (a really cheap online shop I discovered) it was more like £30:

GPS =
  https://www.banggood.com/GPS-UBLOX-NEO-7N-Satellite-Positioning-Module-For-Arduino-51MCU-STM32-p-1203610.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £10.54
GPS Antenna =
  https://www.banggood.com/GPS-Active-Ceramic-Antenna-IPX-IPEX-Interface-For-GPS-Module-p-1203537.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £2.11
WiFi = https://www.banggood.com/Upgraded-Version-1M-Flash-ESP8266-ESP-01-WIFI-Transceiver-Wireless-Module-p-979509.html?rmmds=cart_middle_products
  = £2.53
SD = https://www.banggood.com/Micro-SD-TF-Card-Memory-Shield-Module-SPI-Mciro-SD-Adapter-For-Arduino-p-919914.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £1.02
microSD Card = https://www.banggood.com/4GB-MicroSD-Card-with-Card-Reader-for-RC-FPV-Camera-Quadcopter-p-1050069.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £3.96
Altimeter = https://www.banggood.com/MPL3115A2-IIC-I2C-Intelligent-Temperature-Pressure-Altitude-Sensor-V2_0-For-Arduino-p-1198222.html?rmmds=cart_middle_products
  = £5.16
Switch = https://thepihut.com/products/adafruit-in-line-power-switch-for-2-1mm-barrel-jack
= £2.50 (From Pi Hut, though)

I'm suspicious. I might be inexperienced, and this may be a bad question, but is the cheaper option lower in quality? Is the expensive one over the top? The cheap version really seems to good to be true.

buy at least one genuine Arduino product .... it supports Arduino development

@jsotola What is the best component to buy genuine? Wifi, GPS or SD Module? Should I look for a new Arduino (ie Yun)? What do you mean by Arduino development (libraries, general progress, Arduino foundation, other)?

i was talking about any product found here https://www.arduino.cc/ ....  i made the comment in case you are just starting out and buying a controller board .... i was referring to research and development of the products found at that website

@jsotola Even if they're more expensive?

The pi-hut GPS also has GSM, which makes it more expensive. The Wifi shield also has a way more expensive chip on it that the ESP8266 one you found on banggood. Ordering directly from china is often cheaper, but there is a risk of lesser quality.

fwiw, i've ordered about 1200 ardunio-related items (according to ebay), and i've only been "burned" 5 or 6 times with something that was mis-speced, deffective, or just so crudely made it was unusable. The vast majority of the cheap crap i've bought works fine. You get faster shipping, better packaging, better docs, and better support from someplace like adafruit, but the products themselves are alright, with few exceptions.

@dandavis would you still recommend eBay for starters? They do not know which exact part they need and they will have great help from manuals, datasheets, guides, libraries and example projects. It's very uncommon to get this for eBay parts, but Adafruit will give those.
If you're confident in your embedded systems skills, no worries on eBay parts (usually shops buy their stock through eBay, it seems), but as a starter, you need to have confidence in the parts you use and have enough background info to get you started.

@Paul What do you mean by starter? Perhaps I'm not?

@Paul: I've been using ebay since day 1, about 2-3 years ago. you can still use adafruit docs and libs on cheap parts; anything adafruit sells you can get for at least half-off on ebay, sometimes 10X less. That's great for a hobby you're getting started in and unsure of. I think it's better to go cheap at first; you're more likely to burn stuff up and it won't be as discouraging watching an LED smoke if you got 100 for $1 than w/ adafruit's "special" LEDs. I can get a whole project's part list shipped from ebay for less than adafruit shipping, and to me, that enables a whole lot more learning.

also note shipping times; items may be cheaper on banggood, but you'll be waiting 1-1.5 months for them to arrive (untracked and uninsured)

The cheaper option is not always lower in quality. You can find items for sale on Amazon, Ebay and Aliexpress that all have the same "seller name" and a identical picture of the item. The price is usually 5 to 10 times higher on Amazon than Ebay. Aliexpress is usually the cheapest.
During the past year, I've ordered over 100 Arduino related sensors/modules from Ebay and Aliexpress. Four from Ebay and one from Aliexpress were defective. I got a refund for all five items.
If you are going to buy the cheaper products, it's a good idea to order more than you need in case one is defective.
Some items should not be sold at any price. For example, I purchased a DHT11 temperature and humidity sensor when I first started with Arduinos. It's an inaccurate piece of garbage, and that's exactly where it went.

If something is too good to be true, it usually is.
In all seriousness, going with a reputable shop (Adafruit, Sparkfun, Pololu) can save you a bit of headaches later, especially if you are doing integration.  You might ask (email) the Pi Hut folks why you should buy from their place, rather than the other place, I'm curious what they would say.  I don't think this needs to be an accusatory sort of email (how dare you charge more!), but more of a "I see there is a price difference; obviously, something is going on which I don't know about, can you explain this?"
I've bought cheap stuff from Amazon (Arduino clones), and they'd work... after a fashion.  Bad solder masks, badly soldered components; all would make getting things going a real pain. Sometimes, a component (like a voltage regulator) wouldn't work, and so an Arduino clone would work when plugged in to a USB port, but not in a standalone mode.   Then again, this was a 4 for $10, vs 1 for $15, so it was a bit of a lark, but there was a build quality
If you are putting a lot of effort into the software for this, or paying someone for the software to be developed, or this experiment will be a costly one, the price difference wouldn't be as much of an issue.  Is £90
How many of these are you building, BTW?  If you are building many, cheaper components might be an issue.
Someone might have another take here; the other shop might be quite reputable, but you have to ask why there is a huge disparity in costs, yes.
If you are wanting to sell stuff online, people may ask for warranties, or expect something to work for N months/years; what would happen if these units fail?

BTW: I'm looking to build one as a prototype, see if I'm still interested, make it permanent, see if I'm still interested, then maybe sell a few online. But that doesn't matter. Do you mean actually ask (as in an e-mail)?

Question: do I email The Pi Hut or DFRobot, the manufacturer of most of the components?

I designed a battery backup power supply for a product at my work. I included the INA219 current/voltage measurement chip. For the prototype run I bought that part from two Aliexpress sellers since the cost was half of what it would cost through our normal distributors. (two orders of 50) Half of the chips we way out of spec. Some would read current okay but the voltage was off. Some the voltage was okay and the current was off. I suspect one order of the 50 was badly out of spec parts but since we didn't track which chips ended up in which boards we didn't know which was the bad batch.
In another case, we had been using a cheap buck converter (dc-dc power supply) normally called Mini360. It was a very good module and the chip was from a major IC manufacture. It was cheaper for us to buy the module than to buy the parts so I included it as a through hole component in some of my designs. A couple of months ago we had experienced some problems with a product and I then found that the Mini360 modules we were using was different. The pcb was different, a tiny bit smaller, and the switching regulator use was from a China manufacture. It was a knock-off of the original chip on the earlier Mini360. Because of what we were doing in our product, the new knock-off part caused problems for one of the designs. The part does the same job as the original part, but it wasn't the same. And how it worked for us, in one specific product, meant that I couldn't use it. On the next revision of the product I designed out the module and implemented the module onto our smd board. And we buy the original part from our normal distributors, not China. It costs us more but we need reliability.
For my hobby I use the Arduino framework as it was easier for coding. (I'm a hardware designer) I also use cheap available parts targetted for the Arduino user base. Most of the stuff is decent, good enough. But there always is a higher level of risk when we buy these cheap parts.

that "ebay gamble" is part of the excitement for amateurs, but you're right about relaying on loose-specification listings to refresh an existing supply line for a commercial finished product.

The main reason that some devices on eBay, or where ever, are markedly cheaper is that they are clones produced by a third party, using designs that have been copied/pirated or reverse engineered.
This reduces the third party's set up costs, quality assurance (QA) (i.e. testing) costs and research and development (R&D) costs to almost zero (compared to those of the original manufacturer).
So, generally, the board will, for all intents and purposes, be the same physically, just at a much lower cost, and, as dandavis states in his comment, probably with the same reliability and quality.
However, if you purchase these clones, then the research and development aren't being paid for and may inhibit further growth in the market.
In addition, sometimes the cost is reduced even further as the third party cloner will use inferior and cheaper, alternative, components which may cause the device to fail sooner than the original. They may even come from the same factory and be devices that are using the original components, but which have failed the QA process, for one reason or another... and then fail in extreme circumstances.
So, in summary, you are taking a gamble (albeit a small one), and whilst generally you will end up with a device of the same quality, you may sometimes end up with a bit of a lemon.

The stuff adafruit actually makes (PCB modules+learning kits) can't be beat. But don't forget they also sell a ton of stock items at prices that simply tax noobs, ex selling for a quarter something you can get for about a penny. I think adafruit just buys such items from 10 different ebay sellers, chooses the best sample, and orders thousands more from that vendor to hawk to suckers. Adafruit is not some non-profit, they are there to make money, and they are good at it.

source: Stack Exchange

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

sort: votes


text:
Difference in pinout (types?) Uno/Mega
As a hands-on guy, I've started my first ever Arduino project 5 hours ago with no prior knowledge about Arduinos (I have coding experience tho. included this in case I am missing something obvious to the veterans around here). So far I have been able to hook-up 3 SSD1306 SPI OLED displays to my Uno, and created a script that allows me to control each display separately. Because my goal is to have 5 displays work off one Arduino, I figured to pin everything over to my Mega since it has more outputs (not sure yet about the differences between DIGITAL PWM on the Uno, and the 53 additional DIGITAL pins on the Mega).
First problem I encountered is that I couldn't find where the clock pulse was specified in the demo script. It's pinned on the Uno on pin 13, but this is not specified somewhere in that script, and I think once I understand the differences in pins from both boards, I might be able to help myself a few more steps into the future.
So to sum up my questions.

How or where is the ClockPulse being specified.
Can I use the 53 DIGITAL pins on the Mega, instead of the 13 DIGITAL PMW that I have on my Uno, and if yes, do I need to change some settings?

Here is my current script that works on my Uno, but not on my Mega, even if I use the same DIGITAL PMW pins on my Mega.
#include "HCuOLED.h"
#include "SPI.h"

//#define CS_DI 10
//#define DC_DI 9
//#define RST_DI 8

//HCuOLED HCuOLED_1(SSD1307, CS_DI, DC_DI, RST_DI); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_1(SSD1307, 10, 9, 8); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_2(SSD1307, 7, 6, 5); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SSD1307, 4, 3, 2); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

void setup()
{
  HCuOLED_1.Reset();
  HCuOLED_2.Reset();
  HCuOLED_3.Reset();
}

void loop()
{
  //display 1
  HCuOLED_1.SetFont(Terminal_8pt);
  HCuOLED_1.Cursor(44,0);
  HCuOLED_1.Print("Cpt");
  HCuOLED_1.Cursor(20,10);
  HCuOLED_1.Print("Fastlane");

  HCuOLED_1.Cursor(14,24);
  HCuOLED_1.SetFont(LCDLarge_24pt);
  HCuOLED_1.Print("KM/H");
  HCuOLED_1.Refresh();

  HCuOLED_1.ClearBuffer();

  //display 2
  HCuOLED_2.SetFont(Terminal_8pt);
  HCuOLED_2.Cursor(44,0);
  HCuOLED_2.Print("Cpt");
  HCuOLED_2.Cursor(20,10);
  HCuOLED_2.Print("Fastlane");

  HCuOLED_2.Cursor(14,24);
  HCuOLED_2.SetFont(LCDLarge_24pt);
  HCuOLED_2.Print("RPM");
  HCuOLED_2.Refresh();

  HCuOLED_2.ClearBuffer();

  //display 3
  HCuOLED_3.SetFont(Terminal_8pt);
  HCuOLED_3.Cursor(44,0);
  HCuOLED_3.Print("Cpt");
  HCuOLED_3.Cursor(20,10);
  HCuOLED_3.Print("Fastlane");

  HCuOLED_3.Cursor(14,24);
  HCuOLED_3.SetFont(LCDLarge_24pt);
  HCuOLED_3.Print("Info");
  HCuOLED_3.Refresh();

  HCuOLED_3.ClearBuffer();
}

And here is the original script:
#include "HCuOLED.h"
#include "SPI.h"

/* Example bitmap */
const PROGMEM byte Tiny_Logo_Resistor[] =
{
  0xC0, 0xE0, 0x30, 0x30, 0xF0, 0xE0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0x38, 0x0E, 0x07, 0x1E, 0x78, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x70, 0x1C, 0x07, 0x0F, 0x3C, 0xF0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x80, 0xF0, 0x3C, 0x0F, 0x07, 0x1C, 0x70, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0x78, 0x1E, 0x07, 0x0E, 0x38, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xE0, 0xF0, 0x30, 0x30, 0xE0, 0xC0,
  0x00, 0x01, 0x03, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x3C, 0x38, 0x0E, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x1E, 0x38, 0x1C, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0E, 0x38, 0x38, 0x0E, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x1C, 0x38, 0x1E, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0E, 0x38, 0x3C, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x03, 0x01, 0x00,
};

/* Digital pin number for the displays chip select pin */
#define CS_DI 10
/* Digital pin number for the displays data/command pin */
#define DC_DI 9
/* Digital pin number for the displays reset pin */
#define RST_DI 8

/* Array indexes for the X and Y coordinates */
#define X1 0
#define Y1 1
#define X2 2
#define Y2 3

/* Arrays to store coordinates and direction for the line, rectangle and bitmap */
byte Box[4] = {1,1,20,20};
byte BoxDir[4] = {1,1,1,1};
byte Line[4] = {100,25,120,55};
byte LineDir[4] = {-1,-1,-1,-1};
byte Bitmap[2] = {40,40};
byte BitmapDir[2] = {-1,-1};

/* Create an instance of the library (uncomment one of the lines below) */
//HCuOLED HCuOLED(SSD1307, SS_DI, DC_DI, RST_DI); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED(SH1106, CS_DI, DC_DI, RST_DI); // For SH1106 displays (HCMODU0058 & HCMODU0059)

void setup()
{

  /* Reset the display */
  HCuOLED.Reset();
}

void loop()
{
  /* Display some text using a small 8x8 fixed width font */
  HCuOLED.SetFont(Terminal_8pt);
  HCuOLED.Cursor(44,0);
  HCuOLED.Print("HOBBY");
  HCuOLED.Cursor(20,10);
  HCuOLED.Print("COMPONENTS");

  /* Display a number using a large 4 line LCD style font */
  HCuOLED.Cursor(20,24);
  HCuOLED.SetFont(LCDLarge_24pt);
  HCuOLED.Print("HCuOLED");

  /* Change the draw mode from NORMAL to INVERT */
  HCuOLED.DrawMode(INVERT);
  while(1)
  {
    /* Move the positions of the 3 objects */
    MoveRect();
    MoveLine();
    MoveBitmap();

    /* Draw the objects to the display buffer */
    HCuOLED.Rect(Box[X1],Box[Y1],Box[X2],Box[Y2], SOLID);
    HCuOLED.Line(Line[X1],Line[Y1],Line[X2],Line[Y2]);

    HCuOLED.Cursor(Bitmap[X1],Bitmap[Y1]);
    HCuOLED.Bitmap(84, 2, Tiny_Logo_Resistor);

    /* Write the display buffer to the screen */
    HCuOLED.Refresh();

    /* Draw the objects again. As we are in INVERT mode this will remove them */
    HCuOLED.Rect(Box[X1],Box[Y1],Box[X2],Box[Y2], SOLID);
    HCuOLED.Line(Line[X1],Line[Y1],Line[X2],Line[Y2]);

    HCuOLED.Cursor(Bitmap[X1],Bitmap[Y1]);
    HCuOLED.Bitmap(84, 2, Tiny_Logo_Resistor);
  }
}

/* Update the X and Y coordinates for the box */
void MoveRect(void)
{
  if(Box[X1] == 0 || Box[X1] == 127)
    BoxDir[X1] *= -1;
  Box[X1] += BoxDir[X1];

  if(Box[Y1] == 0 || Box[Y1] == 63)
    BoxDir[Y1] *= -1;
  Box[Y1] += BoxDir[Y1];

  if(Box[X2] == 0 || Box[X2] == 127)
    BoxDir[X2] *= -1;
  Box[X2] += BoxDir[X2];

  if(Box[Y2] == 0 || Box[Y2] == 63)
    BoxDir[Y2] *= -1;
  Box[Y2] += BoxDir[Y2];
}

/* Update the X and Y coordinates for the Line */
void MoveLine(void)
{
  if(Line[X1] == 0 || Line[X1] == 127)
    LineDir[X1] *= -1;
  Line[X1] += LineDir[X1];

  if(Line[Y1] == 0 || Line[Y1] == 63)
    LineDir[Y1] *= -1;
  Line[Y1] += LineDir[Y1];

  if(Line[X2] == 0 || Line[X2] == 127)
    LineDir[X2] *= -1;
  Line[X2] += LineDir[X2];

  if(Line[Y2] == 0 || Line[Y2] == 63)
    LineDir[Y2] *= -1;
  Line[Y2] += LineDir[Y2];
}

/* Update the X and Y coordinates for the bitmap */
void MoveBitmap(void)
{
  if(Bitmap[X1] == 0 || Bitmap[X1] == 43)
    BitmapDir[X1] *= -1;
  Bitmap[X1] += BitmapDir[X1];

  if(Bitmap[Y1] == 0 || Bitmap[Y1] == 47)
    BitmapDir[Y1] *= -1;
  Bitmap[Y1] += BitmapDir[Y1];
}

You are communicating with your OLED displays using SPI - Serial Peripheral Interface.  This is a special hardware peripheral built in to the MCU, and the outputs of it are physically connected inside the MCU to what become pins 11-13 on the Arduino UNO.
This, and other things like the UART, PWM and the analog inputs, are known as alternate functions of the pins.
On small MCUs like the Arduino uses these functions are fixed in hardware (more advanced MCUs employ a system to allow you to map the functions to different pins).
When you use SPI on the UNO it always uses pins 11-13 (MOSI, MISO and SCK in that order).  When you use SPI on the Mega it always uses pins 51, 50 and 52 (in that order for the same functions). You can't change it. Pin 10 on the UNO is the Slave Select pin, and that again is an alternate function which is hard wired. On the mega that function is pin 53.
For SPI to work as a master (which is what you want) then pin 10 on the UNO or pin 53 on the Mega must be set to OUTPUT. It doesn't matter if you actually use it, but it has to be set to OUTPUT as that defines the direction the SPI peripheral operates in.
So for the Mega you would wire your OLED displays to pins 51, 50 and 52 instead of pins 11, 12 and 13. You could use pin 53 as one of your chip select pins (though you don't have to, just as long as you set it to OUTPUT).
Incidentally, you can save pins on your setup by sharing some of them.  The only pin that need to be unique for each OLED is the Chip Select pin. That is the pin that tells the OLED that it is being spoken to. Only when that pin is active will the OLED listen to any of the other pins.
The only other one you may need to connect separately is the reset pins, since you reset the displays in turn - resetting the second would reset the first and undo the configuration. TBH I'd connect the RESET pins of the OLEDs to a single pin, and specify another (unused, or non-existent) pin in the constructors for RESET - then manually reset all the OLEDs together through the one LOW pulse of the RESET pin, and then call the reset functions for each display, which should configure them all.
That way you are then using just (example UNO pins numbers shown):

MOSI  (11)
MISO  (12)
SCK   (13)
DC    (7)
RESET (6)
CS1   (10)
CS2   (9)
CS3   (8)

Amazing stuff! Ill probably have to read it a couple of times before I can fully wrap my head around it. I dont fully understand the RESET part, because the way I see it, it seems that I cannot get arround having to use one pin on the board per display, be it via the regular way, or manually. Could you elaborate? By sharing the DC pins I do free up 3 more pins that allows me to add 2 screens, and have one more pin that will eventually control my rev bar (havent figured that bit out yet, but it will be a bar of LEDs that will take in RPM data).

Also, when i've connected pin 50 and 52 (not using pin 10 on the UNO now), can I assign DC, RESET and CS to any of the other 49 digital pins on the MEGA?
(post became to long)

Yep, DC, CS and RESET can be any pin you like (even Analog pins). When you share pins (like DC) all the displays get sent the DC setting (HIGH or LOW), but only one does anything with it - the display that currently has the CS pin LOW.

Ohh i see now (I think haha). So I can combine all pins except CS, and instead of doing the regular .display () command, I first manually set the output for whatever pin is CS for the display I wanna update to LOW, and then use the .display() function (after updating the data to display that is)?

The library is doing that for you. Just repeat the same numbers in the constructors.

Ahh right. Again, this was already a HUGE help understanding how these boards work. I am a game developer by trade so I'm used to having to do everything myself haha.

I'm getting back at this for a second. Is there a way to calculate wether a UNO or MEGA would have enough cpu/memory power to handle whatever i want? Right now I'm about to use 5 OLED screens, 4 will be text only in white, the fifth will be a coloured one for bitmaps warning lights. Beside those I am going to add a rev bar with approx 30 RGB LEDs.

@sdieters That's pretty impossible to know. It's not so much what you connect, as what you do with them. And that very much depends on how the libraries you use work, etc. The Mega2560 has more memory (both flash and RAM) than the Uno, but still a tiny amount compared to more modern MCUs. Be sure to read up on using PROGMEM to save RAM - that will be your most critical area.

Will do! What do you mean with the more modern MCUs? I always thought the mega was the flagship among DIY hobbyist MCUs.

@sdieters There are many far more powerful MCUs around now than the old 8-bitters. Plenty of 32-bit ones using ARM or MIPS cores. Much faster, much more memory, much more flash, more powerful peripheral interfaces, etc.

Oehh, ill have to look into that once I start designing some more powerful digital dashboard. Hopefully they are as easy to work with as the Arduino

Well, generally they use the same API - often adding more functions as well. Sometimes even the same footprint.  I work almost exclusively with chipKIT. Teensy is very popular.

Alright, it seems I cannot get it to work when sharing the other pins. I currently have shared all pins except the CS pin, and I'm using the following pins: VCC=3.3v, GND=GND, SCK=13, SDA=11, DC=10, RST=9 CS(display1)=8, CS(display2)=7, CS(display3)=6. The odd thing is that I currently only get display 3 to work, the other 2 do nothing. When adding the other 2 displays on pin 5 and 4 without using them in my code, they just flicker (sorta expected that since they get no data, nor are they being reset.) I havent changed any of the script, other then reassigning the Defined Vars and CS pins

Nevermind, got it working now! Forgot to remove the extra RESET commands. I figured by calling those RESET 3 times during the same cycle now they are all connected, only the 3th display would remain working, while the other 2 keeps getting resetted... I only have one HCuOLED_1.Reset() command in the setup instead of 3 for each display.

I am now also able to effortlessly add 2 more displays by just hooking them up to my remaining pins. Thanks again for all your support! Not sure if it is allowed, but if you wanna follow what I am working on, look for my page on FBdotCOMslashCPTfastlane =)

after some time off my project I went back at it to make it work with my MEGA. However, even without setting pin 53 to OUTPUT in the setup function, it still works. Why is this? You can find the details about what I did in here:
https://arduino.stackexchange.com/questions/56301/getting-spi-ssd1307-to-work-on-arduino-mega/56314#56314

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


text:
Arduino sketch- How to add Time Stamp for outgoing MQTT
I'm writing a sketch in order to upload to a Sonoff device ( Remote relay, based ESP8266 ).
All is working great, but I wish my MQTT pubs to contain following format:
[ DATE & TIME ] msg
ESP8266 is connected to the internet.
I;m looking for a way doing it (including periodic time updates ) without running all 1MB memory, meaning: a code that
1) get time from external source (LAN or WAN )
2) update it every 24h
3) Lite code ?
Thanks

please ask a specific question

updated, tough it seemed straight foreward

look into NTC, i think there's a built-in example, if not it's a very common lib with examples once added in the manager.

@dandavis You mean NTP surely...

@Majenko: good eye, that's what i meant, NTP. network time prototcol.

Start with the ESP8266WiFi "NTPClient" example.  That will teach you how you can get the "Unix Epoch" time from the internet.
That value can be fed directly into TimeLib to keep track of the time for you (indeed, TimeLib includes an NTP example for Arduino Ethernet that should help you get started).  Do that periodically (daily, hourly, whatever), and you have your time.  TimeLib can then give you the date and time as individual components (hours, minutes, etc), which you can then construct together (I'd use snprintf) to include in your MQTT message:
int len = strlen(message) + 25;
char mqttMessage[len];
snprintf(mqttMessage, len, "[%04d/%02d/%02d %02d:%02d:%02d] %s",
    year(), month(), day(), hour(), minute(), second(), message);

mqttMessage => "[2018/08/11 20:36:24] foo"


text:
How do I read addresses on multiple DS2413 1-Wire GPIO Breakouts, using the Adafruit sketch?
I am using three DS2413 1-Wire GPIO Breakouts from Adafruit connected to an ESP8266.  I tested the DS2413
 breakouts using their example sketch and it works fine for just one DS2413.  But I cannot get it to work when 2 or more DS2413s are connected.
Adafruit DS2413 Example Sketch
https://github.com/adafruit/Adafruit_DS2413/blob/master/DS2413.pde
Adafruit DS2413 Overview
https://learn.adafruit.com/adafruit-1-wire-gpio-breakout-ds2413?view=all
When I connect 2 or more DS2413s, it only blinks the LEDs connected to the 1st breakout and doesn't read the other addresses.
I made some changes to the void setup section and now I am getting the following in the serial monitor. It sees all the addresses, but it is duplicating them and the first set have "No device found on the bus!" at the end. How can I get the sketch to read all the addresses without these errors?
Serial monitor
Looking for a DS2413 on the bus
3A B2 C2 39 00 00 00 8C No device found on the bus!
3A 8E AE 39 00 00 00 2C No device found on the bus!
3A E5 B6 39 00 00 00 55 No device found on the bus!
Found a DS2413: 3A B2 C2 39 00 00 00 8C
Found a DS2413: 3A 8E AE 39 00 00 00 2C
Found a DS2413: 3A E5 B6 39 00 00 00 55

Here is what the code with my changes.
#include <OneWire.h>

#define DS2413_ONEWIRE_PIN  (4)

#define DS2413_FAMILY_ID    0x3A
#define DS2413_ACCESS_READ  0xF5
#define DS2413_ACCESS_WRITE 0x5A
#define DS2413_ACK_SUCCESS  0xAA
#define DS2413_ACK_ERROR    0xFF

OneWire oneWire(DS2413_ONEWIRE_PIN);
uint8_t address[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

void printBytes(uint8_t* addr, uint8_t count, bool newline=0)
{
  for (uint8_t i = 0; i < count; i++)
  {
    Serial.print(addr[i]>>4, HEX);
    Serial.print(addr[i]&0x0f, HEX);
    Serial.print(" ");
  }
  if (newline)
  {
    Serial.println();
  }
}

byte read(void)
{
  bool ok = false;
  uint8_t results;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_READ);

  results = oneWire.read();                 /* Get the register results   */
  ok = (!results & 0x0F) == (results >> 4); /* Compare nibbles            */
  results &= 0x0F;                          /* Clear inverted values      */

  oneWire.reset();

  // return ok ? results : -1;
  return results;
}

bool write(uint8_t state)
{
  uint8_t ack = 0;

  /* Top six bits must '1' */
  state |= 0xFC;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_WRITE);
  oneWire.write(state);
  oneWire.write(~state);                    /* Invert data and resend     */
  ack = oneWire.read();                     /* 0xAA=success, 0xFF=failure */
  if (ack == DS2413_ACK_SUCCESS)
  {
    oneWire.read();                          /* Read the status byte      */
  }
  oneWire.reset();

  return (ack == DS2413_ACK_SUCCESS ? true : false);
}

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

  Serial.println(F("Looking for a DS2413 on the bus"));

  /* Try to find a device on the bus */
  oneWire.reset_search();
  delay(250);
  while (oneWire.search(address)) {
       printBytes(address, 8);
       Serial.println(F("No device found on the bus!"));
}
  /* Check the CRC in the device address */
  if (OneWire::crc8(address, 7) != address[7])
  {
    Serial.println(F("Invalid CRC!"));
    return;
  }

  /* Make sure we have a DS2413 */
  if (address[0] != DS2413_FAMILY_ID)
  {
    printBytes(address, 8);
    Serial.println(F(" is not a DS2413!"));
    return;
  }

  while (oneWire.search(address)) {
  Serial.print(F("Found a DS2413: "));
  printBytes(address, 8);
  Serial.println(F(""));
}
}

void loop(void)
{
  /* Read */
  /*
  uint8_t state = read();
  if (state == -1)
    Serial.println(F("Failed reading the DS2413"));
  else
    Serial.println(state, BIN);
  */

  /* Write */
  bool ok = false;
  ok = write(0x3);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
}

I was able to get the ESP8266 to read all DS2413 devices without errors as well as blink each LED connected to the DS2413, individually, down the chain.
Here are animations of it working.

I owe all the credit to mortonkopf on Github. His sketch DS2413_button_array_test, was exactly what I needed to be able to read the addresses on all DS2413 devices connected and blink each LED. Here is a link to his OneWire_DS2413_array repo.
https://github.com/mortonkopf/OneWire_DS2413_array
Here is the code I am using to make this work.
// This sketch is based on mortonkopf's DS2413_button_array_test sketch and allows
// you to read multiple DS2413 devices and blink an LED connected to each DS2413,
// individually, down the chain.
// https://github.com/mortonkopf/OneWire_DS2413_array
//
// This sketch is an improvement on the write feature of the Adafruit DS2413
// sketch which only reads 1 DS2413 device.
// https://github.com/adafruit/Adafruit_DS2413
// https://learn.adafruit.com/adafruit-1-wire-gpio-breakout-ds2413/reading-writing-and-arithmatic

#include <OneWire.h>

/* reading pins
0x0 (B00000000) - Both pins LOW
0x1 (B00000001) - IOA = HIGH, IOB = LOW
0x2 (B00000010) - IOA = LOW, IOB = HIGH
0x3 (B00000011) - Both pins HIGH
0xFF (B11111111) - Read Failed!
*/
#define DS2413_ONEWIRE_PIN  (4) // GPIO 4 on Adafruit Feather HUZZAH ESP8266

#define DS2413_FAMILY_ID    0x3A
#define DS2413_ACCESS_READ  0xF5
#define DS2413_ACCESS_WRITE 0x5A
#define DS2413_ACK_SUCCESS  0xAA
#define DS2413_ACK_ERROR    0xFF

#define BUTTON_NO 3 //use this for size of array to store state values//

OneWire oneWire(DS2413_ONEWIRE_PIN);
uint8_t address[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

byte Button_states[BUTTON_NO];//this is the array of button states//

void printBytes(uint8_t* addr, uint8_t count, bool newline=0)
{
  for (uint8_t i = 0; i < count; i++)
  {
    Serial.print(addr[i]>>4, HEX);
    Serial.print(addr[i]&0x0f, HEX);
    Serial.print(" ");
  }
  if (newline)
  {
    Serial.println();
  }
}

byte read(void)
{
  bool ok = false;
  uint8_t results;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_READ);

  results = oneWire.read();                 /* Get the register results   */
  ok = (!results & 0x0F) == (results >> 4); /* Compare nibbles            */
  results &= 0x0F;                          /* Clear inverted values      */

  oneWire.reset();

  // return ok ? results : -1;
  return results;
}

bool write(uint8_t state)
{
  uint8_t ack = 0;

  /* Top six bits must '1' */
  state |= 0xFC;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_WRITE);
  oneWire.write(state);
  oneWire.write(~state);                    /* Invert data and resend     */
  ack = oneWire.read();                     /* 0xAA=success, 0xFF=failure */
  if (ack == DS2413_ACK_SUCCESS)
  {
    oneWire.read();                          /* Read the status byte      */
  }
  oneWire.reset();

  return (ack == DS2413_ACK_SUCCESS ? true : false);
}

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

  Serial.println(F("Looking for a DS2413 on the bus"));
}

void loop(void) {
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !oneWire.search(address)) {
    Serial.println("");
    Serial.print("No more addresses.\n");
    oneWire.reset_search();
    delay(50); //was 250
    return;
  }
  Serial.println("");
  Serial.print("R=");
  for( i = 0; i < 8; i++) {
    Serial.print(address[i], HEX);
    Serial.print(" ");
  }

  if ( OneWire::crc8( address, 7) != address[7]) {
      Serial.print("CRC is not valid!\n");
      return;
  }

  if ( address[0] != DS2413_FAMILY_ID) {
      Serial.print("Device is not a DS2413 family device.\n");
      return;
  }

// Blink each LED connected to the DS2413 one at a time
  bool ok = false;
  ok = write(0x1);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
  ok = write(0x2);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(200);
///////////////////

uint8_t state = read();
  const int IOA = 0x1;
  const int IOB = 0x2;

  if (state == -1)
  {
    Serial.println(F("Failed reading the DS2413"));
  }
  else
  {
    if (state & IOA)
    {
       Serial.print("   A");
    }
    if (state & IOB)
    { //can use this IO if needed to perfom tasks
        Serial.print("   B");
    }
  }

}

Here is a link to the Gist I created for this sketch.
https://gist.github.com/orbitrod/51eb10c1a88f5747dc79298030e4480c

You have two detection loop in your setup function.
This one can be safely deleted as for each detected device it will print the error message
while (oneWire.search(address)) {
   printBytes(address, 8);
   Serial.println(F("No device found on the bus!"));

}


text:
How do I set a 25 kHz PWM signal on an ESP-WROOM-32?
I want to control a single pin of an ESP-WROOM-32 to have a 25 kHz PWM signal. How do I do that in Arduino Studio? I compiled a "hello world" program for such a device successfully in Arduino Studio, now what steps do I need to take? (Other libraries? Source Code?)
FYI: I'd like to do quite the same as provided in Set PWM frequency to 25 kHz but not on an AVM micro-controller but an ESP32. There are tons of explanations for original Arduinos and ESP8266s using bit banging in various forms. But how do I do that on an ESP-WROOM-32 using no bit banging but built in PWM?
Background: I'd like to control a standard 12V PWM fan with this signal. As far as I learned I just can connect a pin with the PWM input of the fan. I just don't seem to be able to figure out how to produce such high frequent PWM signals on an ESP32 :-/ Please help!

you said that you compiled a "hello world" program for the device .... you did not say if you were successful in loading the program into the device and running it ..... did you run the "hello world" program successfully on the device?

Sure I did. If that would be a problem, I would have asked a different question.

why do you use Arduino Studio? you were really successful in installing esp32 core package into that discontinued IDE?

It is discontinued??? Yes, in the meanwhile I downloaded the Espressif Toolchain. ledc seems to originate from there, I guess. My first I've to solve the issues with the circuit before I can attempt anything more with any software. (See below.) I'll get to that next weekend.

It is very simple to set up a PWM signal at any frequency you desire, with any resolution you desire, provided you don't exceed the maximum 'bandwidth': the frequency multplied by the resolution must be less than half the clock speed of the device.
The full explanation with relation to the ESP-IDF is available here. The article explains the intricacies of all the channels and their configurations. I must confess I have not read it all, because my application was very basic.
In setup(), the code required to instantiate a PWM signal on channel chan at frequency freq, with a resolution of bit_num bits is:
double ledcSetup(uint8_t chan, double freq, uint8_t bit_num)

The code to attach the channel chan to an output pin pin is:
void ledcAttachPin(uint8_t pin, uint8_t chan)

Within loop(), or otherwise, inflict a duty cycle duty to a given channel chan using:
void ledcWrite(uint8_t chan, uint32_t duty)

I recommend perusing esp32-hal-ledc.c in the core files you installed that enabled you to program the ESP32 in Arduino Studio. You don't need to include any files to get the above functionality, but it's always good to know a bit about what goes on behind the scenes.
A few things to note, if reading through the core code is too much:

chan can only be between 0 and 15, and the function will return 0 if you try an number outside these bounds;
you can't attach the PWM output to all of the GPIO pins, as some are input only and others might have secondary functions that you need;
duty is a 32-bit type but the maximum value is determined by the resolution you used for bit_num. For example, if bit_num is 8 then the range of duty is from 0 to 255. I don't know what happens if you put higher number: the duty may stay at 100%,  or the duty may be bitmasked such that writing 256 is the same as  0, 257 is 1, etc.

Once you have mastered this, the ESP32 includes 'fading' functionality, whereby the duty cycle changes from x% to y% in z milliseconds. There are a number of tutorials on the internet for such a thing.
FINAL NOTE:
If you haven't already, take a look at Intel's PWM fan specs. It states that you need an open-collector or open-drain source provided, in your case, by the ESP32. There's a chance that the PWM pin is pulled up to 5.25V within the fan; this will hurt the ESP32 if you just wire the two together. Likewise, the Tachometer output is pulled all the way up to 12V. This will kill the ESP32 if you wire it directly to the fan.

Thank you very much for the kindness of helping me. Looks good! I found documentation about LEDC but not for the Arduino platform. One question: I've seen many people connecting the output pin directly to the PWM input of the fan. Therefor I've done likewise. In order to be very careful I used a 220 Ohm resistor in between the fan and the ESP32 as I was wondering if that really is the way of doing it. Now I'm reading about this open-drain principle you're talking about. I don't understand that right now. I'm going to read more about it before it makes sense to ask a question.

BTW: The link to the fan specs doesn't work.

Edited for working link.

@RegisMay Have a look at the Wikipedia entry for Open Collector. It's the same as an Open Drain, but for a transistor rather than a MOSFET: transistors have collectors, emitters and bases while FETs have drains, sources and gates.

I have. I just don't (yet) understand the concept. I understand the physical principles, but not (yet) how and why these are used as I'm lacking sufficient knowledge about the use cases and what problems will be solved exactly. But I'm working on that.

open drain just means it connects and disconnects GND, instead of blinking a positive voltage.

Yes, I understand the basic principle, but the things are not clear enough to me to actually understand how to build the final circuit myself including selecting necessary resistors and their values. Thank you for now, I'll do some reading and then I will get back to this project next weekend.

@RegisMay Did you get this working?

I know it is an old topic, but at the moment I'm also busy with it.
To be sure the ESP32 doesn't get to much voltage from the pwm input, you have to measure on the PWM input if the signal is not above 3V3, otherwhise you need a resistor divider or work with a transistor in between to pull the signal down. Mine is around 3V3 so I can directly connect the ESP32 to the fan, but just like you I put a serie resistor (330) in between for a bit protection. If this input is around 5.25 V and you connect it to the ESP32, it will probably not directly go broke, but this depends on the input resistance of the fan and how much current the internal protection diode can take in the ESP32.
For the tacho signal, it is very simple, just connect it with a pullup resistor (10K) to the desired voltage you want. In my case I will connect it to 3V3 because the ESP32 is working on 3V3. The fan controller pulls it down if rotating.
I use this schematic as guide,
PWM Input:

Tacho open collector output:

website:
Fan controller
Hope this helps, just as reference.

As a matter of fact I still have not completed this project yet. I needed to focus on different things till now, but I will definitively continue on this in near future. Therefore thank you very much for this response!


text:
Arduino Uno - How to write personal data in NTAG213 using RFID-RC522
I am trying to write some data in NTAG213 sticker with this code:
#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

// Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
   return;
}

// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
  return;
}

Serial.print(F("Card UID:"));    //Dump UID
for (byte i = 0; i < mfrc522.uid.size; i++) {
   Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
   Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print(F(" PICC type: "));   // Dump PICC type
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));

byte buffer[34];
byte block;
MFRC522::StatusCode status;
byte len;

 Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
 // Ask personal data: Family name
 Serial.println(F("Type Family name, ending with #"));
 len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
 for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

 block = 1;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("PCD_Authenticate() success: "));

 // Write block
 status = mfrc522.MIFARE_Write(block, buffer, 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("MIFARE_Write() success: "));

 block = 2;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }

 // Write block
 status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("MIFARE_Write() success: "));

 // Ask personal data: First name
 Serial.println(F("Type First name, ending with #"));
 len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
 for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

 block = 4;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }

 // Write block
 status = mfrc522.MIFARE_Write(block, buffer, 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 5;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
   }

   // Write block
   status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
   if (status != MFRC522::STATUS_OK) {
     Serial.print(F("MIFARE_Write() failed: "));
     Serial.println(mfrc522.GetStatusCodeName(status));
     return;
   }
   else Serial.println(F("MIFARE_Write() success: "));

   Serial.println(" ");
   mfrc522.PICC_HaltA(); // Halt PICC
   mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
}

With the tag and card included in the module (RC522) this code works fine:

With the NTAG213 sticker the code doesn't work:

I need to write data in this stickers, how can I do that?

I also tried to use this code, thank you for your answer but I would like to write data to NTAG213 NFC tags from serial monitor. First code (example code from libary) works with serial monitor. How we can write data from serial monitor?

The one that comes with RC552 is MiFare Classic 1K
And the programming running is for the same.
Ntag213 is MiFare Ultralight C, which requires different type of programming..
Try this one
/* mifare ultralight example (25-02-2018)
 *
 *   RFID-RC522 (SPI connexion)
 *
 *   CARD RC522      Arduino (UNO)
 *     SDA  -----------  10 (Configurable, see SS_PIN constant)
 *     SCK  -----------  13
 *     MOSI -----------  11
 *     MISO -----------  12
 *     IRQ  -----------
 *     GND  -----------  GND
 *     RST  -----------  9 (onfigurable, see RST_PIN constant)
 *     3.3V ----------- 3.3V
 *
 */

  #include <SPI.h>
  #include <MFRC522.h>

  #define SS_PIN          10
  #define RST_PIN         6

  MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
  MFRC522::StatusCode status; //variable to get card status

  byte buffer[18];  //data transfer buffer (16+2 bytes data+CRC)
  byte size = sizeof(buffer);

  uint8_t pageAddr = 0x06;  //In this example we will write/read 16 bytes (page 6,7,8 and 9).
                            //Ultraligth mem = 16 pages. 4 bytes per page.
                            //Pages 0 to 4 are for special functions.

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  Serial.println(F("Sketch has been started!"));
  memcpy(buffer,"HELLO WORLD! ;-)",16);
}

void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
    return;

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
    return;

  // Write data ***********************************************

  for (int i=0; i < 4; i++) {
    //data is writen in blocks of 4 bytes (4 bytes per page)
    status = (MFRC522::StatusCode) mfrc522.MIFARE_Ultralight_Write(pageAddr+i, &buffer[i*4], 4);
    if (status != MFRC522::STATUS_OK) {
      Serial.print(F("MIFARE_Read() failed: "));
      Serial.println(mfrc522.GetStatusCodeName(status));
      return;
    }
  }
  Serial.println(F("MIFARE_Ultralight_Write() OK "));
  Serial.println();

  // Read data ***************************************************
  Serial.println(F("Reading data ... "));
  //data in 4 block is readed at once.
  status = (MFRC522::StatusCode) mfrc522.MIFARE_Read(pageAddr, buffer, &size);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Read() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  Serial.print(F("Readed data: "));
  //Dump a byte array to Serial
  for (byte i = 0; i < 16; i++) {
    Serial.write(buffer[i]);
  }
  Serial.println();

  mfrc522.PICC_HaltA();

}


text:
Device Security - EEPROM data
I'm writing code for Arduino that I plan to distribute. But I worry about piracy (the .HEX can extracted from the board and reuploaded to another).
With that in mind, I am storing data to the EEPROM.
Since I am storing data to the EEPROM, can the data be extracted in some way?

You can set the lock fuses to prevent people from reading the flash memory containing your program. I’m not sure if these lock fuses will also protect the eeprom? You could add some very simple encryption. I’ve heard of companies XORing the data with a secret byte.

the only way to protect your program is to not distribute it. .... if someone really wants to copy your program, and they have physical access to the device, then they will find a way to copy the program .... even if it is encrypted, they do not have to decrypt it to copy it

IMHO, due to the amount of code you can fit on an AVR, I (or any coder) can recreate a sketch from hand in a few days (worst-case). The idea is the idea, not the code.

@gre_gor - OP is asking if the EEPROM can be secured, not the firmware

Nothing is 100% secure. For example, EEPROM and flash can be read using techniques like Scanning Probe Microscopy & Scanning Electron Microscope, even if the security bit is set. IMO, the goal to safely securing your data is to make it extremely hard. You should take a look at the ATAES132a from MicroChip.

The first device in the AES family, the ATAES132A, is a high-speed, high-security, 32K Serial EEPROM that enables authentication and confidential nonvolatile data storage

It also boast a tamper resistant hardware

The ATAES132A device contains physical security features to prevent an attacker from determining the
  internal secrets. ATAES132A includes tamper detectors for voltage, temperature, frequency, and light, as
  well as an active metal shield over the circuitry, internal memory encryption, and other various features.
  The ATAES132A physical design and cryptographic protocol are designed to prevent or significantly
  complicate most algorithmic, timing, and side-channel attacks.


text:
Nema 17, Arduino Uno and stepper motor drive ~2H42B
I tried running Nema 17 stepper motor using the drive in the pic below (not the basic L298N drive, which BTW I successfully used to rotate the motor) .
Could any of you review my existing connections and guide me to complete the remaining ones?
Existing Arduino Uno, Nema 17 motor and drive setup:

Existing connections to Drive from left to right:

Thick yellow wire (0v) from power adapter along with a thin black wire (Ground) from Arduino
Thick red wire (12v +) from power adapter
Green wire (A+) from stepper motor
Black wire (A-) from stepper motor
Red wire (B+) from stepper motor
Blue wire (B-) from stepper motor

What I am missing is connections to PUL, DIR, VCC and ENA. I could put the 4 wires from Arduino D8 to D11 respectively but is that enough? Is there an Arduino sketch I could refer to after the connections are ready?

Connect:

VCC to Arduino 5 V
ENA either directly to VCC or to an Arduino pin (for optional enable driver software control - active high).

Pulse (steps) and direction to Arduino GPIO.
Have a look here Arduino forum Simple Stepper Program - I think you will find what you are looking for.

Ok... been abused by « enable signal negative » in the chart page 5...

Here is the user manual for the BH-MSD-2A Micro stepping driver.
Page 5 shows the two tables giving the connections:

You have already connected P2, and that leaves P1 remaining.
The timing diagram below shows the state of the, PUL, DIR and ENA signals required
.
So, the ENA input can either be held high, by connecting to VCC or connected to a digital output pin of the Arduino, to provide  basic ON/OFF control.
This thread, arduino uno with stepper motor, the OP is using a very similar controller to yours, except that theirs is the 6 A version (BH-MSD-6A). Their code, in the thread has a lot of unnecessary code, and apparently has a number of issues. A stripped down version, of the same code, is as follows:
//arduino code
//
#include <TimerOne.h>
#include <EEPROM.h>

int rpm;
int initial_rpm;
int dutycycle_time=0;
int stepper_Enable=5; //STEPPER MOTOR  ENABLE PIN : PUL-
int stepper_Pulse=6;  // STEPPER MOTOR PULSE PIN :  PUL-

int address_eeprom=0;

void displayNumber(int);
void lightNumber(int);

void setup()
{

  Timer1.attachInterrupt( timerIsr ); // attach the service routine here
  pinMode(stepper_Pulse,OUTPUT); // Analog pin A2 is used for ENABLING the steeper motor
  pinMode(stepper_Enable,OUTPUT); // Analog pin A2 is used for DIRECTION the steeper motor
  digitalWrite(stepper_Pulse,HIGH);
  digitalWrite(stepper_Enable,LOW);

  rpm=EEPROM.read(address_eeprom);
}

void loop()
{

  while(digitalRead(stepper_Enable)==HIGH){
     int cycle_freq=(1600/60)*rpm;
     int dutycycle_freq=2*cycle_freq;
     int dutycycle_time=1000000/dutycycle_freq;
      Timer1.initialize(dutycycle_time); // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
      if(analogRead(A3)==LOW )  // STOPPING THE STEPPER MOTOR
       {
         digitalWrite(stepper_Enable,LOW);

       }

  }

  while(digitalRead(stepper_Enable)==LOW)
  {
    int initial_rpm=rpm;
     EEPROM.write(address_eeprom,rpm);

      if(analogRead(A0)==LOW && rpm<300 ) ///increasing speed of stepper motor
    {
          rpm=rpm+1;
         // delay(100);
     }
    if(analogRead(A1)==LOW && rpm>0) ///decreasing speed of stepper motor
    {
          rpm=rpm-1;
         // delay(100);
    }
    if(analogRead(A2)==LOW ) //STARTING THE STEPPER MOTOR
    {
     digitalWrite(stepper_Enable,HIGH);
    }
  }
  if(initial_rpm!=rpm){
    address_eeprom=address_eeprom+1;
  }

}

void timerIsr()
{
  // Toggle LED
  digitalWrite( stepper_Pulse, !digitalRead( stepper_Pulse ));
}

Note that while this should get you started, as the OP states in the thread there are issues with it, that will need fixing.

(I have to go now to fix some Marlin firmware, but I'll come back to this answer later)


text:
NodeMCU - use flash button as input in loop()
I couldn't find a proper answer on the net so I came here as a last resort.
So I want to use the FLASH button as an input in the loop() method.
Is there a way the check if it's pressed or not?

The Flash button on NodeMCU is connected between io 0 and ground.  You can use it as a button.  Set pinMode(0, INPUT_PULLUP) and you will read io 0 LOW if the button is pressed.
NodeMCU schema
To put the module in flashing mode, first the Flash button must be held and the Reset button pushed, only then should the Flash button be released. Normally, the reset to flashing mode is done automatically by esptool before uploading over USB. This uses the circuit connected to serial RST and DTS lines.

I recommend you EasyButton library, you can use pin 0 (D3) in NodeMCU, if you want use a external button module, you can wire your button between D3 pin and GND.
https://github.com/evert-arias/EasyButton
#include <EasyButton.h>

// Arduino pin where the button is connected to.
#define BUTTON_PIN 0

// Instance of the button.
EasyButton button(BUTTON_PIN);

// Callback function to be called when the button is pressed.
void onPressed() {
    Serial.println("Button has been pressed!");
}

void setup() {
    // Initialize Serial for debuging purposes.
    Serial.begin(115200);
    // Initialize the button.
    button.begin();
    // Add the callback function to be called when the button is pressed.
    button.onPressed(onPressed);
}

void loop() {
    // Continuously read the status of the button.
    button.read();
}

Just to complete the other answers, here is sample Lua code to help you get started
inpin=3 -- Select input pin - GPIO0

function pressed()
    print("PRG Pressed")
end

gpio.mode(inpin,gpio.INT,gpio.PULLUP)
gpio.trig(inpin,"down",pressed)

When you press the "Flash" or "PRG" button "PRG Pressed" is printed. You can perform additional magic in the function.
Above sample code adapted from this blog post
I am using this board from MakerFocus

I often use it as an input if I need a button input on my boards. After the initial boot sequence it is just another I/O pin.

The top answer only works for me when the Nodemcu is connected via a serial port and the "Serial Monitor" is turned on.  (It was frustrating because it would always work whenever I connect up the serial monitor for debugging and then stop working when I disconnect it to run standalone).   I think this is because the Nodemcu connects GPIO0 and GPIO16 to the UART's RTS and DTR signals.   The buttons only work when those control lines are in the right states and that might not always be the case.   See the third page in the schematic at https://github.com/nodemcu/nodemcu-devkit-v1.0/blob/master/NODEMCU_DEVKIT_V1.0.PDF


text:
How to parse 20180810T143000Z to time_t
What is the shortest/most elegant way (i.e. use existing lib functions) to parse a string in the form of 20180810T143000Z to a time_t? Note that the literal always represents a UTC timestamp.
I started parsing the string and assigning values to a struct tm *tm in order to do a mktime(tm) at the end. That feels overly complicated, though.

Which time library do you use? I would copy each needed character with an array index to a buffer and convert it to year, month, day, hours, minutes. After that I would use the library to convert that into a time_t for the number of seconds since 1970. Straightforward is not overly complicated in my opinion. Can you show what you have so far? sscanf might work, but some think that is not a elegant function.

Parsing the string really is the only way. However there are many ways of doing it.
My preferred method is to first check that the format is correct, by looking for the T and Z being in the right place:
if (timeString[8] == 'T' && timeString[15] == 'Z') {
    ... parse in here
}

And the parsing is just making numbers with multiplication:
int year = (timeString[0] - '0') * 1000 +
           (timeString[1] - '0') * 100 +
           (timeString[2] - '0') * 10 +
           (timeString[3] - '0');

You can clean things up with a macro if you like:
#define NUM(off, mult) ((timeString[(off)] - '0') * (mult))

Then:
int year =   NUM(0, 1000) + NUM(1, 100) + NUM(2, 10) + NUM(3, 1);
int month =  NUM(4, 10)   + NUM(5, 1);
int day =    NUM(6, 10)   + NUM(7, 1);
int hour =   NUM(9, 10)   + NUM(10, 1);
int minute = NUM(11, 10)  + NUM(12, 1);
int second = NUM(13, 10)  + NUM(14, 1);

And then, yes, put them in a struct tm (or directly assign them calculation results without using the intermediate variables) and call mktime().

@Juraj Yeah, but you haven't included any answer in your answer, only a block of code ;)

"first check that the format is correct" - a valid point but what would you do in the else branch?

I can't tell you that. It depends on the rest of your program. The answer may be "nothing", or it may be "tell the user", it "request a new timestamp", or any number of other things.

@Majenko sorry, I was a little unspecific. I'm still getting familiar with Arduino (as you can tell). What I meant was that in most other environments/platforms I'm familiar with I'd probably throw an exception. So, I believe returning -1 and handle this outside the function will make this more robust.

@MarcelStör Sure - if that's what you want to do.

#include <Time.h>

void setup() {

  Serial.begin(115200);

  char buff[] = "20180810T143000Z";
  for (int i = 0; i < sizeof(buff); i++) {
    buff[i] = buff[i] - '0';
  }
  int yr = buff[0] * 1000 + buff[1] * 100 + buff[2] * 10 + buff[3];
  if (yr > 99)
    yr = yr - 1970;
  else
    yr += 30;
  TimeElements tm;
  tm.Year = yr;
  tm.Month = buff[4] * 10 + buff[5];
  tm.Day = buff[6] * 10 + buff[7];
  // 8 T
  tm.Hour = buff[9] * 10 + buff[10];
  tm.Minute = buff[11] * 10 + buff[12];
  tm.Second = buff[13] * 10 + buff[14];

  time_t t = makeTime(tm);

  sprintf(buff, "%02d%02d%02d %02d%02d%02d", year(t), month(t), day(t), hour(t), minute(t), second(t));

  Serial.println(buff);

}

void loop() {

}

You can install TimeLib in Library Manager. It works on all Arduino platforms.

Yep, I did look into strptime but concluded it would probably not work w/o delimiters. Therefore, I didn't even try.

In buff[i++] * 10 + buff[i++], the order of evaluation of the i++ is unspecified. It may work as expected with any particular combination of compiler version and settings, and fail on the next one. gcc 5.4 warns me that “operation on ‘i’ may be undefined”. The correct way to do that is tm.Month = buff[i++] * 10; tm.Month += buff[i++];.

@EdgarBonet thanks, I just proposed this change: https://arduino.stackexchange.com/review/suggested-edits/38715

@MarcelStör, I read Edgar's comment, but this code is not some snippet, but a complete working example. I don't like edit it without testing. And I can't test it now.

@MarcelStör: What I wrote for tm.Month is valid for every instance where i++ appears more than once in the same expression.

@EdgarBonet I know, makes total sense. That's why proposed that edit. In the end it was ok to get rejected because many more lines are actually affected.

in this case the use of i++ is good. the compiler has no reason to evaluate some subexpression with i++ later in expression before some subexpression with i++ earlier in expression. I will change it. I saw the warning, but I had limited time for this.

Re “the compiler has no reason to evaluate [...]”: it also has no reason to evaluate them in the order you expect! Please, learn about sequence points in C++ before making such wrong assumptions. Note specifically that “Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.”

Here is yet another way to convert the time stamp string to time_t. There are several great answers here already, but you may want to compare binary file sizes. This sketch's is 3884 bytes (IDE Version 1.0.6.2, GCC 4.2.1).
#include <Time.h>
TimeElements myTimeElements;
char timeString[] = "20180810T143000Z";

void setup(){

  Serial.begin(9600);

  myTimeElements.Year = CalendarYrToTm((timeString[0] - '0') * 1000 + (timeString[1] - '0') * 100 + (timeString[2] - '0') * 10 + (timeString[3] - '0'));
  myTimeElements.Month = (timeString[4] - '0') * 10 + (timeString[5] - '0');
  myTimeElements.Day = (timeString[6] - '0') * 10 + (timeString[7] - '0');
  myTimeElements.Hour = (timeString[9] - '0') * 10 + (timeString[10] - '0');
  myTimeElements.Minute = (timeString[11] - '0') * 10 + (timeString[12] - '0');
  myTimeElements.Second = (timeString[13] - '0') * 10 + (timeString[14] - '0');

  // Assemble time elements into time_t.
  time_t t = makeTime(myTimeElements);

  // Print out the contents of "t" one "piece" at a time using the "time_t" functions.
  Serial.println(year(t));
  Serial.println(month(t));
  Serial.println(day(t));
  Serial.println(hour(t));
  Serial.println(minute(t));
  Serial.println(second(t));

}

void loop(){}

For the sake of completeness here's my "answer" working with Strings rather than char[].
time_t convertToTime(String calTimestamp) {
  struct tm tm;
  Serial.println("Parsing " + calTimestamp);
  String year = calTimestamp.substring(0, 4);
  String month = calTimestamp.substring(4, 6);
  if (month.startsWith("0")) {
    month = month.substring(1);
  }
  String day = calTimestamp.substring(6, 8);
  if (day.startsWith("0")) {
    month = day.substring(1);
  }
  tm.tm_year = year.toInt() - 1900;
  tm.tm_mon = month.toInt() - 1;
  tm.tm_mday = day.toInt();
  tm.tm_hour = calTimestamp.substring(9, 11).toInt();
  tm.tm_min = calTimestamp.substring(11, 13).toInt();
  tm.tm_sec = calTimestamp.substring(13, 15).toInt();
  return mktime(&tm);
}

That poor poor heap. I feel for it...

This should work, but note that every call to the substring() method allocates a new String on the heap. Even if you have plenty of free memory, the multiple calls to malloc() and free() can make this quite inefficient.

@EdgarBonet yes, I know, point taken. What is fed into this function is the (partial) result of an HTTP response readStringUntil(). I guess it'd be more efficient to first convert calTimestamp into a char[]?

Quite likely. The String method c_str() returns the internal char * pointer, so no real conversion is needed.

This is not complete without sscanf.
I took the sketch by @Juraj and declared seperate integers to be sure that every %d would match with an integer.
#include <Time.h>

void setup() {

  Serial.begin(115200);

  char buff[] = "20180810T143000Z";

  TimeElements tm;

  int yr, mnth, d, h, m, s;
  sscanf( buff, "%4d%2d%2dT%2d%2d%2dZ", &yr, &mnth, &d, &h, &m, &s);

  tm.Year = yr - 1970;
  tm.Month = mnth;
  tm.Day = d;
  tm.Hour = h;
  tm.Minute = m;
  tm.Second = s;

  time_t t = makeTime(tm);

  sprintf(buff, "%02d-%02d-%02d %02d:%02d:%02d", year(t), month(t), day(t), hour(t), minute(t), second(t));

  Serial.println(buff);
}

void loop() {
}

Marcel Stör, there are now four good solutions. In my opinion they are equally good.

Alternative to my first answer would be to use standard C functions from time.h and sscanf. C function strptime can't parse the timestamp without delimiters. But sscanf can parse your input.
#include <time.h>

void setup() {

  Serial.begin(115200);

  const char* buff = "20180810T143000Z";

  tm tms;
  sscanf(buff, "%04d%02d%02dT%02d%02d%02d", &(tms.tm_year), &(tms.tm_mon), &(tms.tm_mday), &(tms.tm_hour), &(tms.tm_min), &(tms.tm_sec));
  tms.tm_year -= 1900;
  tms.tm_mon -= 1;
  tms.tm_isdst = 0;
  time_t t = mktime(&tms);

  Serial.println(ctime(&t));
}

void loop() {
}

In AVR "%02hhd" must be used because the corresponding members in struct tm are int8_t.

The %d is for an integer, also for an avr microcontroller. The difference is that the TimeLib TimeElements does not use integers, but bytes.

@Jot, this is C time.h

Yes, for the C time.h the tm_year and other elements are all integers. Also for a avr microcontroller the %d matches an integer. The %d expects an 'int', not a 2 or 4 byte variable.

%d on AVR works for sprintf, but sscanf read wrong without hh. try it

I tried it in a number of different ways with different data on the stack, using arduino 1.8.5 with arduino uno board. A 'int' is two bytes, a 'short int' is also two bytes and 'short short int' does not exist. Format "%d" works with a 'int', and "%hd" seems to do the same as the "%d". Format "%hhd" reads a signed byte. Everything is as I remember it, no weird things. If you can prove that you are right with a sketch, can you start a new topic for that?

@Jot, it is only when I use the tm struct members as sscanf parameters. The warning is '%d' expects argument of type 'int*', but argument 4 has type 'int8_t* {aka signed char*}'. and the scanned values are wrong. With regular int variable the hh is not needed.

AVR has int8_t          tm_hour

Now I see it, the tm for avr has int8_t and int16_t elements. Sorry, they are indeed not all integers for avr. I did not know that. Thanks. Do you agree that %d in sscanf matches 'int' for avr? I see that you have removed that confusing last sentence.

I used hh because a compiler warning saying that it is int8_t and it helped to get correct data. I opened time.h, but it was for samd or for esp and there was int. I had limited time so I didn't investigate it further than. Of course %d is for int. I tested int and removed the note. Then I discovered that in tm really is unt8_t in tm.

String datetimestr = "20180810T143000Z";
int splitted = datetimestr.indexOf("T");
String datestr = datetimestr.substring(0, splitted); //20180810
String timestr = datetimestr.substring(splitted + 1, datetimestr.length() - 1); //143000

The question was how to parse the string to a time_t, and you are not answering it.


text:
Unable to Configure MQTT Client ID using Adafruit MQTT Library
I am utilizing the MQTT library that Adafruit has created, located here, and the library itself works wonderfully - however I am finding myself unable to edit the Client ID or configure the PINGRESP. The code that I am currently using can be seen below -
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, "10.116.10.191", 1883);

When the client connects to the MQTT Broker the client ID turns into a random string of letters, numbers, and symbols, as seen below -
1534023607: Client ]7llG5K6J4=^tPHJHqgTUFc<Ep^m3vJ`4vSL2oB<cO[^_chw[GBp]v3smagpOqWS has exceeded timeout, disconnecting.
1534023608: New connection from 10.116.7.21 on port 1883.
1534023608: New client connected from 10.116.7.21 as ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu (c1, k300).
1534023608: Sending CONNACK to ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu (0)
1534023608: Received SUBSCRIBE from ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu
1534023608:     quantity (QoS 0)
1534023608: ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu 0 quantity
1534023608: Sending SUBACK to ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu

After a duration of time has passed the client exceeds the time out and disconnects.. Any advice on overcoming this obstacle would be greatly appreciated. I've tried the following for changing the ClientID, per the client constructor to the MQTT broker -
Adafruit_MQTT_Client(Client *client, const char *server, uint16_t port,
   const char *cid, const char *user, const char *pass):

WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, "10.116.10.191", 1883, "Rear-Controller");

This was the result of adding the clientID, ("Rear-Controller"), after the MQTT Broker port # -
 New client connected from 10.116.7.21 as GFONMktFXFSG1rARE@JWCRv@P^XwLifdo<rCg]YFs4Ndf_>2_XIsjFsAtS08Cf\: (c1, k300, uRear-Controller)

The Client ID is expected to be stored in flash memory (it is read using pgm_read_byte). However, on the Arduino, unless told otherwise it first copies the string literal into RAM.  That means that the function is getting the address of the string in RAM, not in flash, and using it as if it were the address in flash, and that gets gibberish.
You need to force it to be in flash by creating a PROGMEM string:
const char clientid[] PROGMEM = "clientfoo";
Adafruit_MQTT_Client mqtt(&client, "10.116.10.191", 1883, clientid);

I was met with this error:
No matching function for call to 'Adafruit_MQTT_Client::Adafruit_MQTT_Client(WiFiClient*, const char [14], int, const __FlashStringHelper*)'

Not having your code to test I did wonder if that may happen. You may need to cast it to a const char * as well. Or have it separate as PROGMEM.

I converted it to a const char and it successfully compiled, however it still had the gibberish.. That only seems to effect - "(c1, k300, uRear-Controller)"

@HobarGJ See my edit. That should work.

While that did successfully compile, I am still getting the string of gibberish when connecting to the MQTT Broker. The end, "(c1, k300, uRear-Controller)", is correct and reflects the changes though. Would uploading more of my code be any easier for you?

I'd suggest switching to PubSubClient instead. It works.

@HobarGJ i agree with Majenko the MQTT-API said "If the MQTT library requires that you set a client ID then use a unique value like a random GUID.  Most MQTT libraries handle setting the client ID to a random value automatically though." i cannot see your library can require to set client ID, i also using PubSubClient, that works to me sir.


text:
Regain WIFI connectivity
I wrote a code to be implemented in a SONOFF device (ESP8266 chip).
My question is regarding disconnection due to failure/ power fail in wifi network - when such event happens, does wifi connectivity try to reconnect or to over come this possibility - should I enter  inside void loop () to verify wifi connectivity ?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// GPIOs on SONOFF board
int LED_SONOFF = 13;
int REL_SONOFF = 12;
int PIN_SW = 14;

const char* ssid = "Home";
const char* password = "12345678";
const char* mqtt_server = "192.168.2.113";
int last_sw_state = 0;

WiFiClient espClient;
PubSubClient client(espClient);

char msg[50];
const char* clientID = "Sonoff";
char *client_temp = "HomePi/Dvir/Windows/";
const char* outTopic = "HomePi/Dvir/Messages";
const char* outTopic2 = "HomePi/Dvir/Windows/ESP32";
const char* inTopic [strlen(client_temp) + 3];
const char* inTopic2 = "HomePi/Dvir/Windows/All";

String clock;

void start_wifi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

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

  for (int i=0; i<3; i++){
    digitalWrite(LED_SONOFF,LOW);
    delay(50);
    digitalWrite(LED_SONOFF,HIGH);
    delay(50);
  }
}

My question is regarding disconnection due to failure/ power fail in
  wifi network - when such event happens, does wifi connectivity try to
  reconnect or to over come this possibility

use WiFi.setAutoReconnect(true); when initializing WiFi
other useful option is WiFi.setAutoConnect(). It controls if the esp8266 next time starts the WiFi connection with remembered setting, before your sketch starts.

at the end of void start_wifi() or void loop()?

at start when connecting


text:
Doubt using character array
I'm trying to make a led sign with a WS2812b ledstrip, using the FastLed library (by the way, this is a great library!), I'm already able to show a text (so far only one, which I leave saved in an array of characters at the beginning of the program), but I would like to be able to change this text using the serial port of the Arduino, and here is the problem:
When setting the text to be displayed in the array of LEDs, the function that I should use is:
ScrollingMsg.SetText ((unsigned char *) TxtDemo, sizeof (TxtDemo) - 1);}

Where TxtDemo is a variable type char array.
Until here all is right, as I commented I can show the text, but at the time of receiving the data from the serial port and save them in the char array TxtDemo, when I use the function sizeof(TxtDemo), the value I get remains with the original size (quite understandable) of this array.
For example: If the initial text was (saved in TxtDemo):
"Hello world", the sizeof() function, returns "11",
But when I pick up what I want to show on the serial port and store it in the variable TxtDemo, there's no way I can alter the size of that array. So ... what can I do? What do you recommend me to do?

Arrays in C are fixed. sizeof() will always give the amount of allocated memory for the array.
Instead, you should be using strlen() to get the number of characters up to (but not including) the terminating NULL character at the end of the string.
ScrollingMsg.SetText ((unsigned char *) TxtDemo, strlen(TxtDemo));

Make sure that you have enough space in your initial array to store the longest string you will want to send - it will not grow beyond your initial allocation. Also be sure to get the NULL character at the end of your valid text. It's too easy to forget you need to insert that after your last received character.

Thanks for the quick answer... now: how can add the null character???

I do it while reading from serial. For every character I place in the array I set the next entry to 0. Here's an example: https://majenko.co.uk/blog/reading-serial-arduino

Men... that article is, just, GREAT!!!! Thanks!!!

@k.Cyborg You might find this useful too: https://majenko.co.uk/blog/arrays-pointers-what-c


text:
How do I change the default LED pin for displaying uploading
I made a board for my project based on Arduino Pro Mini. The problem is, that I had to put the LED on pin 4 instead of pin 13.
What setting do I have to change to make pin 4 the default one? Or do I have to write my own Board Library?

The blinking while uploading makes the bootloader. Arduino Mini uses Optiboot. The source codes are on GitHub. You would need to change the pin in pin_defs.h and make the bootloader. Then flash it to the 328p with a programmer over ICSP.
Details what to change are in Greenonline's answer.

Following on from Juraj's answer:

The blinking while uploading makes the bootloader. Arduino Mini uses
  Optiboot. The source codes are on GitHub. You would need to
  change the pin in pin_defs.h and make the bootloader. Then flash it to
  the 328p with a programmer over ICSP.

The line that you need to change in pin_defs.h is line number 27:
#define LED B5

As you can see it is currently set to B5. This is the fifth bit in port B which corresponds to pin 13
Pin 4 corresponds to PORTD bit 4, so the line would become
#define LED D4

The Arduino digital pins are connected to three different banks of 8 bits, known as ports (PORTD, PORTB and PORTC`). To see their relation, refer to this table from Arduino Playground - Pins

I copied my answer as intro into this answer

Ok, thanks. I'm not sure it was necessary, unless you planned on deleting your answer. However, I've added a link back to yours to reference the quote, and it makes a bit more sense that way. Thanks again :-).


text:
How can I make a power button for my project powered by a USB powerbank?
I've solved the battery power supply issue for my Arduino project by simply connecting a USB powerbank. However, I just realised that I can't come up with a good way to add an on/off button! There doesn't seem to be a way to turn the Arduino off using software. My second solution would be to cut up the USB cable (or an extension chord) and solder a switch onto the 5V wire.
Is there a more convenient solution that I'm missing?

You could put the microcontroller into sleep-mode. Then use a button (connected to one of the interrupt pins) to wake it up.
But depending on what Arduino board you are using, and what other sensors etc you've connected to the board, this might not save that much current. For example on the UNO board the usb-to-serial converter is always on, so while your MCU is sleeping and trying to save power, the usb-to-serial continues to draw current.
But adding a switch to a usb-cable would be a lot simpler.
PS doesn't the powerbank have an on-off switch?


text:
Is SRAM erased when putting Arduino into sleep_mode_pwr_down?
Question
In the interest of reducing power consumption, I am putting the Arduino into sleep mode between taking sensor readings. However, the data from readings are stored in arrays, and must not be erased when the device enters sleep mode.
For clarity, I am using sleep_mode_pwr_down, and triggering an interrupt using the Watchdog Timer on the ATMega328 chip. See this post for a description of the different sleep modes: What are (or how do I use) the power saving options of the Arduino to extend battery life?
It would be possible to address this issue by writing data to the EEPROM, however, I am unsure whether this is necessary. The question is whether putting the device into sleep_mode_pwr_down erases the dynamic memory?

Specs / Context:
Arduino Uno (ATMega328 chip)

If not, you could use an external SRAM chip - which will provide more RAM than ATmega328 gives anyway.  You can find them with a quick google search: e.g. SRAM 1Mbit.  Standby current is well below 10 uA.

Thanks @MichaelT, it appears from some prototyping I have just done that it is indeed the case that SRAM is not erased (based on dynamic memory within the system). I plan to test this further as this seems somewhat unexpected, but will update this post with any major developments.

Generally, Atmega sleep modes do not erase RAM. Their memory is static and as long as voltage (above 2.7V I believe) is applied, data is held.
However, this also depends on how you plan to wake up the device.
If it receives a RESET, RAM is cleared and program execution starts from the beginning.

If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from sleep.

Check out the AVR's sleep modes to see which fits your application best and how to safely wake it up again

Note that, on reset, the RAM is erased by software (the libc startup code), not by hardware. You can put data in the “.noinit” section if you want to preserve it through a reset.


text:
Arduino fingerprint verification from server
I am thinking to do a hobby project related to fingerprint verification. The flow which I wanted to implement is something like below:

A user can register a fingerprint using an Arduino device
This fingerprint will be saved on a remote server so that user can be verified on some other Arduino devices
When a user tries to verify, the fingerprint will be matched against the fingerprint stored on the server

For this, I am thinking to use the Go language on the server side as an API server, MySQL/SQLite as a database system. Further, in the future, I will build a mobile application to perform some query with the server like running devices, the number of registered users, revoke users etc.
For now, I am planning to buy the following devices:

Arduino UNO
A wifi shield
A fingerprint sensor
An LCD screen

Now the question is, will the devices mentioned above will work for my setup, or I need to buy something else (Are they compatible?)
Also, is there a way to store the fingerprint on a server? I am thinking to store some kind of hash (probably RSA encrypted) of a fingerprint on a server, will it work?
Any relevant example of storing fingerprint on a server?

This question was closed as being too broad, but I don't agree that it really passes that test.

According to the adafruit driver's code, it is capable of loading and storing fingerprint templates (256byte each) from and to its flash
  uint8_t emptyDatabase(void);
  uint8_t storeModel(uint16_t id);
  uint8_t loadModel(uint16_t id);
  uint8_t getModel(void);

These functions would allow you to sync the local database of each device with a server for example or even download and test for each template individually, which would obviously be pretty slow and only viable, if you had to store more templates than the flash itself can.
You can encrypt this data before transmitting in whatever way you wish but that is a topic on its own.
Other than that your components seem to be compatible.
An idea for syncing:
Every unit should check on a fixed interval of 1 second for instance, whether the online database has changed. This may be represented by a simple counter i.e. version that increments with each change and is copied to local storage after downloading the latest changes.
So whenever an Arduino uploads a new fingerprint model or your mobile app removes a fingerprint, the counter on the server is incremented and every other device knows to update its database in case the local version is lower.
Another tip if changes happen very frequently:
Every flash memory just has so many write cycles before it dies.
If you happen to update the database a lot, you should try to minimize the stress on each fingerprint sensor's memory by assigning an arbitrary, unique id to each fingerprint and storing a local 'map' where you have stored which id on this specific device.
This way you can update only the fingerprint(s) that have actually changed.
Good luck.

Another tip if changes happen very frequently I got some FRAM so that I wouldn't have to worry too much about destroying internal EPROM. Adafruit sells some and when combined with the Extended database library, you can have a pretty strong combo.

I believe fingerprint templates must be stored on the device in order to be comparable. I might be wrong tho

@mystery I am thinking to use TCP socket, so if a device updates the fingerprint on the server, the server will inform every other device to sync fingerprint models to their local one, is this approach fine?

Sure, more complicated than polling but go ahead if it works out


text:
Return a char concatenation
My goal is to create a function that concatenate 2 chars into 1, and return it as MQTT subscribe. I get a difference between the results inside and outside the function ( I'm new to Arduino ), and I can't find why:
Code:
// Update variable below:
const char *direction = "up";
const char* clientID = "Sonoff";

//Consts
const char *client_temp = "HomePi/Dvir/Windows/";
const char* outTopic = "HomePi/Dvir/Messages";
//const char* outTopic2 = "HomePi/Dvir/Windows/ESP32";
const char* inTopic2 = "HomePi/Dvir/Windows/All";
char *inTopic;

void setup() {
  Serial.begin(9600);
//  len(create_topic(client_temp, clientID));
  inTopic = create_topic(client_temp, clientID);
  Serial.println(inTopic);
}

char *create_topic(char *chr1, char *chr2){ .   // added *
  char topic[strlen(chr1) +strlen(chr2)+1];
  sprintf(topic,"%s%s",chr1,chr2);
  Serial.println(topic);
  return topic;
}

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

}

Result ( both line should have been same):
HomePi/Dvir/Windows/Sonoff
⸮⸮,茗⸮;⸮_⸮%⸮l?⸮az⸮z⸮%⸮⸮⸮\;⸮m⸮

You cannot return a local string (e.g. topic) in C. Either use a global variable or a parameter with a reference to a local string in the caller context or use malloc()/strdup().

The concatenation is working fine in both instances.
What is wrong, though, is that you can't return a pointer to a locally declared array from a function. That array no longer exists when you leave the function.
The thing to remember with arrays is that you never pass the actual array to or from a function. All you pass is a pointer to the memory address where the array is.  If you allocate an array in a function that memory is allocated on the stack. When you return the array from the function you return an address that is (currently) within the stack.  When you leave the function all memory allocated on the stack by that function is removed, and that includes your array.
There are four ways of solving the problem - all of them have their pitfalls.

Use a global "scratch pad" array that is big enough for any concatenating you may want to do. Do your concatenation in there.
Declare your array static, which means it's allocated only once and can be returned from the function - but like the global one you have to have a fixed size.
Pass a pointer to a suitably sized array to your function to have that array used for the concatenation, and
Allocate memory on the heap using malloc().

My normal method is number 3. It's the safest and most flexible:
const char *a = "part a";
const char *b = " part b";

char all[14];
doConcat(a, b, all);

void doConcat(const char *a, const char *b, char *out) {
    strcpy(out, a);
    strcat(out, b);
}

can you be more specific for solution 3 ?

And he's using char as the return type instead of char *.

Even worse, OP tries to return a char from a char*. Your solution suggestions are on point, although malloc should b avoided on tiny Arduinos.

@Guy.D , create an array of suitable size before calling the function and just pass a pointer to it. Also look up strcat http://www.cplusplus.com/reference/cstring/strcat/

I tried also with char * - fixing my code

Even returning a char * with your current code the results are still only there by chance and are only temporary. You are accessing memory that isn't yours, and is destined to be overwritten at a moment's notice corrupting your results.

Do an experiment. Run create_topic twice and then try and print both results afterwards. Watch the corruption.


text:
Pointer memory allocation in function
I would like to know how Arduino allocate memory for pointers in function arguments.
For instance. I have this code that use 192 bytes (Arduino IDE compiler:
Global variables use 192 bytes (9%) of dynamic memory).
char alph [] = {'a', 'b', 'c','\0'}; // 4 bytes
int numb [] = {1, 2, 3, 4}; // 8 bytes
float flo [] = {1.1, 2.2, 3.3}; // 12 bytes

void fn(){
  Serial.println(alph);
  Serial.println(numb[1]);
  Serial.println(flo[1]);
}

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

void loop(){}

The following code is the same of above, but I'm using pointer to variables in arguments, that use 234 bytes (Arduino IDE compiller: Global variables use 234 bytes (11%) of dynamic memory).
char alph [] = {'a', 'b', 'c','\0'}; // 4 bytes
int numb [] = {1, 2, 3, 4}; // 8 bytes
float flo [] = {1.1, 2.2, 3.3}; // 12 bytes

void fn(char * _alph, int * _numb, float * _flo){
  Serial.println(_alph);
  Serial.println(_numb[1]);
  Serial.println(_flo[1]);
}

void setup()
  Serial.begin(9600);
  fn(alph, numb, flo);
}

void loop(){}

There is a difference of 42 bytes to use three pointers. Why? A char pointer is 1 byte, a int pointer is 2 bytes and a float pointer is 4 byte length. Do the difference must be 7 bytes?

I make it 224 not 234. However, you're forgetting one simple thing: The compiler is clever.

By the way: all pointers are 2 bytes, regardless of what they point to.

They use 192 and 224 bytes ram. I can reduce the 224 to 192 for the second sketch by adding the keyword 'const' in front of all three array declarations. The 'const' keyword give the compiler more possibilities to do clever things.

But if add 'const' to arrays I can't change it dynamically

If you want to find out what happens you’d have to look at the assembly code the compiler produces.

A char pointer is 1 byte, a int pointer is 2 bytes and a float pointer is 4 byte length. - No, a char is 1 byte, an int is 2 bytes, and a float is 4 bytes. However a pointer is always 2 bytes.

When you ask: "why?". The cheapest answer is: "why not?".
The compiler can do clever optimizations as @Majenko wrote. That is what this is about.
Even for such a small sketch, the compiler has many optimization methods to choose from. Changing a single line or adding a variable can make the compiler to choose other optimizations. It is therefor impossible to link the increased number of bytes to those extra pointers.
Sometimes the compiler can decide to keep a variable in a register instead of storing it in a memory location. Sometimes the compiler understands that a variable has a constant value and is used only once, then the compiler might not even use dynamic ram for it.
The used dynamic ram by the sketch is even more trivial, since Arduino sets the compiler to use the minimal size for the code.
Optimizing a sketch is best done with a large sketch. Your small sketch uses the Serial library, and that is the main part of the compiled code. Your own functions and pointers is just some code on the side.
For beginners, the compiler optimizations can be magical Abracadabra. However, using arrays will prevent the compiler to do extreme optimizations. There might even be a logical explanation for the number of increased bytes if the assembly code is studied as @Gerben wrote.