text:
How to leak function addresses?
I'm doing some security research on FreeRTOS embedded systems and I don't have much information about Arduino. Is there any way to leak function or variable addresses on serial console? I can use avr-nm and avr-objdump but, I may need it for dynamically allocated memory.
It gives:
call of overloaded 'println(void (*)(void*))' is ambiguous

When I try to pass function pointers to serial console.
UPDATE:
With using (unsigned char) I can leak something and it is 68 in serial console my code below. I have
000004d0 l     F .text  000000e0 _Z9TaskBlinkPv

from symbols if it is related with TaskBlink.
#include <Arduino_FreeRTOS.h>

// define two tasks for Blink & AnalogRead
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  // Now set up two tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // Stack size
    ,  NULL
    ,  2  // priority
    ,  NULL );

  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"
    ,  128 // This stack size can be checked & adjusted by reading Highwater
    ,  NULL
    ,  1  // priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
  Serial.println((unsigned char) &TaskBlink,HEX);
  for (;;) // A Task shall never return or exit.
  {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  for (;;)
  {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    //Serial.println(sensorValue);
    vTaskDelay(1);  // one tick delay (15ms) in between reads for stability
  }
}

UPDATE 2: When I'm using (unsigned int) it is giving 268 and dissassembling 268 gives:
     262:       9b 8d           ldd     r25, Y+27       ; 0x1b
     264:       8c 8d           ldd     r24, Y+28       ; 0x1c
     266:       98 13           cpse    r25, r24
     268:       05 c0           rjmp    .+10            ; 0x274 <_ZN14HardwareSerial5writeEh+0x24>
     26a:       e8 89           ldd     r30, Y+16       ; 0x10
     26c:       f9 89           ldd     r31, Y+17       ; 0x11
     26e:       80 81           ld      r24, Z
     270:       85 fd           sbrc    r24, 5
     272:       24 c0           rjmp    .+72            ; 0x2bc <_ZN14HardwareSerial5writeEh+0x6c>
     274:       f6 2e           mov     r15, r22

It is not my function nor a tramboline. It is at:
000004d0 <_Z9TaskBlinkPv>:
/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
     4d0:       cf 93           push    r28
     4d2:       df 93           push    r29
     4d4:       cd b7           in      r28, 0x3d       ; 61
     4d6:       de b7           in      r29, 0x3e       ; 62
     4d8:       a1 97           sbiw    r28, 0x21       ; 33
     4da:       0f b6           in      r0, 0x3f        ; 63
     4dc:       f8 94           cli
     4de:       de bf           out     0x3e, r29       ; 62
     4e0:       0f be           out     0x3f, r0        ; 63
     4e2:       cd bf           out     0x3d, r28       ; 61

What am I doing wrong?

Post a complete, working copy of your sketch. We can't discuss about unknows.

Are you aware that ATMega is an Harvard arquitecture MCU? Data space and program space are separated.

Yes, but I don't know it's effect on addresses.

The error you have is exactly a factor 2: Your Serial.print() gave
0x0268, whereas TaskBlink(void *) is at address 0x04d0, which is twice
0x0268. Both addresses are correct: it all depends on what you mean by
“address”.
Functions live in the microcontroller's flash. At the hardware level,
and for the purpose of fetching instructions, the flash is addresses by
16-bit words. This means that address 1 is one word (two bytes) past
address 0. Note that for fetching constant “PROGMEM” data, the lpm
instruction addresses the flash byte-wise. This may seem inconsistent,
but it's the way the hardware is designed. Function pointers are
addresses intended to be put into the program counter by means of the
icall (indirect call) instruction. This instruction expects a
word-wise address, thus function pointers are word-wise addresses.
For some reason – presumably for consistency with other platforms – the
authors of the GNU binutils package chose to always use byte-wise
addresses. When avr-nm and avr-objdump tell you that
TaskBlink(void *) is at address 0x04d0, they mean it starts 0x04d0
bytes after the start of the flash. When Serial.print() tells you
it's at 0x0268, it means the address used at the hardware level is
0x0268, and that's because the function starts 0x0268 words after the
start of the flash.

What you need is
  Serial.println((unsigned int) &TaskBlink, HEX);

The operator "&" gives you an address. In Arduino (ATMega MCU), that is a 16 bit value, that fits inside an unsigned int.
The cast operator "(unsigned int)" means "I will use that value as an unsigned int".
Serial knows how to print numerical values (but not funtion addresses).

What symbol? "&"?

Sorry for deleting comment I mean "symbols" used for relocation (for constructing symbol table) and debugging.

I guess some people can read those for debugging purposes after a crash.


text:
How does the microcontroller know which clock to use?
I had seen some tutorials on how to assemble an Arduino on a breadboard. They all just place the external crystal oscillator according to the circuit and then, just burn the bootloader and it starts working. According to my little knowledge the fuse bits have to be set before using the external clock.
My question is - How does the microcontroller know which clock to use internal or external? Is there any setting already in the bootloader that tells the microcontroller to use the external clock?

Burning the bootloader via the Arduino IDE also sets the fuse bits according to its configuration files.

So, if I have to use the internal clock, I need to change the configuration file?

Yes, or you could find and use a core meant to be used with bare chips. I know of at least one that has the correct configuration.

So your keeping it a secret? Which core(s)?

source: Stack Exchange

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

sort: votes


text:
Arduino UNO Intro to Engineering Project
I am a college student in an intro to engineering class looking to create a final project. My goal is to create a small "present" that opens its lid via a servo and plays jingle bells with LEDs flashing (as shown in the youtube video linked below), before closing the lid once again until a further button press.
https://www.youtube.com/watch?v=V6TcAhXCL6w
The code that this video uses is:
/*
  "Jingle Bells" Melody

 Plays "Jingle Bells"

 circuit:
 * 8-ohm speaker on digital pin 7

#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659

// notes in the melody:
int melody[] = {
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_FS4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_B4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_D5, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_A4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_D5,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4 };

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {

  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 8, 8, 8, 8,
  8, 8, 8, 8, 2,
  8, 8, 4, 8, 8, 4,
  8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 4, 4,
  8, 8, 4, 8, 8, 4, 8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 2 };

void setup() {
    pinMode(3,OUTPUT);
    pinMode(6,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(11,OUTPUT);
    digitalWrite(3, LOW);
    digitalWrite(6, LOW);
    digitalWrite(9, LOW);
    digitalWrite(11, LOW);
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 100; thisNote++) {

    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1800/noteDurations[thisNote];
    // I found that by lengthening the noteDuration,
    // I was able to "slow" the song down.
    tone(7, melody[thisNote],noteDuration);
    LEDon();

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(7);
    LEDoff();
  }
}

void loop() {
  // no need to repeat the melody.
}

int currentLEDpin=3;
void LEDon()
{
    digitalWrite(currentLEDpin, HIGH);
}

void LEDoff()
{
    digitalWrite(currentLEDpin, LOW);
    if (currentLEDpin==3) currentLEDpin=6;
    else if (currentLEDpin==6) currentLEDpin=9;
    else if (currentLEDpin==9) currentLEDpin=11;
    else currentLEDpin=3;
}

My general outline for the project looks like this:

Set LEDs, Piezo, and Servo to OUTPUT
Set pushbutton to INPUT
Start all LEDs off/LOW
Start a loop that has if statement for button push
Open the lid (servo motor about 100 degrees)
Start the song/LED sequence using code borrowed from the youtube video
After finishing the song, close the lid (servo motor back 100 degrees)

I am very much a beginner to coding Arduino, so I was wondering if my uploaded sketch seems correct...
//Notes for Jingle Bells
#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659

//Notes in melody Command
int melody[] = {
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_FS4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_B4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
  NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_E4,
  NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_D5, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_A4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_D5,
  NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
  NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
  NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4 };

// Note Durations (4 = quarter note, 8 = eighth note, etc.)
int noteDurations[] = {
  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 2,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 3, 16, 16,
  8, 8, 8, 8, 3, 8,
  8, 8, 8, 8, 8, 8, 8, 8,
  8, 8, 8, 8, 2,
  8, 8, 4, 8, 8, 4,
  8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 4, 4,
  8, 8, 4, 8, 8, 4, 8, 8, 6, 16, 2,
  8, 8, 6, 16, 8, 8, 8, 16, 16,
  8, 8, 8, 8, 2 };

#include <Servo.h>      //Include built-in Servo sketch
Servo servo;            //Servo sketch reference for setup
const int servoPin=5;   //Set servoPin to 5
int angle = 0;          //Set initial servo angle to 0 degrees

const int buttonPin=2;   //Set buttonPin to 2
int buttonState=0;       //variable for reading pin status

int currentLEDpin=3;    //Set LED pin variable for LED flashes
void LEDon()            //Define LEDon for turning on LED to music
{
    digitalWrite(currentLEDpin, HIGH);
}

void LEDoff()           //Define LEDoff for turning off LED when music off
{
    digitalWrite(currentLEDpin, LOW);
    if (currentLEDpin==3) currentLEDpin=6;
    else if (currentLEDpin==6) currentLEDpin=9;
    else if (currentLEDpin==9) currentLEDpin=11;
    else currentLEDpin=3;
}

void setup() {
    pinMode(3,OUTPUT);           //Set LED Pins to OUTPUTs
    pinMode(6,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(11,OUTPUT);
    digitalWrite(3, LOW);        //Start all LED lights off
    digitalWrite(6, LOW);
    digitalWrite(9, LOW);
    digitalWrite(11, LOW);

    pinMode(buttonPin,INPUT);   //Set button to INPUT

    servo.attach(servoPin);     //Servo setup

}

void loop() {
 buttonState=digitalRead(buttonPin);     //read input value

  if (buttonState == HIGH) {              //check if pushbutton is pressed

  for(angle = 0; angle <110; angle++)    //rotate servo 110 degrees, opening present box lid
    {
    servo.write(angle);
    delay(15);
    }

  for (int thisNote = 0; thisNote < 100; thisNote++) {
    int noteDuration = 1800/noteDurations[thisNote];    //define note duration
    tone(7, melody[thisNote],noteDuration);             //Play melody of Jingle Bells
    LEDon();                                            //Flash LEDs to tune
    int pauseBetweenNotes = noteDuration * 1.30;        //Pause between notes to annunciate each note
    delay(pauseBetweenNotes);
    noTone(7);                                          //Stop playing music when melody over
    LEDoff();                                           //Stop flashing LEDs when melody over
}

  for(angle = 110; angle > 0; angle--)                  //Close present box lid
    {
    servo.write(angle);
    delay(15);
    }
   }

}

So when you say to erase the LEDon and LEDoff calls, is that in this section of the code?:
 for (int thisNote = 0; thisNote < 100; thisNote++) {
    int noteDuration = 1800/noteDurations[thisNote];    //define note duration
    tone(7, melody[thisNote],noteDuration);             //Play melody of Jingle Bells
    LEDon();                                            //Flash LEDs to tune
    int pauseBetweenNotes = noteDuration * 1.30;        //Pause between notes to annunciate each note
    delay(pauseBetweenNotes);
    noTone(7);                                          //Stop playing music when melody over
    LEDoff();                                           //Stop flashing LEDs when melody over
}

I misread your question. You want the leds, so keep the calls and copy the functions from Jingle Bells sketch to your own.

There doesn't seem to be a specific question here.  This is not a code review site so my uploaded sketch seem correct is not a valid question - you must ask about a specific problem, not for general improvement suggestions.

Half of the questions posted here are code-review ...

LEDon and LEDoff are defined in the Jingle Bell sketch. They just lit on/of the leds.
You don't need them for your project, just erase the calls. Otherwise, copy the LEDon/off functions:
int currentLEDpin=3;
void LEDon()
{
    digitalWrite(currentLEDpin, HIGH);
}

void LEDoff()
{
    digitalWrite(currentLEDpin, LOW);
    if (currentLEDpin==3) currentLEDpin=6;
    else if (currentLEDpin==6) currentLEDpin=9;
    else if (currentLEDpin==9) currentLEDpin=11;
    else currentLEDpin=3;
}

You made a mistake:
if(buttonState = HIGH) {               //check if pushbutton is pressed

Here you assign HIGH to buttonState.
The "=" is assignment operator. What you were thinking is "==", the equality-comparison operator (a common mistake). Replace it with
if(buttonState == HIGH) {               //check if pushbutton is pressed

Also, you need to debounce you button. Read about it in this excelent tutorial by Nick Gammon: Switches tutorial. Well, read his whole blog if you have the time.
Otherwise, you are doing well.

Thank you so much for your help!
If you could clarify on where I should copy the LEDon and LEDoff to that would be great! Also, where in the sketch should I erase the calls?

Copy the functions, keep the calls. I misreaded your question.

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


text:
Arduino IDE compiles, UECIDE not
I'm rewriting a personal project and it doesn't compile under UECIDE 0.9.1, but it does with Arduino IDE 1.8.5.
Target is NodeMCU 0.9 with default options.
Arduino IDE 1.8.5
Archiving built core (caching) in: /tmp/arduino_cache_347503/core/core_esp8266_esp8266_nodemcu_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_4a642491bde0820b9be0f8ad42686d29.a
Sketch uses 299199 bytes (28%) of program storage space. Maximum is 1044464 bytes.
Global variables use 37372 bytes (45%) of dynamic memory, leaving 44548 bytes for local variables. Maximum is 81920 bytes.

UECIDE 0.9.1
• Error at line 231 in file Monitor.ino:
‣ expected '{' before ';' token

• Error at line 231 in file Monitor.ino:
‣ expected ')' before ';' token

• Error at line 190 in file Monitor.ino:
‣ redefinition of 'CronEntry cronBlink'

• Error at line 231 in file Monitor.ino:
‣ 'CronEntry cronBlink' previously declared here

Project is too large to post here, so I zipped it and uploaded to Google Drive, where anyone can download it with this link
https://drive.google.com/file/d/1BGvqtPx0547fPfX1Nucwhd_a-MO__vWX/view?usp=sharing
EDIT
(After lambda comment by Majenko)
I was using a struct to hold cron entries, using lambdas:
struct CRON_ENTRY {
  boolean active;       // Task is active.
  unsigned long start;  // Start time (ms uptime).
  unsigned long repeat; // Repeat every (ms).
  fcncron fcn;          // task.
};

CRON_ENTRY cronBlink = {false, 0,   500, [](CRON_ENTRY * c)
{
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();
}

and then replace CRON_ENTRY struct with CronEntry class:
CronEntry cronBlink(false, 0,   500, []() {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();});

I really like lambas because they made code shorter.

ESP8266 support is shaky at best. They keep changing things randomly and breaking things. Time for yet another overhaul of the core...

Actually, this is a problem with UECIDE itself - or rather with the INO parsing routine. You have a lambda function in a constructor, and it really doesn't like that (the CronEntry constructors). Consider moving those to normal functions instead.

I need to rework the parser so it can handle lambda functions. I'll make it my top priority. It needs an overhaul anyway.

Labdas are not something I have really worked with much. I prefer to keep my code in easy to manage blocks, and labdas confuse the hell outta me ;)

UECIDE has a GitHub Issues page

This is a bug in UECIDE. It doesn't like lambda functions in constructors.
A complete rewrite of the sketch parser to use Exuberant Ctags is under way.

I thought that UECIDE and Arduino IDE have different front ends (UI) and the same back end (compiler and tools). Can you explain how they are different?

There are three layers to both. The IDE (editor), the parser (which converts the INO into a CPP file) and the compiler. Only the compiler is the same.


text:
Why does an Arduino Uno have 2 microcontrollers
I was looking at this schematic:
And I noticed that there are 2 microcontrollers (an Atmega328p and a ATmega16U2).  I was wondering why there need to be 2 microcontrollers.  Do they do different things that only 1 of them can do and the other can't ?

Why does an Arduino Uno have 3 microcontrollers - is this a typo? You have only identified two of them.

Atmega328P is a microcontroller which are the heart of Arduino Uno, where the Atmega8U2 is the USB to serial convertor for arduino communicated with computer.
You can refer to this link for more information about this.


text:
Strange Output from DS1307 RTC
I'm using a DS1307 RTC (https://www.adafruit.com/product/3296) and an Arduino mega microcontroller trying to simply set and read the time of the RTC. However, whenever I try to output anything to the Serial Monitor, I get stuff like this:

The code and the wiring is fairly straightforward which is why I'm confused. I'm just directly attaching the Vcc, GRND, SCL and SDA pins of the clock to the Arduino and using a slightly modified version of the example code as a part of the RTC library Adafruit supplied.
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  rtc.begin();

  rtc.adjust(DateTime(2017, 11, 17, 20, 33, 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(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.println();
    delay(1000);
}

So I know I'm doing something wrong but I'm not sure what. Any help would be hugely appreciated.

Can you post a schematic of how you have the DS1307 wired?

Looks like a baud rate issue. Check your clock speed and settings.

Set the serial monitor to 57600 and check.

@ammar.cma In the code above you can see that I did set the serial monitor to 57600

@Trevor What should I be changing it too exactly?

@ThreePhaseEel like I said in the above posted I literally just have it plugged directly into the SDA, SCL, 5V and Ground pins of the arduino.

No idea, it depends on the frequency of your micro and what you are connected to.

I mean not in your code, but in the monitor that you display on : So check on the bottom right on that window, there should the a baud rate that can be set.  COM4 window

Change the baud rate to 57600, it specifies at:
    Serial.begin(57600);

Thank you for the advice @senpaiscuba. I am new to stackoverflow and did not realize you could edit after posting.


text:
Pointers, libraries, and arrays:
I'm trying to pass variable addresses to functions/methods within a custom library that should change the values at the specified addresses.  However, I think I'm missing something as it's taking me ages to tweak things just to get it to compile, let alone gather some useful information from it.
Note:
I've not tested the code as I'm focused on understanding (1.) through to (5.) and is just a quick example of the current pipeline:
Main.ino
#include <customLibrary.h>

CustomLibrary cLib();

byte someByte[6];
unsigned int theAddress;

setup(){};

loop(){

    // (1.)
    theAddress = &someByte; // normally need this here, or before setup(), for it to work.

    cLib.setValues(theAddress);

    // because:
    // cLib.setValues(&someByte);
    // doesn't seem to work
};

customLibrary.h
#ifndef CustomLib
#define CustomLib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class CustomLibrary {
    public:
        CustomLibrary();
        void setValues(unsigned int theAddress); // (2.)
    private:
};
#endif

customLibrary.cpp
#include <customLibrary.h>

CustomLibrary::CustomLibrary(){
};

void CustomLibrary::setValues(unsigned int theAddress){ // (3.)

    byte _someNewValues[6] = {a,b,c,d,e,f};

    // Assign the variable from _someNewValues[_x] to (theAddress + _x)
    int _x = 0;
    for(unsigned int i = theAddress;i < (theAddress + 6);i++){ // (4.)
        // (5.)
        _x++;
    };

};

(1.) - Feels like it should be simpler.
(2-3-4-5.) - I have left out any "*" and "&" hoping that someone can provide the preferred way of doing this, or provide a better solution as it's taking far too long to get this working with everything else leading me to think I'm missing something basic.
There are some excellent tutorials out there which I have been
following with great success, but, only when all the pointers are within the same file.  Once I try and use them in a library it's a constant headache at the moment and I don't understand it enough to know what's wrong.
Need to go before I can proof-read and check it, but I think it's all there.  I'll be back later/tomorrow if there's anything that needs clearing up.
Edit:
I didn't know who to mark for the answer as both @dannyf and @KIIV answered perfectly.  I considered marking the answer based on the time it was posted, but decided instead to let @dannyf have it as his reputation was only 1.
Thank you both! Much appreciated!

somebyte itself is a pointer. so "&somebyte" doesn't make sense.
instead, use "&somebyte[0]" (or "&somebyte[5]" if you want an offset), or "somebyte" (or "somebyte + 5" if you want an offset).
arrays are actually pointers.

Excellent, I had heard that arrays were pointers, just never came across them being an issue explicitly using them as pointers. I missed a second variable, byte anotherByte;, not an array, however, it has an identical pipeline to follow as _someByte[] does.  In that case, what would you do for (2-3-4.)? *theAddress for (2-3-4.)? and at (5.) have something similar to *theAddress = anotherSomeValue; . Apologies, I'm just making 100% sure I've got this because trying to debug it through the error window which is abstract at best when I'm not 100% about something. Thanks!

if you wish to change the value stored at the address pointed to by theAddress, use "*theAddress = someValue;" But the function should indicate that theAddress is a pointer of a particular data type.

To make this a bit more explicit: A reference to an array is a pointer to the array's first member. That is what actually gets passed when you "pass an array" to a function, or a function returns an array.

I'm not sure how it could ever work for you in both variants.
There is simple example how to work with arrays:
class CustomLibrary {
    public:
        CustomLibrary() {;}

        void setValues(byte * address);

        template <class T, int SIZE>
        void setValuesTemplate(T(&bytes)[SIZE])
        {
          for (int8_t i=0; i<SIZE; ++i)
          {
            ++bytes[i]; // just increment the value
          };
        }
 };

void CustomLibrary::setValues(byte * address){
    byte somethingNew[] = {'a','b','c','d','e','f'};

    for (int8_t i=0; i<6; ++i)
    {
      address[i] = somethingNew[i];
    }

};

CustomLibrary lib;

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

void loop(){
  byte someByte[6] = {'z','y','x','w','v','u'};

  Serial.println("Values before:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  lib.setValuesTemplate(someByte);

  Serial.println("Values after templated method:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  lib.setValues(someByte);

  Serial.println("Values after method:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  delay(5000);
};

It's in single .ino file for testing purposes. If you want to use templates, you have to place template method definition into the header file (it doesn't have to be inside class definition, it just have to be in header file).
Range based for loop was introduced by C++11 standard (suported by Arduino IDE for a while - since about version 1.6.5?). It's realy handy on static arrays (like int arr[] = {......}), so you don't have to care about it size. But it's basically everything it can do on avr-g++, as there are no containers, no iterators and so on.
Templates are quite huge topic on C++, in this case it's working with T as array element type and SIZE as its size (it won't work on pointers, it only works on static arrays).
I could've use range based for loop in int too:
    template <class T, int SIZE>
    void setValuesTemplate(T(&arr)[SIZE])
    {
      for (T& item : arr) // it must be a reference type, if you don't want to change local value only
      {
        ++item; // just increment the value
      };
    }

And I didn't even needed that class T part. If you need byte array only:
    template <int SIZE>
    void setValuesTemplate(byte(&arr)[SIZE])
    {
      for (byte& item : arr)
      {
        ++item;
      };
    }

But there is a downside for using templates -> there will one instance of that method for each type/size. But it's possible to use it as a "proxy" and pass it to function that expects just pointer and the size.

Thanks for the help!  That's introduced two new things, which is great as I've not used them before.  template <class,size> and for(byte b : someByte)! As a guess: for(x : y) /* something */ ; is shorthand, like (x) ? x : y;?

@Timeless I've added more detailed description into the answer.


text:
How to use an Arduino to measure speed of rocket
I am not very experienced with Arduino and I am trying to learn it. I was wondering what is the easiest and most effective way to calculate speed and log it every second so to say. This would be mounted in a model rocket to see what speeds it can reach. How would I achieve this?
Would it be hard to send over RF to see it in real time?
Thanks in Advance

You can use an accelerometer or a barometre for measure speed and for RF you can use:

Radio NRF24L01
wifi ESP8266
bluetooth HC-06

I wouldn't recommend WiFi for this. WiFi antenna patterns tend to be very flat to get a long lateral range, which means you don't get any height from them. A rocket will go high, and will rapidly lose WiFi connectivity. Bluetooth may not have the range required. The nRF+PA combo would be best.

I would recommend they start small. Learn to a get an LED to blink first. Baby steps. Learn c,c++ first. What they want to accomplish is way above their head.

Quite different questions, but you need two items:

A gyroscope/accellerometer, I don't think this should be a problem. You need to check beforehand if the Arduino is fast enough, since a rocket acceleration is probably very high.
An RF transceiver, there are several types which work over big distances, but I don't have experience while they move fast. Maybe radio signals might get distorted, but for that hopefully someone has a better answer. Probably you cannot use a (big) external antenna which extends outside the rocket.


text:
what is arduino adc reference?
I'm using arduino for the first time and don't really understand what am I suppose to plug to the ADC refernce PIN... or if I even have to use it while plugging analog sensor to the arduino,
thanks!

Does https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/ help? You don't have to use it.

The AD converter in the ATMega microcontroller (as used in Arduino) converts an input voltage to a number.
This ADC happens to be 10 bit that means 2^10 states which is 1024.
The number 0 (zero) means 0 Volt input voltage.
The number 1023 means the maximum input voltage.
Since 0 is also a value the scale runs from 0 to 1023 making 1024 values.
The scale is linear so 511 means half of that maximum voltage.
What is this maximum input voltage?
That is the ADC Reference voltage. By default the power supply voltage is used so if you run your Arduino on 5 V, then 1023 = 5 V. But if you run your Arduino on 3.3 V, then 1023 = 3.3 V.
There is also in internal reference of 2.56 V (or 1.1 V depending on your Arduino), if you use that then, you guessed it, 1023 = 2.56 V (or 1.1V).
You might have a very fancy external reference voltage already available and if you want to use that, use the external setting and connect that reference voltage to the AREF pin.
If your analog sensor gives 0 to 5 V and your Arduino is also powered by 5 V then you should use the default setting so that the VCC is used as ADC reference.
If your sensor gives a voltage between 0 and 1 V then you could use the internal reference so that more of the 0 to 1023 range is usable. Giving you get better resolution.

The default behaviour is for the analog reference to be Vcc which on many Arduinos is 5V. In that case do not connect anything to AREF.
However if you have a precision voltage reference then you can connect that to AREF (and GND) and specify in your sketch, before doing an analogRead:
 analogReference (EXTERNAL);

I have a page about the ADC converter which may help explain, or may be too much detail. :)

or if I even have to use it while plugging analog sensor to the arduino

Unless you are planning to use some different reference voltage, don't use it at all.
For a 5V Arduino the voltage measured with the default AREF would roughly be 4.88 mV per unit of measurement (ie. 5V / 1024), but more accurately:
float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

The voltage you supply to VREF (if you supply any at all) must be between 1.0V and Vcc where Vcc would be 5V for an Arduino Uno.

“do not connect anything to AREF” and “[call analogReference(EXTERNAL)] before doing an analogRead” (amphasis mine). These are very important points not mentioned in the other answers.

I added the emphasis in my answer in case it was too mild as it was. ;)

The AREF is a reference voltage input pin.
The reference voltage is maximum voltage when you measure analog signal.
In other words, you can measure 0V ~ AREF voltage by using ADC port.
Be aware that the minimum voltage of AREF is 1.0V.

Well, I think you should read the manual first before you use (and even perhaps brake it).
Generally speaking, analog reference is a voltage value between 0.00 and 5.00V, which will be used as virtual reference for all the analog inputs, you connect to your arduino board.
About analog reference is on Arduino site:
https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/


text:
ESP-01 not running custom firmware
I have two esp-01 micro controllers that I'm trying to flash using the Arduino IDE but found some problems in the process. I followed step 1 of this tutorial to install all the dependencies to the IDE.
As for the code, it's one of the examples:

/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

I'm flashing it using the serial port communication, and the circuit is the following:

Having an MB102 as the power supply and a FT232RL as FTDI. Obviously everything at 3.3V.
I can flash the device properly when using the Arduino IDE. This is the output:
C:\PATH\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd ck -cb 115200 -cp COM3 -ca 0x00000 -cf
C:\SOMEPATH\Temp\arduino_build_913175/Blink.ino.bin
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
warning: espcomm_send_command: wrong direction/command: 0x01 0x00, expected 0x01 0x08
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 226352 bytes from
C:\SOMEPATH\Temp\arduino_build_913175/Blink.ino.bin to flash at 0x00000000
erasing flash
    size: 037430 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 36% ]
................................................................................ [ 72% ]
..............................................................                   [ 100% ]
starting app without reboot
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete

So everything looks fine, but after rebooting the device (by turning on and off the power supply) and removing the GPIO0 connection to the ground to avoid the flash mode, nothing happens. Looks like the program is not executing successfuly and the LED doesn't blink or anything.
Does anyone know if I'm doing something wrong? Should I connect GPIO0 to the power supply to get a high voltage after flashing the device, to make sure the GPIO0 doesn't stay at low at boot time and it enters flash mode?
Note that I tried with both ESP-01 to make sure it wasn't a deffective one, and also note that the LED of the mcu is ON, so it is obviously powered on.

Try explicitly setting the pin for GPIO1 instead of using LED_BUILTIN, i.e.: pinMode(1, OUTPUT); and then digitalWrite(1, LOW); and digitalWrite(1, HIGH);. It could be that the header you use for the ESP8266 has a different pin set for the built-in LED.

I'll try, but still I belive it's something related to how I flash it or how it runs the firmware since even uploading a program with basic serial communication (a print saying "HELLO") won't work.

@lpares12 I found on my devices that the usual definitions for the pins simply weren't right (the usual Arduino assignments were ignored in the design.) I also found that the LEDs weren't even close to the same number, either. I don't recall, but it was like I had to hard-code a 6 to get to the LED that would otherwise have been 1. Like that. Later... much later... I found some docs that helped. I still have no idea why the designers went the way they did. But everything worked once I pinned down the numbers.

@jonk but still it doesn't explain why other example codes which do not use the LED don't work. For example, only using the serial communication to print "hello" every second doesn't work either, just outputs random symbols in the serial console (even changing the baud rate in both the code and the serial connection, being always the same of course)

@lpares12 I only used the LED and also the WiFi library with the device. So I can't really add anything to your troubles about the serial console part. I wish I could. If I had to guess (and I do), I'd imagine that it was (1) incorrect library code being used, despite the docs you found; or (2) my own misuse of them, somehow. I tend to assume that the hardware works okay (never been wrong about that assumption.) So it is always "my problem" in having the right device info or the right library code or the right compiler setup. I wish I knew more about that particular issue. But I don't.

@RonBeyer didn't work either setting it explicitly. Will try to erase all the flash memory with esptool and upload the program again.

First suggestion: http://www.esp8266.com/viewtopic.php?f=26&t=4014[http://www.esp8266.com/viewtopic.php?f=26&t=4014] second suggestion: http://www.esp8266.com/viewtopic.php?f=6&t=14276[http://www.esp8266.com/viewtopic.php?f=6&t=14276]

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


text:
someVariable = { somethingThatLooksLikeAFunction }; possible?
Wasn't sure how to title this question...
I was curious whether the title example is possible somehow, and are there any good tricks to using it?
I have been using something similar quite a lot:
newBool = (someTest) ? true:false;
newInt  = (x + (y / z));
[...]

However, I was curious if it was possible to add far more conditions, almost like a function?
For some simple(*) examples:
someThing = {
    int _x = aFunction(_x);
    if(_x) {
        something = somethingElse;
        for(...){ ... }; // etc
    } else {
        /* otherStuff */
    }
};

Or
someThing = {
    for(_x=0;_x<y;_x++){
        z++;
    }
    someThing = (z>y) ? a:b;
};

I understand it's worth just separating it off into functions most of the time, although I'm trying to get away from a function/library-fest as much as possible...  It's getting annoying crawling through everything when I could just have the useful stuff right there, where I need it, instead of 1000 lines away, or in another library.  It also allows the text editor to fold the code out of sight, starting from one variable, instead of on each clause.
With the few tests I have tried, I've not been successful in achieving what I'm experimenting with, so, is this kind of thing possible in any way? and if so, what are the rules/possibilities/different ways you could implement this?
* Emphasis on simple! And a semi-pointless/completely useless "function" alert too!  I'm just curious about the "proof of concept" in the examples...

Something = {code} is just syntatic sugar for code; something=someotherthing

You can do it with a lambda function, though the syntax is somewhat cryptic:
int someThing = [](int y, int z, int a, int b){
    for (int _x = 0; _x < y; _x++) {
        z++;
    }
    return (z > y) ? a : b;
}(100, 0, 10, 20);

In that you are defining a lamda function [] with four parameters, y, z, a and b. Then calling that function with four numbers (100, 0, 10, 20) and assigning the return value to someThing.
It's the same as writing a normal function but there's a lot more brackets around.

That gave me inner smiles :D That's a really nice example! Thank you!  I assume (100, 0, 10, 20) could be (intOne, intTwo, boolOne, boolTwo), for example, too?

Yep. Just like calling any function.

I just don't understand what is the gain doing this. It's overkill using lambdas for something you can in-line for the same result with less code.

@LookAlterno No benefit at all. The compiler will probably optimize it away anyway. But.. why climb a mountain...? Cus it's there.

Then, some time latter, some poor soul have to mantain that code ...

@LookAlterno - I'd massively appreciate any advice or alternate ways if you have any? Reason I asked is that as my program is getting larger, I am ending up with many functions that are used only within a single other function; which is becoming increasingly cumbersome to keep track of.  With something similar to the above, I can just have the "simple but still important" function there and then where I need it, and the text editor folds away to a single variable, instead of on each for, if, etc that each variable pipeline is going through.  I find it far more readable for my uses, so far.

@Timeless. WIthout actual samples of your code is hard to add anything. I use lots of small functions (<20 loc), writing them as I needed. When the code grow too much and start to look complicated, it's time to refactor it until it become manageable again.


text:
Are lambdas a good way to improve readability in this instance?
Disclaimer: The following code hasn't been compiled, and probably won't work in any way.  This is just for opinions relating to this Arduino question as I'm still learning and experimenting with different coding techniques.
As I understand it (and please feel free to offer a (4.)), the following code could be written in numerous ways, including:

No lambdas, and each following lambda as a separate function of its own.
No lambdas, no external functions, and having it all flow within the same function.
Using lambdas in a similar way to the code provided below.
?

As my programs are getting sizeable, I'm currently finding it difficult to keep track using (1.) and/or (2.) when writing programs, especially if bugs show up. This has led me to question if there was a way to reduce a great many if and for (etc) into a single, text-editor-foldable "seed" (i.e. a single variable).
In my original question it was suggested that a possible way to do this could be option (3.) using lambdas.  However, it was also pointed out that it may be overkill/not practical, and without any examples of what I'm trying to achieve, it was difficult to make a more informed judgement. So with this in mind, I have thrown together an example showing how lambdas could help me achieve some readability to my code.
If this is an acceptable technique, or not, I would be extremely grateful for any advice.
Code, lambda example, unfolded:
// Structs data, fans;
void temperatures(int _temperaturePin) {

  data.cTemp = [](int _tPin) { // current temperature
    float _finalReading = 0.0f;
    for (int i = 0; i < temperatureResolution; i++) {
      float _currentReading = analogRead(_tPin);
      _finalReading += ( 10000 / ( ( 1023 / _currentReading ) - 1 ) );
    }
    _finalReading = (_finalReading / temperatureResolution);
    return (uint8_t)_finalReading;
  }(_temperaturePin);

  bool fanState = []( int rOne, int rTwo, int rThree ) { // fans on or off
    int _lowMin = data.tempTarget - ((data.tempTarget - data.tempMin) / 2);
    int _medMax = data.tempTarget + (( data.tempMax - data.tempTarget) / 2);
    bool _fanState = false;
    if (data.cTemp < data.minTemp) {
      digitalWrite(rOne, LOW);
      digitalWrite(rTwo, LOW);
      fans.off = !_fanState;
    } else {
      _fanState = true;
    }
    if ((data.cTemp > data.tempMin) && (data.cTemp > _lowMin)) {
      digitalWrite(rOne, LOW);
      digitalWrite(rTwo, HIGH);
      fans.low = _fanState;
    }
    if ((data.cTemp < data.tempTarget) && (data.cTemp < _medMax)) {
      digitalWrite(rOne, HIGH);
      digitalWrite(rThree, LOW);
      fans.medium = _fanState;
    }
    if (data.cTemp > data.tempMax) {
      digitalWrite(rOne, HIGH);
      digitalWrite(rThree, HIGH);
      fans.high = _fanState;
    }
    return _fanState;
  } (relayOne, relayTwo, relayThree);

  bool overloadProtection = [](bool _fState, int _lCount, int rCount) { // overload protection on or off
    bool _protect;
    int _pwmValue = 255;
    if (_fState) {
      _protect = ((_lCount > MAXLEDS) || ((_lCount > (MAXLEDS / 2) && (_rCount > MAXRELAYS) ))) ? true : false;
    }
    if (_protect) {
      for (int i = 0; i < _lCount; i++) {
        _pwmValue -= 10;
      }
    }
    for (int i = 0; i < _lCount; i++) {
      if (ledPins[i] == HIGH) {
        analogWrite(ledPins[i], _pwmValue);
      } else {
        digitalWrite(ledPins[i], LOW);
      }
    }
    return _protect;
  }(fanState, sizeof(ledPins), sizeof(relayPins);
}

Code, lambda example, folded:

I can see that methods vs lambdas don't appear to make a huge difference to overall word count in this case, however, I can happily fold away temperatures() and know that's the root of everything I need for anything temperature related (without having to break off into another library; as far as I am aware), instead of having potentially 3 more functions sitting there and cluttering up screen space.
This also makes working within temperatures() a less daunting task than having potentially 100's of for and if (etc) statements permanently in view.
I'm only a hobbyist programmer at the moment, learning in my own time with no formal programming education, so I am 100% completely open to any suggestions or advice, especially due to ignorance regarding this subject on my part.
Much appreciated!
P.S. codereview.stackexchange requires working code to post there otherwise I would have.

You can also use UECIDE instead of Arduino IDE. With UECIDE you don't need to open all source files in you project.

I currently use Atom as it allows split windows in both horizontal and vertical directions at the same time, and Notepad++ for single/double files. I only tend to use the normal IDE to compile and debug and write the *.ino.  UECIDE didn't work when I tried it (~2 years ago though maybe?), I'll definitely have another look, anything should beat the normal IDE! thanks!

I use UECIDE, but keep Arduino IDE mostly to do OTA upgrades to my NodeMCU projects.

Standard method using normal functions
Quickly tell me, what does the temperature() function do?
// Structs data, fans;
void temperatures(int _temperaturePin)
{
  data.cTemp = getTemperature(_temperaturePin);
  bool fanState = getFanState(relayOne, relayTwo, relayThree);
  bool overloadProtection = getOverloadProtecton(fanState, sizeof(ledPins), sizeof(relayPins);
}

Well, it get the temperature, fan status and overload protection status. No need to know about lambdas, or even know C/C++: if you know any programming language (PHP, Javascript), you will able to understand what this code do.
Of course, getTemperature and others are implemented as traditional functions elsewhere. It's not important or relevant to know how they work, just what they do/return. I can write it in another source file and forget about them, never to be seen again.
Lamba method
Same question (with your original code), what does the temperature() function do?
   // Structs data, fans;

    void temperatures(int _temperaturePin) {

      data.cTemp = [](int _tPin) { // current temperature
        float _finalReading = 0.0f;
        for (int i = 0; i < temperatureResolution; i++) {
          float _currentReading = analogRead(_tPin);
          _finalReading += ( 10000 / ( ( 1023 / _currentReading ) - 1 ) );
        }
        _finalReading = (_finalReading / temperatureResolution);
        return (uint8_t)_finalReading;
      }(_temperaturePin);
// More code ...

You have made one giant monolithic block of code, which is anatema by any standard. And code folding doesn't really solve that.
This not so easy to read. You have to scan searching for the each lambda end, taking mental notes about what is finally executing inside temperatures(). To much work, to much visual clutter, merging the what to do with the how to do it.
Think about testing. How do you test your lambdas? You can't do it easily. You need to extract the code from your application, to start with. And add all those external variables your are accessing from inside the lambda.
With traditional functions, no need to change your application to test your functions; just write a test program to exercise your code.
Think about code reuse. It's dificult with your code identify common code to refactor/reuse it.

Eventually it will be along the lines of, Computer computerOne; then computerOne.oledUpdate(temperatures(), timeAndDate(), etc() ).  All my previous iterations are becoming method/library nightmares, it would be nice to just have everything I need in less functions with less abstraction.  For myself personally, it's perfectly readable so far, and takes up much less screen space.  I will be using the "normal" way (how you have done it) within setup() and loop() mostly.

In addition to Computer, I also have Room which contains DomesticRooms, OfficeRooms, Car, and a load of other libraries, with Computer one of the sub libraries already.  My aim was to hopefully at least remove something from the amount of files and functions I am ending up with.  It's becoming extremely difficult having only 4 editing windows open at once on one screen.  I suppose my aim is to reduce the amount of files, and to reduce the amount of methods within each file; unless of course this is normal?

There is a reason, why the lambda concept was added to the C++ standard. This isn't it. This is called obfuscation.
void temperatures(int pin)
{
  // read the temperature with higher precision than single adc read:
  data.cTemp = 0.0f;
  for (int i = 0; i < temperatureResolution; i++) {
    data.cTemp += ( 10000 / ( ( 1023.0 / analogRead(pin) ) - 1 ) );
  }
  data.cTemp /= temperatureResolution;

Even this is a much better than misusing the lambda.
The main goal should be readability (= self docummented code), so anyone can quickly understand what is going on there.
That is also one of the reasons why the functions exists. The primary goal is you don't have to use the same snippets of code again and again (copy-paste). Try to fix the same bug on many places instead of one function.
In this code you should learn about concepts of finite state machines and ring buffers/floating averages, ...
Anyway, I've always hated parts of code in 10000 lines long file with only two methods or so. It's freaking hell to maintain that kind of code. Yes, having many tabs is also hard, but not harder than scrolling in mile long file. (I hate folding)

I was just trying to see if I could get around having to turn yet another group of methods into another library/lists of other methods.  The example above is what I "quickly" threw together as I've essentially turned 3 methods into one, I could in effect turn 100's of methods into one without having to make a library (but never would do that).  My real code is massive, and is becoming a huge struggle to keep track of easily - I was just after a way to remove long files, or loads of files that are more focused. - I'm struggling with finding that balance.

@Timeless I'm tending to use loads of files (almost like in Java - one file per class but I keep subclasses inside of class) to keep simple responsibility of classes / files.

Same as what I have been doing, so much fun :D Oh well, I'm glad Articy Draft exists, it's extremely helpful for pre-planning file structures sometimes


text:
Purpose of USB (FTDI) and ICSP connectors
As an Arduino newbie I am a little bit confused about possible ways of programming and communicating with this device. I have done some research and it seems that:
ICSP is used for programming with a bootloader in MCU.
The USB (FTDI) port is used (mostly) for sending text messages to the PC and programming without a bootloader.
Am I right? How can I detect whether I have a bootloader installed (Uno R3 clone)? Thank you very much!

The ICSP is used for 'bare metal' programming. This what you'd use if you wanted to replace or remove the bootloader, change the clock oscillator settings, or program the device as a bare 328.
The USB port is for communicating with a program running on the Arduino. When it's first booted, the bootloader program checks to see if there's any activity on the serial link from the Arduino host program on a PC. If there is, then it allows downloading of a program from it. If not, it continues on to the last code that was programmed into it.
The easiest way to see whether a bootloader is installed is simply to start it up with the PC host, and see whether it can talk to it.

This is slightly mis-stating things.  "bare metal" programming tends to refer to approaches with little in the way of runtime framework, for example targeting the ATmega not the Arduino APIs, and is something you can do even when using the bootloader to get your code onto the chip.  Rather, the ICSP connector is for chips that haven't been initialized with a bootloader, or need the kinds of fuse or oscillator settings you mention which the bootloader may be unwilling to make.

As for the ability of a PC host to talk with the board, the base of that is really determined by the virtual USB firmware in the other ATmega on the board - there will be a virtual serial device if that exists, even if the main ATmega has been pulled off the board.  To determine if there's a bootloader in the main ATmega, one should use avrdude (likely via the Arduino IDE) to try to upload something - but failure in that could as easily be a wrong baud rate, lack of auto reset, or bad manual reset timing, as a missing bootloader.


text:
Why is my DS18B20-PAR not picked up?
I have had a DS18B20-PAR for some time and have often used it without a problem until now. Yesterday it just suddenly stopped working. I was trying to use it along with two i2C sensors at the time. I don't really know of anything which could have fried it, though.
Edit: It is turning out much more complicated than I thought. I can't ever get it to work on pin 10. The sensor sometimes works on other pins (3, 9 and 11), but it often does not. I can still use pin 10 to blink and fade an LED, and receive input from a button, but it never picks up my DS18B20-PAR. What is happening here?
My setup:
I have just one DS18B20-PAR connected to my Arduino Uno look-alike as shown in the following image:

Please note that on the DS18B20-PAR the third pin is internally not connected.
The code:
My Arduino is running this code (a OneWire example sketch which has always worked before):
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(10);  // on pin 10 (a 4.7K resistor is necessary)

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

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

On the serial monitor is just prints "No more addresses." every 250 milliseconds.

If the setup worked fine and then stopped, you must examine what changed. If your code is unchanged then it could be your sensor or your Arduino.
You can try putting the sensor on a different input pin and update the code accordingly.
You can try the sensor on a different Arduino or a new sensor if the same type on your Arduino.
These are the first steps to troubleshooting.

I don't have another Arduino or another sensor unfortunately.


text:
SSID was not declared in this scope
so I am new to arduino and coding in general, I am trying to use the arduino to remotely survey plants, I am using this guide: https://create.arduino.cc/projecthub/arduino/plant-communicator-7ea06f. The entire code is:
#include <WiFi101.h>
#include<WiFiSSLClient.h>
const char* ssid = SKY1C9D0;    //  your network SSID (name)
const char* password = SYDTSTQR;  // your network password
String httpsRequest = https://hooks.zapier.com/hooks/catch/2821422/84ehn1/;
// your Zapier URL
   const char* host = "hooks.zapier.com";
WiFiSSLClient client;
void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(2000);
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, password) != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
}
void loop() {
  float temperature = 22;
  int moisture = 150;
  int light = 40;
  String warning = "This is a warning message";
  warning.replace(" ", "%20");
  send_email(temperature, moistue, light, warning );
  delay(20000)
}
void send_email(float temperature, int moisture, int light, String warning)     {
  // convert values to String
  String _temperature = String(temperature);
  String _moisture = String(moisture);
  String _light = String(light);
  String _warning = warning;
  if (client.connect(host, 443)) {
    client.println("POST " + httpsRequest + "temperature=" + _temperature +                 "&moisture=" + _moisture + "&light=" + _light + "&warning=" + _warning + "     HTTP/1.1");
    client.println("Host: " + String(host));
    client.println("Connection: close");
    client.println();
    delay(1000);
    while (client.available()) { // Print on the console the answer of the server
      char c = client.read();
      Serial.write(c);
    }
    client.stop();  // Disconnect from the server
  }
  else {
    Serial.println("Failed to connect to client");
 }
}

The error is specifically highlighted here:
    const char* ssid = SECRET_SSID;    //  your network SSID (name). The error is that the ssid has not been declared.
I am unsure of what to do to fix this and any other possible errors that have gone unnoticed. I would highly appreciate any help or guidance.
Thank you

const char* ssid = "myAP"; and  const char* password = "myAP passworld"; is not working? You have to REPLACE it with correct credentials.

I have tried using correct credentials, still does not work, I removed credentials only so I could post the code online

Also the httpsRequest have to be a string, you can't just put the https address like this.

have you replaced SECRET_SSID with the actual SSID or defined a value for a variable SECRET_SSID? The error seems to be saying that SECRET_SSID is not defined or declared so the compiler doesn't know what that text is. This looks like C so is there a #define missing?

I have now edited it with the actual ssid and password, it still does not work

@KIIV how would I include the https address then?

String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";. However HTTP request should be GET, as you are not posting anything and Requested path should be without protocol and without host

A problem in the include file on the line previous could cause the following line to be misinterpreted. To test that try moving the ssid after the password and see if the error changes. Obviously make sure all strings are properly quoted.
#include <WiFi101.h>
#include <WiFiSSLClient.h>

const char* password = "SYDTSTQR";  // your network password
const char* ssid = "SKY1C9D0";    //  your network SSID (name)
String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";

You need quotes around literal string values.
const char* ssid = "SKY1C9D0" ; // your network SSID (name)
const char* password = "SYDTSTQR" ;


text:
Arduino Nano wih mfrc522 warning error
UPDATE
I have managed to get rid of the WARNING: Communication failure, is the MFRC522 properly connected?. Unfortunately, that did not fix the firmware error it now says 0x80. I have now also tried using different IDEs from arduino in the hopes of fixing this, still nothing. The connection error between the reader and the arduino has come back as well.
Furthermore...
*****************************
MFRC522 Digital self test
*****************************
Firmware Version: 0x92 = v2.0
-----------------------------
Only known versions supported
-----------------------------
Performing test...
-----------------------------
Result: DEFECT or UNKNOWN

would this now mean that my device is a defect?
Also, that version has gone back to showing unknown and the other hexadecimal codes.
I have just bought the parts. The arduino nano v3 and the MFRC522 based RFID reader. I have followed the typical pin layout after downloading the library from arduino. When I go to test one of the examples I get a warning within the arduino serial monitor :
Firmware Version: 0xFF = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?
Scan PICC to see UID, SAK, type, and data blocks...

I try to scan one of the existing cards but nothing happens. It either stats that it is version 0xFF or 0x0. I am new with this and this is my first 'project'. the pins are defined.

I have 3.3V on the reader to 3v3 on the arduino
I have RST on the reader to D9 on the arduion
I have GND on the reader to GND on the arduino (on the same side as the 3v3 is )
I have MISO on the reader to D12 on the arduino
I have MOSI on the reader to D11 on the arduino
I have SCK on the reader to D13 (on the same side as the 3v3 is)
I have SDA on the reader to D10 on the arduino
The code I am using is from the arduino library manager:
  /*
  * --------------------------------------------------------------------------------------------------------------------
  * Example sketch/program to test your firmware.
  * --------------------------------------------------------------------------------------------------------------------
  * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
  *
  * This example test the firmware of your MFRC522 reader module, only known version can be checked. If the test passed
  * it do not mean that your module is faultless! Some modules have bad or broken antennas or the PICC is broken.
  * NOTE: for more informations read the README.rst
  *
  * @author Rotzbua
  * @license Released into the public domain.
  *
  * Typical pin layout used:
  * -----------------------------------------------------------------------------------------
  *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
  *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
  * Signal      Pin          Pin           Pin       Pin        Pin              Pin
  * -----------------------------------------------------------------------------------------
  * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
  * SPI SS      SDA(SS)      10            53        D10        10               10
  * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
  * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
  * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3              15
  */

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

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

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

 /**
  * Check firmware only once at startup
  */
 void setup() {
   Serial.begin(9600);   // Initialize serial communications with the PC
   while (!Serial);      // Do nothing if no serial port is opened (added for    Arduinos based on ATMEGA32U4)
   SPI.begin();          // Init SPI bus
   mfrc522.PCD_Init();   // Init MFRC522 module

Serial.println(F("*****************************"));
Serial.println(F("MFRC522 Digital self test"));
Serial.println(F("*****************************"));
mfrc522.PCD_DumpVersionToSerial();  // Show version of PCD - MFRC522 Card Reader
Serial.println(F("-----------------------------"));
Serial.println(F("Only known versions supported"));
Serial.println(F("-----------------------------"));
Serial.println(F("Performing test..."));
bool result = mfrc522.PCD_PerformSelfTest(); // perform the test
Serial.println(F("-----------------------------"));
Serial.print(F("Result: "));
if (result)
  Serial.println(F("OK"));
else
  Serial.println(F("DEFECT or UNKNOWN"));
Serial.println();
 }

 void loop() {} // nothing to do

This happens when you wrongly interconnect the pins. are you using i2c comm ?

Or SPI communication ?

What are they? I am really new to this

The communication method used by your module with arduino. Its either SPI or I2C. This error happens when these comm. pins are wrongly connected.

I am not sure what one it uses, I just connected the pins directly to each other using F-F jumper cables

Put your schematic in the question.

Put your code too

You are using SPI comm. The code is fine too. Usually this "communication failure" happens due to wrong pin connections. Say for eg. If MOSI and MISO are interchanged. Check all connections, ground and VCC connections once more. I have also seen that soldering the pins of MFRC522,  instead of simply connecting by wire has solved this issue most of the time. Another work around is repeatedly calling PCD_init() function even after failing result inside loop() . And see whether its working. If none of these worked, hard luck. I think its firmware issue or defective board.

Ugh... Looks like I have a faulty board :( Thank you for your help

Anyway try both the methods...especially soldering method. These are really delicate and cheap modules. Lotta defective boards are there in the market.


text:
Relay active low and ESP8266 GPIO pins
I am using a ESP8266, specifically the ESP-12-E :

I have a Relay, SRD-05VDC-SL-C connected to GPIO pin 4.
It is wired in Normally Open(with my device to be powered wired into the top and middle pins counting from the top to the bottom of the picture below):

In my arduino code when I issue:
  pinMode(4, OUTPUT);

This seems to pull the pin LOW, which is the active state of the relay, powering it, which turns my device on before my control code has even had chance to run. I want to get the pin for output but keep it floating.
How do I setup my pin for output, but leave it 'floating' from code, or keep it high / floating, so that I have to explicitly issue:
digitalWrite(4, LOW);

Before low is sent to activate my relay?
Hope this makes sense!

use digitalWrite(4, HIGH); before pinMode(4, OUTPUT);

@Trevor_G Wait what. That's actually the answer. RenegadeAndy, have you tried anything at all?

@HarrySvensson no. I didnt expect the act of calling the pinMode() function to actually cause the pin to go to LOW.

@RenegadeAndy I do hope this is the last time you write "no" to that question. Why should we help you if you can't even try things on your own.

Sorry...without being informed how would I have known to try this? Researching GPIO and reading tutorials , which ALL say run pinMode before digitalWrite, how was I to know to try this? You have done little to nothing to help. @Trevor_G said all that was needed, you are not being helpful at all in your allegation.

FYI: Most of these devices have similar output stages where the latch that holds the output state is before the pin driver itself. If you write to it when the pin is input the state just sits there internal. BTW: some folks just toggle the pin direction with the internal state set rather than the pin state itself. Not a method I'm keen on though since they rely on the week pullup.

@HarrySvensson Yes, it never feels right adding one sentence answers...

GPIO4 is LOW during reset (and thus boot), so an active-low  relay will erroneously click on power-on if wired to GPIO4. use GPIO 3 or maybe 2 or 16. you also might want to set pinMode(n, INPUT_PULLUP) to lock it into floating until needed.

@danadavis how did you know this about which pins are low on boot etc? Whee is this docced?

RenegadeAndy, Thanks a lot, I could not find this solution anywhere, thank you so much, it solved my task, happiness to you,

The answer thanks to Trevor_G was:
use digitalWrite(4, HIGH); before pinMode(4, OUTPUT);

Yes this really helped

authors: Никита Чаузов


text:
Why my ISR is giving impossible values?
I have a very simple ISR:
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;
volatile uint32_t count = 0;
volatile uint32_t toggle = PATTERN_A;

// My ISR
void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

The idea is that the toggle variable takes values 0xFF00FF00 or 0xFF00FF00 depending on the evenness of the count variable. This is the only place where toggle is changed, but it's used (read-only) in the sketch.
I don't know why, but toggle gets all sort of random values during execution.
What is happening here?

The problem is a combination of several causes.
Assignments are not atomic
An atomic operation is something that is completely done or not. The opposite is some operation that can be disrupted while executing, leaving thing in a inconsistent state.
This is how the count++ works at machine level in Arduino:
void callback()
{
    count++;
  fa:   80 91 0a 02     lds r24, 0x020A
  fe:   90 91 0b 02     lds r25, 0x020B
 102:   a0 91 0c 02     lds r26, 0x020C
 106:   b0 91 0d 02     lds r27, 0x020D
 10a:   01 96           adiw    r24, 0x01   ; 1
 10c:   a1 1d           adc r26, r1
 10e:   b1 1d           adc r27, r1
 110:   80 93 0a 02     sts 0x020A, r24
 114:   90 93 0b 02     sts 0x020B, r25
 118:   a0 93 0c 02     sts 0x020C, r26
 11c:   b0 93 0d 02     sts 0x020D, r27

The first four instruction loads the four count bytes into four separate register, the laboriously increment it by one and then store it back in RAM.
Now, toggle is a variable of interest and you want to use it inside loop, like this:
void loop()
{
    uint32_t x = toggle;
    ...
}

And at machine level you get
    uint32_t x = toggle;
 414:   60 91 04 01     lds r22, 0x0104
 418:   70 91 05 01     lds r23, 0x0105
 41c:   80 91 06 01     lds r24, 0x0106
 420:   90 91 07 01     lds r25, 0x0107

Here we are simply copying the toggle variable into our x variable. As you can see, the copy takes four machine instructions to get completed.
Now, what happens if an interrupt comes while you are copying (or using) toggle?
An interrupt suspend the assignment, go to the ISR (callback in this case and change toggle value. Upon return, copying continues, mixing bytes from the old and new value.
You must use volatile
Any global variable used inside an ISR must be declared volatile. This is an hint to the compiler that the variable could change unexpectedly. Therefore, the volatile variable must be always read afresh, discarding any cached value.
Critical section
The rule for using values changed by ISR is simple:

Always copy the ISR's global variables to your own temporary variable.
Before coping, disable interrupts and reenable it after the copy is done. This prevent the ISR from executing while your are copy the values.

Demo
This little demo shows you all of this in action.
The sketch collect all the values from toggle (not disabling interrupts) during one minute and after that print a table showing what it got.
/*
 * This sketch show how to deal with variables shared between ISR and main thread.
 *
 * By Look Alterno 2018
 */

#include "TimerOne.h"

volatile uint32_t count = 0;
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;

volatile uint32_t toggle = PATTERN_A;

#define MAX_CASES 16
struct {
    unsigned long value;
    int count;
} found[MAX_CASES];
int freeFound = 0;

#define PRINT_INTERVAL 60000L

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

    while(!Serial);

    Serial.println("");
    Serial.println("Test assignment under interrupts");
    Serial.println("");

    Serial.print("Value A=");
    Serial.println(PATTERN_A, HEX);
    Serial.print("Value B=");
    Serial.println(PATTERN_B, HEX);

    Timer1.initialize(500);
    Timer1.pwm(9, 512);
    Timer1.attachInterrupt(callback);

    pinMode(A0, INPUT);
    randomSeed(analogRead(A0));
}

void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

void loop()
{
  static unsigned long prev = 0;

  //  A random delay to simulate some real, variable work being done.
    delayMicroseconds(random(250));

  // This is the critical section.
//  noInterrupts();
    uint32_t x = toggle;
//  interrupts();

  // Now, let's see what value we got.
    if(x != PATTERN_A && x != PATTERN_B) {
        insert(x);
    }

  // Print values found
  unsigned long now = millis();
  if (now - prev > PRINT_INTERVAL) {
    printFound();
    prev = now;
  }
}

/*
 * Add a value to a table for counting.
 */
void insert(unsigned long x)
{
    int index = 0;

    while(index < freeFound && found[index].value != x) {
        index++;
    }

    if(index < MAX_CASES) {
        if(index == freeFound) {
            found[index].value = x;
            found[index].count = 1;
            freeFound++;
      Serial.print(freeFound);
      Serial.print(". Add=");
      Serial.println(x, HEX);
        } else {
            found[index].count++;
        }
    } else {
        Serial.print("*** Table overflow. value=");
        Serial.print(x, HEX);
        Serial.println(" ***");
    }
}

/*
 * Print the table of found values so far.
 */
void printFound() {
  Serial.println("");
  Serial.println("Values found");
  Serial.println("");
  Serial.println("Value - Count");
  for (int i=0; i < freeFound; i++) {
    Serial.print(found[i].value, HEX); Serial.print(" - "); Serial.println(found[i].count);
  }
}

If you uncomment noInterrupts and interrupts, every thing works just fine.
Other CPU
More powerful CPUs have atomic assignments, but following this practices makes your code portable across platforms, no matter what. Think of defensive programming

you can do it branch-less by defining an array with both states
const uint32_t PATTERN[2] = { 0x00FF00FF, 0xFF00FF00 }; and evaluating it via PATTERN[count & 1];.

@Kwasmich. Your proposal is more compact, but I'm trying to keep it simple and focused on the central issue. As a personal matter, I prefer the "?:" pattern. You can explore this issue comparing the standard "?:" vs your proposal, from performance, convenience and clarity. I'm waiting for your post.

@Kwasmich: Note that branchless is not necessarily better. Especially on the AVR which, owing to its very shallow pipeline, has very cheap branching.

Moderator's note: Due to the dispute about this answer we have reverted the community wiki flag, and rolled back the answer to the (almost) original one. Anyone who believes they can post a better answer is free to do so.

@User42 You are right. There is no point in making the code more compact, if it does not save time or flash space.

@Edgar Bonet True. Not all optimizations from x86 apply to AVR. Here one has to trade between precious flash space and execution time. For example it takes less flash space for swapping A and B the naive way using a temporary variable than having the BitTwiddling tripple XOR solution.


text:
analogWrite(DAC0, X), Analog voltage on DAC0 pin is higher for lower X value - is this normal?
I am using an Arduino DUE. Using the analogWrite(DAC0, X) command I am writing an analog value to this pin. X = 0 - 255 as I understand it.
I am observing that when X is lower, the voltage on DAC0 is higher nad when X is higher the voltage is lower.
Is that expected?
My code is simple:
void setup()
{
  analogWriteResolution(12);
}

void loop()
{
  analogWrite(DAC0, 10 );
}

voltage is lower ... how do you know what the output voltage is? ... you have not described how you are measuring the voltage.

Using a DMM between the DAC0 pin and GND.

I don't understand. How else does one measure voltage?

@jsotola  The load? I'm not sure what you are getting at.

Look, comments under questions are for clarifying the question, not trying to answer them obliquely or not. If you want to ask under what load the measurement was made, then ask it.

That doesn’t sound right. Try setting x to 0 and measure with DC. You should get ~0.56 V. Repeat with 4095, and you should get ~2.76 V.
Also, note that with analogWriteResolution(12) your range is not 8-bits (0-255), but 12-bits (0-4095).
The output should follow:
Vout = Vref * Xin⧸(2N-1) + Voffset
where

Voffset = 0.56 V
Vref = 2.2 V
0 ≤ Xin ≤ 4095

According to the page about analogWrite: Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs. - so that shouldn't be an issue.

@NickGammon Oops, that slipped passed me. I'll edit. Thanks


text:
How can i get rid of the error "cannot convert 'String' to 'const char*'"
I want to get this code to recognise different commands and be able to parse the rest of the command, fore example I send "/sleep 5", and it will sleep for 5 seconds. However, I keep on getting this error "cannot convert 'String' to 'const char*'". here is my code:
#define maxCommandLength 64

String commands[] = {"/test", "/say", "/reset", "/sleep"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Power on.");
}
char serial[maxCommandLength];
boolean valid;
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Clearing command buffer(char 'serial'");
  for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
    serial[i] = ' ';
  }
  if (Serial.available()) {
    Serial.readBytesUntil(' ', serial, maxCommandLength);
  }
  if (serial[0] == '/') { //if it is a command
    Serial.print("Command recieved. \nCommand class:");
    Serial.println(serial);
    //test if command is valid
    for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
      valid = strcmp(serial,commands[i]);
      if(valid){
        break;
      }
    }
    //execution of command
    Serial.readBytesUntil(' ', serial, maxCommandLength);
    //.......
  }
}

there is no reason for command to be a String array. Instead make it a const char**:
const char** commands = {"/test", "/say", "/reset", "/sleep"};

I found that yours wouldn't compile, but this would:
const char* commands[] = {"/test", "/say", "/reset", "/sleep"};

@RowanRadosav-McRae  If this answers your question please accept the answer.

You can call the .c_str() method of String class returning (temporary) const char * representation of underlying string, in your case:
valid = strcmp(serial,commands[i].c_str());
//                               ^^^^^^^^

should work. Just make sure you don't keep the returned const char * around longer than necessary because by spec it is no guaranteed to remain valid.


text:
Arduino Uno as Xbox One Controller?
I’m very new to Arduino and have been doing a lot of research on how to connect my Arduino Uno to my Xbox One as a wired controller, unfortunately I haven’t been able to find much help.  I found UnoJoy but it seems to only work with PlayStation.  I know that it is possible because the Uno has HID.  I’m sorry if this has been answered before, but how do I code the Uno so the Xbox will recognize it so I can assign (push buttons, toggle switches, rotary encoders) to certain functions in game?

The Uno does not normally have HID.  It is true that USB its interface chip can be reprogrammed to do that, but it's complicated and complicates normal operation.  You'd be better of with a direct USB board like a Leonardo or something else based on a 32u4, or something based on a suitable ARM part like most of the Teensy series.

I expect if you do some research you will find there is a body of knowledge on fully custom game controllers.  Actually had some unrelated boards assembled once by someone who had invested in short-run assembly equipment in order to serve that market.


text:
SD card doesn't work properly
I have this SD-card module. I have formatted the SD with this tool. My problem is that the Arduino Uno can't initialize the SD. I tried with this script:
// include the SD library:
#include <SPI.h>
#include <SD.h>

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

const int chipSelect = 7;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
}

void loop(void) {
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("Doesn't work properly");
  } else{
    Serial.println("works properly");
  }
  delay(2000);
}

And the result:
Doesn't work properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
works properly
works properly
works properly
works properly
works properly
works properly
Doesn't work properly
Doesn't work properly
Doesn't work properly
works properly
works properly
works properly
Doesn't work properly

The "works properly" happens, usually, when I move the module slightly. Is there a way to repair the module?
OS: Windows 10

It sounds like maybe you have unreliable wiring connections.  Your module won't directly plug into an Arduino Uno, so how have you physically made the electrical connections?

I use: MISO -> Pin 12,
MOSI -> Pin 11,
SCK -> Pin 13,
SDCS ->Pin 10,
5V -> 5V,
GND -> GND

Yes, but how are these connections physically made?

With Jumper Wires like this: https://www.exploringarduino.com/parts/jumper-wires/

Show us a photopgraph of your actual setup.

https://imageshack.com/a/img923/318/ptdhHE.jpg

Manufacturing flaws in such jumper wires are not unknown, and the connections there or in the Arduino can wear.  Also long wire runs are not encouraged for things like this, either signals or power/ground.

Your stated wiring doesn't appear to match your code or picture.  To which signal is the green wire connected?

I connect the SDCS (green) to Pin 7 as in the code above; in the previous comment I make a typo. Could be a problem with the module?

I have formatted the SD with this tool. .... this does not describe what you actually did

I formatted the sd with the tool that is linked.


text:
DS2436 Arduino UNO programming
I am struggling with programming my DS2436 chip using an Arduino UNO. To be honest, I am trying to modify DS18B20 code (the one that is anywhere on the internet) to work with DS2436. It's just harder for me to understand how whole memory and adressing thing work, since DS2436 has those pages of memory blocks, unlike DS18B20, which has only 1. Also the language factor is stopping me, I am not a native speaker.
I keep getting wrong data/temperature/CRC. Can someone assist me, please? I need this thing to show me voltage/temperature and cycles.
#include <OneWire.h>
OneWire  ds(10);

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

void loop(void) {
  byte i;
  byte addr[8];
  byte data[32];
  byte type_s;
  byte present = 0;
  float celsius, fahrenheit;

  if (!ds.search(addr)) {
    ds.reset_search();
    delay(1000);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }
  Serial.print("\n");
  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
    Serial.print("\n");
  }
  if (addr[0] != 0x1B) {
    Serial.print("Device is not a DS2436 family device!");
    Serial.print("\n");
  }
  {
    Serial.print("CRC= ");
    Serial.print(OneWire::crc8(data, 8), HEX);
  }
  Serial.print("\n");
  ds.reset();
  ds.select(addr);
  ds.write(0xD2, 1);
  delay(1000);
  present = ds.reset();
  ds.select(addr);
  ds.write(0xB2);
  Serial.print("  Data = ");
  for (int i = 0; i < 13; i++) {
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();
  unsigned int raw = (data[1] << 8) | data[0];
  int sig = raw & 0x8000;
  if (sig) {
    raw = (raw ^ 0xffff) + 1;
  }
  celsius = (float)raw * 0.03125;
  Serial.print("Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius ");
  Serial.print("\n");
  Serial.print("_______________________________________________");
  Serial.print("\n");
}

Please take a look at the OWFS sources, it has host code examples for almost every onewire chip ever produced: https://github.com/owfs/owfs/blob/master/module/owlib/src/c/ow_2436.c

You are a savior!

Yes necro, but having my own example of a DS2436 to try this out on, and having to write code for it with little else to go on, seems like the IC doesn't really know what to send you when reading the bus after sending the read register command.
As per the datasheet, 0xFF is data the IC sends when the bus master reaches the end of a page or an address that's reserved. Adding in ds.write(0x60); before performing the read cycles fixes most of this.
Haven't gotten into much past that, but it seems like there's also something not quite right going on with your arithmetic to turn your binary into temperature. Even with my fix getting something serviceable as output, I get 1024.00 Celsius.

Re “there's also something not quite right going on with your arithmetic to turn your binary into temperature”: It is indeed broken. Try this fix: int16_t raw = (uint16_t) data[1] << 8 | data[0]; float celsius = raw * (1.0/256);

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


text:
How do I execute some code at a certain time without RTC module?
I am building a project when I need my arduino to execute some code at two given hours of the day, for example one at 19:00 and another at 06:00. I know that with a RTC module I can do this easily, however how can I do that without a RTC module? I do not want to have to connect my arduino to a computer neither to the internet. It does not also have to be precise, a couple of minutes off would be ok.
My board is an Uno R3.

It depends on your arduino board. Is there a resonator or a crystal? If you have a crystal then you could use the time and timealarms libraries and let the time library run on millis(). You can also use millis() for 11 hours and 13 hours without the time library, because millis() can count up to 50 days.

@Jot My board is an Arduino Uno Rev3.

the esp8266 can read time from NTP service on Internet

Any built-in time facilities are highly inaccurate, from my experience 1-3 minutes off / day - after a month it could easily be executed an hour earlier/later than intedned. You need either RTC or NTP.

@wondra that is probably with a resonator. I have a uno clone with a crystal and it is less than one hour off per year.

If you start with the "BlinkWithoutDelay" sketch that comes with the Arduino IDE, you can execute your code alternating between 11 hours and 13 hours.
// Power up the circuit at exactly 06:00.
unsigned long delayInterval = 0;
unsigned long previousMillis = 0;
bool twoHoursAdded = false;

void setup(){

}

void loop(){

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= delayInterval){

    // previousMillis = currentMillis;

    // Use this "method" of incrementing the previousMillis variable
    // instead of the code used in the BlinkWithoutDelay sketch.
    previousMillis += delayInterval;

    if(twoHoursAdded == false){
      delayInterval = 1000UL * 60UL * 60UL * 13UL;
      twoHoursAdded = true;
    }
    else{
      delayInterval = 1000UL * 60UL * 60UL * 11UL;
      twoHoursAdded = false;
    }

    // Your code here that is run at 06:00 and 19:00.

  }
}

"Down sides" to using this code.

If there is a "power failure", the timing will be off, WAY off until you reboot the Arduino at exactly the right time.
You have to power up the Arduino at exactly the right moment for "it's" timing to match your "clock" timing.

If it's within your budget, have a look at the DS3231 modules available on aliexpress.com / ebay.com. They have a lithium battery backup incase of power outage and are really easy to connect to your Arduino using I2C. There are several libraries on Github that simplify using the DS3231 modules.

I am not sure why you are opposed to the RTC or whether you were excluding all external circuitry for the solution. So, I am just throwing this out there...
A CMOS-4060 ripple counter can be programmed for just about any time period and using two of them would give you two separate time constants.

source Substitute the relay for a signal wire to the CPU.
The Cmos 4060 is a 14-bit binary counter. However - only ten of those bits are connected to output pins. The remaining bits - Q1, Q2, Q3 and Q11 - do exist. You just can't reach them.
The 4060 also has two inverters - connected in series across pins 11, 10 & 9. Together with R3, R4, R5 and C3 - they form a simple oscillator.
While the oscillator is running - the 14-bit counter counts the number of oscillations - and the state of the count is reflected in the output pins.
By adjusting R4 you can alter the frequency of the oscillator. So you can control the speed at which the count progresses. In other words - you can decide how long it will take for any given output pin to go high.
When that pin goes high - it switches the transistor - and the transistor in turn operates the relay.
In single-shot mode - the output pin does a second job. It uses D1 to disable the oscillator - so the count stops with the output pin high. .
If you want to use the timer in repeating mode - simply leave out D1. The count will carry on indefinitely. And the output pin will continue to switch the transistor on and off - at the same regular time intervals.
For example, if you want a period of 9 Hours - the Range table shows that you can use the output at Pin 2. You need Pin 2 to go high after 9 x 60 x 60 = 32 400 seconds. The Setup table tells you to divide this by 512 - giving about 63 seconds. Adjust R4 so that the Yellow LED lights 63 seconds after power is applied. This will give an output at Pin 2 after about 9 Hours.
If you increase the value of R3 - and reduce R4 by the corresponding amount - you can set the time delay more precisely. Select a value for R3 that takes you close to the time you're after. And use the reduced value pot - to make the fine adjustment. Note that even finer adjustments are possible with a multi-turn pot.

As mentioned with VE7JRO's solution, this solution (while being pretty accurate) will eventually drift with time and must be powered up at an exact time that is synchronized with the desired trip times.

This is terrible advice. Why would anyone want to add a dozen extra parts only to have a time source that is way worse than the internal timebase of the Arduino Uno? In terms of frequency stability, an RC oscillator like this is about the worst you can get. The ceramic resonator clocking the Arduino is way better, and the quartz crystal of an RTC module is better yet. People go to the trouble of adding an RTC only because it is a better timebase than the millis() they already have.