text:
Create a sketch that allows me to run a DC motor and LED sequence at the same time
I need a program created that will both run a DC motor and an LED sequence at the same time. The image is what the DC motor code should do.
/*
-==:: 3 Volts DC Motor Driver with Dual 555 Timer IC ::==-
  * Control Pin from 555 IC is needed to STOP the motor
  * Trigger Pin from 555 IC is needed to drive forward or backward
  * PWM on Trigger Pin is used to set the speed
  * Note : Forward and Backward is interchangeable via Motor connection.
 */

int controlPin = 2; // 555 pinout 5
int triggerPin = 3; // 555 pinout 2

// the setup routine runs once when you press reset:

void setup()  {
  pinMode(controlPin, OUTPUT);
  pinMode(triggerPin, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop()  {
//  move FORWARD;
    digitalWrite(controlPin, HIGH);
    digitalWrite(triggerPin, HIGH); //full speed
    delay(3000);
//    PWM testing to control motor speed
//    analogWrite(triggerPin, 128+70); //minimum speed (128+70)
//    delay(3000);

//  STOP;
    digitalWrite(controlPin, LOW);
    digitalWrite(triggerPin, HIGH);
    delay(3000);

//  move BACKWARD;
    digitalWrite(controlPin, HIGH);
    digitalWrite(triggerPin, LOW); //full speed
    delay(3000);

//    PWM testing to control motor speed

//    analogWrite(triggerPin, 128-70); //minimum speed (128-70)
//    delay(3000);

//  STOP;
    digitalWrite(controlPin, LOW);
    digitalWrite(triggerPin, HIGH);
    delay(3000);
}

As for the LED code I have no idea. I just found this code on the web. The important thing is that the codes execute at the same time continuously.

an arduino always runs any program sequentially. ... it's just that it does it so fast, that it looks like it does it at the same time

I edited the post. I understand that, but what I need is that it continuously runs both things at once... run a dc motor and LED chain.

As for the LED code I have no idea ... what should the LED do? ... you need to have that clearly in your mind, otherwise you cannot write the code

do not post a picture of your code ... you will not find anybody that is willing to type it into their computer for testing purposes .... put your original text back into your question and format it as code

Posting pictures of the code is counter productive!

Edit... Sorry about that didn't think it through. As for the LED I just need them to blink randomly or in an order if its needed. About ten LEDs of different colours.

Have you tried anything to solve this yourself? We are not a free code writing service.

As stated in the comments, the Arduino can only execute 1 command at a time. There is no real multi-threading on this hardware. But you can to the work in sequence so fast, that you won't notice the difference with motors or LEDs. Here it is important to use non-blocking code, which doesn't block the execution of other code, when it is only waiting (the delay() function is just busy waiting).
For doing anything non-blocking (as setting LEDs or changing the state of a motor) you can use the millis() function. Refer to the BlinkWithoutDelay example from the Arduino IDE. For a very simple sequence (as blinking) you can directly use the code from the example. Basically you use a timestamp, which holds the last time, the blink code was executed. On every iteration of the loop() function you check, if a certain time has passed since the timestamp have been taken. If so, execute the code again and update the timestamp:
unsigned long timestamp=0;
void loop(){
  if(millis()-timestamp > 500){
    digitalWrite(led_pin,!digitalRead(led_pin));
    timestamp = millis();
  }
}

This code would toggle the led_pin each 500ms.
For coding complex sequences you can make a state machine. For this you create a numeric state variable. In the loop() function you use a switch-case-statement, to execute the right code for each state of your programm. Also directly in the loop() function you change the state variable depending on the time through the above code. This would look somewhat like this:
int state = 0;
unsigned long timestamp = 0;
void loop(){
  if(millis() - timestamp > 1000){
    state++;
    timestamp = millis();
  }

  switch(state){
    case 0:
      digitalWrite(led_pin,!digitalRead(led_pin));
      //  move FORWARD;
      digitalWrite(controlPin, HIGH);
      digitalWrite(triggerPin, HIGH); //full speed
      break;
    case 1:
    case 2:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 3:
      digitalWrite(led_pin,!digitalRead(led_pin));
      // stop moving
      digitalWrite(controlPin, LOW);
      digitalWrite(triggerPin, HIGH);
      break;
    case 4:
    case 5:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 6:
      digitalWrite(led_pin,!digitalRead(led_pin));
      //  move BACKWARD;
      digitalWrite(controlPin, HIGH);
      digitalWrite(triggerPin, LOW); //full speed
      break;
    case 7:
    case 8:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 9:
      digitalWrite(led_pin,!digitalRead(led_pin));
      // stop moving
      digitalWrite(controlPin, LOW);
      digitalWrite(triggerPin, HIGH);
      break;
    case 10:
    case 11:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 12:
      state = 0;
      break;
  }
}

This code would toggle the led_pin every second and also doing the moto sequence 3s forward, 3s stop, 3s backwards, 3s stop. This sequence loops forever.
When you only want to let the led blink continuously, it would be easier to exclude this part of the code from the state machine, but I wanted to show how this principle would work (for example if you want to include a complex blinking sequence).

I TRIED TO USE THIS CODE BUT AN ERROR SAYS LED_PIN WAS NOT DECLARED IN THIS SCOPE... HAVE ANY IDEA WHAT THAT MEANS?

Yes, I didn't put in the trivial stuff, because I just wanted to show the working principle. For toggling a pin, you have to define the pin somewhere (for example as global variable). Put in the pin you use for the LED. Also you have to set the pinMode to OUTPUT for this pin in your setup function.     And also don't forget your shift-lock, since you don't have to yell at me :D

Okay thank you. That helps some, im really new to this language and I am trying to build a DIY project fr an event on Friday. I really don't like to pull all this info out from you, but id greatly appreciate it.

Oh yeah sorry about that!

You should read some basic tutorial for Arduino. Also refer to the Blink example from the Arduino IDE. For working further with Arduino you should fully understand, what each command there does, since that are basics (dealing with digital or analog output/input is really important)   And if my answer is good, you may choose it as correct :D

ahh lol I don't have time... :(


text:
Read CID from SD card with ESP8266
I would like to get the serial numbers of SD cards, with follow code:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

cid_t cid;  // *****at the top with the other globals (for get cid)

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = 4;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println();

  // *****list all files in the card with date and size
  //Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  //root.openRoot(volume);
  //root.ls(LS_R | LS_DATE | LS_SIZE);

  card.readCID(&cid);
  Serial.print("Serial number: "); Serial.println(cid.src); // psn is the serial number field of the struct

}

void loop(void) {

}

I tried to get serial from SD card but I only get this "Serial number: 2065301974". I really need it in hex format, for example "0x0033515c".
Also, I would like to get the complete CID like this:
CID: 0x1B, 0x53, 0x4D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x45, 0x5D, 0x04, 0xE5, 0x00, 0xF9, 0x69

TLDR. Is your question "how do I convert a decimal string into a hex number"?

I see no "src" in the cid_t structure....

the CID is not a true "serial number" it's easily hackable. don't use this for security.

cid_t is a structure that has all sorts of information in it in different formats.  The serial number (psn) is just a 32-bit unsigned integer.  You can print it as hex by printing it as hex.
Serial.println(cid.psn, HEX);

If you want to get the raw data of the structure (which I assume may correspond to the raw data read from the card, but don't quote me on that) you can access the struct as 8-bit values:
uint8_t *p = (uint8_t *)&cid;
for (int i = 0; i < sizeof(cid); i++) {
    Serial.print("0x");
    Serial.print(p[i], HEX);
    Serial.print(" ");
}
Serial.println();

Thank you for your help. I tried this and I got: 12 10 17 4D 49 42 53 54 2 0 0 5 A2 0 19 11 0 0 0 0 I know that is wrong because I got serial of sd card on linux and the real serial number ir "0x000005a2" and what I really want is the complete cid number as shown here a.d-cd.net/ec9effas-960.jpg I´m very grateful –

These are the data obtained from Linux: cid: 041641534d492d534403000000001601 serial: 0x03000000 And these are the data obtained from ESP8266: cid (with your code): 1210174E4361726410001C5019AF0000 serial (whit cid.psn): 0xAF1900C5 Then, apparently it is not showing the correct dada... I think something is wrong with the code. Please help me.

How are you getting the data in Linux?

The CID I find in this file SYS->BLOCK->MMCBLK0->DEVICE->cid and the serial I find in this file SYS->BLOCK->MMCBLK0->DEVICE->serial

Are you sure that you are looking at the right device?

Yes, because when I disconnect the sd card... this folder "MMCBLK0" disappears... and when I connect the sd card... this folder "MMCBLK0" appears... Is it OK?

What device are you using for this test? (the Linux device I mean)...?

The Linux kernel handles two different formats of CID. Maybe that has something to do with it. The source is here.

I think I need get raw cid. Any idea for get on Arduino? The complete CID (32 digits, like this: 041641534d492d534403000000001601)

To print the serial number in hex Serial.println accepts a format parameter:
Serial.println(cid.psn, HEX);

The cid variable is a struct so you can access the the other fields via the structure. But if you really want to access the raw bytes you could cast cid to a pointer then access the individual bytes:
uint8_t *rawcid = reinterpret_cast<uint8_t*>(&cid);
Serial.println(*(cid+3), HEX); // print the 4th byte

Be aware that casting like this can be tricky and you will likely shoot yourself in the foot more than once.

Thank you for your help. I tried this and I got: 12 10 17 4D 49 42 53 54 2 0 0 5 A2 0 19 11 0 0 0 0
I know that is wrong because I got serial of sd card on linux and the real serial number ir "0x000005a2" and what I really want is the complete cid number as shown here https://a.d-cd.net/ec9effas-960.jpg
I´m very grateful

The serial number is just a small part of the Cid. You can see 0 0 5 A2 which as uint32_t is 000005a2 in the string of bytes you have.

These are the data obtained from Linux:
cid: 041641534d492d534403000000001601
serial: 0x03000000
And these are the data obtained from ESP8266:
cid (with your code): 1210174E4361726410001C5019AF0000
serial (whit cid.psn): 0xAF1900C5
Then, apparently it is not showing the correct dada...
I think something is wrong with the code.
Please help me.

source: Stack Exchange

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

sort: votes


text:
Why do random characters fill up my Arduino LCD Display?
I am making a water pump system for plants and I am running into trouble with displaying my Temperature and Humidity values. I am using a 20x4 LCD, Arduino board uno, Capacitive soil moisture sensor, 5v DC water pump, DHT22, and a single relay. When the motor is on, the display first shows the values as expected. Then, all of a sudden random characters fill and move across my screen. When I don't connect my motor to the Arduino, the values show up on the LCD as expected. Please do leave comments so that I am able to improve my code. Thanks.
//Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"

//Pins Used
#define DHTpin 2
#define DHTtype DHT22

//Initialization
DHT dht(DHTpin, DHTtype);
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

int sensor_pin = 0; // Soil Sensor input at Analog PIN A0
int pinValue;
int output_value ;
void setup() {
  // put your setup code here, to run once:
  pinMode(3,OUTPUT);
     Serial.begin(9600);
   Serial.println("Reading From the Sensor ...");

  lcd.begin(20, 4);
  delay(4000);
}

  // put your main code here, to run repeatedly:

  void loop() {
  lcd.clear();
  dht.begin();

  float humid = dht.readHumidity();
  float temp = dht.readTemperature();

  lcd.setCursor(0, 2);
  lcd.print("Temperature: ");
  lcd.print(temp);
  lcd.print("C");

  lcd.setCursor(0, 3);
  lcd.print("Humidity: ");
  lcd.print(humid);
  lcd.print("%");

 pinValue = analogRead(sensor_pin);
 output_value = map(pinValue,700, 300,0,100);

  Serial.print("Mositure : ");
  Serial.print(output_value);
  Serial.println("%");
   if(output_value> 0 && output_value <= 51){
    digitalWrite(3,LOW);
    lcd.setCursor(0,0);
    lcd.print("ON");
    lcd.setCursor(0,1);
    lcd.print("MOISTURE VAL: ");
    lcd.print(output_value);
    lcd.print("%");

    delay(1000);

     }else if(output_value > 51 && output_value <= 100){
      digitalWrite(3,HIGH);
      lcd.setCursor(0,0);
      lcd.print("OFF");
      lcd.setCursor(0,1);
      lcd.print("MOISTURE VAL: ");
      lcd.print(output_value);
      lcd.print("%");

      delay(1000);

     }
     delay(1000);
}

EDIT (1)
Here are some pics of the circuitry and the LCD message. If you find these pictures to not be helpful, I can sketch this circuit. Thank You.

Try to display some static string (not DHT/moisture sensor value) on the LCD and switch on the motor. If the problem still occurs, it is probably caused by EMI from the water pump motor.

Please add a wiring diagram into your question, showing how the components are connected to each other. A photograph of the layout would help, too.

How a project is wired can make a difference. Two people could wire up the same schematic and they could have very different results. Schematics will show if lines are connected but do not show how well the overall implementation is executed. Motors can be electrically very noisy. Proper routing of the currents involved is a must for stable operation. It is difficult to go into all the factors that must be considered. In your case it would help if you could post pictures of the way you wired your project.

I have added pictures to my question now

@ JSC, I printed some static strings, and I am still getting these random characters. How do I eliminate the EMI from my system?

@VarunPoondi Did you manage to solve it? I am facing the same issue.

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


text:
"Soft WDT reset" stack error: RFID-RC522 with NodeMCU
I have been all over the internet to try and find a solution to this, but after one solid week of intense Google searching I have come up with nothing.
What I'm trying to accomplish:
I am simply trying to use the RFID-RC522 NFC reader on an NodeMCU development board (built in ESP8266) with the mfrc522 library.
Problem:
Upon initiating the mfrc522 library, reaching the line mfrc522.PCD_Init(); the Serial outputs the following "error":
Soft WDT reset

ctx: cont
sp: 3ffefa10 end: 3ffefc40 offset: 01b0

>>>stack>>>
3ffefbc0:  00241001 00000001 3ffeec20 40106895
3ffefbd0:  00000002 3ffee9d8 3ffee9f4 40202794
3ffefbe0:  402010b2 00000001 00000032 402010a7
3ffefbf0:  3fffdad0 00000010 3ffee9d8 4020290d
3ffefc00:  402010b2 3ffee9d8 3ffee9d8 40202a01
3ffefc10:  feefeffe 00000000 3ffeebec 40202080
3ffefc20:  feefeffe 00000000 3ffeec08 40203e08
3ffefc30:  feefeffe feefeffe 3ffeec20 40100108
<<<stack<<<
R+⸮⸮⸮

I found a tool that can translate the error EspExceptionDecoder, translated error:
Decoding 10 results
0x40106895: __digitalWrite at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring_digital.c line 84
0x40202794: MFRC522::PCD_ReadRegister(MFRC522::PCD_Register) at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x402010a7: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 51
0x4020290d: MFRC522::PCD_Reset() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x40202a01: MFRC522::PCD_Init() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x40202080: setup at C:\Users\my_user\OneDrive\Arduino\projekter\RFID_DumpInfo_test/RFID_DumpInfo_test.ino line 53
0x40203e08: loop_wrapper at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_main.cpp line 57
0x40100108: cont_norm at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/cont.S line 109

When the mfrc522.PCD_init(); line is commented out the stack-error does not appear.
Reading the NFC tags has worked before on the NodeMCU unit, and I sometimes stubmled upon this error when adding one simple line like var1 = var2; somewhere in the loop, but now the error is there constantly, even with code that once worked - however I did change the pin-loadout, and I suspect that this is the problem.
What I have tried:

With the configurable pins I have tried most combinations I could
think of, trying both the SS and the RST in every available pin.
this Github
example suggets
this
instructables tutorial.
3 different RFID-RC522 modules (same model)
2 different NodeMCU units (same model)

Pin layout:
My pin layout for the RFID-RC522 module is as follows;

SDA (SS): D4
RST: D3
SCK: D5
MOSI: D7
MISO: D6
GND: GND
3v3: 3v3

Arduino project info:

Arduino IDE 1.8.5
Latest MFRC522 from the Library Manager
Board: NodeMCU 1.0 (ESP-12E Module)

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

#define SS_PIN          D4
#define RST_PIN         D3

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
    Serial.begin(9600);
    delay(100);
    SPI.begin();
  delay(100);
    mfrc522.PCD_Init();
    mfrc522.PCD_DumpVersionToSerial();
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

I've been on this issue for days now, and my Google searches tell me that I'm not the only one who has had this problem before. Any input is very welcome.

I have come to the conclusion that using RFID with NodeMCU is not going to work - I can't confirm this, but I'm pretty sure the two libraries (ESP8266 and mfrc522) have some complications caused by one another.
A good workaround is using the TX and RX pins to communicate from an Arduino Nano which has the RFID reader to a NodeMCU board - this way you can send the NFC data to your WiFi board without complications.

can you also try to increase the serial boud rate to fe. 115200 instead of 9600?
In some cases I had some issues with 9600, because some buffers were not cleared fast enough and forces some WDT resets.
Cheers,
Jorgen

now this is interesting!  i had this issue backwards.  I thought that slower was "better".  UPVOTED!  :)

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

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


text:
NodeMCU ESP8266 12E loses code after power is reconnected
I have uploaded a simple code to control a 8 channel relay by turning individual relays on and off
When I upload the code it works properly, the code works properly and the relays turn on and off in the desired pattern. However when i disconnect the USB cable from my computer and reconnect it, the code isnt working anymore, there is no visible action happening. Is the code erased from memory after power is cut?
int pins[] = {D0, D1, D2, D4, D5, D6, D7, D8};
int i;

void setup()
{
  Serial.begin(115200);
  for(i=0;i<8;i++)
  {
    pinMode(pins[i],OUTPUT);
    digitalWrite(pins[i],HIGH);
  }
}
void loop()
{
  for(i=0;i<8;i++)
  {
    digitalWrite(pins[i],LOW);//Turns this relay on
    Serial.println(pins[i]);
//Turn the previous relay off
    if(i==0)
    {
      digitalWrite(pins[7],HIGH);
    }
    else
    {
      digitalWrite(pins[i-1],HIGH);
    }
    delay(700);
  }
}

My circuit:
NodeMCU | Relay
D0 IN1
D1 IN2
D2 IN3
D4 IN4
D5 IN5
D6 IN6
D7 IN7
D8 IN8
Vin VCC
GND GND

Your usage of D0 is forcing bootloader mode to run on boot...?

@Majenko D0 is io16

Well, whatever random D number they decided to assign to GPIO 0 then.... Why couldn't they just number them what they are, rather than randomly assigning other numbers to them?

I had the same issue and solved the problem by the following link : https://github.com/esp8266/Arduino/issues/1074#issuecomment-258669539

D3 (GPIO0) and D4 (GPIO2) both need to be high on startup for the user program to be executed. The relay board connected to those pins are preventing a sufficient high on those pins.
If you need to use those pins then try using a stronger pull-up resistor on those pins. Try 330-470 ohms.
Either that or you will need to add additional circuitry between the port pins and the relay driver. Also please be aware that this will place a high on the relay driver input and will try to turn on the relays. Your powerup conditions may not be what you expect.

Your code will block the loop for more than 5 seconds. For the NodeMcu I found that if the main loop is delayed for long time strange things will happen. So you may also try refactoring to get rid of the for loop and using a simple counter to toggle the relays in each iteration of the main loop. so that your main loop will only be blocked for less than a second.


text:
Arduino Uno Keeps Resetting (Power issue)
Arduinites!
Hoping you can help a newbie. I'm putting together a board for a Christmas present this year. It's replacing the factory board that comes on a beer fridge/vending machine, with minimal interactions.
Basically, when the beer can falls into an outlet chute, it trips a switch that triggers some LEDs and audio. Pretty simple stuff. The fridge supplied +5v to the previous board, so I thought I could remove it and simply swap in the Arduino.
The code runs fine when the Arduino is powered by USB/laptop. I spliced a USB header onto the +5v wire supplied by the fridge and plugged it all in. Now, it will boot up, play some weird fuzz out of the speaker, and reset after about 10 seconds.
How can I use the +5v to power my nutty creation? The previous board had a capacitor on it which I removed (I know next to nothing about some of this stuff but it seems like maybe that would help?)
Here's a photo of what I'm working with. If I need to provide any additional information or photos I can do that.

If you have any advice, please ELI5 with regards to what I might be able to place in my circuit to get this working (links or definitions are incredibly helpful!)
Any help is appreciated!

Without knowing the specs of the power supply it's impossible to tell. It may only have a very low current capacity, or it may be unsmoothed, or similar.

@Majenko thanks for the reply. what's the best way to determine more information about the specs? Multimeter?

First step is to examine the power supply and see if there are any clues. Second step is probably to monitor the power with an oscilloscope looking for brownouts.

Holy jumper wires, Batman!  It might help if you used ribbon jumpers, so you can make sure you don't have an accidental short somewhere.

@computercarguy haha, thanks for the recommendation! You're right, that would definitely clean up the board. Everything works fine when plugged in to my computer, so although it definitely looks a little unwieldly I'm sure it's wired alright for now.

@Majenko I've added some photos from the back of the fridge (informational) and a pic of the power supply board and transformer. In your mind, does this shed any additional information as to why this is happening?

I think @Majenko is on the right track. It's probably a noisy and/or low current power supply.
You also mentioned the old board had a capacitor on it, which makes me suspicious. What happens if you add a capacitor (say 470uF, 16V) across the 5v supply? That capacitor may have been smoothing out the supply, especially with an electrically-noisy compressor nearby.

@toxicantidote thanks for the reply. Where exactly would I add the capacitor? Seems like it would need to somehow be added somewhere before the 5v hits the Arduino, yes?

The main problem here is the current IMHO. The IC on the power supply is a 78L05, which provides at most 100mA. The arduino itself can drain around 30mA; each LED can be around 20mA (you did not specify how many and how much current they absorb), and the audio board is usually hungry. So I think that 100mA are not enough. You can confirm this by measuring the current when it works. Are you forced to use that power supply? Otherwise take a small cheap USB charger (1-2$) and you will have something like 1A+ of available current

@frarugi87 thanks for the reply. I don't have to use it as a power source but it is certainly the cleaner option if I can figure out how to make it work! I have 8 LEDs on the board along with the audio chip, so I could see it being underpowered, but I guess I don't understand why it would work when plugged into a laptop USB and not this source.

@DaveKiss well, a (recent) laptop USB usually can provide at least 500mA (or even more, if it has some USB3 ports). If it is a current issue, I don't think you can solve it with just a capacitor (BTW, use a large electrolytic capacitor rated at 10V or more; connect the pin labelled "-" to the ground and the other to +5V - but don't invert the pins!!! Explosion risk). But maybe it is worth trying. In any case, another supply rated at 1A or more in my opinion will solve your problem


text:
Arduino Yún shield password reset
I'm using a Yún shield from Dragino with an Arduino Uno, but the default wifi password for the shield (which should be "dragino") isn't working.
I tried the wifi reset (holding down the reset button for 5 seconds) and a factory reset (holding down the reset button for 30 seconds) but the password still seems to be incorrect.
Is there any way I can reset the password?

Can you describe how you're determining that the password isn't working?

Try connecting via ethernet to 192.168.255.1 with root/root
The SSH access for Dragrove is:
IP: 192.168.255.1 on LAN port. If you want to connect to the Dragrove via WiFi, the IP should be 192.168.1.108.
Username: root
Password: root
http://www.seeedstudio.com/wiki/Dragrove_-_Generic_gateway_for_internet_of_things

Dragino is just the password for the first initial setup. You probably set a new password. Even if you reset the shield, it keeps your password. This happened to me to and then I put in my password and it worked.


text:
Why can't I upload GRBL but I can upload other sketches
I had GRBL running on an Arduino UNO (China Copy).
When I tried to update to the newest GRBL Version I was not able to upload the sketch:

avrdude: stk500_recv(): programmer is not responding)

I was unable to reprogram a bootloader via another ARDUINO (Arduino ISP) but I was able to update the firmware (dfu-programmer)
The funny thing is that I was only able to program the DFU as AT90USB82 not as ATmega8U2 while the chip has an ATmega8U2 printing.
I can upload any example sketch from Arduino IDE but not GRBL.
Any suggestions?


text:
Is analogWrite() inferior to writing directly into registers?
I'm trying to control a DC motor's speed with my Arduino Mega analogWrite(), but it doesn't seem to function properly. The motor never completely slows down, just slows down a bit (which is still pretty fast) and then stops spinning completely.
I'm trying to create a robot with different speeds, and it just has to have a slow speed. I know it isn't the code, since the relay and motor works just fine when I use the digitalWrite().
Is it better to write directly into the timer registers to implement the PWM, OR what else could be causing the problem?

To answer that we would have to see the code and how you wired things up. At the end of the day analogWrite writes to the registers, so there is no direct reason not to use it. A possible issue is the amount of power available for the motor. A schematic would help sort things out.

Could it be that the power is in excess or in shortage, because i used a 12V relay to interface the motor to the arduino

A relay will have a physical time it can take to operate. You need a motor driver board (or MOSFET wired suitably). Unless you are referring to a solid-state relay and not a mechanical one.

Motors will stall if there isn't enough current.  Motors have a minimal required speed, before they stall. It also depends on the load on the motor. Not that a 50% duty cycle doesn't mean the motor will run at half the speed. There is no one-to-one correlation.

analogWrite() is already PWM, Arduino doesn't produce a true analog signal
Motors tend to draw a lot of current so you might want to control the motor with a MOSFET then connect your power supply directly to the motor. PWM will still work in that case, you just need to connect the output pin to the gate pin of the MOSFET
If you want more of an assurance when working with motors, try buying a motor shield. You current problem, speed problem and many will be resolved. It also makes it easy to control multiple motors.


text:
What would cause a delay when using serial between the Arduino IDE & external clients?
I have been working on a problem for a couple of days that I can't figure out.
I am using a Teensy3.6 with Arduino IDE to build a CAN Bus monitor for a car. For those familiar, I am trying to save the data in the format of can-utils so it can be easily replayed on Linux machines. The board uses the FlexCAN library to facilitate communication.
Everything works well using the Arduino Serial Monitor. However, I want to save the output to a host computer. Unfortunately, I've not been able to get any other serial programs to work. I have tried PuTTY & Python via PySerial. The output seems to get interrupted & doesn't print on a new line correctly.
Sample Output from Arduino Serial Monitor:
(1302.864746) can0 1C5#2C032C032E01
(1302.864868) can0 1F4#000000000000
(1302.865356) can0 287#0000
(1302.865601) can0 F1#340000400000
(1302.865845) can0 96#BFF00A120000
(1302.866455) can0 97#35800A1518300A0A
(1302.866821) can0 98#00000A0080000A13
(1302.867065) can0 1E5#4400335000000103
(1302.867554) can0 C7#00000000
(1302.867798) can0 1E9#FF8300EFFC0000
(1302.868042) can0 232#0000000000000000
(1302.868652) can0 1E1#00000000001CC0
(1302.868896) can0 2F9#83000000000007
(1302.869019) can0 222#001607AD0C00
(1302.869629) can0 BC#A11E005C00000000
(1302.869751) can0 D3#2C02
(1302.869995) can0 186#44005D0000017C
(1302.870483) can0 224#CBC8C8
(1302.870605) can0 228#005B5F5B
(1302.870850) can0 1F3#80BC00
(1302.871460) can0 B9#000A800002000000

Output from PuTTY/PySerial:
(1443.927002) can0 C1#10026B0210037D86
(1443.927246) can0 C5#10026B0310026B02
(1443.927490) can0 D1#40007FFF00FF00
(1443.927856) can0 1EB#0241(1444.011230) can0 AA#2C032C030253FC00
(1444.011597) can0 C9#8000002000101800
(1444.012085) can0 1E7#019000000000316D
(1444.012329) can0 1ED#019000000000316D
(1444.012451) can0 34A#000000001B
(1444.012939) can0 1EF#00000000

My naive opinion is it seems the CAN data comes faster than the serial is writing. However, it's odd that it works fine in the Arduino IDE. It happens about 1x/second--which is well enough to cause a headache.
Outside of SD cards or writing locally--does anyone know why this might happen? Or how I could save this data to a host computer? Worst case I can copy/paste the output from the Arduino Serial Monitor, but that isn't very elegant.
Thank you!
Edit: Here is some relevant code from my Arduino IDE. I modified the object oriented can example from flexcan to print in my desired format.
#include <FlexCAN.h>
static CAN_message_t msg;
elapsedMicros sinceStart;

class CANHandler : public CANListener{
  void printFrame(CAN_message_t &frame);
  void gotFrame(CAN_message_t &frame, int mailbox); //overrides the parent version so we can actually do something
};

void CANHandler::printFrame(CAN_message_t &frame){
   Serial.print("("); Serial.print(sinceStart / 1000.0 / 1000.0, 6);
   Serial.print(") "); //cast to 6 decimals to make compatible with can-utils
   Serial.print("can0 "); // to identify a CAN channel for can-utils
   Serial.print(frame.id, HEX);
   Serial.print("#");
   for ( uint8_t i = 0; i < frame.len; i++ ) {
     if(frame.buf[i] < 15){
        Serial.print("0"); Serial.print(frame.buf[i], HEX);
     } else {
        Serial.print(frame.buf[i], HEX);
     }
 }
 Serial.println();
}

void CANHandler::gotFrame(CAN_message_t &frame, int mailbox){
printFrame(frame);
}

CANHandler canHandler;

void setup() {
    Serial.begin(115200);
    Can0.begin(500000);
    Can0.attachObj(&canHandler);
    CanHandler.attachGeneralHandler();
}

void loop() {
//run until exit
}

so, one thing about interrupt-driven routines (I am assuming that the CANHandler is one such) is that they can truly fire at any time, including during while the handler is already running. There are a few strategies for dealing with this. One is to have the handler return as soon as possible and then deal with the slow task (serial output in this case) in a main program loop. But you'd have to find a way to stash the CAN frame somewhere for later processing in this case.

The IDE buffers what it is sending to the screen. As Chris points out, the interrupt driven routine is likely your issue. I use a ramdrive to stash data in cases like this.

@ChrisCombs Can the handler really be started again, if it is already running? If the handler function is called from an interrupt routine, it will not be interrupted by another interrupt, as long as you don't re-enable interrupts on purpose inside it (and why would you do this in such a case). If another interrupt fires during the ISR execution, it will be executed after the current ISR exited. That's at least, how I understand it.

My understanding is that you have to explicitly disable interrupts inside your ISR if you want this behavior. But I could certainly be mistaken!

If your data input rate is higher than, or even close to, your serial output rate (baudRate/10 char/s), your system will be unable to keep up.
With an interrupt driven system, make sure your interrupt function executes and returns as quickly as possible, i.e., does as little as needed to not lose data. Let the background process (the main sketch code) deal with the incoming data as it appears. Make sure the both processes are short enough to deal with the worst-case input-data bursts without losing any. For the background process, use as high a baud rate as it is capable of - and as it's downstream neighbor (Storage device? Another MCU or PC?) is capable of - keeping up with.


text:
Dragino Lora shield for Arduino sensor use
I am new to arduino and lora technology and i have dragino lorashield for arduino Uno and dragino gateway. I have also MQ-3 gas sensor and I want to detect the alcohol value and to send it to the gateway using the lorashield after that the gateway should send the data to ThingSpeak platform.
Currently the code for my MQ-3 sensor is as below. I would like to ask you for some help as I dont know how to write the code for the dragino and to send it to the gateway. Thanks in advance!

void setup() {
 Serial.begin(9600);
}
void loop() {
 float sensor_volt;
 float RS_gas; // Get value of RS in a GAS
 float ratio; // Get ratio RS_GAS/RS_air
 int sensorValue = analogRead(A0);
 sensor_volt=(float)sensorValue/1024*5.0;
 RS_gas = (5.0-sensor_volt)/sensor_volt; // omit *RL
 /*-Replace the name "R0" with the value of R0 in the demo of First
Test -*/
 ratio = RS_gas/0.01; // ratio = RS/R0
 /*-------------------------------------------------------------------
----*/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 delay(1000);
}

The code is working fine when I am using only the arduino. How do I modify it to use lora and to send the data to the gateway?

start with any example sketches that you can find

please format your code ... put ``` (three backticks) on a blank line before the code and same after the code


text:
I tried to make a obstacle avoiding car (OAB), but my code seems to have a lot of errors
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 200
#define MAX_SPEED 190
#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR34_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);
Servo myservo;

boolean goesForward=false;
int distance = 100;
int speedSet = 0;

void setup() {

myservo.attach(10);
myservo.write(115);
delay(2000);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
}

void loop() {
int distanceR = 0;
int distanceL = 0;
delay(40);

if(distance<=15)
{
moveStop();
delay(100);
moveBackward();
delay(300);
moveStop();
delay(200);
distanceR = lookRight();
delay(200);
distanceL = lookLeft();
delay(200);

if(distanceR>=distanceL)
{
turnRight();
moveStop();
}else
{
turnLeft();
moveStop();
}
}else
{
moveForward();
}
distance = readPing();
}

int lookRight()
{
myservo.write(50);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
}

int lookLeft()
{
myservo.write(170);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
delay(100);
}

int readPing() {
delay(70);
int cm = sonar.ping_cm();
if(cm==0)
{
cm = 250;
}
return cm;
}

void moveStop() {
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
}

void moveForward() {

if(!goesForward)
{
goesForward=true;
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
{
motor1.setSpeed(speedSet);
motor2.setSpeed(speedSet);
motor3.setSpeed(speedSet);
motor4.setSpeed(speedSet);
delay(5);
}
}
}

void moveBackward() {
goesForward=false;
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
{
motor1.setSpeed(speedSet);
motor2.setSpeed(speedSet);
motor3.setSpeed(speedSet);
motor4.setSpeed(speedSet);
delay(5);
}
}

void turnRight() {
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
delay(500);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
}

void turnLeft() {
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
delay(500);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
}

These are the error messages:

    Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

sketch_nov27b:44:15: error: stray '\342' in program

 void setup() {

               ^

sketch_nov27b:44:16: error: stray '\200' in program

 void setup() {

                ^

sketch_nov27b:44:17: error: stray '\213' in program

 void setup() {

                 ^

sketch_nov27b:44:18: error: stray '\342' in program

 void setup() {

                  ^

sketch_nov27b:44:19: error: stray '\200' in program

 void setup() {

                   ^

sketch_nov27b:44:20: error: stray '\213' in program

 void setup() {

[ trimmed ]
                       ^

sketch_nov27b:199:24: error: stray '\342' in program

 void turnLeft() {

                        ^

sketch_nov27b:199:25: error: stray '\200' in program

 void turnLeft() {

                         ^

sketch_nov27b:199:26: error: stray '\213' in program

 void turnLeft() {

                          ^

sketch_nov27b:199:27: error: stray '\342' in program

 void turnLeft() {

                           ^

sketch_nov27b:199:28: error: stray '\200' in program

 void turnLeft() {

                            ^

sketch_nov27b:199:29: error: stray '\213' in program

 void turnLeft() {

                             ^

Multiple libraries were found for "Servo.h"

 Used: C:\Users\amish\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\Servo

exit status 1

stray '\342' in program

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

You already asked about this sort of problem a few minutes ago. It's the same issue. Make sure you use a text editor for code or an IDE, nothing like Word. And be careful when you copy/paste from web pages.

could u pls recommend one

i am actually new to this so i have no idea of these text editors

Why do you ask essentially the same question again? You should really first look into, why you have those unprintable characters in the code? Have you just copied it somewhere? Then check that source.

For removing the unprintable characters, you can use Notepad++. Look for example (here)[https://www.shahabjafri.com/2020/03/01/how-to-find-non-ascii-unprintable-characters-using-notepad-plus-plus/] for a tutorial on how to find the unprintable characters (just found by googling). When you have removed them, you can again work in the Arduino IDE

Duplicate: trying to do a security motion sensor using the peizer and hc-sr04 but i am not able to find the errors the error code is all the way down

You copied and pasted the code from a website that presents the code using typography, not code blocks.
You have lots of typographical special characters in your code from pasting it.
Instead of copying and pasting code you should read and understand code then write your own.


text:
I have made a Nano send 4 pot values to an Uno please help with code
Happy New Year!
So I have made a Nano send 4 pot values to an Arduino Uno over serial but I have a problem: I don't know how to separate these values. Here's the code:
Master:
    int Pot = A0;
    int Pot2 = A1;
    int Pot3 = A2;
    int Pot4 = A3;

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

    void loop() {
      int Value = analogRead(Pot);
      int Value2 = analogRead(Pot2);
      int Value3 = analogRead(Pot3);
      int Value4 = analogRead(Pot4);
      Serial.write(Value); //Write the serial data
      Serial.write(Value2); //Write the serial data
      Serial.write(Value3); //Write the serial data
      Serial.write(Value4); //Write the serial data
      delay(150);
    }

Slave:
    int incomingByte; // for incoming serial data

    void setup() {
      Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
      }
    }

And a bit from the serial logs:

    I received: 255
    I received: 247
    I received: 11
    I received: 0

It updates and sends these four values for the four pots, it can read them but they are together, and it sometimes also kind of lags if I can say it like that; it sometimes takes longer to update but then it goes to normal again.
Thanks!

This is actually a huge topic, one that I could write volumes on. However I will try and be concise. But it is such a common question it's time to finally write a definitive answer.
Sending data between devices, be that computers, Arduinos, or anything else like that, is very much like speaking to someone.
It is very common to do something like you have done and just "send" the data. However that is, as you have rightly noticed, very much akin to sending someone a message all in capitals with no spaces or punctuation. Like this:

WHATAPIECEOFWORKISMANHOWNOBLEINREASONHOWINFINITEINFACULTYINFORMANDMOVINGHOWEXPRESSANDADMIRABLEINACTIONHOWLIKEANANGELINAPPREHENSIONHOWLIKEAGODTHEBEAUTYOFTHEWORLDTHEPARAGONOFANIMALSANDYETTOMEWHATISTHISQUINTESSENCEOFDUSTMANDELIGHTSNOTMENONORWOMANEITHERTHOUGHBYYOURSMILINGYOUSEEMTOSAYSO

Only through effort and the application of known predefined standards (i.e., English vocabulary) is it possible to make out what the message says.
So in language we introduce "meta" information - that is, information in a message that tells you not about the content of the message, but about the message itself.  The simplest is to introduce spaces to indicate where words start and end. So that message now becomes:

WHAT A PIECE OF WORK IS MAN HOW NOBLE IN REASON HOW INFINITE IN FACULTY IN FORM AND MOVING HOW EXPRESS AND ADMIRABLE IN ACTION HOW LIKE AN ANGEL IN APPREHENSION HOW LIKE A GOD THE BEAUTY OF THE WORLD THE PARAGON OF ANIMALS AND YET TO ME WHAT IS THIS QUINTESSENCE OF DUST MAN DELIGHTS NOT ME NO NOR WOMAN EITHER THOUGH BY YOUR SMILING YOU SEEM TO SAY SO

There, that's much more readable. But still lacking. So we add more "meta" characters that provide even more information about the formation of the message: punctuation.  Now we can have:

What a piece of work is a man! How noble in reason, how infinite in faculty! In form and moving how express and admirable! In action how like an Angel! in apprehension how like a god! The beauty of the world! The paragon of animals! And yet to me, what is this quintessence of dust? Man delights not me; no, nor Woman neither; though by your smiling you seem to say so.

And now the message is completely plain. What we have done here is introduce characters that aren't part of the message but form the structure of the message. These characters are distinct from the message by being of a different type of character. Not letters, but symbols instead. It's possible to add any symbol you could imagine and attach a meaning to it to convey any information about the message you like. There is no limit.
But that's where computer communication differs.
When sending data over serial you have a limited range of values you can send. You have one byte for sending information, which means that you can only send one of 256 possible "symbols".
When you're sending, as you are, binary data you use all 256 symbols for your data. There are no symbols left for any "punctuation" in your message. It becomes impossible to go even from the first to the second examples above, let alone the third.
So what can be done?
Well, there's two approaches:

Re-encode your data to use less "symbols" leaving some available for meta information
Nominate some of the symbols used for data to be also used for meta information and create some way of distinguishing them from the actual data

The first method is probably the simplest - change the data encoding to use a smaller range of symbols. The most obvious way is to use ASCII encoding - use just 10 symbols to represent numerical data, but use a lot more of them. I'm sure you know the symbols: "0123456789". You then have such standard symbols as "New Line" (or \n) to mark when your message is finished, and commas to separate different parts of your message.
It's easy to encode and transmit, but harder to receive.  Sending is as simple as:
Serial.print(Value);
Serial.print(F(","));
Serial.print(Value2);
Serial.print(F(","));
Serial.print(Value3);
Serial.print(F(","));
Serial.println(Value4);

Receiving that data and making sense of it is far more involved. You have to read everything up to a comma (or to the end of the line and split it on a comma) and then convert the ASCII text back into numbers. It could be done on the fly on a character-by-character bases (read a character, if it's a number then multiply your current value by 10 and add the new number to it, if it's a comma then move on to to the next number, or if it's the end-of-line then reset to the first number again) or as a whole chunk of data (read the whole lot into a char array until you reach \n then split it with strtok() on the commas, and convert each chunk with atoi()).
That method though is not efficient. It takes a lot of bytes to represent just a small number (for instance the number 100 takes 3 bytes whereas the value 100 will fit into a single byte as a raw value), and processing it afterwards is slow and cumbersome.
Method 2 from the list above is far more efficient, but takes a little more in-depth knowledge and thought.
Step one is to design a strict format for your message. You need some way of saying "This is the start of the message" and "This is the end of the message" and everything in between is considered the data for the message. Since you are working with fixed sized variables you don't need anything within that data to separate the values.
You have 4 integer values. That's 8 bytes in total (each integer takes 2 bytes for 16 bits).  You could pack those together in to a struct for easier handling:
struct data {
    int value1;
    int value2;
    int value3;
    int value4;
};

struct data values;

That is good if you have lots of different kinds of data, but since yours are all the same a simple array might be better:
int values[4];

Now the ASCII character set has a set of control characters that are intended to be used for building these kind of messages. For example character 2 is "STX" or "Start Of Text". Character 4 is "EOT" or "End Of Transmission".  So you could choose to start your message with character 2, then send your 8 bytes, and follow it with character 4.  Then you just look for a 2, read 8 bytes, and check it's followed by a 4.  That would work, right?
Well, no. Not quite. What if you're sending the value 2 or 4 as part of your data? How would it distinguish those from the start/end characters?  You can't.
It's now time to introduce a new concept: Data Link Escape. This is where you nominate another special character. This one says "The next character is data. Treat it as such". DLE is character 16 in ASCII, so you might like to use that. 27 is sometimes used too, or 255. You can use whatever you like, but I like 16 (DLE).
The idea here is that if you are sending a byte that could be either a control character or a data character (i.e., 2 or 4) then you first send the DLE character if and only if that character should be interpreted as data. So if you are sending a start byte you send just 2. If you're sending the value of 2 in your data you send 16 then 2.
But what, you ask, if you are sending the value 16 in your data? Simple: you just send it twice. The first time is the DLE character which says the next byte is data. The next is interpreted as data regardless because it's following the DLE character.
Sounds complex, yes? Well, not really. Let's visualise it.  Take our original text message. Let's nominate A as the start of message and B as the end of message. We'll even add C as a space character. D will be our DLE character.  Our message would now look like (I won't do it all, too tedious...):

AWHDATCDACPIEDCECOFCWORKCISCMDANB

To you as a human it looks garbled, but that's because you're trying to apply standard English rules to it. But if we take it one character at a time and apply our new rules to it it's different:

A - start of message
W - letter W
H - letter H
D - Next character is a letter
A - letter A
T - letter T
C - Space

... etc ...
We do just the same with your binary data. Let's say we're sending the values 23, 2, 16 and 1928 as integers. In little-endian (I'll go into that later on) that's represented as the values
23,0,2,0,16,0,136,7

so with our start and end characters, and adding our DLE character 16 we end up with
2,23,0,16,2,0,16,16,0,136,7,4

You might like to write a little function to send data in that format:

int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

void sendPacket(const uint8_t *data, int len) {
    Serial.write(STX);
    for (int i = 0; i < len; i++) {
        // Escape the special characters
        if ((data[i] == STX) || (data[i] == EOT) || (data[i] == DLE)) {
            Serial.write(DLE);
        }
        Serial.write(data[i]);
    }
    Serial.write(EOT);
}

// then use it:

sendPacket((uint8_t *)values, sizeof(values));

Now reception can be done one byte at a time and fed into your array as raw data. Something like this:

int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

bool rxData(uint8_t *data, int len) {
    static int pos = 0; // Where in the data are we now?
    static bool isDLE = false; // Are we in DLE mode?
    static bool messageStarted = false; // Are we receiving yet?

    if (Serial.available()) {
        int b = Serial.read(); // Read one byte

        if (!messageStarted) { // We're not receiving yet - should we start?
            if (b == STX) { // STX received, start receiving.
                messageStarted = true;
            }
            // Anything else is ignored.
            return false; // Message not complete yet
        }

        // If we're here we must be part way through receiving.

        // If we received a DLE last time then we always treat it as data
        if (isDLE) {
            data[pos++] = b;
            isDLE = false; // No longer in DLE mode
            if (pos > len) { // Too many bytes in the message, something bad happened
                // ABORT
                pos = 0;
                messageStarted = false;
            }
            return false; // Message not complete yet
        }

        // If we have an STX and we're not in DLE mode then we must be
        // out of sync. Reset the counter and flags and start a fresh message
        if (b == STX) {
            pos = 0;
            isDLE = false;
            return false; // Message not complete yet
        }

        // Are we at the end of the message?
        if (b == EOT) {
            if (pos == len) { // Did we receive the right number of bytes?
                messageStarted = false;
                return true; // Message complete
            }
            // Something bad must have happened. Not the right amount of
            // bytes received for a valid message. ABORT.
            messageStarted = false;
            pos = 0;
            isDLE = false;
            return false; // Message not complete yet
        }

        // Check for a DLE character
        if (b == DLE) {
            isDLE = true;
            return false; // Message not complete yet
        }

        // Anything else is a data byte.
        data[pos++] = b;
        if (pos > len) { // Too many bytes in the message, something bad happened
            // ABORT
            pos = 0;
            messageStarted = false;
        }
    }
    return false; // Message not complete yet
}

// Then use it:

if (rxData((uint8_t *)values, sizeof(values)) {
    Serial.print("You got: ");
    Serial.print(values[0]);
    Serial.print(", ");
    Serial.print(values[1]);
    Serial.print(", ");
    Serial.print(values[2]);
    Serial.print(", ");
    Serial.println(values[3]);
}

Now I haven't tested any of this code, so take it with a pinch of salt.
Now a little word on endianness.  An integer is 16 bits in size. That takes two bytes to represent (2 x 8 = 16). The "endianness" of a system is the order in which those two bytes are stored in memory.  In a little-endian system, like the Arduino, the value 1928 is stored as the bytes 136,7. But on a big-endian system it's stored as 7,136. The "biggest" (i.e., most significant byte) value comes first. When sending binary data like this it's vital to ensure that both ends of the link agree on the order of the bytes. And then there's word size to consider. 8-bit systems use a 16-bit word for integers. 32-bit systems use a 32-bit word. So sending an int from an Arduino to a Pi, for example, will cause confusion - the Arduino sends 2 bytes (for 16 bits) and the Pi expects 4 bytes (for 32 bits).
To combat the latter it is good to use the fixed width variable types that specify exactly how many bits are used. Instead of int use uint16_t (for Unsigned INTeger 16 bits). That way you're unambiguous about what size it is.
To combat the former problem (if needed) there are a standard set of functions that alter values from native to "network" endianness. Network endianness is a standard used for IP communication and is the same as big-endian.  If you're only ever going to communicate between little-endian Arduinos then there's no real need for this. But if that is not going to be a certainty then using htons() for "Host to Network Short" and ntohs() for "Network to Host Short" ("short" is a 16 bit word, like int16_t) could be of benefit. It's best to use them when storing or retrieving values in your values[] array:
values[0] = htons(analogRead(0));

and:
Serial.print(ntohs(values[0]);

You may need to include the header machine/endian.h in your code depending on which system you're using.
I could go into so much more depth about things like variable length packets, checksums, sliding window reception and such, but for now this covers the basic concepts. Maybe I'll write a book.

Thank you. I never read an answer like this. Please write the book, I'll buy it whatever it may take.

If your goal is to "talk" to a computer vs. a human, then a format that can be parsed easily is better than one that is easy to read.
For example, you have:
I received: 255
I received: 247
I received: 11
I received: 0

While this could be parsed by your Uno, it will be a lot simpler if you send the data something like:
255|247|11|0

Now you can use a "C" string parsing function like strtok() to parse on the "|" character.  Of course there are many other ways to do this as well but this is one possible solution to your question.

So like this? And also what kind of serial speeds do I use? @Majenko This is the sender:
    int pot1 = A0;
    int pot2 = A1;
    int pot3 = A2;
    int pot4 = A3;

    // Some symbols for easy reference
    #define STX 2
    #define EOT 4
    #define DLE 16

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

    void sendPacket(const uint8_t *data, int len) {
      Serial.write(STX);
      for (int i = 0; i < len; i++) {
        // Escape the special characters
        if ((data[i] == STX) || (data[i] == EOT) || (data[i] == DLE)) {
          Serial.write(DLE);
        }
        Serial.write(data[i]);
      }
      Serial.write(EOT);
    }

    void loop() {

      int values[4] = {analogRead(pot1), analogRead(pot2), analogRead(pot3), analogRead(pot4)};
      sendPacket((uint8_t *)values, sizeof(values));

    }

And this is the receiver:
int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

bool rxData(uint8_t *data, int len) {
  static int pos = 0; // Where in the data are we now?
  static bool isDLE = false; // Are we in DLE mode?
  static bool messageStarted = false; // Are we receiving yet?

  if (Serial.available()) {
    int b = Serial.read(); // Read one byte

    if (!messageStarted) { // We're not receiving yet - should we start?
      if (b == STX) { // STX received, start receiving.
        messageStarted = true;
      }
      // Anything else is ignored.
      return false; // Message not complete yet
    }

    // If we're here we must be part way through receiving.

    // If we received a DLE last time then we always treat it as data
    if (isDLE) {
      data[pos++] = b;
      isDLE = false; // No longer in DLE mode
      if (pos > len) { // Too many bytes in the message, something bad happened
        // ABORT
        pos = 0;
        messageStarted = false;
      }
      return false; // Message not complete yet
    }

    // If we have an STX and we're not in DLE mode then we must be
    // out of sync. Reset the counter and flags and start a fresh message
    if (b == STX) {
      pos = 0;
      isDLE = false;
      return false; // Message not complete yet
    }

    // Are we at the end of the message?
    if (b == EOT) {
      if (pos == len) { // Did we receive the right number of bytes?
        messageStarted = false;
        return true; // Message complete
      }
      // Something bad must have happened. Not the right amount of
      // bytes received for a valid message. ABORT.
      messageStarted = false;
      pos = 0;
      isDLE = false;
      return false; // Message not complete yet
    }

    // Check for a DLE character
    if (b == DLE) {
      isDLE = true;
      return false; // Message not complete yet
    }

    // Anything else is a data byte.
    data[pos++] = b;
    if (pos > len) { // Too many bytes in the message, something bad happened
      // ABORT
      pos = 0;
      messageStarted = false;
    }
  }
  return false; // Message not complete yet
}

void loop() {
  // put your main code here, to run repeatedly:
  if (rxData((uint8_t *)values, sizeof(values))) {
  Serial.print("You got: ");
    Serial.print(values[0]);
    Serial.print(", ");
    Serial.print(values[1]);
    Serial.print(", ");
    Serial.print(values[2]);
    Serial.print(", ");
    Serial.println(values[3]);
  }
}

Look in this please @Majenko


text:
Hello, help with CODE servo mechanism and DS1307
I am trying to make a auto feeder for birds!,
I can't setup my code, the aim is to move servo when the certain time comes,
My commend if doesnt work, what else commend can I use?
#include <Wire.h>
#include "RTClib.h"
#include <Servo.h>

RTC_DS1307 RTC;
Servo myservo;

void setup () {
    Serial.begin(9600);
    Wire.begin();
    RTC.begin();
    myservo.attach(9);
    myservo.write(45);

  if (! RTC.isrunning()) {
   Serial.println("RTC is NOT running!");

  RTC.adjust(DateTime(2017,05,18,11,10,0));
  }
}

void loop () {
    DateTime now = RTC.now();
Serial.print(now.year(), DEC);
 Serial.print('/');
 Serial.print(now.month(), DEC);
 Serial.print('/');
 Serial.print(now.day(), DEC);
 Serial.print(" (");
 Serial.print(") ");
 Serial.print(now.hour(), DEC);
 Serial.print(':');
 Serial.print(now.minute(), DEC);
 Serial.print(':');
 Serial.print(now.second(), DEC);
 Serial.println();
 Serial.print(" since midnight 1/1/1970 = ");
 Serial.print(now.unixtime());
 Serial.print("s = ");
 Serial.print(now.unixtime() / 86400L);
 Serial.println("d");

    if ( now.hour()== 10 && now.minute() == 18){
      Serial.print('a');

    }

}

my code doesnt work is meaningless ... something like my code does xyz, and i would like it to do abc123 has a meaning

also, please indent your code properly ... it shows the fliw of the code, like paragraphs in a book ... it is indented properly in first half of setup(), and then it gets messy ... the first line of loop() is indented properly and then all the serial.print statements are badly indented ... my guess is that you added the badly formatted code


text:
Use external power - nodemcu 0.9
I'd like to deploy my project so I'm looking for a way to power the nodemcu.
I'd like to know if there's a way to power it with a 9V battery without any other external circuit.
Until now I've found information for the nodemcu 1.0 and it supports up to 20V on the VIN port. Here's the article I read:
http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/
I'd like to use the two port: 5V and GND but I'm not sure, here there is no VIN port and I'd prefer to not burn my board.
Are there any better way to power my project?

you can feed more than 5v in, especially for short periods of time.

It looks like the 0.9 uses the SPX3819 regulator. That can run with up to 16V on the input, so 9V on the 5V pin (as long as USB never gets connected) should work fine.
Except: 9V PP3 batteries are useless. If it can even provide enough power to run the board (which is doubtful) it won't last more than a few hours.  You would have to ensure that you use very very deep sleep mode to get any semblence of longevity out of it.
The 3.3V regulator will be throwing away half to two-thirds of the power as heat. So wasteful. You would be better off investing in a 3.3V switch-mode ("buck") regulator circuit (cheap on eBay) to directly power the 3.3V pin of the board instead of 9V into the on-board regulator.

Thank you, I'm actually using DeepSleep in fact the board should sleep more or less for 6 hours, wake for few seconds (1 min max) and the go to deep sleep again. I cannot use a power bank because when the board is in deep sleep because it stop to provide power

About the 3.3V regulator, does the AMS1117-3.3 is ok? From here I read that the Vin-Vout should be between 1.5V and 12V, is it correct?
http://www.advanced-monolithic.com/pdf/ds1117.pdf

That is just as inefficient. But it can handle more current before it melts.

You want to look for a "UBEC" (that's the magic word). Something like this.


text:
Corrupted files generated by Arduino with SdFat library. How to avoid that?
I got:

https://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
http://wiki.iteadstudio.com/Stackable_SD_Card_shield_V3.0 (set to 5V logic)

with this sketch using SPI/SdFat+OneWire/DallasTemperature+EmonLib and no matter what I try I got corrupted files like this.
I even haven't attached my sensors yet :(
I have tried with 3 SD cards so far, each formatted with SD Memory Card Formatter and each one has this problem.
There is a separate question like that (Corrupted files generated by Arduino with SD library. How to avoid that?) but it concerns SPI confict but here SD is my only SPI device on the bus.
Any ideas?

This SD shield has CS on D4, not D10

Did this solve your problem?

yes, it did solve it


text:
Arduino WiFi Rev2 JSON String
I have been trying to use the WifiNINA library to access the JSON output from the following API using the WifiNINA library and the Arduino Wifi Rev2.
This is the code that I have been using (it is an edited example form the library):
/*
  Web client

 This sketch connects to a website (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo)
 using the WiFi module.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and UNO WiFi Rev.2)

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */

#include <SPI.h>
#include <WiFiNINA.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.alphavantage.co";    // name address for Google (using DNS)

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

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo HTTP/1.1");
    client.println("Host: https://www.alphavantage.co");
    client.println("Connection: close");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

However, when I run the library, all that the serial monitor returns is:
Attempting to connect to SSID: HIDDEN
Connected to wifi
SSID: HIDDEN
IP Address: HIDDEN
signal strength (RSSI):-40 dBm

Starting connection to server...
connected to server
HTTP/1.1 301 Moved Permanently
Connection: close
Server: gunicorn/19.7.0
Date: Sun, 07 Apr 2019 15:02:16 GMT
Transfer-Encoding: chunked
Location: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=full&datatype=json&apikey=8UV48KKJJM1JW700
Content-Type: text/html; charset=utf-8
Via: 1.1 vegur

0

disconnecting from server.

I would like the code to return the string from the link. The output should like this (instead of just the 0). I had to shorten the example output below because of size restraints, but it should be the full webpage.
{
    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2019-04-05 16:00:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (5min)": {
        "2019-04-05 16:00:00": {
            "1. open": "119.8100",
            "2. high": "119.9100",
            "3. low": "119.7350",
            "4. close": "119.8800",
            "5. volume": "728814"
        },
        "2019-04-05 15:55:00": {
            "1. open": "119.9200",
            "2. high": "119.9200",
            "3. low": "119.7800",
            "4. close": "119.8000",
            "5. volume": "307126"
        },
        "2019-04-05 15:50:00": {
            "1. open": "119.9300",
            "2. high": "119.9300",
            "3. low": "119.8800",
            "4. close": "119.9200",
            "5. volume": "235238"
        }
    }
}

And if you use the redirected URL instead...?

@Majenko Thanks for your your suggestion. I just checked, and the url that is claimed as the destination (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=full&datatype=json&apikey=8UV48KKJJM1JW700) is the final destination. It does not redirect.

But that is not the URL you are using. You use URL A. The website sends you a redirect message (301) with URL B. You then need to take the Location: header and do a GET of that new URL. Basically it's filling in the missing default parameters for you and handing you a full URL to use. If you just use that new URL instead of your current one (i.e., add all the missing parameters) then it should work.

Thank you again. I just edited the URL that the Arduino uses to (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=compact&datatype=json&apikey=8UV48KKJJM1JW700), and it is coming up with the same output on the serial monitor (with the new destination).

It's not that the API is incompatible with the Arduino, it's that the Arduino Firmware update tool used to add the required SSL certificate to the wifi module fails to do so because the SSL certificate for www.alphavantage.co does not exist at their domain.
This can be verified by:
openssl s_client -showcerts -connect www.alphavantage.co:443

I don't understand your answer. Web browsers don't have a security problem with this site. and your command returns public certificates of the site

The target site uses HTTPS. If you connect to port 80, it redirects to HTTPS on port 443.
Use the WiFiSSLClient of the library. See the WiFiSSLClient example. Basically it is same as the example you used. There are two differences. It uses WiFiSSLClient instead of WiFiClient and connects to standard https port 443.

Thanks for the suggestion. I just tried making the edit, and this is what came up in the serial monitor:               Attempting to connect to SSID: BLOCKED
Connected to wifi
SSID: BLOCKED
IP Address: BLOCKED
signal strength (RSSI):-46 dBm
        Starting connection to server...

        disconnecting from server.

not a problem until it doesn't connect, but it should be client.println("Host: www.alphavantage.co"); without https://

I just made that change too, and it still does not work.

do you have the latest version of the firmware and library?

Thank you for the help, but after further investigation, I have discovered that this specific API is not compatible with Arduino.

Arduino can process JSON


text:
Using RTC DS1307 and OLED on Arduino MEGA
I'm using RTC DS1307 and OLED on an Arduino MEGA together.
When I try to use a rtc code like
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
or DateTime now = rtc.now(); the OLED display starts not showing what i wish in "void loop".
The summary of the code is below:
#include "Arduino.h"
#include "U8g2lib.h"
#include "U8x8lib.h"
#include "RTClib.h"
#include "Wire.h"
#include "SPI.h"
U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);   // Adafruit Feather M0 Basic Proto + FeatherWing OLED
RTC_DS1307 rtc;
void setup() {

  Serial1.begin(57600);
 if (! rtc.isrunning()) {
    Serial1.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
     }
     if (! rtc.begin()) {
    Serial1.println("Couldn't find RTC");
    while (1);
  }
  Serial1.end();

  Serial2.begin(9600);
  while (!Serial2) {
    ; // wait for Serial2 port to connect. Needed for native USB port only
  }
  u8g2.begin();

  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x13_te);
  u8g2.drawStr(30, 25, "WELCOME!");
  u8g2.sendBuffer();
  delay(2000);
  Serial2.setTimeout(1100);
}

void loop() {
 u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x13_te);
  u8g2.drawUTF8(0,12,"EepromA");
  u8g2.setCursor(55,12);
  //u8g2.print(EepromA);
  u8g2.setCursor(100,12);
  u8g2.print("EepromA");
  u8g2.drawUTF8(0,22,"EepromB");
  u8g2.setCursor(55,22);
 // u8g2.print(EepromB);
  u8g2.setCursor(100,22);
  u8g2.print("EepromB");
  u8g2.drawUTF8(0,32,"EepromC");
  u8g2.setCursor(55,32);
//  u8g2.print(EepromC);
  u8g2.setCursor(100,32);
  u8g2.print("EepromC");
  u8g2.sendBuffer();
      delay(50);

}

It seems like it is about i2c of Arduino Mega but how to solve the problem?
Note: After a search on the website I found some similar problems, I have removed R2 and R3 pull-up resistors on RTC module, this did not solve it.

Does it display "WELCOME"?

@geometrikal, yes it displays.

This means the hardware and pullups are not an issue and the I2C clock is good. It might be that you are filling the I2C buffer too quickly. Try adding a longer delay in the loop.

In addition, when i uncomment OLED codes, the RTC also works fine.

So either RTC or OLED works, but never at the same time?

Exactly right  ..


text:
Can I determine if I have been pinged?
I have a project using a Wemos D1 Mini.  Is there a way for the sketch running on the Wemos to know when it's been pinged?

I am sure there is. But, what do you mean by "pinged"? Are you doing something with radar or sonar or ethernet? What have you done so far and what exactly did not work (I.e. what did you expect to happen and what actually happened)? It will also probably help if you posted a minimal example of code that recreates the problem. Please refer to the Tour....

I assume you mean if you have received (and responded to) an ICMP PING packet...?

you can't at Arduino level. deeper may be, but I don't see anything related in the SDK API

I don't know if LWIP (leightweight IP stack) is built from source or provided as a binary blob for the Arduino ESP8266 core.. This is where you would handle ping requests / responses. Maybe it's also possible via LWIP APIs which hook these calls? Anyway it's for sure possible in the esp-open-rtos SDK (which build LWIP from source so you can also modify it)

just use http instead. you can curl it from the command line just like a ping.

Dandavis: ?? I don't understand.  I have a device that it on the local WiFi.  I want it to respond to a ping with an LED or bell or some other notification.  I think juraj had the correct answer.


text:
Follow up question to Calling a timer when a button is pushed
I have changed the code with some help here. There are two buttons each one is set to turn on a LED. When the LED turns on it is timed and when the time is up it turns off. The problem I am having is that only one LED can be on at a time even though I am not using the delay() and I am using millis() to keep track of time. So if I press button one the first LED will turn on. Even if I press button two at this time the second LED wont turn on until the first one turns off.
const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long previousMillis = 0;

void timer() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin2, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin2, LOW);
}

void timer2() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin3, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin3, LOW);
}

void setup() {
Serial.begin(9600);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(buttonPin6, INPUT);
pinMode(buttonPin7, INPUT);

}

void loop() {

int buttonState2 = digitalRead(buttonPin6);
if (buttonState2 == HIGH) timer2();

int buttonState = digitalRead(buttonPin7);
if (buttonState == HIGH) timer();

}

If someone's answer is correct, you should tick their answer as correct.

As jogco says, you are (effectively) using a delay in your timer function, by doing this:
while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

What you want is to remember the time each LED was switched on, and each every time through the loop check if the required time has passed. Something like this:
const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long led1_start = 0;
unsigned long led2_start = 0;
boolean led1_on = false;
boolean led2_on = false;

void timerOn(int led) {

    switch(led) {
        case 1:
            led1_start = millis();
            digitalWrite(ledPin2, HIGH);
            led1_on = true;
            break;
        case 2:
            led2_start = millis();
            digitalWrite(ledPin3, HIGH);
            led2_on = true;
            break;
    }
}

void timerOff(int led) {

    switch(led) {
        case 1:
            digitalWrite(ledPin2, LOW);
            led1_on = false;
            break;
        case 2:
            digitalWrite(ledPin3, LOW);
            led2_on = false;
            break;
    }
}

boolean checkTime(unsigned long startTime) {
      return ((startTime + onTime) >= millis());
}

void setup() {
    Serial.begin(9600);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(buttonPin6, INPUT);
    pinMode(buttonPin7, INPUT);
}

void loop() {

    int buttonState2 = digitalRead(buttonPin6);
    if (buttonState2 == HIGH) timerOn(2);

    int buttonState = digitalRead(buttonPin7);
    if (buttonState == HIGH) timerOn(1);

    if (led1_on) {
        if (checkTime(led1_start)) timerOff(1);
    }

    if (led2_on) {
        if (checkTime(led2_start)) timerOff(2);
    }

}

In fact I would look at arrays for the pin numbers and status/time variables, to make it more reusable...
int ledPins[2] = {2, 3};
int ledStart[2] = {0, 0};
int buttonPins[2] = {6, 7};

... and the like

I will look over this closely. I need more practice with using switch/cases and booleans. thank you.

Yes, it is because in timer() and timer2() you busy-loop with while until the condition is not met. Hence, when buttonState2 is HIGH, your code will execute timer2() until the condition of the while loop is not met. You are effectively doing a delay.


text:
What is this? Looks like a sensor
I got an Arduino kit from my dad.
But inside this box is a thing, maybe a sensor. But I can't find what it is.
Anyone recognize this 'thing' on the picture?

What is written on the chip? Is there anything printed on the reverse of the board?

No it's just a black surface. also the backside is blank.

I can see the ghost of some lettering on the chip. Look closely. You may need a magnifying glass (or even microscope) and some spit to make it visible.

My guess is that it’s a touch sensor. Where you have to touch the white circle. But the number of components on the board makes me doubt that guess.

@Gerben That was my first thought, and main concern, too. Hence wanting to try and find a chip number. Chances are it's just a generic op-amp on there though.

Have you tried hooking it to a 5V supply and connecting it to a Arduino/buzzer?  Then just wave various other items from the kit at it.  But it would be easier to read the writing on the IC, zoom on you phone might work.

To read letters on chips it is good just draw over the chip with chalk (or any other fine powder (be it sugar, baby powder, lady powder...), then decently blow out what is on top and the letters wiil be left powder-filed and readable. Then you can simply remove the rest of powder totally if you wish (with finger, or nearly anything damp/wet). Good trick to know :)

Appears to be a touch sensor that can be found on various on-line retail web pages:
http://www.satistronics.com/
https://www.arduiner.com/
Also, the back may have a URL as this one does:

...however, the URL appears not to function.

The back has no text, but it looks  the same. I followed your link and it shows exactly what I have. Thank you for sharing this with me

The sensor is a K1208043 touch sensor. Here's an updated link.


text:
Pass Color to a function without using a specific Adafruit_NeoPixel
I'm initializing my strips as an array:
// Declare NeoPixel strip array:
Adafruit_NeoPixel strip[] = {
  Adafruit_NeoPixel(LED_COUNT[0], LED_PIN[0], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[1], LED_PIN[1], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[2], LED_PIN[2], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[3], LED_PIN[3], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[4], LED_PIN[4], NEO_RGBW + NEO_KHZ800)
};

and when I pass Color to a function, I'm arbitrarily using my first strip to create the Color:
  everyother( strip[0].Color( 0, 255, 0), strip[0].Color( 255, 0, 0), 500);

but in the subroutine I use those colors to set pixels to every strip of the array in a loop:
// set every other color to color1 or color2
void everyother( uint32_t color1, uint32_t color2, int wait) {
  for(int k=0; k<NUM_STRIPS; k++) {
    for( int j=0; j<LED_COUNT[k]; j++) {
      if( j%2 == 0) strip[k].setPixelColor(j, color1);
      else strip[k].setPixelColor(j, color2);
    }
  }
  for(int k=0; k<NUM_STRIPS; k++) strip[k].show();
  delay(wait);
}

Is there another way to define Color that isn't using a real Adafruit_NeoPixel? Yes, it works this way but it feels sloppy.

Looking at the library at https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.h, you can see that the Color method is static (see line 307):
static uint32_t   Color(uint8_t r, uint8_t g, uint8_t b) {
  return ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;

This means instead of
strip[0].Color( 0, 255, 0)

You can use:
Adafruit_NeoPixel::Color( 0, 255, 0)

Your call to everyother will be:
everyother(Adafruit_NeoPixel::Color( 0, 255, 0),
           Adafruit_NeoPixel::Color( 255, 0, 0),
           500);

And since everyother is now not a good name, you can think of a better one, e.g. fillLeds (always start a method name with a verb).
Offtopic:

A subroutine is barely used anymore, I think the last time I heard it, is from the Basic programming language
A function is now used instead
But when a function is inside a class, it's not called a function, but called method.

Thanks for the response. I knew it was gonna be something simple that I was missing. And thanks for the tips. If you need help writing assembly for a VAX, hit me up.

@JohnnyRollerfeet ... you're welcome... I don't have a VAX at hand lol, but in case I see one, I know who to call. Now I also know why you used the term subroutine. Good luck with your project.


text:
Declaring and using array of structures in Arduino
Printing structure variables, I get default values. What is wrong with my code?
struct SCENARIO
{
  int Lamp_Pin = -1;
  int PB_Pin = -1;
} ;

SCENARIO  _red;
SCENARIO  _yellow;
SCENARIO  _white;
SCENARIO  _stop;
SCENARIO btns[4] = { _red,  _yellow, _white, _stop};

void setup()
{
  _stop.Lamp_Pin = 8;
  _stop.PB_Pin = 4;

 ///// initializing other 3 objects i.e. red & white & yellow
 ////
for (int i = 0; i < 4; i++)
  {
    Serial.print(i);Serial.print(":");
    Serial.print(btns[i].Lamp_Pin);Serial.print(":");
    Serial.println( btns[i].PB_Pin );
    //pinMode(  btns[i].Lamp_Pin, OUTPUT);
    //pinMode(  btns[i].PB_Pin, INPUT);
  }
}

The image below shows what I get. It seems I have not initialized the variables!

The problem is that a struct is handled as a value type, not as a reference type.
This means that a copy of _stop is made and put in btns (btns[3] actually).
So what you need to do is putting pointers into the btns array:
SCENARIO* btns[4] = { &_red, &_yellow, &_white, &_stop};

The symbol * denotes a pointer, and & means the address of a variable (so it points to the variable and is not a copy).
Now when you change _stop, also btns[3] which points to _stop will show the correct initialized value.
For printing you should use:
Serial.println( (*btns[i]).LampPin);Serial.print(":");
Serial.println( (*btns[i]).PB_Pin );

Because *btns[i] is a pointer, but because this is a very often used feature, a special notation can be used:
Serial.print(btns[i]->Lamp_Pin);Serial.print(":");
Serial.println( btns[i]->PB_Pin);

Thanks! Coming from managed world, I forgot the pointers behavior!

@BehzadSedighzadeh Luckily in C# they don't exist anymore, but with programming lower level devices, you don't want to rely mostly on automatic memory allocation and garbage collection and pointers are 'directly to the point(er)'.

If an answers helped you, upvote it (arrow next to the question), for the best answer, accept the answer (under the arrows next to a question).

In this line:
SCENARIO btns[4] = { _red,  _yellow, _white, _stop};

you are making 4 copies of the structures and placing them in an array.
Instead you should either create the array directly with the values:
SCENARIO btns[4] = {
    {-1, -1},
    {-1, -1},
    {-1, -1},
    {8, 4}
};

And only use the array, or use pointers in the array:
SCENARIO *btns[4] = { &_red,  &_yellow, &_white, &_stop };

and then access the entries as pointers:
Serial.print(btns[i]->Lamp_Pin);
Serial.print(":");
Serial.println( btns[i]->PB_Pin );

Thanks. I mostly code in C# and in this case I had forgotten Array of structures looks different than managed world!


text:
cast double to long leads to unexpected results
I wrote a little program to show my problem:
void setup()
{
  Serial.begin(9600);

  double K=39.85;
  double a=K*100;
  Serial.print("a= ");
  Serial.println(a);

  long val_long = 0;
  val_long = a;
  Serial.print("val_long= ");
  Serial.println(val_long);
}

void loop() {
}

I get this back from my Arduino uno:
a= 3985.00
val_long=3984

I've been pondering for a long time and can't find the mistake! Why is the long value decremented by one? Can anybody help me please?

upvote for uncluding minimal sketch

The problem is that float numbers are seldom an exact representation. So the float is stored as the closest number that is exactly representable as a float, namely
10446438 × 2−18 = 39.84999847412109375.
When you multiply this by 100, you get 16322559 × 2−12 = 3984.999755859375.
And than casting to an int or long results in 3984, not 3985.
so whenever you cast a value from a float or double to an int or long, you always should add 0.5 (so all values from [x - 0.5, x + 0.5) are rounded to x assuming x >= 0, thus:
val_long = int(a + 0.5);

Beware of negative values, see therefore https://www.cs.cmu.edu/~rbd/papers/cmj-float-to-int.html
Better is to use the round function, see comment of Edgar Bonet below.
UPDATE
See comment of Lightness Races with Monica
In case it's not wanted to round up, but you still want 39.84999847412109375 to be 39.85, than you have to add a value that has the value of the least significant bit (actually slightly less but that is impossible to define). In most cases, it's best to add half the significance you want. So if you need two decimal accuracy, add 0.005.

Thank you so much, you made my day! Now everything works fine.

Serial.println(a,5); might have revealed that issue already. Especially on 8bit Arduinos with double being only 32 bit wide. (Same as float)

I edited the answer to add the exact numbers. 2. You can use round(), from the Arduino core. It's a macro that adds ±0.5 (depending on the sign) before casting to long.

@EdgarBonet Thank you very much.  I will also add in my answer a note to your comment.

"so whenever you cast a value from a float or double to an int or long, you always should add 0.5" If rounding is what you want. Sometimes it isn't, then you need another workaround for little inaccuracies. Your solution will change the behaviour when K==39.856, for example. Your answer should address this.

@LightnessRaceswithMonica I'm not sure I understand what you mean … when K == 39.856, adding half and rounding (down) gives 40, which is the normal way of converting. What (other little inaccuracies) you mean exactly?

@MichelKeijzers If K is 39.856 then a is 3985.6, so program's output is 3985, which is presumably deliberate. Your suggestion changes the output to 3986. You've changed the meaning of the program without mentioning it. An alternative is to use "another workaround for [these] little inaccuracies [like the one causing this bug]", such as epsilons. That being said, if K will only ever have max 2 meaningful decimal places, then this is moot.

Ah ok, you  mean it's rounding up while that is not always what is wanted... I will add this indeed. good point.


text:
Learn Arduino Basics : Temperature sensor with LCD Display and Potentiometer setup
I have temperature sensor, potentiometer and LCD screen attached to mini breadboard and wired to an Arduino. My temp sensor appears to be working fine however sometimes it reads inaccurate numbers which is unusual. It only does this when I have all my components on the same mini breadboard. When I detach then reattach my temperature sensor to a separate breadboard its hasn't been noticeably inaccurate. There is no issue but I was thinking that maybe the temperature sensor is hotter because its closer other to components or maybe because the close electrical wiring range is making it hotter. My solution is putting the temp gauge on another breadboard but I was save space to use one. Any ideas as why my gauge reads random hotter temperatures more often when sharing a board?

What temperature sensor do you have?

what do you mean by hotter?

LM35 temerature sensor. By hotter I mean; when the sensor begins reading inaccurately, the degrees ranges from 5-10 degrees hotter than what it should be.

It could be measuring the heat of nearby components, or it could be a wiring issue. Breadboards are convenient but it also allows people to use poor wiring practices. Long wires, poor ground return paths, insufficient bypass capacitors.
The first thing to do is to arrange the layout so that there is little chance of the other components heating the sensor. You might also try using a fan to blow on all the components. Make it so that if there is any heat generated it does not accumulate it the parts. If that clears up the problem then look into making a better thermal layout. Maybe with the sensor physically separate from the rest of the circuit.
If the fan makes no difference then you may need to consider the way it has been wired.