text:
ESP8266 SPIFFS not saving correctly?
Hey all I am having some issues with the SPIFFS for this Wemos D1 mini ESP8266 controller.
This is my Arduino sketch:
#include <FS.h>
#include <ArduinoJson.h>

struct RGBLA {
  uint8_t R;
  uint8_t G;
  uint8_t B;
  uint8_t L;
  uint8_t A;
};

void setup() {
  if (!SPIFFS.begin()) {
    Serial.println("error while mounting filesystem!");
  } else {
    // put your setup code here, to run once:
    RGBLA returnedVars = readSPIFFS();

    Serial.begin(115200);
    Serial.println();
    Serial.println("Starting...");

    Serial.println("readSPIFFS 1");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    Serial.println("==================================");

    returnedVars = saveToSPIFFS(25,77, 107, 250, 155, false);
    Serial.println("saveToSPIFFS #1");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    Serial.println("==================================");

    returnedVars = saveToSPIFFS(205,17, 68, 50, 15, true);
    Serial.println("saveToSPIFFS #2");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    returnedVars = readSPIFFS();
    Serial.println("readSPIFFS 2");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    Serial.println();
    Serial.println("END!");
  }
}

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

RGBLA saveToSPIFFS(uint8_t R, uint8_t G, uint8_t B, uint8_t L, uint8_t A, bool saveA) {
  File configFile = SPIFFS.open("/config.json", "w+");

  if (configFile.size() > 3072) {
    Serial.println("Config file size is too large.");
  } else {
    Serial.print("Writing json to Config file...");

    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();

    //Get the old value and save it
    RGBLA returnedVars = readSPIFFS();

    Serial.println("Old Values?");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    if (saveA) {
      //Save Ambient Light data
      json["R"] = returnedVars.R;
      json["G"] = returnedVars.G;
      json["B"] = returnedVars.B;
      json["L"] = returnedVars.L;
      json["A"] = A;

      //Now save the new data
      returnedVars.A = A;
    } else {
      //Save RGBL data
      json["R"] = R;
      json["G"] = G;
      json["B"] = B;
      json["L"] = L;
      json["A"] = returnedVars.A;

      //Now save the new data
      returnedVars.R = R;
      returnedVars.G = G;
      returnedVars.B = B;
      returnedVars.L = L;
    }

    json.printTo(configFile);
    configFile.close();

    //Read new saved values into struct
    //returnedVars = readSPIFFS();
    return returnedVars;
  }
}

RGBLA readSPIFFS() {
  bool exist = SPIFFS.exists("/config.json");

  if (exist) {
    Serial.println("YAY!");
  } else {
    Serial.println("Boo!");
  }

  File configFile = SPIFFS.open("/config.json", "r");
  std::unique_ptr<char[]> buf(new char[configFile.size()]);
  configFile.readBytes(buf.get(), configFile.size());
  DynamicJsonBuffer jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());
  RGBLA returnedVars;

  String debugLogData;
  json.printTo(debugLogData);

  Serial.println("===============");
  Serial.println(debugLogData);
  Serial.println("===============");
  returnedVars.R = json["R"];
  returnedVars.G = json["G"];
  returnedVars.B = json["B"];
  returnedVars.L = json["L"];
  returnedVars.A = json["A"];

  configFile.close();

  return returnedVars;
}

And this is the console output:
Starting...
readSPIFFS 1
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25
==================================
Writing json to Config file...YAY!
===============
{}
===============
Old Values?
R: 0
G: 0
B: 0
L: 0
AmbientLight: 0
saveToSPIFFS #1
R: 25
G: 77
B: 107
L: 250
AmbientLight: 0
==================================
Writing json to Config file...YAY!
===============
{}
===============
Old Values?
R: 0
G: 0
B: 0
L: 0
AmbientLight: 0
saveToSPIFFS #2
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25
YAY!
===============
{"R":0,"G":0,"B":0,"L":0,"A":25}
===============
readSPIFFS 2
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

END!

As you can see, the first old values has all 0's which is incorrect. AmbientLight should be 25 at that point since readSPIFFS 1 has 25. So this should read:
Old Values?
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

saveToSPIFFS #1 is sending values 25, 77, 107, 250, 155 and false which then outputs correctly as:
R: 25
G: 77
B: 107
L: 250
AmbientLight: 0

But this time AmbientLight should still be 25 since it was sent false. It should have taken the old value (25) and placed it into the newer save.
R: 25
G: 77
B: 107
L: 250
AmbientLight: 25

Moving on to saveToSPIFFS #2 the values again are incorrect. The AmbientLight however is correct here. Instead of this output:
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

it should be gathering the 4 previous old values:
R: 25
G: 77
B: 107
L: 250
AmbientLight: 25

The json after this should not be this:
{"R":0,"G":0,"B":0,"L":0,"A":25}

It should be this:
{"R":250,"G":77,"B":107,"L":250,"A":25}

And lastly, the output of readSPIFFS 2:
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

Is incorrect. It should output:
R: 25
G: 77
B: 107
L: 250
AmbientLight: 25

Then after a reset it should have that and not the below for readSPIFFS 1:
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

So, where am I messing up here?
UPDATE
struct RGBLA {
  uint8_t R;
  uint8_t G;
  uint8_t B;
  uint8_t L;
  uint8_t A;
};

void setup() {
   RGBLA returnedValues = readSPIFFS();

   Serial.println("readSPIFFS 1");
   Serial.print("R: ");
   Serial.println(returnedVars.R);
   Serial.print("G: ");
   Serial.println(returnedVars.G);
   Serial.print("B: ");
   Serial.println(returnedVars.B);
   Serial.print("L: ");
   Serial.println(returnedVars.L);
   Serial.print("AmbientLight: ");
   Serial.println(returnedVars.A);

   returnedValues = saveToSPIFFS(205, 17, 68, 50, 15, false);

   Serial.println("saveToSPIFFS 1");
   Serial.print("R: ");
   Serial.println(returnedVars.R);
   Serial.print("G: ");
   Serial.println(returnedVars.G);
   Serial.print("B: ");
   Serial.println(returnedVars.B);
   Serial.print("L: ");
   Serial.println(returnedVars.L);
   Serial.print("AmbientLight: ");
   Serial.println(returnedVars.A);
}

RGBLA readSPIFFS() {
   RGBLA returnedVars;
   File configFile = SPIFFS.open("/config.json", "r");

   if (configFile ) {
     Serial.println("YAY!");
     configFile.readBytes((byte*) &returnedValues, sizeof(RGBLA));
     configFile.close();
   } else {
     Serial.println("Boo!");
   }

   return returnedValues;
}

RGBLA saveToSPIFFS() {
   File configFile = SPIFFS.open("/config.json", "w+");

   if (configFile.size() > 3072) {
     Serial.println("Config file size is too large.");
   } else {
     Serial.print("Writing to Config file...");

     //Get the old value and save it
     RGBLA returnedVars = readSPIFFS();

     Serial.println("Old Values:");
     Serial.print("R: ");
     Serial.println(returnedVars.R);
     Serial.print("G: ");
     Serial.println(returnedVars.G);
     Serial.print("B: ");
     Serial.println(returnedVars.B);
     Serial.print("L: ");
     Serial.println(returnedVars.L);
     Serial.print("AmbientLight: ");
     Serial.println(returnedVars.A);

     if (saveA) {
       //Save Ambient Light data
       returnedVars.A = A;
     } else {
       //Save RGBL data
       returnedVars.R = R;
       returnedVars.G = G;
       returnedVars.B = B;
       returnedVars.L = L;
     }

     configFile.write((byte*) &returnedVars, sizeof(RGBLA));
     configFile.close();

     return returnedVars;
}

why do you save it as JSON? simple file.write((byte*) rgbla, sizeof (RGBLA)) and file.read((byte*) rgbla, sizeof (RGBLA)) would work

@Juraj  can you put that as a potential answer and provide an example?

if it will be only one instance of the RGBLA struct and one file to save it, then create one global instance of the struct and rather  return a succes state from functions

You can write a struct to file as binary data. This example is from my project.
global data:
struct Stats {
  int heatingTime; // minutes
  int consumedPower; // watts
};

Stats statsData;

snippet from setup():
  File file = SPIFFS.open(STATS_FILENAME, "r");
  if (file) {
    file.readBytes((byte*) &statsData, sizeof(statsData));
    file.close();
  }

snippet from statsSave() function:
  File file = SPIFFS.open(STATS_FILENAME, "w");
  if (file) {
    file.write((byte*) &statsData, sizeof(statsData));
    file.close();
  }

your updated readSPIFFS should be:
RGBLA readSPIFFS() {

  RGBLA returnedVars;
  File configFile = SPIFFS.open("/config.json", "r");
  if (configFile ) {
    Serial.println("YAY!");
    configFile.readBytes((byte*) &returnedValues, sizeof(RGBLA));
    configFile.close();
  } else {
    Serial.println("Boo!");
  }
  return returnedValues;
}

So I can still return RGBLA like RGBLA returnedVars = readSPIFFS();?

Check out my updated OP.

configFile.readBytes((byte*) &returnedValues, sizeof(returnedValues)); or configFile.readBytes((byte*) &returnedValues, sizeof(RGBLA));

Alright corrected that in the update. Do I still need to use return returnedVars; or is it already populating the strut?

what is configFile["R"]?

Getting the value for R in the RGBLA.

you read it to the struct with readbytes. it is in returnedValues after readBytes

Alright I updated the OP again to reflect the changes. Is it correct now?

you read into local variable returnedValues and return copies the struct values into returnedValues in variable in setup

Ok I updated the OP again to reflect those changes. I also added the saveToSPIFFS but I am unsure how to save it as it has old data that needs to be saved with the new data (example: RGBL is new data while A is old data) all that needs to be saved into that config file.

Ok I think I have it now. Updated the OP update.

After finally being able to test this out i am getting the error of invalid conversion from 'byte {aka unsigned char}' to 'char*' [-fpermissive]**

invalid conversion from 'char' to 'const uint8_t {aka const unsigned char*}' [-fpermissive]**

change cast to required type. those are only different names for byte.


text:
USART, SPI or Bit-Bang for the continuous transfer of bytes without inserted extra bits
I have heard that

The SPI hardware introduces a 9th, HIGH bit between bytes
USART still uses start and stop bits when in synchronous mode

Are both these statements true? Can I modify the built-in SPI library to avoid #1? Or will I have to bit-bang the protocol needed?

Page 217&220 of Atmel-42735B-ATmega328/P_Datasheet_Complete-11/2016 do not mention an 9th bit and to me it seems highly unlikely. Have you actually tried if it works for you?

@Paul I've tried it, but it didn't work, but it could be a problem with the actual program. Sucks that no datasheet exists for my use case

#2 is false. It's basically USART in SPI mode.  #1 Without using clock signal, it's possible there is some pause as you can't write data in advance.

BTW: what is the use case? Why do you even need this bitstream?

@KIIV your question is most relevant here, because the question does not make sense. It is a typical http://xyproblem.info/ When it is for the maximum number of bytes per second, then extra bits or bytes can not be the issue. When it is for a communication protocol then there is manchester code. When a byte needs to be transferred without delay, then 8-bit parallel between two arduino boards is possible plus extra interrupt. There are many ways and many solutions if we would know the problem.

Are both these statements true?

Neither of those statements are true.
SPI never inserts extra bits. That would break everything if it did. What you are probably seeing (or think you are seeing) is a delay between bytes being sent. That delay is irrelevant, since the data is only ever sampled on an edge of the clock signal (which edge depends on the mode of the SPI communication) and with no clock edge in that delay period there is no data.
USART in synchronous mode is SPI. There are no start or stop bits in synchronous mode, since the clock is used to synchronise the communication rather than needing start or stop bits.

The SPI peripheral on the ATMega328 cannot continuously send data without a brief pause after every byte, as it does not sample the input buffer immediately after clocking the last bit, no matter what settings are used. At best, you can clock out bytes at the speed you expect +2 clocks when using assembler. The UART does allow continuous streaming of data, and should be used for maximum speed if you do not also need the clock signal. I have tested this with cycle-counted code, setting the SPI peripheral to 8Mhz (its maximum speed with a 16Mhz crystal, as the Arduino UNO uses). With the UART, using a 16 cycle loop in ASM, it's possible to load it with data continuously (I have used this to generate composite video). With the SPI peripheral, you need to add 2 clocks after the peripheral finishes, before it can load the next byte. So at 8Mhz, you can load data into it every 18 clock cycles. This is why it may appear to be clocking out 9 bits instead of 8, if you don't take account of the clock signal.

source: Stack Exchange

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

sort: votes


text:
Elegoo Nano timer prescaler problem
I am trying to use Timer2 on an Elegoo Nano to produce a "tick" interrupt every 10uS. My plan was to set Timer2 to CTC mode with a /8 prescaler (to get a timer clock of 2MHz from the 16MHz chip clock) and a compare value of 19 (to reset the timer every 20 counts) which should trigger the compareA ISR at 100KHz (every 10us). The problem is that only prescale values of 64 or greater work as expected. Setting the prescaler  to any value lower than 64 actually results in the "tick" interval getting much longer (10 times the interval or more). I have carefully studied the ATmega628 datasheet to see if I am configuring every register correctly, but I don't see anything wrong with what I am doing. Here is my code...
void initTimer() {

    // ---Disable interrupts during timer initialization
    cli();

    // ---Counter compare value (make CTC interrupt fire every 10uS)
    OCR2A = 19;

    // ---Clear TCCR A register (not used)
    TCCR2A = 0;

    // ---Enable CTC mode with divide-by-8 prescaler
    TCCR2B = _BV( WGM22 ) | _BV( CS21 );

    // ---Enable Timer2 CTC interrupts for compare A match
    TIMSK2 |= _BV( OCIE2A );

    // ---Initialize timer 2 to zero (not really needed in my situation)
    TCNT2 = 0;

    // ---Turn interrupts back on
   sei();
}

SIGNAL( TIMER2_COMPA_vect ) {

    /*
    ** This should execute every 10uS, but for prescaler values
    ** below 64 the interval is many times longer than expected.
    */
}

Can anyone point out my mistake?

Ok, I figured it out. It wasn't my timer initialization that was wrong, it was when I was doing it. Although I didn't show it in my original code sample, my initialization function actually returns a dummy boolean value so I could call it automatically if the .cpp file containing the function and the ISR is included in the project, like this...
bool initTimer() {

    // ---Set up the timer for CTC interrupts with a 10uS period
    ---
    ---
    ---

    // ---This return value is necessary, but ignored
    return true;
}

bool dummy = initTimer();

That final line calls initTimer() during Arduino boot just by including this source file in the project. It's a nice way to "auto-configure" utility objects without needing to explicitly call an initialization function. The boolean dummy return value from initTimer() is needed since C/C++ compilers choke on calling functions this way without storing a return value.
void initTimer() {

    // ---Do stuff...
}

// ---The compiler can't digest this...
initTimer();

Anyway, I have used this technique many times over several decades in desktop and mobile applications, so I did it in this Arduino project without giving it too much thought, but I failed to consider that it would execute the timer2 initialization BEFORE the Arduino setup routines. Anything I did to timer2 was being overwritten by the Arduino boot code which ran after my initTimer() function. My initialization was having some effect on the operation of timer2 because the Arduino boot setup assumes the timer2 config registers are starting off empty (zeroed) so it just sets config bits without clearing everything first. Any bits I turn on stay on, but Arduino boot up sets additional bits so the resulting timer configuration is unpredictable. The solution was simple... call the initTimer() function from the standard Arduino setup() function instead to ensure it executes LAST.

Can anyone point out my mistake?

Your mistake is in thinking that it's possible to do more than you can within a 10uS period.
At 16MHz each instruction takes 63ns (for single-clock instructions). 10nS gives you a maximum of (10,000 / 63) 156 assembly instructions.  Into that you have to fit the preamble and postamble to store the registers to the stack and retrieve them again.
The remaining clock cycles (maybe no more than 100) won't give you much time to do complex things. And given that many of the Arduino API calls are quite heavyweight, even just something as "simple" as a digitalWrite() can overflow that many times over.

Thanks Majenko, I had considered that, but since my ISR just decrements a few countdown variables I figured I could probably get away with it. See the answer I posted to my own question... I was configuring the timer correctly but I was doing it in a way that it was happening before the Arduino boot setup code had run so my settings were being overwritten when the Arduino routines configured timer2. After I changed my code to call the my timer2 initialization from setup() instead, a 10uS ISR interval is working fine.

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


text:
Where is my BUG?
Thank you everyone for help on my last post, i managed to make it work.  I still keep trying to craft my skill with the arduino.  This time I need to make a coffee hot plate simulation.  When the sensor is not up to temp an LED will blink, once the sensor gets up to temp the LED will blink but turn off (go to low) after five seconds. This is the code i am working on.  The sensor is at temp and the LED is still blinking instead of turning off.  When its low it blinks as should.  I think the bug is in the millis() portion of code.  Any ideas would be greatly appreciated.  I also ran the println screen, and the temp is consistantly around 210-220.
const int led         =  11;       // hot plate led on pin 11
const int sensor      =   9;       // temp sensor on pin 9
const int LOWER_BOUND = 174;       // lower temp
const int UPPER_BOUND = 220;       // upper temp

int val = 0;                       // analog reading

unsigned const long period = 5000; // time it takes to turn led off at temp

unsigned long startMillis;
unsigned long currentMillis;

void setup() {
    Serial.begin(9600);
    pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);
    startMillis = millis();
}

void loop() {

    val = analogRead(sensor);      // temp recorder
    Serial.println(val);
    currentMillis = millis();

    if (val == UPPER_BOUND){
        digitalWrite(led, HIGH);
    }

    else if (val == UPPER_BOUND && currentMillis - startMillis == period) {
        digitalWrite(led, LOW);
    }

    else (val <= LOWER_BOUND); {
        digitalWrite(led, LOW);
        delay(200);
        digitalWrite(led, HIGH);
        delay(200);
    }
}

Sorry but im confused... Someone corrected my last post for me, i followed the instructions, indent than hit the space bar 4 times to activate the code block.  Ill try my best to edit it through.  my apologies.

so, learn how to indent the code properly .... it will help you a lot when you are debugging by showing the code in logical blocks ..... look at example code in the arduino IDE ..... your correction is a good attempt .... i'll fix it though

reformatted the code for you .... look at the end of the code and see if the correct number of closing braces } are there ..... the code reformat will be visible when it is accepted

I see what you are saying now.  It does look nicer and easier to follow for myself and others.  Ill be sure to follow this format in the future.  Thank you.

the code inside else if (val == UPPER_BOUND && currentMillis - startMillis == period) { can never run, since if (val == UPPER_BOUND){ will also be true - swap the order of the first two ifs

the last else is missing an if and has a stray ; it should be else if (val <= LOWER_BOUND) { - the way the code is written, the else now performs (val <= LOWER_BOUND); ... and the following block is always executed

what's also not clear is what the LED should do when the temperature is above LOWER_BOUND but not exactly equal to UPPER_BOUND

and one final flaw .. you set startMillis in setup ... so 5 seconds after power on, regardless of temperature, currentMillis - startMillis >= period will always be true (not that it matters with your current logic)

As Long as the temperature is below UPPER_BOUND the LED should just blink.  Once at or above the UPPER_BOUND temperature, the led should blink for 5 seconds than turn off.  I did make the changes suggested bu Jaromanda X, and right now when below UPPER_BOUND, it blinks, when at or above UPPER_BOUND LED stays steadily lit.

First, let me point out a few technical issues with your program:

const int sensor = 9; is wrong. On an Uno, you can only use
analogRead() on the pins labeled A0 through A5.
if (val == UPPER_BOUND). Never test an analog reading for exact
equality. The reading is noisy, and you shouldn't expect continuity.
It can very well jump from UPPER_BOUND-1 on one reading to
UPPER_BOUND+1 on the next one. Instead, test for
val >= UPPER_BOUND.
currentMillis - startMillis == period. Again, you should not test
for exact equality. This time it's for a more subtle reason that has
to do with the implementation of millis(): some values (roughly one
every 42) are skipped over. Here again, test for >= period.

There is also the issue, already pointed out by PhoenixRevealed, of
your code defining two thresholds, while your prose only mentions one.
This may well be just you being sloppy and not describing your
requirements precisely enough.
Next, and since you are interested in perfecting your learning process,
let me advise you on two techniques that are worth learning, because
they are extremely useful for mostly any Arduino project more complex
than just blinking an LED:

Avoid using delay(). While the Arduino is busy delaying, it can
do nothing else. For instance, it cannot monitor the temperature
changes on the hot plate. In this particular case, it may well be the
case that you don't care, because the hot plate is so slow that you
can afford to be 400 ms late. But if you get into the habit of
relying on delay(), it will bite you sooner or later. So the sooner
you learn to blink an LED without using delay(), the
better.
Learn to program a finite state machine. This is a programming
concept that is very well suited for describing reactive systems,
i.e. systems that have to react to external “events”. It is a very
useful concept for writing most programs that are meant to control
hardware. There are quite a few tutorials out there. I would
recommend The Finite State Machine, by Majenko.

Here is my interpretation of your requirements in terms of a finite
state machine: your Arduino can be in any of 3 states: COLD (initial
state, the plate has not reached the required temperature), WAITING
(the plate reached the temperature and we are delaying five seconds),
DONE (the five seconds have elapsed). The rules for changing states
are:

COLD → WAITING: when in the COLD state, if the temperature
reaches a specified threshold, go to the WAITING state.
WAITING → DONE: when in the WAITING state, once five seconds
have elapsed since we entered the state, go to the DONE state.
When we are in the DONE state... nothing more ever happens.

Here is the corresponding state diagram:

Notice that once we reach the DONE state, the system gets stuck. This
situation can only be recovered from by rebooting the Arduino. You may
want to revise your specification in order accommodate a DONE → COLD
transition in some way. But from your specification as written in your
question, I assume you are fine with the system getting stuck.
I tried to implement this state diagram in code, using the traditional
switch/case construct. But then I got lazy and noticed that calling
exit() is the easiest way of implementing the DONE state, as
this function is precisely designed to get the program stuck in a
do-nothing state. Then, since there are only two states left to care
about, a boolean can be used as a state variable. In the end, the code I
propose may not look like a finite state machine. However, it is
important to notice that, event if such case, the finite state machine
is a very useful concept for thinking about your program and writing
down its requirements.
// Pinout
const uint8_t LED = 11;
const uint8_t SENSOR = A0;

// Threshold temperature reading.
const int THRESHOLD_TEMP_READING = 220;

// Timing.
const uint32_t LED_TOGGLE_PERIOD = 200;
const uint32_t WAIT_TIME = 5000;

bool is_hot = false;
uint32_t last_led_toggle;
uint32_t wait_started;

void setup()
{
    pinMode(LED, OUTPUT);
    pinMode(SENSOR, INPUT);
}

void loop()
{
    // Read the time once per loop.
    uint32_t now = millis();

    // Toggle the LED state.
    if (now - last_led_toggle >= LED_TOGGLE_PERIOD) {
        digitalWrite(LED, !digitalRead(LED));
        last_led_toggle = now;
    }

    if (is_hot) {
        // If the plate is hot, keep blinking during WAIT_TIME.
        if (millis() - wait_started >= WAIT_TIME) {
            digitalWrite(LED, LOW);  // turn off the LED
            exit(0);                  // stop everything
        }
    } else {
        // If the plate is cold, take note when it gets hot.
        if (analogRead(SENSOR) >= THRESHOLD_TEMP_READING) {
            is_hot = true;
            wait_started = now;
        }
    }
}

So when using analogRead() I should never measure or read exact values?  I should probably know this by now, but does A0-A5 give off a sine wave compared to a square wave compared to the PWM pins?  I appreciate you all giving an explanation on what I am doing wrong.  It helps me understand what I need to look for and how to go about things in later projects.

@Steven: Please, rephrase the questions in your comment in a clearer way. As written, I cannot make any sense of them.

Does the A0-A5 pins output a sine wave instead of a square wave, like a PWM pin does? and Would that be the reason why we cannot measure exact values through analogRead()?

@Steven: 1. The A0 – A5 pins can serve as analog inputs. Otherwise you can use them as regular digital IO (i.e. output either HIGH or LOW). The Arduino Uno has no analog outputs. It cannot output a sine wave on any pin. 2. The reason you cannot measure exact values is that there is no such thing as an exact measurement in the physical world. But this is not quite the point I discuss in my answer. Instead, I am telling you to never compare a measurement with an expected value using the == operator. The key word here is “test” for exact equality.

So I did read up on the FSM, and it does seem to be better constructed, than some of what I have been doing.  And I get what your explaining now, with the A0-A5 pins.  It does make sense that nothing in the physical world has an exact measurement.  That is something I did not consider, and explains why with "==" I could not get the proper output i was expecting, even with making suggested edits.

I see a couple of issues with your code. The biggest problem is that you capture startMillis in setup() and then compare it with currentMillis in your loop. If it takes more than five seconds for the pot to get hot enough you will never match (currentMillis - startMillis) == period because (currentMillis - startMillis) will already be > period before you start testing it. Changing "== period" to ">= period" will fix this, but it still won't behave the way you want since you should be setting startMillis when the pot first reached the target temp, not at program startup.
Also, your code does nothing when the temp is between LOWER_BOUND and UPPER_BOUND, which I suspect is not what you want. You don't specify whether "up to temp" means at or above LOWER_BOUND or at or above UPPER_BOUND. I'm going to assume that you want the LED to flash when the temp is below LOWER_BOUND, go solid on while the temp is between LOWER_BOUND and UPPER_BOUND, and then turn completely off five seconds after the pot reaches UPPER_BOUND.
Personally I would rewrite it like this, both for functionality and readbility...
int val = 0;                       // analog reading

unsigned const long period = 5000; // time it takes to turn led off at temp

// ---We don't need this till later, zero it so the loop knows not to use it till then
unsigned long startMillis = 0;

void setup() {

    Serial.begin(9600);
    pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);

}

void loop() {

    val = analogRead(sensor);      // temp recorder
    Serial.println(val);

    if ( val <= LOWER_BOUND ) {

        // ---Coffee temp is low, flash the LED
        digitalWrite(led, LOW);
        delay(200);
        digitalWrite(led, HIGH);
        delay(200);

    } else if ( val < UPPER_BOUND ) {

        // ---Coffee temp is medium, turn the LED solid on (assumes switched cathode)
        digitalWrite(led, LOW);

    } else {

        // ---Coffee is hot!
        if ( !startMillis ) {

            // ---Coffee just reached UPPER_BOUND... start timing (LED is already on)
            startMillis = millis();

        } else {

            // ---Has the period timed out yet?
            if ( ( millis() - startMillis ) >= period ) {

                  // ---More than 5 seconds has passed, make sure LED is off
                  digitalWrite(led, HIGH);

            }
        }
    }
}

A couple of points about this implementation...

I have not tested this code on a physical Arduino.
Notice that we don't care to start storing or watching millis() until the pot first reaches UPPER_BOUND. Until then all the program cares about is the temp of the coffee.
Like your original code, this implementation doesn't consider the wraparound of millis() every 50 days or so. It's unlikely a coffee pot will take over 50 days to reach the target temperature, so I wouldn't worry about it, but you should consider this situation when coding long-running applications (I refuse to call them "sketches").
I based this on your original code, so like yours, once the temp reaches at least LOWER_BOUND it continuously writes to the LED pin every pass through the loop, even though it likely hasn't changed since the last iteration. If I was doing this for real I would restructure it so it only writes to the pin when the state of the LED actually changes. This is only an efficiency issue though... writing the same value to a pin repeatedly will work fine, it just isn't very elegant.
If the coffee starts to cool down after reaching UPPER_BOUND then behaviour is undefined. I suspect that it would work normally when the coffee temp is low or medium, but if the coffee reached the UPPER_BOUND the second or more times I believe the LED would turn off immediately rather than after 5 seconds. It wouldn't be difficult to enhance the code to behave correctly no matter how many times the pot temp cycles up and down, but this solution was to the problem as you described it, which was a coffee pot warming up just once from cold to a target temperature.

I made a few changes to the code, I added the global variables for led, and sensor.  I also eliminated lower bound, and only kept to measure upper bound. It worked really well.  Between this code and my code, I noticed I am using a lot of unnecessary variables, and some that are useless.  I found that when using both an upper and lower bound, the code would only run the lower bound, im assuming this because, i gave lower bound a value, when it does not need it,  So in the program, although it kinda worked it would never work as intended because of that value.

I also believe I understand millis() a little better now, I thought millis() had to be started within the setup for it work properly.

You have received very valuable comments, all valid.However, to address your original question - once you reach upper bound and continue to apply heat - your  code have no means to detect greater then upper bound value.


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

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

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


text:
formatting strings in Arduino for output
I wander what is the best option for formatting strings in Arduino for output.
I mean what's a preferable way in the point of view of performance, memory usage  – things like that.
I see, people usually use direct Serial.print/println, like this:
  int x = 5;
  // 1st option
  Serial.print("x = ");
  Serial.println(x);

Or like this:
  // 2nd option
  Serial.println("x = " + String(x));

But what is wrong with, I believe, more traditional way of doing this:
  // 3rd optoin
  char strBuf[50];
  sprintf(strBuf, "x = %d", x);
  Serial.println(strBuf);

  // better one?

If you need the result in a single string then your 3rd option is the preferred way.
If you don't, then the first option of printing each part separately is the most efficient in terms of memory.
The second version, String concatenation, is the worst option in all respects and should be avoided at all costs.
I often use sprintf to a buffer if I need a specific format (for instance leading zeroes on a number).
If you want to avoid the extra code bloat of sprintf you can use various combinations of strcpy, strcat and itoa etc to build up a string into a memory buffer (if you really need to put it in a buffer).
Note that on an 8-bit Arduino sprintf has no float support - so you would still need to use dtostrf to format a float into a char buffer first, or print it directly.

I agree with Majenko's answer.
I created a simple CStringBuilder class to combine the first and third approach mentioned in your question. It enables to build the c-string with printf and with Print functions, which can print float or IPAddress. It is available in StreamLib in library manager.
#include <CStringBuilder.h>
#include <IPAddress.h>

const char* s = "Lorem ipsum";
char c = 'X';
int i = 42;
float f = PI;
IPAddress ipAddress(192, 168, 0, 1);

void setup()
{
  Serial.begin(115200);
  while (!Serial);

  char buff[150];
  CStringBuilder sb(buff, sizeof(buff));

  sb.print(F("Some text: "));
  sb.println(s);
  sb.print(F("Some char: "));
  sb.println(c);
  sb.print(F("HEX of char: "));
  sb.println(c, HEX);
  sb.print(F("Some integer: "));
  sb.println(i);
  sb.print(F("Some float: "));
  sb.println(f, 3);
  sb.print(F("IP address: "));
  sb.println(ipAddress);

  int l = sb.length();
  sb.print("this text doesn't fit in the remaining space in the buffer");
  if (sb.getWriteError()) {
    sb.setLength(l);
  }
  sb.println("test test");

  Serial.print("size to print: ");
  Serial.println(sb.length());
  Serial.println();
  Serial.println(buff);

  sb.reset();
  sb.printf(F("Formatted: %s;%c;%05d\r\n"), s, c, i);
  Serial.println(buff);
}

void loop()
{

}

Other classes in the library are BufferedPrint and ChunkedPrint.  Both support sprintf.

The printf() family of functions is far preferable to me as the programmer, but in a resource-constrained environment such as the smaller AVR (and other) processors, the extra code space may not be justified or available, or the performance hit of interpreting the format string may be limiting. And sprintf(buf, ...); Serial.print(buf); also takes a stack hit for the temporary buffer (compared to just printf(...); ) It's a trade-off between code size and speed vs. you having more flexibility to write the code to the create the output you want.

printf will use roughly the same buffer space as sprintf; it has to buffer the print somewhere.

Good point about the data space (IF we know that printf() family use a buffer on the stack rather than a static one). My comment about code space still applies.

The wrong thig with option 3 is the buffer length, you should use snprintf instead.
The other problem is that first you build the string, then you print the output, the program traverses the string twice. Option 2 creates object from string, then applies + operator to create a new string, then prints it - it is comfortable with short strings, but least efficient (depends on the compiler optimalizations).
Option 1 is most effective, since it directly prints arguments to the output char by char (see Arduino Print class) and traverses the arguments only once.
You can use stdarg.h to create one-liner with Serial.prints:
#include <stdarg.h>

void Serialprintln(const char* input...) {
  va_list args;
  va_start(args, input);
  for(const char* i=input; *i!=0; ++i) {
    if(*i!='%') { Serial.print(*i); continue; }
    switch(*(++i)) {
      case '%': Serial.print('%'); break;
      case 's': Serial.print(va_arg(args, char*)); break;
      case 'd': Serial.print(va_arg(args, int), DEC); break;
      case 'b': Serial.print(va_arg(args, int), BIN); break;
      case 'o': Serial.print(va_arg(args, int), OCT); break;
      case 'x': Serial.print(va_arg(args, int), HEX); break;
      case 'f': Serial.print(va_arg(args, double), 2); break;
    }
  }
  Serial.println();
  va_end(args);
}

Then you can use it like sprintf (but efficiently):
void setup() {
  int n = 42;
  float f = 42.42;
  const char* s = "answer";
  Serial.begin(9600);
  // The answer is 42 (101010 BIN, 2A HEX), in float 42.42
  Serialprintln("The %s is %d (%b BIN, %x HEX), in float %f", s, n, n, n, f);
}

void loop() {
}

The third option, sprintf, is unsafe and may give buffer overruns if buffer is not sized correctly.  You can use snprintf instead.
However I would recommend my SafeString library and tutorial
for general string processing and output.


text:
Timer with ajustable time delay
I have a led strip, and each led should be turned on sequentially, such as this one:
[http://1.bp.blogspot.com/-CTT6yvYtdos/VihhhBItwjI/AAAAAAAAAvM/q1jbUylMMdM/s400/ezgif.com-video-to-gif.gif][1]
The time delay between 2 consecutive leds is ts, and that time should be adjusted externally through a pushbutton switch. Each time the button is pressed, the time period shoud increment in a fixed amount.
I've already used the timerOne library, but it just works with a fixed time delay ts. How can I solve this issue with VARIABLE time delay?
I prefer to use interruptions rather than polling, since this system will be more complex (other buttons and variables will be involved).
Thanks!
Fernando

Re “the timerOne library [...] just works with a fixed time delay”: what makes you believe that?

https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L55
Defines the function in TimerOne called SetPeriod(). That will change the period.

I've found the solution, through the function
attachInterrupt(function,period);
inside loop()
In other words, I wrote
loop(){
Timer1.attachInterrupt(function,period);
// rest of the code
}
where period changes inside the ISR called when the external button is pressed.
Thanks a lot @jose can u c!!

I've found the solution, through the function
attachInterrupt(function,period);

inside
loop()

In other words, I wrote
loop(){
Timer1.attachInterrupt(function,period);
// rest of the code
}

where "period" changes inside the ISR called when the external button is pressed.
Thanks a lot @jose can u c!!


text:
Code for a rolling average
Below is some code I wrote to find the rolling average of a temp sensor hooked up to an arduino and display it to an lcd display. My issue is that for the first minute it is running, the average is not correct. It starts at 0 and then progresses up to where it should be (~85F) in increments of approximately 3. After the first minute it is fine and works as it should.
What I want the code to do is to simply take the average of the sum of the values that have been recorded in the first minute.
My knowledge of C is fairly limited(I only had a semester long class on it) so that is why it is simple. I am a mechanical engineering student and this code is for project at my internship.
#include <Adafruit_MLX90614.h>
Adafruit_MLX90614 tempSensor;

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

double array[30];
double rollingaverage=0;
int i=0, j=0;
double sum=0;
double newreading;
void setup() {

  Serial.begin(9600);
  lcd.begin(20,4);
  mlx.begin();
  Wire.begin();

}

void loop() {
  if(j=0){
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      sum += array[i];
      if(i>0){
          rollingaverage = sum/(i+1);
      }
      j=1;
  }
  else{
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      if(i < 29){ //wraps i back around to 0 if it is at 29 to subtract the oldest value
          sum = sum + array[i] - array[i+1];
          rollingaverage = sum/30;
      }
      else{
          sum = sum + array[i] - array[0];
          rollingaverage = sum/30;
          i=0; //reset index to 0
      }
  }
  i++;

  lcd.clear();
  lcd.print("Belt: "); lcd.print(rollingaverage);
  lcd.setCursor(1,2);
  lcd.print("Air: "); lcd.print(mlx.readAmbientTempF());

delay(2000);
}

Its not a huge deal because it works fine after the first minute, it is just annoying that I can't figure out why it doesn't work as intended in the first minute. Thanks

Example, if you have 25 valid values and 5 zero, you need a counter for "valid values" and change rollingaverage = sum/30; and replace 30 with the counter value.

if(j==0) instead of (j=0) would be nicer perhaps.

Your problem stems from you starting out with 30 values of 0 which you include in your average.  You have to take that into account and ignore those values, dividing your total by only the number of actual values you have.
I have a library that does it all for you that would make things easier for you:

https://github.com/MajenkoLibraries/Average

One way is to initialize the whole buffer to the first value. Your average won't be "true" in some sense, until the whole buffer has been replaced with read data, but as long as that first value isn't too different from the true temperature, your average during that period will be more sensible. I.e., it won't have to  ramp up from zero.
Another way is to use an Exponential Average instead of the Rolling- or Boxcar-Average. The Exponential Average doesn't depend on storing old samples and can adjust well - i.e. within a few samples, depending on 'X' (see below) - to a sudden change (which temperatures don't normally do, anyway).
It calculates a new average by summing X percent of the current average + (100-X) percent of the next sample - you choose the value of 'X' that works best in your own application.  I have good results averaging temperatures, even from analog sensors, using X=75. For fixed-point numbers such as the 4 binary places returned by the Max DS18b20 sensors, would be
// (3 * avg + 1 * sample) / 4
avg = (((avg<<2) - avg + sample) + 2) >> 2;

For floating point numbers, it would just be:
avg = (3. * avg + sample)/4.;

Update:

Initialization is as much an issue with an exponential average as it
  is with a boxcar average.

Yes, it is. I initialize my exponential averagers with the first sample and usually get along pretty well. It might not work so well if the averager was too heavily damped.

... a boxcar of width 30 ...

An exponential average, by its nature, can give recent samples more weight than older ones so giving so little weight as you suggest to the next sample will make it quite heavy-handed! X=75% has worked quite well for me to reduce noise without heavy-handed damping. What works well for one system may not work for another, but by running a saved sample-set through a few trials on your desktop will quickly get you to a reasonable X.
We don't know how that width (30) was arrived at; perhaps it is necessary? But averaging, by its nature, being both low-pass (usually desired) and delaying (generally not desired), spreads sudden features like spikes while it limits their amplitude. I've sometimes use a spike suppressor ahead of a lighter averaging filter, where the alternative average-only would have required enough averaging to damp significant signal features too heavily.

Initialization is as much an issue with an exponential average as it is with a boxcar average. Specifically, a boxcar of width 30 has roughly the same “averaging strength” as an exponential average with X = 100×(1−1/30). And the latter will need more than 30 samples to completely settle.

The other answers address the problem with your code, however a better solution is to use a different algorithm.
I would use exponential smoothing (which is simpler to code, requires less data and produces a similar result). This is the technique I used to use when responsible for producing statistical performance reports. If readings are plotted this results in a smoother graph, which shows trends and discounts noise.
Briefly take the current sample, multiply by a discounting factor and add the a proportion of the current value.

s = x * α + (1-α) * s

To produce results from the start initialise the sample to the first reading then calculate.
See https://en.wikipedia.org/wiki/Exponential_smoothing
I would probably start with a smoothing factor of 0.3 - choose a smaller value to give more weight to past values.

You are essentially repeating JRobert's answer.


text:
Powering Arduino Uno, CAN Crocodile and NeoPixels from Car
I have purchased a cigarette adapter that gives me 2 USB ports, however this gives me 5v and up to 2.4A.
Thats ok for powering the Arduino Uno, I need 12/24v to power the CAN crocodile.
I also want to drive quite a lot of NeoPixels.
How can I do this?

Being specific in your question will help; what does "quite a lot" of NeoPixels mean, in quantified terms?

Sorry, 186 neopixels.

A reasonable estimate for current consumption of 5V NeoPixels is 60mA per pixel. For 186 pixels, that means about 11.16A at 5V; well over the 2.4A of the adapter being used for your other components.
There exist modules called "DC-to-DC Buck Converters", which can step down the 12-14V of your automobile to pretty much any voltage under the input voltage. To be safe, look for a buck converter of at least a 75W rating, and which meets your criteria for input and output range (minimum of 12V input, could be rated higher; output range inclusive of 5V.)
Be sure that the Ground connections for the NeoPixel power supply and the other supply are shared/connected, but don't share the +5V line between supplies.

Thank you, this is all a bit beyond my understanding...I'm a very good coder but electronics is something I play with...is there an off the shelf solution that I can purchase to provide me with connections suitable for the Arduino Uno with CANBus shield and the NeoPixels?

You can search the usual online vendors (amazon, ebay) for "Buck Converter" and make sure they can handle your input and output voltage needs, and at least 75W (your NeoPixels alone could draw up to 55W, and it's safe to have some buffer). Most of what you'll find are bare PC Boards with components mounted on them, but no case/enclosure. Your definition of off-the-shelf may be different.

How about this: https://www.amazon.co.uk/Droking-Converter-Step-down-Regulator-Voltmeter/dp/B07CV6QQ8Q/ref=sr_1_34_sspa?ie=UTF8&qid=1538492915&sr=8-34-spons&keywords=%22buck+converter%22&psc=1

That one is limited to 2A, so it won't work. In general, this community avoids direct product recommendations. On the link you gave, there are "also viewed" items that include higher-current buck converters.

I haven't worked out the current requirement, https://www.amazon.co.uk/dp/B01N9FB78X/ref=sspa_dk_detail_1?psc=1&pd_rd_i=B01N9FB78X&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_p=8e5be0e3-b258-4b06-8b6e-695b24f935a4&pf_rd_r=ZTFR1W9099TXMBWXGJ6S&pd_rd_wg=JYlov&pf_rd_s=desktop-dp-sims&pf_rd_t=40701&pd_rd_w=BVivb&pf_rd_i=desktop-dp-sims&pd_rd_r=467c2bda-c656-11e8-a52e-91026566f7d5

That next link is a "boost converter" which raises output voltage above the input voltage. Something along these lines https://www.ebay.com/itm/24V-12V-To-5V-20A-Buck-Converter-100W-High-Current-Voltage-DC-10-35V-Regulator/223167400971

And on Amazon, although it states the output voltage is 5V: https://www.amazon.co.uk/Converter-DROK-Current-Regulator-Regulated/dp/B00F0FYPPQ/ref=sr_1_1?ie=UTF8&qid=1538494335&sr=8-1&keywords=24V+12V+To+5V+20A+Buck+Converter%2C+100W+High+Current+Voltage+DC+10-35V+Regulator

I still need at least 12v for the CAN crocodile.

Is your car not a 12V system?

Yes, its an Audi A5, I'm looking for a solution that I can plug into the power outlet in the boot, which is a cigarette lighter style socket... I need 5v for the Arduino and CANBus shield, 12v for the CAN Crocodile and 5V for the neopixels but these can draw quite a bit of current, something that protects the car system from going pop.

You don’t need a converter for the 12 V.

What I need is a convenient interface to the various voltages.

12V from the car, 5V from the buck converter. What other voltages do you need?

Just looking for a suitable mechanical interface where I can attach all the wires...looking for something ready made I can just attach to.

I don't think you'll find something more ready-made than what has been shown so far...


text:
Neopixle animation help
Ok I'm stupid when it comes to coding. I have a simple project that I need some help with. Is it possible to make neopixle change what animation runs via multiple switches. Example they stay off till switch is flipped then if a different switch is flipped they run a different animation and vice versa.

Can you show us the code you have written so far?

There is too much unspecific language (e.g. "change what animation runs", "stay off") that it's hard to work out what you are actually asking. Also no need to write at the start of your post "I'm stupid when it comes to coding".  You're not, everyone has problems to solve, that's why this site exists.  Consider editing your question also taking into account VE7JRO's comment.

I get so confused with this stuff lol. What I wanted is the pixels to stay off then when a switch is flipped it does a color wipe and they stay on. Then if another switch is flipped they do a continuous color wipe. And the same in the reverse sequence.

Yes absolutely it is possible. As a beginner, I suggest something like this:

simulate this circuit – Schematic created using CircuitLab
In your setup you will need to declare D4 - D7 as inputs. I have used D4 - D7 but you can choose whatever pins are available.
Then in the loop part of the code you want to look for the rising edge on the input (ie when the switch is pressed). Switch debounce is less important for this application as it is not a counter but rather a mode change.
I have written a good answer for detecting a button press here.
Nick Gammon has an excellent switch tutorial gammon.com.au/switches that covers all kinds of conceivable situations (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.)
I would imagine the code would look something like this:
if( digitalRead(SW1) == HIGH )
    mode = 1;

if( digitalRead(SW2) == HIGH )
    mode = 2;

if( digitalRead(SW3) == HIGH )
    mode = 3;

if( digitalRead(SW4) == HIGH )
    mode = 4;

You could then use a switch-case statement to run the various NeoPixel patterns.
For more programming reference see: https://www.arduino.cc/reference/en/

Thanx makes it much more understandable

This is driving me nuts lol. does anyone know somewhere i can pay someone to write arduino code.

The Arduino Forum has a Gigs and Collaborations section where you can offer to pay to have code written for you. However if you just want a fancy light show, you can buy those off the shelf, if you aren't interested in learning the programming side of things.

I would like to learn it. Just got frustrated with it for a awheil. I'm trying to make lights for a golf cart. Just like a car has stop,tail,and turn signals. I get  close then mess it up to the point it doesn't work anymore lol

We can do code reviews here on Arduino Stack Exchange. Just add the code review tag to the question you ask.

@Gcompston is there a (part of a) video of something similar to what you want to achieve?


text:
Interfacing 4 ESCs and an Arduino with a single LiPo battery
I have 4 BLDC motors, and 4 ESCs, one for each motor. But I have one LiPo battery from which I want to power one Arduino Mega and all the 4 ESCs. Can I remove the connectors from the ESCs and put them on a breadboard in a single column/row so that they are connected together, and then connect the + and - of the battery (after removing its connector as well) to the respective breadboard column/row, so that they are essentially connected together to power all the ESCs? Also, I would want to use a jumper from the Arduino Vin and GND pins to the same column/row on the breadboard. Will this method of powering all the 4 ESCs and the Arduino from a single LiPo work?

Yes, but you don't want to use a breadboard for it.

Please edit the post to explain what ESCs and BLDCs are.  These are not obvious acronyms.

Powering all the ESCs from a single LIPO is not an issue.
Using a breadboard to distribute this power is highly unlikely to work, breadboard connectors are usually only good to a few hundred mA, 1A is you want to push your luck.  Most ESCs and BLDC motors are in the 5A to 50A range (each, your power bus has to handle 4 times this current).
Also, ESCs tend to inject a lot of noise into the power bus.  If you connect the arduino to the ESC power bus, you will likely get random resets and really poor noise performance on the ADCs.  Keep in mind that some ESCs actively brake the motors using regenerative braking, which puts the kinetic energy of the motor back into the power bus.  This can increase the voltage on the power bus to more than the nominal battery voltage and can have large voltage spikes on it causing a failure on the Arduino.
If you are prototyping, use a separate power supply/battery for the arduino and connect all the grounds together instead of using a single supply.  If you are building a rover/uav/whatever and don't want a second battery, use a high quality BEC (or the BEC output from a high quality ESC) and remember that the 5V output on a BEC/ESC can be significantly higher than 5V in reality).
ESC = Electronic Speed Controlled
BEC = Battery eliminator circuit (I think, basically a 5V-ish regulator)
BLDC = Brushless DC motor (three phase in this case)


text:
limit length of the generated timestamp from ESP32 with DS3231 to 13
I am using ESP-WROOM-32 (Olimex ESP32-PoE) with DS3231. I have used the a patch from PR on RTClib to avoid the rollover from the DS3231.
Since the DS3231 RTC provides Unix Epoch Timestamps which have a precision of only seconds, I wish to concatenate the millis() to the above mentioned timestamps to provide millisecond precision.
This is critical since I want to store information to InfluxDB from the nodes with ms precision. For that the timestamps should always be 13 digits.
code
#include <RTClib.h>
#include <Wire.h>

// PoE setting for Olimex PoE board

#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT
#define ETH_PHY_POWER 12

// Pins for I2C on Olimex PoE board
#define I2C_SDA 13
#define I2C_SCL 16

RTC_DS3231 rtc;
RTC_Millis software_time;

void setup() {
  // put your setup code here, to run once:
  Wire.begin(I2C_SDA, I2C_SCL, 400000);
  Serial.begin(9600);
  if (!rtc.begin()) {
    Serial.println("No RTC Detected");
  }
  // adjust RTC Time
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // adjust software timer
  software_time.adjust(rtc.now());

}

void loop() {
  // put your main code here, to run repeatedly:
  DateTime rtc_now_time = rtc.now();
  DateTime software_now_time = software_time.now();
  Serial.println();
  Serial.print("RTC now: "); Serial.print(rtc_now_time.unixtime());
  Serial.println();
  Serial.print("millis: "); Serial.print(millis());
  delay(100);

}

Output
RTC now: 1538502183
millis: 28
RTC now: 1538502183
millis: 128
RTC now: 1538502183
millis: 228
RTC now: 1538502183
millis: 328
RTC now: 1538502183
millis: 428
RTC now: 1538502183
millis: 528
RTC now: 1538502183
millis: 628
RTC now: 1538502183
millis: 728
RTC now: 1538502183
millis: 828
RTC now: 1538502183
millis: 928
RTC now: 1538502184
millis: 1028

I will store the timestamps in String so I was thinking of concatenating the .unixtime() with millis(). However since I want all my timestamps to be of fixed lenght (13) with the increasing millis value seems to be difficult because as soon as the number goes more that 999 the a digit increases making the string length 14.
Side Effect
if the timestamps for ms do not match length of 13, InfluxDB rejects the data passed through
Epoch Time
the output provided above is of 10 digits which is the epoch time since 1970. The precision of the timestamps above is of seconds. If one wants to add milliseconds to it one needs to add 3 more digits behind it. If precision needs to be microseconds it should have 6 digits and so on..
One can check the timestamps above on [https://epochconverter.com]
Any suggestions on overcoming this issue ?

Please explain the 13 digits or give a link to the format. Is the format "1234567890123"? As readable text with a decimal number? Should it be the number of milliseconds since 1970? Epoch = 1538498157 which is 10 digits, that means three extra digits for milliseconds? Will it still work if you make the three digits for the milliseconds zero? This number: https://currentmillis.com/ ?

Yes. it can work even if the milliseconds are zero. unfortunately the rtc does not provide ms precision hence I am adding the millis which is ms from the beginning of the controller.

So making them zero solves all problems? This is a similar question: https://stackoverflow.com/questions/44644383/how-to-get-millisecond-resolution-from-ds3231-rtc You can do millis() % 1000.

I have seen the post. I just am not sure if I understood the work around it completely. I can try the millis() %1000 and push the information on influxdb and inform you if it works.

@Jot your suggestion of millis() % 1000 works. Influx does parses the timestamp in human readable RFC3339

but it can give in one second two timestamps in wrong ordering

@Juraj what is the solution? How to get some kind of synchronization? Perhaps set the sqw output to 1Hz and tie it to an interrupt. In the interrupt set a previousMillis. Shan-Desai, can you connect the sqw signal to an interrupt input?

@Jot So I did connect the SQW pin of the RTC to a GPIO pin and following this tutorial and set the SQW to 1kHz settings. The problem is serial port, i2c and the interrupt are messing everything up. the values are of the timestamps are not updated accordingly and Serial print provides the same values for long time. Rarely, I see any change in the timestamp values

For getting millisecond resolution out of an RTC, I think the only
viable solution is to sync with the 1 Hz square wave output, as
suggested by Jot in a comment. Note that, since you are only counting
seconds and milliseconds, you probably don't care about hours, minutes,
days, months, etc. So you won't use the RTC for timekeeping: only for
providing the 1 Hz reference signal and, maybe, an initial
timestamp at program startup.
Connect the SQW pin of the DS3231 to an interrupt-capable input of your
MCU. Add the following to your setup():
pinMode(SQW_PIN, INPUT_PULLUP);
rtc.writeSqwPinMode(DS3231_SquareWave1Hz);
attachInterrupt(digitalPinToInterrupt(SQW_PIN), tick, FALLING);

Use the interrupt routine to both keep track of the total second count
(seconds elapsed since the Unix epoch) and record the micros() value
of the last tick:
volatile uint32_t seconds_since_epoch;
volatile uint32_t micros_on_tick;

void tick() {
    seconds_since_epoch++;
    micros_on_tick = micros();
}

Now you can combine these two values to get a millisecond-resolved
timestamp as follows:
uint64_t millis_since_epoch() {
    noInterrupts();
    uint32_t seconds = seconds_since_epoch;
    uint32_t microseconds = micros_on_tick;
    interrupts();
    uint32_t extra_micros = micros() - microseconds;
    uint16_t extra_millis = extra_micros / 1000;
    if (extra_millis > 999)
        extra_millis = 999;
    return (uint64_t) seconds * 1000 + extra_millis;
}

The value returned from this function is the 13-digit number you want,
provided seconds_since_epoch has been sensibly initialized.

won't I need the RTC to provide me the initial epoch time in seconds?

@Shan-Desai: Yes, that's the easiest way to initialize seconds_since_epoch.

You sir are a Legend! Thank you for this solution. Works great. With a little function to make the uint64_t to String was needed but rest everything works like a charm.

the goal is to generate unique and ordered millis part of timestamps in one epoch second.
unsigned long thisNowMillis;
uint32_t thisNow;

-
 uint32_t now = rtc_now_time.unixtime();
 if (now != thisNow) {
   thisNow = now;
   thisNowMillis = millis();
 }
 Serial.print("millis: "); Serial.print(millis() - thisNowMillis);

not tested and it will not work for counting intervals between timestamps.

will check this and get back to you


text:
Arduino log file directly to file
I have problem because I need to read values and then save them in a .txt file, but Arduino doesn't have a physical connection with my computer. It only has a connection with a computer using Ubuntu without Arduino IDE or other programs. Also, I don't have an ethernet connection and SD card. I need only to have this data stored. The best way is to send them at the end of cycle to a special text file. Has anybody faced that before?

I'm thinking about writing a bash script for reading all values sent by serial and then save them, but how do I get that information from serial?

Also, it’s unclear what you mean when you say “Arduino doesn’t have physical connection with my computer” and then “it only has connection with computer using Ubuntu”. The two statements contradict each other.

There are many examples you can find online of simple serial capture to a file.  Bash may not really be the best choice as serial ports aren't just simple files (typically needing at minimum configuration), but something like python with pyserial can work well.

How much data is it? Perhaps it can be stored in eeprom, and retrieved later via the serial.

Any serial terminal emulator application can connect to the Arduino. Select one that has log-to-file capability and open its log file after you've connected it to your Arduino's /dev/tty... device.
Start the Arduino and let it collect & send the data to your terminal program. Close the terminal app's log file (easy step to forget - ask me how I know :) and there's your data.

The Arduino IDE provides a built-in serial monitor functionality, which emulates a serial port over USB. There are many tutorials available for its use.
However, as best I recall the Arduino serial monitor does not allow you to save a log file. If you don't want to write your own code to do this you can use a different terminal emulator, such as putty.

No, serial port emulation is not a function of the Arduino IDE.  It is a function of drivers in (or for various older versions and clones) added to, the host operating system.

Like what Chris mentioned in the comment, you can use pyserial to do it. You can even add timestamp to your data and append them to the same log file.


text:
My brand new LCD screen doesn't display anything, even though there is no code errors?
I have a LCD screen, and I wanted to use it with a Simon Says game that I am making. I tried the tutorial on the Arduino website, but it doesn't work. Then I tried another tutorial on Adafruit. On this one, the LCD screen seemed brighter which is good, but it also doesn't work.
What it is supposed to look like:

My code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

void setup() {
  lcd.begin(16, 2);
}

void loop() {
  lcd.print("Test!");
  delay(500);
  lcd.clear();
  delay(500);
}

I have verified that the wiring is correct on the official version and the Adafruit version, and my screen is brand new from the kit, so what is wrong?
Edit 1:
Let me define "doesn't work." I can turn the potentiometer, but nothing changes. I can't even see white rectangles or even a single pixel on the display. It is blank. Absolutely nothing to see other than the blacklight, which does work.
Edit 2:
Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!

Define "doesn't work". Can you adjust the contrast to see dark blocks? Can you see anything else beside the blocks?

I can't even see any dark blocks. Nothing works except for the blacklight. If I were to turn the potentiometer, nothing happens.

Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!


text:
Problem uploading to board error, but I've selected the port and the board type?
I am having an issue when I try to upload a program to the board. I am working on a Simon Says game, and when I first started uploading, my computer handled it fine. Everything worked properly.
However, now I have added 3 LEDs for the colors and 3 buttons. I wrote a program for them to start the game, and then went to test it. That's when my Arduino would beep 3 times and then 75% of the time my computer would give me this error:

Problem uploading to board.
  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

25% of the other time I get this:

An error occurred while uploading the sketch

It seems as though my project is getting too complicated for the Arduino to handle maybe? This is my code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

int s = 13; // Speaker
int r = 6;  // Red LED
int y = 5;  // Yellow LED
int g = 4;  // Green LED
int b1 = 3; // Red button
int b2 = 2; // Yellow button
int b3 = 1; // Green button - I don't know if pin 1 works.

void setup() {
  lcd.begin(16, 2);
  pinMode(s, OUTPUT);
  pinMode(r, OUTPUT);
  pinMode(y, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(b1, INPUT);
  pinMode(b2, INPUT);
  // pinMode(b3, INPUT); Does pin 1 work?
}

void loop() {
  lcd.print("Press any button");
  lcd.setCursor(4, 1);
  lcd.print("to play!");
  while (true) {
    if (digitalRead(b1) == HIGH) {
      break;
    }
    delay(50);
  }
  lcd.clear();
  delay(1000);
  lcd.setCursor(1, 0);
  lcd.print("Simon's turn!");
  delay(1000);
  while (true) {
    // For now, I don't want to loop. I will finish the program when this     problem is resolved.
    delay(50);
  }
}

Does anyone know the solution to this problem?

What precisely is wired to pin 1?

Pin 1 goes to the button which goes with the green LED. It can tell when the button is pressed. I didn't know if that was the problem, but when I commented it out, the upload still had an error (not in the code).

Anything besides the button? Any pullup or pulldown resistor?  If you disconnect everything from pin 1 does it start working again?

Let me try that.

Okay, I removed everything from pin 1, tried to upload again. Unfortunately, still an error. Also, there is nothing else other than the button.
Edit
There is a potentiometer, but it doesn't even connect to pin 1. It is for the LCD display adjustment.

Arduino play around from time to time. Which one do you use.
Unplug it and plug it back in. If Pin D0 and D1 are occupied, you may have problems with uploading.

I use the Uno. I have unplugged and plugged back in, that didn't affect anything. Pin D0 and D1 are not occupied. Any more suggestions?

Something is blocking the port. It is not a compiler error.

Can you upload other scripts. Or is it only happen on this one?

It only happens with this one, which is strange. I've started a new file and it works fine.

Hi Ben. Sorry. I was a little bit busy. I am glad you resolve your problem by creating a new file. I work in IT Support. I also like to know why something is causing the problems. I may have a look at it at some point. Sorry. Just very busy now, with my Arduino projects. I may come across a similar problem and then I will post the answer here.

Remove anything that is connected to the Tx and Rx pin(communication pins)
And try uploading the code and it might possibly work


text:
Wake up ESP8266 from deepSleep with a button
I have a button with two isolated tracks. I want to be able to wake up esp from deepSleep with this button, and also detect that it was clicked. So i can't connect it to reset, because esp won't work if i don't release a button. And if it's not at deepSleep, it will reset, and i don't want it. How to do this?

Can you post code that you have so far?  Also, what do you mean by "two isolated tracks"?

Connect the button, with a pull-up to a GPIO. Also connect the button via a small capacitor to the reset pin. The arduino boards use the same trick to reset the ATMega328 via the USB to serial chips DTR-pin.

I don't have any code that would relate to this functionality yet. By "two isolated tracks" i mean that this button has 4 pins, and 2 paths are isolated, so you can connect two separate things to same button. One path will wake up ESP, and second will be connected to one of GPIOs.  Will thing with capacitor also reset it when it's running? I want it only to reset once at sleep, and don't do it while working.

Could you please draw me it in paint or something?

Possible duplicate of Deep Sleep Reset with Shock Sensor

Use some other pin to hold RESET HIGH or to disconnect the button from RESET while the esp8266 is not running.

simulate this circuit – Schematic created using CircuitLab
I asked on EE SE for the missing part of the circuit.

You can't stop deepSleep, all you can do is reset the board so connect the button to the reset pin and make the appropiate set-up:

Connect a pullup resistor (10k) in RST
Connect the button from RST
to GND

When you push, RST has GND so the ESP gets reseted.
Remember that deepsleep only works for about an hour so you have to contemplate this situation, too, maybe with a static variable...
EDIT Thanks Juraj for the comment: "from SDK API "system_deep_sleep(0): there is no wakeup timer; in order to wake up, connect a GPIO to pin RST; the chip will wake up by a falling-edge on pin RST."

from SDK API "system_deep_sleep(0): there is no wakeup timer; in order to wake up, connect a GPIO to pin RST; the chip will wake up by a falling-edge on pin RST."

the reference assumes the esp8266 is used as 'coprocessor' for a main MCU, because it wasn't designed to be used standalone. so the mentioned GPIO pin is a pin of the main MCU


text:
Neo 6M GPS Module does not work properly inside own sketch
I am doing a project right now that involves a Neo 6M GPS module, a micro sd card module and 6 BH1750 light sensors. All the modules work fine when testing them standalone, especially the GPS module works as it should with TinyGPS++ example sketches.
When i run the "DeviceExample" sketch, it takes around 6 seconds to revieve time and around 10 seconds to recieve the location. However in my own sketch it only updates time every 3 or more seconds as well as i think it also updates location very slow.
Sometimes it even works for a short time, sometimes it never works, no matter how long the sketch runs.
Here is an example log:
As you can see, the sketch did not retrieve full date 20 secs after starting, but time is updating every second. Yet you can see that the time isn't updated anymore 5 seconds before the module is retrieving location and then the update interval gets slowed down, even though the module itself still indicates the update interval of around .5-1 second.
The Neo 6M GPS module is connected directly to RX,TX,GND,VCC and works fine with the example sketches. Has anybody a solution to this?
ms(), longitude, latitude,month,day,year,hour,min,sec,centisecs,alt,6 lux values
17642, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
17980, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
18333, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
18803, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,106,106,6,0,3,93,
19131, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,33,33,6,0,3,0,
19530, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,0,0,6,0,3,40,
19956, 0.000000, 0.000000,0,0,2000,22,26,15,95,0.00,106,106,6,0,3,106,
20311, 0.000000, 0.000000,0,0,2000,22,26,15,95,0.00,106,106,6,0,3,106,
20787, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
21114, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
21504, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
21942, 0.000000, 0.000000,0,0,2000,22,26,17,95,0.00,106,106,6,0,3,106,
22292, 0.000000, 0.000000,0,0,2000,22,26,17,95,0.00,106,106,6,0,3,106,

...
240540, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
240869, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
241249, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
241697, 0.000000, 0.000000,10,14,2018,22,29,57,95,0.00,106,106,6,0,3,106,
242035, 0.000000, 0.000000,10,14,2018,22,29,57,95,0.00,106,106,6,0,3,106,
242531, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,109,109,6,0,3,106,
242859, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,106,106,6,0,3,106,
243238, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,106,106,6,0,3,106,
243687, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
244016, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
244425, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
244892, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
245260, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
245754, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
246083, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
246494, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,109,6,0,3,106,
246947, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,109,109,6,0,3,106,
247320, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
247820, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,109,106,6,0,3,106,
248160, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
248676, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
249027, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
249425, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
249889, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,109,6,0,3,106,
250253,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
250768,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
251097,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
251608,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,109,106,6,0,3,106,
252021,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
252412,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
252883,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,109,106,6,0,3,106,
253248,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
253765,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
254094,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
254608,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,109,6,0,3,106,
255020,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,
255412,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,
255882,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,

Here is the sketch:
////
//initialising constants
static const  int out_min = 5;
static const  int out_max = 10;
static
const uint8_t RXPin = 0,
              TXPin = 1;
static
const uint16_t GPSBaud = 9600;
static
const uint16_t chipSelect = 4;
//initialising Objects
SoftwareSerial ss(RXPin, TXPin);
TinyGPSPlus gps;

BH1750 active_sensor(0x23); // We will use this adress for stating the active sensor
BH1750 inactive_sensor(0x5C);
SdFat sd;
SdFile file;

//initialising variables for collecting data
float lng_;
float lat_;

String month_ = "";
String day_ = "";
String year_ = "";

uint16_t lux_ = 0;
uint8_t hour_ = 0;
uint8_t min_ = 0;
uint8_t second_ = 0;
uint8_t centisecond_ = 0;
float altitude_ = 0;

unsigned long runtime_ = 0;

uint16_t values[6];
char buf[6];
char data_buffer[12];
char fileName[13] = FILE_BASE_NAME "00.csv";
uint8_t lines = 0;

void setup() {
  digitalWrite(2, HIGH);
  pinMode(2, INPUT);
  Serial.begin(115200);
  Wire.begin();

  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);

  for (int i = out_min; i <= out_max; i++)
  {
    pinMode(i, OUTPUT);
    digitalWrite(i, LOW);
  }

  ss.begin(GPSBaud);

  if (active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
   Serial.println(F("BH1750 Advanced begin"));
  } else {
    Serial.println(F("Error initialising BH1750"));
  }
}

void(* resetFunc) (void) = 0;
void loop() {

  while (ss.available() > 0)
    if (gps.encode(ss.read())) {
      digitalWrite(3, HIGH);
    }
  if (millis() > 5000 && gps.charsProcessed() < 10) {
    while (true);
  }
  if (gps.location.isValid()) {
    lat_ = gps.location.lat();
    lng_ = gps.location.lng();
  }

  if (gps.date.isValid()) {
    day_ = gps.date.day();
    month_ = gps.date.month();
    year_ = gps.date.year();
  }

  if (gps.time.isValid()) {
    hour_ = gps.time.hour();
    min_ = gps.time.minute();
    second_ = gps.time.second();
    centisecond_ = gps.time.centisecond();
    altitude_ = gps.altitude.meters();
  }

  int i;
  for (i = 5; i <= 10; i++) {
    digitalWrite(i, LOW);
    switch (i) {
      case 7:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
      case 8:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
      case 9:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE_2);
      case 10:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE_2);
      case 5:
        active_sensor.begin(BH1750::CONTINUOUS_LOW_RES_MODE);
      case 6:
        active_sensor.begin(BH1750::CONTINUOUS_LOW_RES_MODE);
    }
    delay(15);
    lux_ = active_sensor.readLightLevel();
    values[i - 5] = lux_;
    digitalWrite(i, HIGH);
  }
  delay(10);
  digitalWrite(3, LOW);
  delay(5);
  file.print(millis());
  file.write(',');
  dtostrf(lng_, 9, 6, data_buffer);
  file.print(data_buffer);
  file.write(',');
  dtostrf(lat_, 9, 6, data_buffer);
  file.print(data_buffer);
  file.write(',');

  file.print(month_);
  file.write(',');
  file.print(day_);
  file.write(',');
  file.print(year_);
  file.write(',');

  file.print(hour_);
  file.write(',');
  file.print(min_);
  file.write(',');
  file.print(second_);
  file.write(',');
  file.print(centisecond_);
  file.write(',');
  file.print(altitude_);
  file.write(',');

  for (int i = 0; i <= 5; i++) {
    file.print(values[i]);
    file.write(',');
  }
  file.println();
  lines++;

  int state = digitalRead(2);

}

Example Output:

You can't (and certainly shouldn't ever even try to) use SoftwareSerial on pins 0 and 1. Not when you're using Serial, since they are the same pins.
Pick a different pair of pins for your GPS connection.

But Pin 0 and 1 are the only Serial Pins on the arduino nano i use. Could i instead just remove all Serial functions? (Yet i think, i already tried that and it did not help)

The whole point of SoftwareSerial is that it doesn't use the serial pins.

I just had to look that up, since i never heard about that before. So i tried and even without using Serial it does not work. Why would all the internet still use the standard RX and TX pins, if they also use the SoftwareSerial library...

Just use different pins for SoftwareSerial. The point behind it is, that you can use it, if you need more serial interfaces, than the board already has. Serial is the Hardware serial interface and it's definitely better than SoftwareSerial, which has some serious limitations. You are using it because you don't have a second hardware serial on an Arduino UNO.

@Th3Fi3nD Because once upon a time some idiot without a clue did it, and then another idiot without a clue copied him. And then more idiots without a clue copied those, and since the internet is peopled by idiots without clues it rapidly became the norm. Now whenever anyone looks for example code they get a derivative of that original clueless idiot's code.  I wish it were like a vampire - then I could hunt down the original and kill it and all the descendants would revert to good code - but alas it isn't....

I see^^ This is commonly when trying to get help for arduino stuff. Anyways, i will try this out and let you know if it works.

So this does not help at all. It still takes several seconds to update...


text:
Is there an open source compiler for Arduino Sketch codes?
I am working on a web app to program some nodeMCU devices that were flashed with the arduinoOTA library.
http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html
I tried the example and the OTA upload of the binary file compiled from Arduino IDE works.
Let's say my web app will allow user to code in Sketch, is there any open source server side or client side compiler that can compile the Sketch code into the bin file?

turn on verbose console output in Arduino IDE and you will see all the executed commands to compile and link. the builder is external and it is Open Source

see for example Sloeber, the Arduino Eclipse plugin, how it uses Arduino toolchain and core packages without Arduino IDE

@Juraj Please write this as an answer or give URL for a tutorial, etc. that already exists on the web, if you know of one.

The AVC GCC is used and is open source  https://gcc.gnu.org/

Just have a look here https://github.com/arduino/Arduino/wiki/Build-Process to understand the process.
In fact Arduino code is not "C or C++" at 100%. You can't compile directy as some informations are missing.
This is why when you "compile" with the IDE, it copies the files in a temp folder, add some lines at beginning of theses files and then call the basic and well known avr-gcc.
If you have a dedicated server you just have to search for the avr-gcc package according to the OS.
Eg, for Debian: https://packages.debian.org/stretch/gcc-avr
Then or you send directly the code avr-gcc is waitng for, or you apply on the code the same changes the IDE is doing before sending the code to GCC.
Hope this help

Arduino IDE runs external tools to create the hex or bin file. First the ino files of a project are processed by arduino builder to cpp file. Then the arduino builder invokes the toolchain of the MCU architecture - compiler and linker. For example AVR tools for 328p or 2560; ARM toolchain from SAMD; xtensa tools for Espressif chips.
New is Arduino CLI, which focuses on using Arduino with command line.
Tha Arduino builder, Arduino CLI and esp8266 Arduino core are Open Source. Extensa tools and Espressif SDK are not open source, but are free.

Try PlatformIO: https://platformio.org
Opensource and cross platform.

Great answer to some other question :)


text:
Standalone 328P Arduino
I am creating a standalone Arduino using Atmega328P. The circuit is below.

However, I'm seeing
avrdude: Device signature = 0x000000 error

whenever I try to burn the Arduino Uno bootloader. I'm assuming that the chip isn't responding to the SPI lines?
I know I'm doing something wrong but I can't see it.
My connections are
SCLK --> Arduino Pin 13
MISO --> Arduino Pin 12
MOSI --> Arduino Pin 11
Reset --> Arduino Pin 10

VIN --> 5V
GND --> GND

I'm using a true Arduino UNO as the ISP. I've uploaded the ArduinoISP code into it, choose Arduino as ISP as Programmer and Arduino Uno on boards. The programming connections are just wired from Arduino UNO pins to some vias I've purposely added on the layout.
As mentioned in the comments, I'm adding an image of the layout here.

I've tried this very circuit on an atmega328P soldered in a TQFP adapter and with the other components soldered on the adapter as well (looks like a jungle of wires) and somehow I was able to burn the bootloader.
Hoping someone can point out what's wrong.

Are you trying to run the ATmega at 3.3 V on a 16 MHz crystal?

Yes. Will there be a problem on doing it @tttapa?

Check the datasheet, that voltage/frequency combination is out of spec. Either raise the voltage, or lower the frequency.

Thanks for pointing it out! Yeah, just saw it now on the datasheet.

I've just tried removing the regulator and connecting 5V with the VCC line. I'm still seeing the same error. Would there be other mistakes?

It's not possible to see on that schematic how your programming device is connected up to the board. Also PCB layout images could be useful to check for mistakes.

Do you know if the clock is running? Or can you provide a clock? 10µF between dtr and reset? and no diode from reset to vcc?

C3 should be 0.1uF for Serial downloads.  D10 from the ISP connects to Reset directly, not thru the cap.

@Majenko I've added the layout on the question. The SPI lines from Arduino UNO are tapped on the SPI lines of the atmega328P. There are vias on the left side of the vias so I can add wires. The connections are stated in the question above.

@Jot yes, I've looked at it on scope and the clock is running. I mean  i have 16 MHz oscillator on it. I'm not using FTDI when burning the bootloader. I'm using the SPI lines. So basically, the cap there is left floating.

Is there a ground pour or ground plane layer that has been omitted from that image?

It's not obvious from the schematic, but pins 3,4,21 need to be grounded.  Did you do that?

@Majenko yes, there is ground pour that is not shown. But yes, all ground pins are connected to ground.

noobiejp, I think we mentioned a lot of things and you answered our questions. So we have to look for more obscure things. Perhaps you can try the Nick Gammon sketch https://www.gammon.com.au/bootloader Perhaps you can try a programmer instead of Arduino as ISP. Perhaps your atmega32u4 is broken. Do you have another Arduino Uno that you can try to put a bootloader into? If that works, you can try to put a bootloader into a Leonardo or Micro. If that works, you can try your pcb board.

Your power supply is incorrect. You cannot connect a 317 this way

It seems that you are using a lm317 voltage regulator to power your atmega328p MCU but I think you forgot the part that lm317 needs feedback of 1.25v with voltage divider network to set its variable output voltage in the schematic you have connected adj pin of  lm317 directly to GND.
S0 check your output vtg from your regulator and another issue voltage regulator only works great when difference between regulating voltage is lower then the supply voltage.

From the schematic it appears you are using a LM317 voltage regulator from USB V_IN.  The voltage drop is too large and your issues may be due to brown out, i.e. insufficient voltage:  See this SE post.  You can solve it by using a lower dropout regulator (5 V to 3.3 V) or just use the standard USB 5 V, bypass V_IN to V_CC.

Hi! I've already tried bypassing the regulator by removing it and tying VIN to VCC. So the whole VCC line will get 5V straight from USB. However, still not burning the bootloader.


text:
Output clock signal on MKRZERO
I have to port a Project written for an Arduino Micro to an MKRZERO.
It communicates via UART with an IC and should also provide a clock signal.
The former code I have used is this:
#define OUTPUTPIN 8
#define CLOCKOUTPIN 5
#define CONTRLEDPIN 13

void Setup() {
pinMode(OUTPUTPIN, OUTPUT);
// Needed for initialization
digitalWrite(OUTPUTPIN, HIGH);
// set clock PIN
pinMode(CLOCKOUTPIN, OUTPUT);
// sets PIN for internal LED
pinMode(CONTRLEDPIN, OUTPUT);

TCCR3A = (1 << COM3A0);
TCCR3B = ((1 << WGM32) | (1 << CS30));
TIMSK3 = 0;
OCR3A = 7;
}

As the MKRZERO uses a different IC the registers are not the same. I've waded through the data sheet document but cannot find something similar.
Does somebody have any experience with the MKRZERO and can help me with this?

The IC on the MKRZERO is an Atmel SAMD21.  Look up the datasheet and read the section on timer counter.  Yes, it's a long document, but you will find all of the information there.


text:
My Serial plotter isn't working (arduino)
I'm trying to upload this code and it works properly but I can't see anything on my serial plotter
const int AnalogIn_Pin0=  A0;
const int AnalogIn_Pin1=A1;
const int Pwmout_PIN=11;
float AnalogIn_Val0=0;
float AnalogIn_Val1=0;
int Pwmout_Val=0;
float Error=0;
float ErrorInteg=0;
float Control=0;
float ControlFilt=0;
float kp=0.2;
float Pole =-10;
float Ki =0.01;
int deltaT=0.01;
int deltaT_ms=(int)deltaT*1000;

void setup() {
  pinMode (Pwmout_PIN,OUTPUT);
  Serial.begin (9600);
}

void loop() {
  AnalogIn_Val0=(float)constrain (analogRead(AnalogIn_Pin0),0,600);
  AnalogIn_Val1=0.97*AnalogIn_Val1+0.03*(float)analogRead(AnalogIn_Pin1);
  Error= (AnalogIn_Val0-AnalogIn_Val1);
  ErrorInteg=ErrorInteg+Error*deltaT;
  ControlFilt=kp*Error+Ki *ErrorInteg;
  Pwmout_Val= constrain (map ((int)ControlFilt,0,1023,0,255),0,220);
 analogWrite (Pwmout_PIN,Pwmout_Val);
 Serial.print(AnalogIn_Val0);
 Serial.print("");
 Serial.print(AnalogIn_Val1);
 Serial.print("");
 Serial.print( Pwmout_Val);
 delay (deltaT_ms);

}

works properly ... then why did you post your question?

you do not say what you actually see ..... maybe your plotter is defective

it's not plotting, the hardware works properly

It looks like that will just output a long string of numbers. No separators between fields, no separators between records (like: 5678298549328756238746524983759823462938746238974692387463298574369587234658723468734629375605237643724123046503453948765.... How is anything supposed to make sense of the data?

You must have each set of data point (or points) on a separate line and if you are plotting more that one value you need a space or a tab between each value.
So to have 3 lines on your plot, I think you want this:
 Serial.print(AnalogIn_Val0);
 Serial.print(' ');
 Serial.print(AnalogIn_Val1);
 Serial.print(' ');
 Serial.println(Pwmout_Val);

The output in the serial monitor should be something like this:
123 456 789
234 567 901
...


text:
TinyDuino radio connection
I am currently running a project with 2 TinyDuinos and 2 TinyShields 433MHz Radio (SI4432) in order to pass 3 axes (x , y ,z) from one to the other from long distance.
I have tried

to concat the axes as one string and send the string,
to send an array like string axes = { x , y , z } to the
receiver (of course the variables are already defined),
send only one string. In this case I have only the first 2 letters of the string. For example if the string was string first = "456" , I would get "45" on the receiver

The Radio shield's examples uses uint8_t type and arrays to send and receive the data, I have already tried to cast the string to char* and then to uint8_t and nothing different happens. Maybe I am missing something.
Below there are my code screen shots. I will put 2 links for the examples of the transmitter and the receiver I got some code from
Similar Project : https://tinycircuits.com/blogs/learn/121634375-football-play-calling-watch-tutorial
Radio Shield Page: https://tinycircuits.com/products/433mhz-long-range-radio-tinyshield
TinyDuino Main Shield : https://tinycircuits.com/collections/all/products/tinyduino-processor-board
Code Screenshots

Please add the code in your question, don't use images/screenshots.  This allows easier editing by others and more crucially helps the search engines.

For this kind of thing you need to craft a packet to contain your data. The best method is to use a struct.
struct coords {
    int x;
    int y;
    int z;
};

Then you can define a variable from it:
struct coords myCoords;

And set individual values:
myCoords.x = 23;
myCoords.y = 180;
myCoords.z = -3817;

Now you can cast it to whatever type you need for sending:
manager.sendtoWait((uint8_t *)&myCoords, sizeof(struct coords), SERVER_ADDRESS);

Receiving is done in much the same way:
struct coords recCoords;
uint8_t len = sizeof(struct coords);
uint8_t from;

if (manager.recvfromAck((uint8_t *)&recCoords, &len, &from)) {
    Serial.print("X = ");
    Serial.println(recCoords.x);
    Serial.print("Y = ");
    Serial.println(recCoords.y);
    Serial.print("Z = ");
    Serial.println(recCoords.z);
}

In future please post your actual code, not pictures of your code. It makes it a real pain having to keep scrolling up and manually typing in bits of your code rather than being able to copy-and-paste a couple of lines.


text:
Iteed SD card breakout info for Arduino
I got an SD card breakout from an online shop, its the iteed kind without the level shifter, it has the 3.3 / 5 V switch. I cannot find any libraries or write example for it.
Has anyone dealt with it before with Arduino? I have tried finding info but I only get the level shifter kind that has the MOSI pins!
enter image description here

Use standard Arduino SD library or the SdFat library. All SD card 'modules' are only a holder and eventually level converters. The SPI device is the SD card itself.
Set the SD adapter to the voltage of your board, connect it to power and SPI bus, choose some pin as SS pin, insert SD card and it must work.
Pins: MISO is master in slave out, MOSI is master out slave in. DO is data out, DI is data in. SD card is slave, so MISO to DO and MOSI to DI

Thanks, do you by any chance know how to connect it as all the examples show mosi and miso pins but i dont have those on this breakout, even in the data log example it asks for mosi and miso pins but i only have DO, CLK, DI, CS, i can only find CLK and CS in examples

MISO is master in slave out, MOSI is master out slave in. DO is data out, DI is data in. SD card is slave, so MISO to DO and MOSI to DI

So, a quick google for "Itead SD card breakout" comes up with their website/wiki where there is a schematic.  Can't believe you did not try this.  It is just that - a breakout board.  It will allow you to connect Arduino to an SD card.  You can look up any generic example for SD + Arduino on the web.
They explicitly say

It can work with 5V or 3.3V power supply, and both 5V/3.3V IO operation level. It can be controlled directly by a wide range of microcontrollers such as Arduino, AVR, PIC, ARM and MSP430.

Alrighty, For anyone else struggling with this in the future.
Using arduino mega and iteed sd breakout withoit level shifter
G-Ground
DO-50
CLK-52
DI-51
CS-53
+-5V
then in the code before setup specify chip select to 53
Thanks for all the help.