text:
Where Can I Find a 12v Solder-less Breadboard Power Supply?
I am trying to find a 12 V input and 12 V output breadboard power supply but I can't find one. I am making an Arduino-controlled lock but the Arduino cannot power the lock strike by itself so I need to use a separate power supply. The link to make things clearer:
http://www.instructables.com/id/Arduino-RFID-Door-Lock/#step0

If your input is 12V then why do you need a 12V output?

To be a able to use it with a breadboard, I am using a 120vac to 12vdc switching adapter to power the breadboard power supply.

What's wrong with just using wires?

I want to separate the power from the outlet to positive and ground.

... What is that supposed to mean?

I plug the switch adapter into the outlet and into the breadboard power supply. From there i can use 12v of power from my breadboard since it connects into the sockets of the breadboard.

I can't find a power supply that outputs 12v

That's odd as you said you already using a 12v switcher.  Apparently you are misusing "power supply" to describe some other function.  Be more specific about what this mystery item should do - imagine for a minute you are managing an engineer who will create this new invention from scratch: what is the requirement?

Do you want a DC barrel jack on a board with wires or breadboard pins?

https://www.sparkfun.com/products/114 this is basically what i want, but i want it to output 12v.

There is nothing special about a power supply that connects to a breadboard directly versus one that connects via wires.

@IgnacioVazquez-Abrams so does that mean that a dc barrel jack would work?

Provided you connect a regulated power supply to it.

@IgnacioVazquez-Abrams thank you, if you put that as an answer i will accept it.

Could that be a typo in the first sentence of your question, and you meant a 120v input, 12v output supply? That would explain a lot of the confusion that followed...

There is nothing special about a "breadboard power adapter" that isn't served by a normal regulated supply. Simply use wires or a barrel jack or some other connector to connect any regulated supply to the breadboard as desired.

They sell 5V/3.3V breadboard supplies on eBay for $3-$5 shipped from China. Buy one and rewire/modify it to bypass the voltage regulator


text:
Can't upload Blinky on CH32V003F4P6 using Arduino IDE
Warn : Transport "sdi" was already selected
Ready for Remote Connections
Error: open failed

*** [upload] Error 1

I have bought a development board (CH32V003F4P6) and I cannot upload a blinky example to the thing. The Chinese company I got it from doesn't seem to have English support, so I'm struggling to figure out what is wrong. I've got Platform IO, Ardunio, MounRiver, and gcc all installed for CH32V003 and they all have the same problem, they cannot upload to the thing.
I read this hackaday article and it seems there is both SPI and Serial transfers.
I checked my USB (I'm using Linux) and it shows up.
Bus 003 Device 048: ID 1a86:7523 QinHeng Electronics CH340 serial converter
I have absolutely no idea where to go from here in order to upload to this thing.

Do you have rights for accessing serial ports (added correct group, udev rules ...)?

https://hackaday.com/2023/03/02/a-ch32v003-toolchain-if-you-can-get-one-to-try-it-on/

google official WCH Link-E Programmer

Yes I have rights to the serial ports. It doesn't work even if I use sudo. The people who sold it to me said I didn't need the WCH Link-E Programmer because this was built in.

if the programmer is built-in then use the correct software for that programmer

I have. It is Eclipse, but the error message is the same regardless of the software.

source: Stack Exchange

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

sort: votes


text:
DHT11 Sensor - reading either all zeros or all -999 (depending on library)
So I've been trying to get a small project set up for the upcoming eclipse, just to read changes in the humidity and temp during the eclipse.
I have two DHT11 sensors, I'm only using one.
I have downloaded this library (it's at the bottom), and this is the code I'm using.
#include <dht.h>
#define pin 13
dht DHT;
void setup() {

  Serial.begin(9600);
  delay(2500);
  Serial.print("DHT11 Sensor: April 8 Solar eclipse data\n\n");
  delay(1500);
}

void loop() {
  DHT.read11(pin);
    Serial.print(" ");
    Serial.print(DHT.humidity);
    Serial.print(" ");
    Serial.print(DHT.temperature);
    Serial.print(",\n");
    delay(2500);

}

The goal here is to have csv's that I can copy/paste into a .csv and import to matlab to do what I need on there.
I keep getting the title and "0.00 0.00," for the two data sets.
With other libraries and borrowed code sometimes I get -999 for the datasets.
My set up

simulate this circuit – Schematic created using CircuitLab
My schematic isn't super accurate, the sensor's on the breadboard. LMK your thoughts.

@StarCat just delete the comment then

I attempted the resistor, I put one end in the power row between the 5V into the breadboard and the power pin for the sensor, and the other end into a slot between the data wire out to the Mega, and the pin for the sensor.
Still zeros.

Try a pin other than 13.  There is additional circuitry around pin 13 for the built in LED.

Can be a bad sensor or bad cable too.

You can cross-check your sensor with this tutorial. https://www.theengineeringprojects.com/2017/08/dht11-arduino-interfacing.html If your sensor does not work after following this, maybe you have to replace your sensor.

If you are using a standalone DHT11 sensor (Without breakout board) you will need a 1KΩ pullup-resistor between 5v and Data.
The DHT's data pin is an open collector, meaning it can only pull a wire to ground to transmit data. If that wire wasn't pulled up to begin with, it won't have anything to pull down.
If your DHT11 is on a breakout board with the 1KΩ resistor already in place, I would suspect a bad sensor...

I have used DHT11's successfully in at least two different projects. Take a look at https://www.fpaynter.com/2021/07/temperature-display-for-3d-printer-enclosure/ and https://www.fpaynter.com/2017/01/3d-printer-filament-de-humidifier-bin/.  Both these posts have the entire code.

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


text:
Read Simultaneously RFID TAG with multiple RFID Reader [MFRC522]
i have a project that use two RFID Reader, the project for counting tag from conveyor belt, in this case the reader will placed in the middle of the conveyor belt and the reader faces each other.
So i have question, can two RFID Reader reading one or many tag simultaneously? I tried before but when i tried to scan, the two readers did not respond, but if i scan one tag and one reader it will work correctly.
For example:
i have readers 0 and readers 1, and two variables count0 and count1, remember the readers faces each others, so i put one tag in the middle of reader0 and reader1, if the reader 0 scan the tag, count0 will increase to 1 and if reader 1 scan the tag in the SAME TIME it wouldn’t be counting because the reader 0 has scan that tag.
but in my case, the readers(0 and 1) didnt response if i put the tag in the middle of readers.
i use this tutorial for my project https://youtu.be/HmGmFknAIqc
and for this project the data count0 and count1 i send it to nodemcu using SoftwareSerial(5,6).
Im new for using Arduino and i still learn about it(i dont understand too much)
Heres my arduino code
/**
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from more than one PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from more than one PICC (that is: a RFID Tag or Card) using a
 * MFRC522 based RFID Reader on the Arduino SPI interface.
 *
 * Warning: This may not work! Multiple devices at one SPI are difficult and cause many trouble!! Engineering skill
 *          and knowledge are required!
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS 1    SDA(SS)      ** custom, take a unused pin, only HIGH/LOW required **
 * SPI SS 2    SDA(SS)      ** custom, take a unused pin, only HIGH/LOW required **
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 */
#include <Wire.h>
#include <SPI.h>
#include <MFRC522.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h> //library penampil LCD

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_1_PIN        10         // Configurable, take a unused pin, only HIGH/LOW required, must be diffrent to SS 2
#define SS_2_PIN        8          // Configurable, take a unused pin, only HIGH/LOW required, must be diffrent to SS 1

#define NR_OF_READERS   2

LiquidCrystal_I2C lcd(0x27,20,4); //0x3f dapat dicari dengan i2c scanner
SoftwareSerial s(5,6);
//SoftwareSerial s1(2,3);

byte ssPins[] = {SS_1_PIN, SS_2_PIN};

MFRC522 mfrc522[NR_OF_READERS];   // Create MFRC522 instance.
int i = 1;
byte code[10];
String uidString;
int count0 = 0;
int count1 = 0;

/**
 * Initialize.
 */
void setup() {
  s.begin(9600);
 // s1.begin(9600);
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial);
  SPI.begin();        // Init SPI bus

  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {
    mfrc522[reader].PCD_Init(ssPins[reader], RST_PIN); // Init each MFRC522 card
    Serial.print(F("Reader "));
    Serial.print(reader);
    Serial.print(F(": "));
    mfrc522[reader].PCD_DumpVersionToSerial();
  }

//  lcd.init();
//  lcd.init();
//  lcd.backlight(); //menghidupkan lampu latar LCD
//  lcd.setCursor (3,0);
//  lcd.print("Final Project");
//  delay (1000);
//  lcd.clear();
}

/**
 * Main loop.
 */
void loop() {
//  lcd.setCursor (0,0);
//  lcd.print("SCAN RFID");

  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {
    // Look for new cards
    if(reader == 0){
      reader0(reader);
    }else if(reader == 1){
      reader1(reader);
    }
  }
}

/** SCAN RFID TAG READER0 */
void reader0(int reader){
    if (mfrc522[reader].PICC_IsNewCardPresent() && mfrc522[reader].PICC_ReadCardSerial()) {
      Serial.println();
      Serial.print(F("Reader "));
      Serial.print(reader);
      // Show some details of the PICC (that is: the tag/card)
      Serial.println();
      Serial.print(F("Card UID = "));
      dump_byte_array(mfrc522[reader].uid.uidByte, mfrc522[reader].uid.size);
      Serial.println();
//      Serial.print(F("PICC type: "));
//      MFRC522::PICC_Type piccType = mfrc522[reader].PICC_GetType(mfrc522[reader].uid.sak);
//      Serial.println(mfrc522[reader].PICC_GetTypeName(piccType));
      count0++;
      lcd.setCursor (0,0);

      Serial.print("Counter ");
      Serial.print(reader);
      Serial.print(" = ");
      Serial.print(count0);
      Serial.println();
      s.write(count0);
       }

      mfrc522[reader].PICC_HaltA();
      mfrc522[reader].PCD_StopCrypto1();
}

/** SCAN RFID TAG READER1 */
void reader1(int reader){
    if (mfrc522[reader].PICC_IsNewCardPresent() && mfrc522[reader].PICC_ReadCardSerial()) {
      Serial.println();
      Serial.print(F("Reader "));
      Serial.print(reader);
      Serial.println();
      // Show some details of the PICC (that is: the tag/card)
      Serial.print(F("Card UID = "));
      dump_byte_array(mfrc522[reader].uid.uidByte, mfrc522[reader].uid.size);
      Serial.println();
//      Serial.print(F("PICC type: "));
//      MFRC522::PICC_Type piccType = mfrc522[reader].PICC_GetType(mfrc522[reader].uid.sak);
//      Serial.println(mfrc522[reader].PICC_GetTypeName(piccType));
      count1++;
      lcd.setCursor (0,0);

      Serial.print("Counter ");
      Serial.print(reader);
      Serial.print(" = ");
      Serial.print(count1);
      Serial.println();
      s.write(count1);
    }

      mfrc522[reader].PICC_HaltA();
      // Stop encryption on PCD
      mfrc522[reader].PCD_StopCrypto1();
}

/**
 * Helper routine to dump a byte array as hex values to Serial.
 */
void dump_byte_array(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

anyway sorry for my bad english :D

I'm just starting a project using RFID tags to track cars and engines on a model railroad.
Although I haven't gotten very far yet, my first thought was to use a multiplexer to select which reader I receive data from at any given time. It won't be simultaneous but I should be able to read a dozen or more per second which is probably enough.

Take a look at this this link it might be of a help to you. It uses four RFID readers at the same time

That's because you can only listen at one SoftwareSerial interface at a time. On the other interface you will receive nothing.
The SoftwareSerial library uses interrupts to watch at the pins. These interrupts cannot easily be shared between different interfaces, thus the SoftwareSerial library doesn't support it.
You can do 2 things:

You could ditch the code for reporting to the serial monitor (so no debugging code and no interaction with the serial monitor on the PC) and only use the LCD for displaying information. Then you can use the free hardware serial port to communicate with one of the RFID readers. The other can be services through a single SoftwareSerial interface.
You could ditch the Uno and buy an Arduino Mega, which has 4 hardware serial ports. Then you can connect both RFID readers to hardware serial interfaces, using the first serial interface for communication with the PC and still having one interface left. This would be my preferred way.

Sorry, did you mean SoftwareSerial that i used in there? i use SoftwareSerial for sending data to nodemcu and then nodemcu will send to thingspeak, the code hasnt revised, i only use SoftwareSerial(5,6) and for now i didnt use LCD. Im new in Arduino i dont understand too much

i use this tutorial https://youtu.be/HmGmFknAIqc

mfrc522 is not as common any more, but if you want to use them rather then rdm6300 (more expensive device, but cheaper tags), then you can
Mfrc522 uses spi interface which means that each slave needs its own slave select port from arduino to enable arduino to chose whom its talking to at which point.
You should read this about multiple SPI devices
because SPI is a synchronous communication I would recommend one mcu per reader (nanos' or pro-minis are cheap) and they can communicate results to central arduino


text:
Servo motor troubles

The image is as clear as I can make it.
Here are the basics of my problem. My program is meant to make 6 red LED lights in sequence fade in and out, toggle 5 white LED's on and off with a button, and make a servo rotate from 90 to 15 degrees on a button press, and revert to 0 degrees when the button is no longer pressed.
All of my code has compiled correctly, the LED's do what they are supposed to do, but the servo is acting strange. At first, it would move fine but then after a few button presses it would kind of spaz out and glitch back to place instead of smoothly move, which will not work for my purposes. After even more time, the servo stopped working at all. I looked around and found some answers saying to route it through an alternative power source, but I did that with the power module that came with my kit and it still refuses to move. I swapped it out with a different servo and that one won't work either, which makes me wonder if my wiring is incorrect - and yet the motor is on and makes vibrations, instead of moving, so I know power is getting through. In addition, the onboard LED's on the mega2560 are turning on and off in response to my button, so I know that's wired in correctly as well! So why won't the servo move, and why won't it respond to my button presses?
Basically, using a 3.3V - 5.0 volt Elegoo power module, how do I correctly wire the servo to only draw power from the 9v battery I attach to said module? I've seen people saying something about putting the grounds of the board and the module together but I don't know how to do that and I'm getting frustrated looking all over the internet trying to find out how so I figured I would just ask a question.
Wiring details:
The 5 white LED's are in parallel, and the red LED's are in series; they are all powered by the arduino's 5V power source, and wired into the arduino GND pin.
Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery. The light on the module is on, and I have used the included jumpers to make sure I'm using the 5V source and not the 3.3V one.
Here is my code:
#include <Servo.h>
Servo servo1;
//------------------------
// White LED's:
int wL1 = 3;
int wL2 = 4;
int wL3 = 5;
int wL4 = 6;
int wL5 = 7;
//------------------------
// Red LED's:
int rL1 = 8;
//------------------------
// Buttons:
int wLbutton = 2;
int wLreading;
int wL1state = HIGH;
int wL2state = HIGH;
int wL3state = HIGH;
int wL4state = HIGH;
int wL5state = HIGH;
int wLprevious = LOW;

int servoButton = 1;
int servoState = false;
int servoReading;
int servoPrevious = LOW;
//--------------------------
// Fading:
int brightness = 0;
int fade = 1;
//--------------------------
// Delays:
long time = 0;
long time2 = 0;
long debounce = 100;

unsigned long previousMillis = 0;
const long interval = 1000;
//--------------------------

// Setup ======================================================================================================================================

void setup()
{
  pinMode(wL1,OUTPUT);          // White LED's
  pinMode(wL2,OUTPUT);
  pinMode(wL3,OUTPUT);
  pinMode(wL4,OUTPUT);
  pinMode(wL5,OUTPUT);

  pinMode(rL1,OUTPUT);          // Red LED's

  pinMode(wLbutton, INPUT);     // Buttons
  pinMode(servoButton, INPUT);

  servo1.attach(10);
  servo1.write(90);             // Servo

  if (wL1state = HIGH)
{
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low at the beginning of the circuit (this doesnt run after the first time).
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
}
}

// Loop =========================================================================================================================================

void loop() {

// White LED Button -----------------------------------------------------------------------------------------------------------------------------

wLreading = digitalRead(wLbutton);                                             // Read the state of the White LED Button

if (wLreading == HIGH && wLprevious == LOW && millis() - time > debounce)      // If the button is different state from last reading and ignores noise
{
  if (wL1state == HIGH)                                                        // If the current button state of the White LED button is high
  {
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
  }
  else {
    wL1state = HIGH;                                                           // Otherwise, set the state of the White LED button to high
  }
  time = millis();                                                             // Set the last time the button was pressed to the current time
}

digitalWrite(wL1,wL1state);
digitalWrite(wL2,wL1state);
digitalWrite(wL3,wL1state);
digitalWrite(wL4,wL1state);
digitalWrite(wL5,wL1state);

wLprevious = wLreading;                                                        // Set the previous reading of the White LED button to current reading

// Servo Button ----------------------------------------------------------------------------------------------------------------------------------

servoState = digitalRead(servoButton);

if (servoState == HIGH)
  {
    servo1.write(75);
  }
  else
  {
    servo1.write(0);
  }

// Red LED'S breathing ----------------------------------------------------------------------------------------------------------------------------

 analogWrite(rL1,brightness);                                                 // Write the set brightness to the red LED
 brightness = brightness + fade;                                              // Set new brightness to brightness value + fade value

 if (brightness <= 0 || brightness >=255)                                     // If brightness is less than 0 or more than 255
  {
  fade = -fade;                                                               // Negate the fade value, reversing the direction of the fade
  }
  delay(10);                                                                  // Wait a short delay to see the fade
}```

When you say 9V battery, do you mean one of those rectangle shaped alkaline ones with two terminals on top?  Those aren't really good for powering motors or servos.  They can't really produce much current.  They're the equivalent of 6AAAA batteries.  I don't know if this is all of your problem but you should use some AA or AAA and you will have a better time of it.

Show us your circuit.  That should seem obvious since you said that you thought the fault may be in the wiring.  Do you have a pull-down resistor for the buttons?  Why don't you have them wired the normal way to read LOW when pressed so you can use the internal pull-ups and don't have to have extra resistors?

is the servo problem repeatable? ... does the servo work correctly after a reset and then degrades after a few button presses?

@Delta_G Thank you for the info on the 9V battery, yes that's the kind I am using. I'll have to buy a AA or AAA battery pack. How many of those do I need to power the servo then?
As for your second comment, the reasoning behind my white LED's having multiple resistors is that in the future I want them to turn on in sequence with a short time period between each consecutive light, rather than all at once, but I just haven't figured out how to do that yet. I'll leave that to a separate question. I'll attach a photo to my post if that helps.

@jsotola no, it won't work at all currently, even after a reset.

Why are you talking about resistors on leds?  I didn't ask about that.  I asked if you had a pull-down resistor for your button or is your button floating when it isn't pressed?  If that's the case then it may be reading noise and registering presses when you aren't actually pressing it.  The question was, why didn't you wire your button the normal way so that it reads LOW when it is pressed so that you don't need extra resistors for the buttons.  If you wire the right way then you don't need resistors at all for the buttons.  .  Please read carefully.  I never mentioned resistors on leds.

@Delta_G Ok chill. I misunderstood, it's not the end of the world. I have a pull down resistor as you can see in the image. I don't know what you mean by 'extra resistors' if you aren't talking about the LED's, I only have one for the button.

@Delta_G I already fixed the problem so I'm closing the question. Please don't be so blunt in your comments. I'm new and I'm doing my best.

Sorry, I didn't mean to be unchill.  Just to point out that you had misunderstood.  The extra resistors I'm talking about are the ones that are supposed to be on the buttons.
When I asked at first I didn't know if they were there.  If you wired your buttons the right way round you wouldn't need them.  But with the buttons wired to go HIGH when pressed you must have pull-down resistors or you'll get random noise presses of your button when nobody is pressing it.

I think you read my comment with some sort of emphasis in your head and responded to THAT not being chill.  I don't read anything there other than trying to tell you that you had misunderstood me and trying to clarify what I was talking about.  On the internet when speaking in text you can't hear someone's inflection, so it is important not to think that they wrote it in the same voice that you hear in your head.

No matter how it is communicated, saying something like 'Please read carefully' will always bring people's defenses up. Try changing your way of communicating so that doesn't happen. Instead you could say something like "i think you misunderstood, let me clarify.' instead you settled for 'why are you talking about x' and 'read more carefully, i never mentioned x'. I like getting help from people, but the way you said things felt insulting, and i'm sure i wouldn't be alone feeling that way if you said to someone else.

I've seen people saying something about putting the grounds of the board and the module together

Yes, I believe this is what you need to do.

Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery.

From what I understand, you are wiring like this
Servo 5V - 5V Power module
Servo GND - GND Power module
Servo Signal - pin 10 Arduino
If so, you need to  make a Y-connection like this:
Servo GND - Power module GND - Arduino GND (these 3 pins should be connected together)

I've connected the three together and still nothing. I have noticed that as soon as i connect the servo to the power module, the green light turns off. Is this a result of the power of the 9V not being enough?

You can see in the photo I attached in the post on the left, the Y connection you mentioned.

Hmm before anything I see a weird thing in your image. In your Y connection you are connecting the yellow wire from servo. Are you sure it's the GND wire?

And I also recommend you do this way. First, remove all LEDS and try to make your servo work. Then, you can add LEDs. That way you can easily figure out where the problem is. Just divide into steps, don't try to combine everything at start.

That was the issue. It worked and began responding again one I fixed the y connection. Then I got my 9v dc plug and using that the servo began working. Thank you so much.

You're welcome!


text:
Unable to type in Arduino IDE running on OS X
I'm trying to use the Arduino IDE (1.6.8 downloaded from arduino.cc) on a MacBook running OS X (10.11.5 beta).
The IDE seems to run and I can open and upload the examples and they run. But…
I can't type in the editor window of the IDE – either with the examples or with the new sketch that opens when you launch the IDE.
I have a similar problem with the version of the IDE distributed with mBlock (1.6.5) if I use the Edit in Arduino IDE button. I also tried the 1.6.9 hourly version. All to no avail. So I'm thinking that this is a OS X problem, or maybe an issue with version of Java (1.8.0).
Any ideas or troubleshooting suggestions?

Make sure that in preferences the option Use external editor is not checked. You could also try downloading an older version.

Yes! Thank you. I'd forgotten I'd done that. Make it an answer if you'd like and I'll accept it.

Make sure that in preferences the option Use external editor is not checked.

you may also consider Sublime Text -> with the STino plug-in, it is a full-fledged editor that does everything your arduino IDE does, in a much more stylish way.

I find solution on this forum [http://forum.arduino.cc/index.php?topic=93338.]
File | Preferences | Use External Editor (Don't use)

This is the same solution as the accepted answer.

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


text:
Counter using Ultrasonic Sensor (self.arduino)
I am doing a pretty simple arduino project that uses a Parallax Ping Ultrasonic Sensor to increment a counter when an object moves past the desired distance. (object leaves, counter goes up, object comes back, this loops forever). My problem is now that every time i run this.. the serial monitor just shows me Count: 1 over and over again and does not increment.
Any help would be appreciated!
example of what i want the Serial Monitor to write:
Count:0
Count:1
Count:2 ....
What it is currently doing:
Count:0
Count:0
Count:0
const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm, count;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

    // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
// count = 1;

 if (inches > 5)
{
  Serial.print("Count: ");
  Serial.print(count);
  Serial.print('\n');
  delay(1000);
        count++;

}

}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{

  return microseconds / 29 / 2;
}

Count is a local variable - it gets re-created afresh every time the loop() runs.
Either make it global, or make it static.
These two options look like this:
Global
long count = 0;

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

Static
void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
  static long count = 0;

Both will do the same job, but the static form is preferred since it is always better to keep a variable's scope as narrow as possible.  It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.

i did int count inside the loop and it still didn't do anything...

You need to place it outside the loop (i.e. global).

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


text:
LCD1602A displaying blocks
I am having an issue with the LCD1602A and Arduino Uno. I have followed a tutorial on youtube that has got the device working, however the LCD is only displaying white blocks in all 16 segments of the top row.

Pin Out
LCD

VSS -> GND on Breadboard
VDD ->  5V on Breadboard
V0  -> Connected to 5K potentiometer
RS  -> Pin 1 on Arduino Uno
RW  -> GND on Breadboard
E   -> Pin 2 on Arduino Uno
D0  -> Not Connected
D1  -> Not Connected
D2  -> Not Connected
D3  -> Not Connected
D4  -> Pin 7 on Arduino
D5  -> Pin 6 on Arduino
D6  -> Pin 5 on Arduino
D7  -> Pin 4 on Arduino
A   ->  5V on Breadboard
K   -> GND on Breadboard

Code
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)
void setup() {
 lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display }
}
void loop() {
 lcd.print("Arduino"); // Prints "Arduino" on the LCD
 delay(3000); // 3 seconds delay
 lcd.setCursor(2,1); // Sets the location at which subsequent text written to the LCD will be displayed
 lcd.print("12345");
 delay(3000);
 lcd.clear(); // Clears the display
 lcd.blink(); //Displays the blinking LCD cursor
 delay(4000);
 lcd.setCursor(7,1);
 delay(3000);
 lcd.noBlink(); // Turns off the blinking LCD cursor
 lcd.cursor(); // Displays an underscore (line) at the position to which the next character will be written
 delay(4000);
 lcd.noCursor(); // Hides the LCD cursor
 lcd.clear(); // Clears the LCD screen
}

Now the program compiles and uploads OK the potentiometer dims the blocks perfectly fine.
However it is supposed to print Arduino and 12345 and I am unsure why.
What am I missing?
Thanks

Check your contrast Settings.

Checked contrast settings using potentiometer no luck. These only dim the blocks.

Your pin out text does not match the pin assigment in the lcd() line.
Should be LiquidCrystal lcd(1,2,7,6,5,4), e.g., your data wires are flipped.

Thanks for your help.


text:
Time synchronization of GPS based Wireless Network
I am working on an ARDUINO based wireless network. In this network, each node or device is having its own GPS module. Each GPS module has to get location data and have to send to a single base-station. Let say we have 10 nodes in our network. A specific time(let say 1 sec) is assigned to each node when it can receive location and send it to the base-station (everything to be done in that 1 sec allocated time). So, all nodes will be done sending the data to the station and now the 2nd cycle repeats and so on.
For experiment purpose, I have created two nodes and connected LEDs each one. I am getting time from GPS module using tinygps library. To verify the time synchronization, I have programmed MCU in such a way that it turns ON the LED for 50 ms after every 10 sec. Uploaded the same code on both devices.
If both devices are sync then LEDs will TURN ON and OFF at the same time. But that's is not the case. LEDs of both devices are turning ON and OFF with a huge difference of time (almost 4 to 5 sec). Which shows that GPS times are not synchronized.
Following is the code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

const int LEDPIN = 13;
void setup()
{
  Serial.begin(9600);
  ss.begin(GPSBaud);

  Serial.println(F("FullExample.ino"));
  Serial.println(F("An extensive example of many interesting TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP  Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
  Serial.println(F("           (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
  Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

  pinMode(LEDPIN,OUTPUT);
  digitalWrite(LEDPIN,LOW);
}

unsigned double interval = 50;
bool pinState = LOW;
unsigned double startmillis;
void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printDateTime(gps.date, gps.time);
  double sec = gps.time.second();

    while(1){

      if(millis()-startmillis >= interval){
            // 50 milli seconds passed
            digitalWrite(LEDPIN,LOW);
            Serial.println("50 millis passed.");
            smartDelay(1000);
          }
          else{
             // Still in loop. Turn ON LED
             digitalWrite(LEDPIN,HIGH);
          }

          }

  smartDelay(0);

  if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
}

// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void printFloat(float val, bool valid, int len, int prec)
{
  if (!valid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartDelay(0);
}

static void printInt(unsigned long val, bool valid, int len)
{
  char sz[32] = "*****************";
  if (valid)
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
}

static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
{
  if (!d.isValid())
  {
    Serial.print(F("********** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
    Serial.print(sz);
  }

  if (!t.isValid())
  {
    Serial.print(F("******** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
  }

  printInt(d.age(), d.isValid(), 5);
  smartDelay(0);
}

static void printStr(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartDelay(0);
}

After a bit research, I found the following paper which is very helpful to solve my problem:

https://www.frontiersin.org/articles/10.3389/fbuil.2018.00082/full

The problem is, they have not provided the code anywhere which I can use for my problem.
Please let me know what should I do to synchronize the GPS time for two devices and then, in the long run, for a network.

Your question is unclear, but somehow I doubt that your problem will be solved with the techniques and software described in that paper. How do you know (for example) that your two units are taking a time reading at the same time? Please try to be more specific.

I am getting the time readings from GPS continue-sly. At every 10th sec (10th means 10, then 20 then 30 sec), program turns ON the LED for 50 ms. Same program is burnt on both devices.
I hope that makes it more clearer.

Start by removing from the code everything you do not need, so that you get a minimal example. Why the infinite while(1) loop? Why did you put unreachable code after that loop? Why don't you ever set startmillis?

I am breaking the while(1) loop after it reaches the condition. startmillis stores the millis when condition of 10 sec is met. I am breaking that loop when difference between millis from when the timer started and when 50 ms have been passed after that.

The mentioned paper solves my problem but I am not getting any code.


text:
Serial communication arduino mega and D1 Wemos Mini
Can anyone help me connecting arduino mega to D1 Wemos Mini serially? Please let me know most efficient and easy steps to setup a communication.
Using that following tutorial:
https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino/amp/
Following is the circuit diagram:
https://i.sstatic.net/oOKwL.png

Rx to Tx3 and Tx to RX3, gnd and 3.3 V. ready. in Mega in code use Serial3 to communicate with esp8266.

@Juraj Is the Wemos Mini 5V tolerant? Otherwise a voltage divider would be needed between Mega TX and Wemos RX

@AliHassanRaza What exactly is your problem with setting up the connection? Serial (aka UART) has only 2 lines plus ground connection. There are many tutorials on the web. Did they not help you? What exactly couldn't you understand there?

@chrisl, voltage divider would limit the speed and complicate troubleshooting.. the esp8266 can handle 5 V logic pull-up current for a test. in long term setup I recommend a level shifter, not voltage divider

I am not getting anything when I try to serially communicate them.

Then you need to show us your code and wiring. Please edit your question and add the information there, not in the comments, as the comments are only temporary

if (esp.available()>0)
{
Serial.println("Inside");
int data = esp.read();
Serial.println(data);
}
It is not going inside this condition, neither at arduino side nor at esp side

Using that following tutorial:
https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino/amp/

what is esp? SoftwareSerial? use hardware Serial3 (or 1 or 2). SoftwareSerial doesn't work on all pins of Mega

Apart from ensuring you're wiring TX -> RX and connecting all grounds, you can use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.
Here are the library's features:

This library:

can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
works with "software-serial" libraries
is non blocking
uses packet delimiters
uses consistent overhead byte stuffing
uses CRC-8 (Polynomial 0x9B with lookup table)
allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  char buff[] = "hi";

  myTransfer.txObj(buff, sizeof(buff));
  myTransfer.sendData(sizeof(buff));
  delay(100);
}

Example RX Arduino Sketch:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  if(myTransfer.available())
  {
    char buff[40];

    myTransfer.rxObj(buff, sizeof(buff));

    Serial.println("New Data: ");
    Serial.write(buff, sizeof(buff));
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}


text:
UNIX time in ms to human date time
Been struggling with something for a few days.
Loading data from a website via JSON and it includes an updated date time in milliseconds. This is an EPOCH date and I can get the right value using some of the online convertor sites, epochconvertor.com
That said when I try and parse it in my sketch it’s not retuning the correct date.
JSON
“currentupdatedms”:1588312648603
Convertor Shows as:
1 May 2020 05:57:28.603
My sketch is showing:
1 May 2020 02:33:00
That’s in the JSON and I can’t use a Long as it’s 13 digits. Tried Long Long and it accepts the value but when I later divide by 1000 to get seconds the number changes completely when I try printing it to serial or the OLED.
Plan is to use the Timeh library to display it as a human date time.
Any thoughts be appreciated.
Here is my code and I have tried various methods:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <TimeLib.h>
#include <time.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

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

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define ARDUINOJSON_JSON_LONG_LONG 1 //Not needed???
#define   ONE_HOUR   3600
const size_t capacity = JSON_OBJECT_SIZE(8) + 140;
DynamicJsonDocument doc(capacity);

/*Notes
   Need to look at conversion of Update and Changed times as they are not showing correctly
   Move the conversion of time datetime in ms to a seperate function
   Move the get request and JSON section to seperate function
*/

const char* ssid = "SSID";
const char* password = "PWD";

void setup () {

  Serial.begin(4800);

  Wire.begin(2, 0);           // set I2C pins (SDA = GPIO2, SCL = GPIO0), default clock is 100kHz

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;); // Don't proceed, loop forever
  }

  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);

  WiFi.begin(ssid, password);

  display.setCursor(0, 0);
  display.println(F("Connecting to Wifi..."));
  display.display();

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to Wifi...");
  }

  display.setCursor(0, 10);
  display.println(F("Wifi Connected..."));
  display.display();
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    display.setCursor(0, 20);
    display.println(F("Requesting Data..."));
    display.display();
    delay(2000); // Pause for 2 seconds

    HTTPClient http;  //Declare an object of class HTTPClient

    http.begin("http://corona.tuply.co.za/DataHandler.ashx?w=s&uq=8f1fp8p5jdxi84481");  //Specify request destination
    int httpCode = http.GET();                                                                  //Send the request

    if (httpCode > 0) { //Check the returning code

      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload

      deserializeJson(doc, payload);

      int TotalCases = doc["TotalCases"];
      int TotalCasesToday = doc["TotalCasesToday"];
      int TotalDeaths = doc["TotalDeaths"];
      int TotalDeathsToday = doc["TotalDeathsToday"];
      int TotalRecovered = doc["TotalRecovered"];
      int TotalTerritories = doc["TotalTerritories"];
      long long CurrentUpdatedMS = doc["CurrentUpdatedMS"];
      long long CurrentChangedMS = doc["CurrentChangedMS"];

      //delay(10000);

      time_t CurrentUpdateMS_t = (CurrentUpdatedMS/1000) + ONE_HOUR; //ONE_HOUR added for BST

      char buffUpdateMS[32];
      sprintf(buffUpdateMS, "%02d/%02d/%02d %02d:%02d:%02d", day(CurrentUpdateMS_t), month(CurrentUpdateMS_t), year(CurrentUpdateMS_t), hour(CurrentUpdateMS_t), minute(CurrentUpdateMS_t), second(CurrentUpdateMS_t));
      Serial.print("U:");
      Serial.println(buffUpdateMS);
      Serial.print("ctime: ");
      Serial.println(ctime(&CurrentUpdateMS_t));

      time_t CurrentChangedMS_t = CurrentChangedMS/1000 + ONE_HOUR; //ONE_HOUR added for BST

      char buffChangedMS[32];
      sprintf(buffChangedMS, "%02d/%02d/%02d %02d:%02d:%02d", day(CurrentChangedMS_t), month(CurrentChangedMS_t), year(CurrentChangedMS_t), hour(CurrentChangedMS_t), minute(CurrentChangedMS_t), second(CurrentChangedMS_t));
      Serial.print("C:");
      Serial.println(buffChangedMS);
      Serial.print("ctime: ");
      Serial.println(ctime(&CurrentChangedMS_t));

      display.clearDisplay();

      display.setCursor(0, 0);
      display.print(F("T Cases: "));
      display.println(TotalCases);

      Serial.print("Total Cases: ");
      Serial.println(TotalCases);

      Serial.print("Total Cases Today: ");
      Serial.println(TotalCasesToday);

      display.setCursor(0, 10);
      display.print(F("T Deaths: "));
      display.println(TotalDeaths);

      Serial.print("Total Deaths: ");
      Serial.println(TotalDeaths);

      Serial.print("Total Deaths Today: ");
      Serial.println(TotalDeathsToday);

      display.setCursor(0, 20);
      display.print(F("T Recov: "));
      display.println(TotalRecovered);

      Serial.print("Total Recovered: ");
      Serial.println(TotalRecovered);

      Serial.print("Total Territories: ");
      Serial.println(TotalTerritories);

      display.setCursor(0, 30);
      display.print(F("U T: "));
      display.println(buffUpdateMS);

      display.setCursor(0, 40);
      display.print(F("C T: "));
      display.println(buffChangedMS);

      display.display();

    }

    http.end();   //Close connection

  }

  delay(60000);    //Send a request every 60 seconds

}

If I run that now I get this JSON string:
{"TotalCases":4036128,"TotalCasesToday":26837,"TotalDeaths":276825,"TotalDeathsToday":849,"TotalRecovered":1400460,"TotalTerritories":214,"CurrentUpdatedMS":1589027095790,"CurrentChangedMS":1589026765665}
CurrentUpdateMS = 1589027095790 which is Sat May 09 2020 13:24:55, granted there may be an hour difference with BST.
Instead I am getting:
Sat May  9 13:23:32 2020
Also appears to stay the same after refreshes which I have set to 60 seconds.
I tried the Time.h library with same results.
Thankful for any input or suggestions.

Do not mix time.h with TimeLib.h: they both define their own version of time_t. 2. This program is too long for a question here. You should break down your problem into small pieces and tackle them one at a time. First, Serial.println(CurrentUpdatedMS) in order to know whether the issue lies in the JSON deserialization or in the interpretation of the number as a time. Then, write a minimal, reproducible example addressing only that issue. See my answer as an example of what a “minimal, reproducible example” may look like.

It's hard to know what is wrong with your code... because you are not
showing it in the question! Here is a basic test I tried on my Uno:
#include <time.h>

const uint64_t ms = 1588312648603;

void setup() {
    time_t t = ms/1000 - UNIX_OFFSET;
    Serial.begin(9600);
    Serial.println(ctime(&t));
}

void loop(){}

It's output is:
Fri May 01 05:57:28 2020

Note that this <time.h> comes from the avr-libc. It uses an epoch
different from the Unix epoch, hence the UNIX_OFFSET correction.
Edit: I tried replacing avr-libc's <time.h> by Adafruit
RTClib (declaring DateTime t(ms/1000);) and Paul
Stoffregen’s Time library (with time_t t = ms/1000;). In all
cases I get the same time displayed.


text:
Large number into variable
Probably something easy but I’ve not resolved it.
I’m extracting data from a JSON string and all the values are correct accept for two.
They are referring to two date time values and are in milliseconds.
One is the date refreshed and the other is date updated.
Problem is they are both very large and I’m having difficulty assigning them in the IDE.
One is 1588447162117 which is showing as 020-05-02 20:19:53.948  on the dashboard using the JSON.
Here is the code I have thus far to get the data from JSON:
#include <ArduinoJson.h>

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

  const char* input = "{TotalCases:3308678,TotalCasesToday:4458,TotalDeaths:234123,TotalDeathsToday:293,TotalRecovered:1042991,TotalTerritories:124,CurrentUpdatedMS:1588312648603,CurrentChangedMS:1588312648603}";

  StaticJsonDocument<512> doc;

  DeserializationError err = deserializeJson(doc, input);

  if (err) {
    Serial.print("Error: ");
    Serial.println(err.c_str());
    return;
  }

  unsigned long TotalCases = doc["TotalCases"];
  unsigned long TotalCasesToday = doc["TotalCasesToday"];
  unsigned long TotalDeaths = doc["TotalDeaths"];
  unsigned long TotalDeathsToday = doc["TotalDeathsToday"];
  unsigned long TotalRecovered = doc["TotalRecovered"];
  unsigned long TotalTerritories = doc["TotalTerritories"];
  unsigned long CurrentUpdatedMS = doc["CurrentUpdatedMS"];
  unsigned long CurrentChangedMS = doc["CurrentChangedMS"];

  Serial.print("Total Cases: ");
  Serial.println(TotalCases);
  Serial.print("Total Cases Today: ");
  Serial.println(TotalCasesToday);
  Serial.print("Total Deaths: ");
  Serial.println(TotalDeaths);
  Serial.print("Total Deaths Today: ");
  Serial.println(TotalDeathsToday);
  Serial.print("Total Recovered: ");
  Serial.println(TotalRecovered);
  Serial.print("Total Territories: ");
  Serial.println(TotalTerritories);
  Serial.print("Update time in ms:");
  Serial.println(CurrentUpdatedMS);
  Serial.print("Change time in ms:");
  Serial.print(CurrentChangedMS);
}

void loop()
{

}

**Serial monitor output**

Total Cases: 3308678
Total Cases Today: 4458
Total Deaths: 234123
Total Deaths Today: 293
Total Recovered: 1042991
Total Territories: 124
Update time in ms:0
Change time in ms:0

Should be good to manipulate it once I can work with it in a variable.
Thanks for any input,
Shane

what exactly is your question?

I guess you want to use uint64_t but depending on your hardware that might not be possible

What JSON library are you using? How did you code the reading of the value? Note that that number is about 2^40.53, so it won't fit in 32 bits. But it will if you drop the last 3 digits, which reduces the resolution to one second.

Please show your code

that number is hexadecimal 171D6D42F05 ... it fits into 64 bits

Isn't a long 32 bits on most Arduinos? Which Arduino boards support 64 bit integers?

Any. It's not down to the board. It's down to the compiler. The board defines how efficiently it handles them. Any board can use uint64_t

Fair point. I used to write 6502 code, where anything beyond 8 bits required manual carrying and such. A modern compiler will take care of that for you, at the cost of reduced performance.

JSON is overcomplicated for embedded purposes compared the the much more useful C++ struct. Why are you using JSON instead of something like a struct?

I didn't try myself, but just by looking at the docs I suggest you try:

Adding

#define ARDUINOJSON_USE_LONG_LONG 1

at the top of the sketch, before including ArduinoJson.h.

Declare CurrentUpdatedMS and CurrentUpdatedMS as either
unsigned long long or uint64_t.

Edit: To answer the question in the comment:

When you said you looked at the docs where did you check?

I had to follow a (not so simple) path: Deserialization tutorial →
JsonDocument::operator[] → JsonVariant →
JsonVariant::as<T>(). This last page states that the method
as<unsigned long long>() “may require ARDUINOJSON_USE_LONG_LONG”.
Unfortunately, the macro is not linked, so I have to search for it and
found ARDUINOJSON_USE_LONG_LONG.

Thanks I have it working now and will process it like that. When you said you looked at the docs where did you check? Just so I can know where to look in future.

Hi.
That’s worked well as I could assign the value though it is a UNIX timestamp and not appearing correctly when I print or display on a OLED. Tried a couple of things to remedy this including casting to long, u_int 64 etc but it still returns the incorrect time. My data has dateupdated in MS as 13 digits when I should be able to process 10. Would appreciate any thoughts I’ve tried various options. Is there a way to convert that object in the JSON to a string?


text:
coding problems
I'm working on a Arduino controlled solenoid motor project that I found on Instructables. I have been able to piece together what I think is most of the code but I'm getting some syntax errors and was wondering if I could get some help? Here is the code and the errors.
   // Including Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>

LiquidCrystal_I2C mydisplay(0x27,16,2);

// Define Input/Output Pins
#define solenoidpin 9
#define potpin 1
#define ignitioninputpin 2
///#define interruptnumber 3
#define isr_rpm(INT0_vect)

// Defineing Variables
 int previousstate;
 byte buttonstate;
 int counter1;
 int start;
 int finish;
 int elapsed;
 int RPM;

// Main setup
void setup(){
  pinMode(ignitioninputpin,INPUT);
  digitalWrite(ignitioninputpin,HIGH);
////  attachInterrupt(3,isr_rpm, FALLING);
  counter1=1;

  mydisplay.init();
  mydisplay.backlight();
  mydisplay.setCursor(0,1);
  mydisplay.print(" Soleniod Motor ");

  previousstate=HIGH;
  Serial.begin(19200);
  buttonstate = digitalRead(ignitioninputpin);
}

// Main program loop
void loop() {
  buttonstate = digitalRead(ignitioninputpin);
  Serial.println(buttonstate);
  Serial.write("previousstate");
  Serial.println(previousstate);
  Serial.println(counter1);
  float elapsed=start=finish;
  float RPM= (6000/elapsed);
{

if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
    digitalWrite(solenoidpin,HIGH);
  }

if  (buttonstate==HIGH && previousstate==LOW && (counter1%2)==0){
    digitalWrite(solenoidpin,HIGH);
  }

if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
    digitalWrite(solenoidpin,LOW);
  }

if  ((counter1%2)==0){                                            for rpm calcs
    finish=start;
    start=millis();
  }

if  ((counter1%6)==0){
    mydisplay.setCursor(0,0);
    mydisplay.print(" RPM ");
    mydisplay.print(RPM);
    mydisplay.setCursor(0,1);
    mydisplay.print(" Solenoid Motor ");
  }

void ISR1();
  buttonstate=LOW;
  counter1=counter1+1;
  previousstate=HIGH;
  }
 }

Error messages:
Binary sketch size: 7,594 bytes (of a 32,256 byte maximum)

A good starting place may be: "'isr_rpm' was not declared in this scope"
That should be fixable. Then ..

Another thing you might consider is losing the extraneous spaces in your include filenames.  <[space]Wire.h[space]> is not the same as <Wire.h>

Another thing to watch out for is making sure you balance your brackets properly.  You seem to have an extra one there.  Fix your indenting and you'll soon spot it.

One more thing I have just noticed - check your usage of & in your if() statements...  It may not be causing a problem, but it's certainly bad programming style since & doesn't mean what I think you think it means.

@Majenko I also noticed the use of &, there are also a few other things the OP has done, also a redundant if() statement.

@RSM There are numerous flaws in the methodology of the program, yes.  Including the use (or lack of use) of previousstate and the copious amount of expensive modulus operations...  Also this line: float elapsed = start = finish;...  I mean... well...  Also local variables (float RPM & elapsed) conflicting with global variables (int RPM & elapsed)...!

@Majenko: modulus 6 may be expensive, but modulus 2 is cheap.

@Majenko I have taken the time to write an answer and point the elapsed equation out. But the OP rightly stated they are new to it.

Do not name a function ISR(): this name is already used by a macro.

@EdgarBonet If the compiler optimizes it right, yes.  Better to do it properly than assume the compiler will fix it for you.

@Majenko: If you do not trust your compiler for this kind of trivial stuff, then write in assembly, not in C.

@EdgarBonet I am right not to trust the compiler.  % 2 causes a call to __divmodhi4 which is hardly efficient - certainly not as efficient as just doing & 1.  One of the things you soon learn with embedded programming is efficient programming where you can second guess the compiler and do it better.

@Majenko: What compiler are you using? I would not use a compiler dumb enough to call __divmodhi4 for % 2, and I suggest you consider switching to a decent compiler.

@EdgarBonet The standard avr-gcc.  The compiler has no concept of what % is.  It just knows that to do a % operation it has to call the libc function that performs that operation.  It can't know that, just because the second argument is a 2 that it'd be better done with a completely different set of operations since it doesn't know what % does.  Just like if you call "sin(0)" it can't know that it'd be better to substitute that with "0" since it doesn't know what sin() does.  It's just a function, which is all % is.  To the compiler it's the same as %(counter1, 2)

Let us continue this discussion in chat.

@KeyPrice Since your last edit you have made some fundamental errors with your program.  Most notably with your ISR1() function.  Fix your indenting so you can see where the error lies.  Good indenting makes for easy to understand programs. You cannot understand your program because you have a very broken layout.  Start with fixing the layout and you will see your errors as plain as day.  If you can't fix your layout then use an autoformatter to do it for you.

Where did the error messages go? They appear to have been deleted by edit #7. All that is left is a compile status message

Welcome to Arduino.SE. I am not going to rewrite the code for you but from this and other answers and comments you should be able to correct the code for yourself from constructive criticism.
To start at the beginning.
You have defined interruptpinnumber but you don't use it in the attachInterrupt function as you declare interrupt pin 1(digital pin 3) and not 0 as the interrupt pin, this will cause problems in your code.
Next, for your timing variables, they need to be unsigned long as the millis() function will return unsigned long. There is also no need to declare them volatile as you are not using them in the ISR routine.
On the topic of the ISR, you have used the arduino attachInterrupt() and you have used the actual ISR() routine from the AVR libraries, also without including it. In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being isr_rpm) in the attachInterrupt() function to be executed when the interrupt occurs, actually exists.
Also there are some basic arithmetic issues with the elapsed time calculation, that is if you were trying to determine the difference.
As @Majenko also pointed out and I was going to too, that the use of a bitwise AND, & in your if() statements might not be a problem but best to learn now that you should use logical AND for comparison &&.
There is also a redundant if statement, that I will leave to you to find as it is your code and you can determine if it is of use or not. Also you need to keep track of you braces as this will cause the errors you are seeing too.
Edit
I think I need to elaborate on a few things as I think you got confused a bit more.
Concerning the whole arduino attachInterrupt function, the isr_rpm() needs to be a function and not a define, I think this caused it

 In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being isr_rpm) in the attachInterrupt() function to be executed when the interrupt occurs, actually exists.

A function of that would be:
void isr_rpm(){

   //code

}

As @Majenko has kindly done you a favor and annotated your code, look at the stuff related to the interrupt routine (and other stuff) and compare it with the below avrfreaks tutorial, and the original code if you have it, the problem to begin with was that you had too many braces:
void ISR(){
      buttonState = LOW;
      counter1 = counter1 + 1;
      previousState = HIGH;
    }
    }

it should be:
ISR(INT0_vect){
      buttonState = LOW;
      counter1 = counter1 + 1;
      previousState = HIGH;
    }

There is no need to give your own special name to ISR either, this is from the newer code.
AVRfreaks tutorial concerning interrupts and the ISR stuff it will give you an explanation on the volatile stuff too.
I cannot stress the point more but, look through your code that Majenko has annotated and see where you can fix the code.

Thanks guys so much, I have been able to fix about 90% of it and I think I'm down to just a few little brackets and indents and such. after having about a pot of coffee and reading some more reference material along with all of your comments I chose to stick with the actual ISR(). Majenko thanks for mentioning the curly brackets it helped a lot and RSM i could not have made it through the morning with out the coffee and your guidance. as soon as i figure out how the formatting on these posts go i will put up the new and improved code.

@KeyPrice - I am sure I helped but I should have possibly been more exact about the use of an ISR as I think that has lead to the completely new code problems. I would review the annotated code by Majenko and compare that with my notes. Also if you have your original code also look at that as that had some formatting errors mainly and the ISR would have been fine if you put the vector in those brackets. Have she more coffee and read through the ISR() link in my post. Also try http://www.avrfreaks.net/forum/tut-newbies-guide-avr-interrupts?page=all. It is a good tutorial.

Ok, I swore I wasn't going to do this, but I have re-formatted your latest code and I am going to go through and annotate it.
// Including Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>  /// << WHY?!  You're not using it!

LiquidCrystal_I2C mydisplay(0x27, 16, 2);

// Define Input/Output Pins
#define solenoidpin 9
#define potpin 1
#define ignitioninputpin 2
///#define interruptnumber 3
#define isr_rpm(INT0_vect)  /// << What is this hoping to achieve?

// Defineing Variables
int previousstate;
byte buttonstate;
int counter1;
int start;  ///
int finish; /// << These should be unsigned long
int elapsed;///
int RPM;

// Main setup
void setup() {
    pinMode(ignitioninputpin, INPUT);
    digitalWrite(ignitioninputpin, HIGH);
    ////  attachInterrupt(3,isr_rpm, FALLING);  /// << This will never work with that #define I pointed out...
    counter1 = 1;
    mydisplay.init();
    mydisplay.backlight();
    mydisplay.setCursor(0, 1);
    mydisplay.print(" Soleniod Motor ");
    previousstate = HIGH;
    Serial.begin(19200);
    buttonstate = digitalRead(ignitioninputpin);
}

// Main program loop
void loop() {
    buttonstate = digitalRead(ignitioninputpin);
    Serial.println(buttonstate);
    Serial.write("previousstate");
    Serial.println(previousstate);
    Serial.println(counter1);
    float elapsed = start = finish;  /// << You already defined these as ints in the global
    float RPM = (6000 / elapsed);    /// << scope. Why are you defining them again as floats?!  Also,
                                     /// << elapsed = start = finish?!?!  I think you have an = instead of a -
    { /// << Why are you starting a new block here???
        if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << counter1 % 2 is very inefficient since counter1 is signed.
            digitalWrite(solenoidpin, HIGH);
        }

        if (buttonstate == HIGH && previousstate == LOW && (counter1 % 2) == 0) { /// << previousstate never changes from HIGH - this will NEVER run!
            digitalWrite(solenoidpin, HIGH);
        }

        if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << You have already checked this state above with a different outcome.  WHY?!?!
            digitalWrite(solenoidpin, LOW);
        }

        if ((counter1 % 2) == 0) {
            for rpm calcs /// << This isn't even C!!!
            finish = start;

        start = millis();
        }

        if ((counter1 % 6) == 0) {
            mydisplay.setCursor(0, 0);
            mydisplay.print(" RPM ");
            mydisplay.print(RPM);
            mydisplay.setCursor(0, 1);
            mydisplay.print(" Solenoid Motor ");
        }

        void ISR1(); /// << This is a function prototype, not a function definition.
        buttonstate = LOW;       /// << I guess these should be inside
        counter1 = counter1 + 1; /// << a function called ISR1() but that
        previousstate = HIGH;    /// << function hasn't been written.
    }
}

You're trying to mess around writing low-level interrupt routines without having a clue how to work with low level interrupt routines.  Go back and read the manuals on how to do external interrupts with Arduino.  It's very very simple.
There are things about your program that just make me thing "What?!?!" and things that are just plain missing.


text:
increment or decrement the values of an array
I wanted to simulate the Dawn light with my arduino Uno using array implementation.
I desired to change the brightness of the LEDs using fade effect( Smoothly and keep it unchanged until the next function called out) from 0 brightness to specific values in array ( it means specific brightness for each LED).
I wrote my code and compiled it but unfortunately nothing happens when I upload it to my device.
The device is already connected and I have tested some other on/off led codes.
Here is my pre-code:
//Dawn Light Simulation
int LEDArray[] = {3, 5, 6, 9, 10, 11};
int LedNum = 6;
int i;
int j;

int Dawn[] = {30, 20, 20, 20, 100, 0};

int Current[] = {0, 0, 0, 0, 0, 0};
unsigned long time_for_fadestep;
#define Fade_Interval 1200;

void setup() {

  for (int i = 0; i < LedNum; i++)
    pinMode(LEDArray[i], OUTPUT);

}

void DawnMode()
{
  if (millis() > time_for_fadestep) {
    time_for_fadestep = millis() + Fade_Interval;
    for (int j = 0; j < LedNum; j++){
        if (Dawn[j] > Current[j]) Current[j++];
        if (Dawn[j] < Current[j]) Current[j--];
          analogWrite(LEDArray[j], Current[j]);

    }
  }
}
void loop() {
  DawnMode();
  delay(5000);
}

I think you actually meant Current[j]++ not Current[j++], and the same with the Current[j--]

Also you should watch your method of delaying - you will fall afoul of the millis() integer wrap around problem. Instead you should be working with a past timestamp and a delay length (if (millis() - last > delaytime)) to combat it.

Hey Majenko,
Regarding of  ''Current[j++]'', I have made so many changes and got nothing in return,
relaed to your explanation about milis() , could you please explain more.....

Dear @Majenko ,here is a topic for my source to use milis() ,
link

time_for_fadestep was never initialized!

Also you are using 5s delay but your Fade_Interval is 1.2second. Your first led will take 5*30=180s to get to the 30% brightness. Get rid of that delay.

@HadiMirdamadi That source is not good. You should use the official BlinkWithoutDelay example to base your time code on.

@HadiMirdamadi The second code with micros() has been done right. I don't know why he did the first one wrong.

@Fahad Actually, that's not true. time_for_fadestep is in the global scope, thus it gets placed in the BSS. The BSS is cleared during startup, so time_for_fadestep will always be initialized to 0. It's good for readability to be explicit though and assign it manually.

Hey Guys, The code has been executed fine, I made some updates with milis() and also could do the smooth transition between the array's values.... tnx for your comments


text:
Uno R3 connected via Ethernet shield becomes unreachable after a few minutes
I'm setting up an Elegoo Uno R3 with a Seeed 5200 ethernet shield to monitor water flow and temperature. It needs to run unattended for weeks at time (being called several times a day by a remote script).
I'm normally able to send and receive UDP packets for a few minutes when I've just reset/power-cycled the Arduino. After that, it stops responding to UDP messages. By adding some serial output I can see that it hangs unpredictably at different parts of loop(). Sometimes it seems that physically shifting the device will get it to wake up; or it will wake up on its own after a minute or two. Most of the time it works until it quits, then doesn't work until I reset it.
It does respond to ping while it's otherwise unresponsive.
Is there anything wrong with my code? This is my first Arduino project. Otherwise could it be a hardware problem? If I buy another, I'll buy a genuine Arduino. Is Seeed a reliable source for the ethernet shield?
(By the way--I think it's safe to disregard the PACKETLEN thing, which is a leftover artifact. In the end it's unnecessary to read the incoming message anyway, so the packetBuffer array is superfluous but doesn't seem to change anything one way or another.)
Thanks in advance. Best wishes,
Dan
#include <SPI.h>
#include <EthernetV2_0.h>

#define PACKETLEN 48

//Flow and temp globals
byte sensorInterrupt = 0;  // 0 = digital pin 2
byte flowPin       = 2;
byte tempPin = 0;

float calibrationFactor = 45; // we're going to measure for 10s intervals
float minFlow = 270;          // minimum 6 L/min, measured for 10 s
volatile byte pulseCount;
unsigned long startTime, timeDelta;

int tempReading;
float tempVoltage;
float temperature;

//Communication globals
IPAddress ip(xxx, xxx, xxx, xxx);
byte mac[] = {
  0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx
};
EthernetUDP Udp;

unsigned int localPort = xxxx;
char packetBuffer[PACKETLEN+1];  //buffer to hold incoming packet,

int packetSize;
byte flowOk, tempOk;
IPAddress remoteIP;
unsigned int remotePort;

void pulseCounter()
{
  pulseCount++;
}

void setup()
{

  //Serial.begin(9600);
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);

  pinMode(flowPin, INPUT);
  digitalWrite(flowPin, HIGH);

  // attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

void loop()
{

    delay(2000);

    if(packetSize = Udp.parsePacket())
    {
        remoteIP = Udp.remoteIP();
        remotePort = Udp.remotePort();

        //Measure the flow for 10 seconds
        flowOk = 0;
        pulseCount = 0;
        startTime = millis();
        attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
        while((timeDelta = millis() - startTime) <= 10000) ;
        detachInterrupt(sensorInterrupt);
        if (pulseCount >= minFlow)
            flowOk = 1;

        //Check the temperature
        tempOk = 0;
        tempReading = analogRead(tempPin);
        tempVoltage = tempReading * 5.0 / 1024.0;
        temperature = (tempVoltage - 0.5) * 100;
        if (temperature < 35.0)
            tempOk = 1;

        Udp.beginPacket(remoteIP, remotePort);
        if (flowOk && tempOk)
            Udp.write("Ok");
        else
            Udp.write("Not ok");
        Udp.endPacket();
    }

}

If its doing it at random places its most likely to be a memory issue, maybe a buffer overrun?

Thanks for the comment. I assume you're right about a memory issue in one of the libraries. I will post the fix below.

I don't know where my compiler was finding the UDP code in the above sketch, because it's not in EthernetV2_0.h. The problem was fixed by adding the following lines, from the example sketch UDPSendReceiveString written by Michael Margolis and included with the Ethernet_Shield_W5200 library:
#include <EthernetUdpV2_0.h>

#define SDCARD_CS 4

void setup():
    //...//
    pinMode(SDCARD_CS, OUTPUT);
    digitalWrite(SDCARD_CS, HIGH);


text:
Decision maker loop problem
Today, I've started a decision maker, using a Arduino UNO R3, a button and a RGB led.
This project makes a decision for you (yes, no, or maybe) when you don't know your own decision about something.
The code I used in the project is the following one (written by me):
#define out OUTPUT
#define in INPUT
#define H HIGH
#define L LOW

int red = 2;
int green = 3;
int blue = 4;

int randomValue = 0;

int button = 5;
int buttonState = 0;

void setup(){
    pinMode(red, out);
    pinMode(green, out);
    pinMode(blue, out);

    pinMode(button, in);
}

void loop(){
    buttonState = digitalRead(button);
    if(buttonState == H){
        randomValue = random(0,4);
        if(randomValue == 1){
            digitalWrite(red, H);
            delay(200);
            digitalWrite(red, L);
            clear();
        }
        if(randomValue == 2){
            digitalWrite(green, H);
            delay(200);
            digitalWrite(green, L);
            clear();
        }
        if(randomValue == 3) {
            digitalWrite(blue, H);
            delay(200);
            digitalWrite(blue, L);
            clear();
        }

    }
}

The connections are correct, and the code also. The problem is: when I push the button, the LED starts showing random colors, and what I want is for the LED to show one color per push.
What can I do?

There is one basic concept that you are lacking.  At the moment you are looking to see if the button is pressed, not when the button has been pressed.
Instead of just looking to see if it is HIGH you need to look if it was LOW but is now HIGH. It's that transition from LOW to HIGH that you need to use as your trigger for when to set the LED colour, and that means remembering the state of the button the last time you went through the loop.
buttonState = digitalRead(button);
if (buttonState != oldButtonState) {
    oldButtonState = buttonState;
    if(buttonState == H) {
        // Do your stuff
    }
}

oldButtonState is defined the same as buttonState.

oldButtonState is a new variable?

Of course. What else could it be?

You may also need to debounce the button – if you still see multiple changes before the decision is finalized :-) Unless, of course, you consider a bit of dithering to be a good thing…


text:
Do I have to use an RTC to build a clock?
While I was researching ideas for an Arduino clock, I found several clocks that incorporated an RTC (Real Time Clock) module.
I don't know why it is used in some clocks.
So, here are my questions:

How does an RTC module work?
Do I have to use it "like a rule" (is an RTC necessary or unnecessary) in my clock?

It is only necessary if you want the clock to keep accurate time.  ;-)

Or if you want to set alarms:  https://arduino.stackexchange.com/questions/30638/how-to-set-alarms-on-the-ds3231-easily

How does a RTC module works?

It counts. As simple as that. Once a second it ticks and counts up. It also remembers - most have a battery backup and will continue ticking when you turn the main power off.

I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

If you want accuracy and continuation, yes.  An RTC is designed to tick at (as close as reasonably possible) once per second. Trying to do that with just an Arduino is incredibly difficult. The ceramic resonator on an Arduino is not as accurate as the quartz crystals used with an RTC. After a week you may find you are an hour out.

RTC modules are used because they make it easier to keep accurate time. They do this by maintaining time when the system is shut down or rebooted (by way of a battery or some other mechanism for keeping running independently of the host system) and by providing a time base that is, usually, more accurate than that of the host.
Another way to keep very accurate time (potentially better than you can get with all but the best RTC modules) is to get your time from a GPS or from the Internet using NTP. If you're going to use a GPS anyway or need an Internet connection then either of those approaches are very good ways to go. If you don't, then they are considerably more expensive than an RTC module.

I built a clock designed a while ago by Geoff Graham, who synchronized to a GPS around every 24 hours, and used the internal clock in-between. The GPS corrected for drift in the internal clock (and, of course, gave you the time accurately in the process).
This is more expensive than a RTC, but more accurate. If you also had an RTC it would drift less during the day. Or, you could read from the GPS all the time and not have an RTC.
I made a GPS clock myself which does that - just shows the GPS time.

Higher-contrast image:

Internals:

This is another project that uses an RTC clock chip (indicated on photo):

However if you go for just an RTC chip you can expect it to drift over time. They are more accurate than counting processor ticks (and survive a power outage because of the backup battery) but are not as accurate as the GPS.
Those clock chips are pretty cheap. I got 30 of them for $10 from eBay.

How does a RTC module works?

It is a specialized counter. It counts seconds, minutes, hours, days, months and years, properly handling such annoying problems as leap year, different days in months, etc.
Additionally it allows powering with a battery, so that clock ticks even when the device is not powered on, until battery discharges.
Usually RTC is clocked at 32768Hz using standarized quartz crystal.

I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

Unless your microcontroller has RTC built-in, you should use an external one. There are many RTCs with I2C interface.
Built-in timer available in Arduino is not accurate enough and cannot tick when you remove power. Inaccurate counter will cause your clock to drift considerably and no backup power forces your clock to be connected all the time.
You can check out this example to see how to hook up:
https://iobtoolkit.com/docs/tutorials/i2c_terminal_mcp7940n.html
Disclaimer: i'm the author of IOB, but you don't need to use it. It's just a nice analysis of a rather popular RTC.

For this "rule", and for many "rules" like this, the answer is "it's more of a guideline" (usually "it's not required, but may be easier that way").
Keeping time requires 3 things: an accurate "tick", a way of knowing the time initially, and counting the time since then.
The (16mHz) clock on the Arduino will give you a reasonably accurate "tick" - on the order of 50 parts per million. That means, over a million seconds, your clock will drift about 50 seconds. This works about (ballpark) 1 minute per fortnight. Is this accurate enough? This depends on what you are using it for.
The next thing on the list is knowing the time initially. If you buy a RTC, it may be set to the right time, or it may not. Even if it is "set", it may not be set to your timezone. Setting these is pretty easy. It will need to be set every time the clock (be it a RTC or your homebrew clock) loses power. For this reason, RTCs usually have a battery back up. How will your clock get it's time when it starts up? Note that, if your project is network connected, you may be able to get the clock from the internet - this will also mean the drift of your clock will not be an issue - you can retrieve it once per day, so it will never drift more than 4 seconds before it gets corrected.
The final thing that it needs (and the easiest) is a way of counting the time. This is probably the easiest - use the millis() function. Note that this overflows (resets to 0) after 4294967296 milliseconds - about once every 50 days. Millis() will tell you the number of milliseconds since the Arduino last rebooted. If you want your clock to run more than 50 days, you need to be prepared to that. This will happen part way through a second.
Note that this will give you milliseconds, and, fairly easily, seconds, minutes, hours. If you want the day (of the month), then you need to keep track of which month and year, since the length of each month will vary, as will leap days.


text:
Bootloader only works once with usb to serial module
When programming the Pro Mini using this USB-to-serial adapter the boot loader only works once. After the first programming the programmer is out of sync or not responding.
To be able to program the Pro Mini again I have to burn the bootloader using my Uno as an ISP.
Programming the Pro Mini through an Uno does not present the same problem.
Are the lock bits not being set properly or somehow overridden?

Does that adapter really have a DTR signal?

Please show your full wiring.

I actually have the same adapter and it does not have the DTR signal. Therefore it cannot be used. A reset signal cannot be generated. The adapter has 3.3V, RST, TXD, RXD, GND and 5V. The RTS is not the same as DTR.

It does NOT have a DTR signal. Thank you for your help. Will order one that does.

Make sure you add the inline 100nF capacitor in the DTR line or the newer versions of avrdude will fail miserably.

@mikepatel.  It is not true that RTS will not work.  Using it is mentioned in official arduino guides: https://www.arduino.cc/en/Guide/ArduinoMini  this sounds more like a fuses problem with the bootloader memory not being preserved.

The module I had does not have a DTR signal. I mistook the RTS for DTR. Ordering correct module.

You have received faulty advice. The RTS signal is usable, and in fact used in official guides. Your problem is likely something else.

It sounds likely that the OP (long since gone...) was resetting the board manually to get the bootloader to run even that once; and that the bootloader allowed itself to be overwritten, a critical fuse got changed, or that one successful upload otherwise left itself or the board in an un-bootable state.

no. the problem is OP didn't reset (see his answer), but a fresh bootloader doesn't need reset to bootloader


text:
Briefly "wake up" Arduino in response to an event
I want to connect a device to a door handle, so whenever someone opens the door I'll be able to send a message via my arduino that is connected to a WIFI shield.
I have a simple orientation sensor, so I know when the handle is being pushed. The problem is I don't want to keep the Arduino on all of the time (energy issues).
The orientation sensor closes a circuit for about 100ms, so I thought to connect the battery to the Arduino in series with the sensor, but the problem is that it might take more than 100ms to connect and send the data - I need at least 5 seconds to be sure.
Any ideas on how to make the Arduino "power up" for 10 seconds each time someone uses the door handle and then to cut off the power?

Easy answer: Don't.
Have the Arduino sleep most of the time, and let the door handle invoke an interrupt that wakes it up. Then do whatever processing is required, and then go back to sleep.
This won't work as well with a full Arduino as it would with a bare MCU since the rest of the board has its own quiescent load, but once you get it working with an Arduino you can get a bare MCU, wire it up, write the code to it, and away you go.

I had a similar situation some time ago. I don't have the schematic at hand, but it looked more or less like the one below.

It works as follows:

Momentary switch closes and saturates Q1 via R1. It also powers the Arduino. The I/O in on the Arduino has not been programmed yet so it floats. Q1 energizes the coil of the relay which closes its N.O. contact. Now the circuit has latched and you have power to the Arduino for as long as you want.
Arduino starts, does its work (xmits signal or whatever) and then programs the selected I/O pin as output and pulls it low. This will divert current away from the base of Q1, which will cut the current to the coil and everything closes down and no power is drawn from the battery.
R1 should be some 10 times greater than R2 for this to work. Say R1 = 1K, and R2 = 100 Ohm.

This is a concept drawn from memory, it might require some refining :-)

I was going to suggest something along these lines - having the Arduino use a relay to turn itself off would fit the bill quite nicely. Of course the current draw of the relay might be more than it's worth, but I confess very little knowledge in that area

You may find the answer to How can a let my atmega328 run for a year on batteries? from SE Electrical Engineering helpful. It is a very detailed resource on power saving measures for the Arduino.

You are much better off sleeping the Arduino. In power-down mode the processor can use as little as 100 nA (0.1 µA) which is somewhat less than the self-discharge rate of batteries anyway.
I have a page about power saving techniques.
You also would want to make a custom board, or at least choose an Arduino without a voltage regulator, LEDs, USB chip, etc.
The Atmega328P, when in power-down sleep mode, can be woken by an external interrupt, such as what your door could provide.


text:
ACS712 sensor reading for AC current
I'm trying to track down a clearly/simply articulated piece of code to take a reading from the ACS712 current sensor (link to download PDF data sheet).
I understand that these sensors are noisy, and that reading AC current is quite different to DC current.
After looking at a range of examples in a variety of forums etc., I've based the following on http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/
void ac_read() {
  int rVal = 0;
  int maxVal = 0;
  int minVal = 1023;
  int sampleDuration = 100; // 100ms

  uint32_t startTime = millis();
  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0);
    if (rVal > maxVal)
      maxVal = rVal;

    if (rVal < minVal)
      minVal = rVal;
  }

  // Subtract min from max to determine the peak to peak range
  // 1023 = the max value we'll get on the input (1024, zero indexed)
  // 5.0 = 5v total on adc input
  double volt = ((maxVal - minVal) * (5.0/1023.0));

  // div by 2 is to calculate RMS from peak to peak
  // 0.35355 is factor to calculate RMS from peak to peak
  // see http://www.learningaboutelectronics.com/Articles/Voltage-rms-calculator.php
  double voltRMS = volt * 0.35355;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = voltRMS
  double ampsRMS = (voltRMS * 1000)/100;
  Serial.println(ampsRMS);
}

I unfortunately don't have sufficient test equipment at present to validate this, but I'm getting a value of around 8.9 for a 2300W device, which afaict is roughly accurate (based on this calculator http://www.rapidtables.com/calc/electric/Watt_to_Amp_Calculator.htm).
Is anyone able to confirm the above makes sense/is logical/sane?  Is there anything obviously incorrect?

I think I've just worked it out—typo in my code should have been x 1000 for millivolts (which I copy and pasted into the comments).  Will update the example in a sec.

Hi Ata—yes, I've successfully got the ACS712 working with AC on Arduino—see the answer marked as "correct" below, as this was the basic approach I used.  You don't need a differential amplifier, but if you don't use that you need to do extra work in code.  Assuming you're working with AC not DC (DC is much more straightforward).

Measuring the peak-to-peak current and scaling the result will get you an answer which will at least go up and down with the magnitude of your average AC current, so yes it is NOT incorrect.  As you suggested it will be sensitive to noise from the sensor - in fact as you are taking the highest and lowest single readings the noise will always cause the measurement to be higher than actual.
However, I think you could do better.  Given that the code is already having to take many samples (basically as fast as it can) for 100mS (which will sample 5 cycles of the waveform if it is 50Hz and 6 if it is 60Hz, depending on where you are in the world), then you could actually do the maths to measure the RMS value and by basing this on all of the signal the effect of the noise will be reduced.
You need to know the ADC reading when there is no current rZero (which should be around 511 but could be off a bit due to offset errors) - you could measure this with nothing connected to calibrate the sensor, or take a long term average even with the AC signal present.
As the henrysbench tutorial points out it is important that the Arduino samples the signal at a high enough frequency (say 1000Hz - hence 100 samples for your 100mS sample duration)- the count of the number of times that the while loop executes sampleCount will confirm if this still the case even with the extra computation time of this code.
Also if you increase the sample time please be careful that the unsigned long rSquaredSum can't overflow, but I would avoid use of doubles within the while loop as they will definitely slow it down a LOT.
void ac_read() {
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
}

Thanks @c-barnes.  I'd seen something akin to this approach in my initial research (yours is clearer than other examples I'd seen, so thanks!), but given the need for the rZero value I hadn't pursued it.  As I expect this code to run on a number of devices/with a variety of sensors, I'm interested in how I could "take a long term average even with the AC signal present".  Are you able to point to an example or explain how this would be done with the AC present?  The other option would be to implement a "calibrate" mode when no devices are attached to get this value.

I'm pretty sure you've got to use rZero – the sensor (if is the one I'm thinking of, haven't looked specifically for it tonight) reads +/- current, since the ADC can't give you a negative value the sensor uses Vcc/2 as the quiescent (0 A) voltage. Subtracting rZero gives you the negative part of the range.

You mention that you don't have much test equipment, but you don't need any to measure rZero – just let the device run for a bit with no load (disconnect or turn it off) and average a few readings – they should be close to 511/512 but may be off by a bit. The average is rZero.

The beauty of AC is that it averages out to nothing, which is why you needed to measure RMS in the first place.  So even when AC is present if you just accumulate the sampled values and, as above, divide by the number of samples at the end of the period you will get an estimate of rZero.  The only issue is that the AC only averages out to zero if you measure over a whole number of cycles.  If you know the AC frequency you can set sampleDuration accordingly, or sample over a much longer time (few seconds) so that any non whole cycle is a small proportion of the total.


text:
How to clear of contents of string in Arduino?
Currently I convert the characters in char received[20] to string using String randomString(received) and I am able to display it using Serial.println(randomString). After displaying the string, I would like to know the easiest way to clear out its contents.

Have a look at the related question at stackoverflow: http://stackoverflow.com/questions/632846/clearing-a-char-array-c ...

Why are you converting a char array to a String just to print it? Do you realise just how bad that is for the poor little Arduino? http://hacking.majenko.co.uk/the-evils-of-arduino-strings

In C and C++ a null terminated array of characters is a string (although not a String). Many routines for reading input terminate the result with a null as does an assignment like"
char foo[] = "This is a string.";

All you would need to do to "clear" this string is to assign a null to the first character. For example:
foo[0] = '\0';

This clears only the first byte. With = { 0 }; everything is cleared.

For C (null terminated) strings, if the first character is a null, then the string is empty or clear. Functionally that solves the problem, but if there are security concerns then you are right that the whole string should be cleared.

Although an old question, I thought I would chime in. If I took the time to understand the question properly, I believe you wanted to clear the contents of the String and not the char array. This may help those who wanted to empty a string for other reasons.
String randomString(received);
Serial.println(randomString);
randomString.clear(); // This will clear the string

It should be noted that for outputing, there was no need to convert to string first if that was all that was required, because println will prefer a char array anyway.
Again String has a .clear() method for those who reached this page via web search.
Update:
It has been pointed out thanks to @VE7JRO in the comments, that the clear methods availablity is not universal. The ESP devices with Arduino compatibile core libraries do have it, as may others. But AVR devices such as the UNO do not. Which I have confirmed.
A revised version to suit all cases where the .clear method is unavailable.
String randomString(received);
Serial.println(randomString);
randomString = ""; // This will clear the string

Arduino IDE 1.8.9 says this about the clear() function "'class String' has no member named 'clear'". What version of the IDE / other software are you using?

@VE7RJO Using platformio, it shows the method. Which I have alreay used in code. It may depend on whether using AVR or the ESP's but it is certainly present on the ESP8266.

The OP's question "title" mentions "Arduino", which as far as I know is not an ESP8266. Perhaps another Arduino user with a newer version of the IDE could confirm / deny whether this woks or not.

@VE7JRO Have revised after testing. Thanks.

First version with conversion from char[] to Arduino String class:
char received[20];
...
// Some code that assigns received
...
String randomString(received);
Serial.println(randomString);

// Clear string
randomString = "";

Second version without the Arduino String class:
char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Empty received buffer
received[0] = 0;

And third version where the buffer is cleared:
char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Clear received buffer
memset(received, 0, sizeof(received));

Cheers!