text:
Why is our refresh rate consistently decreasing in logging on SD card?
The current code is used to gather the state of 12 infrared beams and log them to an SD card using the real time clock to mark the time. The code uses a switch to turn the device on and off and an LED to indicate if data is being written to the SD. When we later looked at the data on the SD card the refresh rate was slowly decreasing and we ended up with only 10 logs a second after a few hours. Why is this happening and how is it fixed?
#include <SD.h>   //For talking to SD Card
#include <Wire.h>  //For RTC
#include "RTClib.h" //For RTC

//Define pins
//SD card is on standard SPI pins
//RTC is on Standard I2C Pins
const int CS_PIN   = 53;

//Default rate of 25ms
int refresh_rate = 25;

//Define RTC object
RTC_DS1307 RTC;

//Initialize variables
String year, month, day, hour, minute, second, time, date;

#define SENSOR1 22
#define SENSOR2 23
#define SENSOR3 24
#define SENSOR4 25
#define SENSOR5 26
#define SENSOR6 27
#define SENSOR7 32
#define SENSOR8 33
#define SENSOR9 34
#define SENSOR10 35
#define SENSOR11 36
#define SENSOR12 37
#define LEDPIN 6
#define SWITCH 10

// variables will change:
int sensorState1 = 0, lastState1 = 0;
int sensorState2 = 0, lastState2 = 0;
int sensorState3 = 0, lastState3 = 0;
int sensorState4 = 0, lastState4 = 0;
int sensorState5 = 0, lastState5 = 0;
int sensorState6 = 0, lastState6 = 0;
int sensorState7 = 0, lastState7 = 0;
int sensorState8 = 0, lastState8 = 0;
int sensorState9 = 0, lastState9 = 0;
int sensorState10 = 0, lastState10 = 0;
int sensorState11 = 0, lastState11 = 0;
int sensorState12 = 0, lastState12 = 0;

//Variable for reading the Switch Status
int SWITCHSTATE ;

//define integers for sensor change
int SensorChange1 = 0;
int SensorChange2 = 0;
int SensorChange3 = 0;
int SensorChange4 = 0;
int SensorChange5 = 0;
int SensorChange6 = 0;
int SensorChange7 = 0;
int SensorChange8 = 0;
int SensorChange9 = 0;
int SensorChange10 = 0;
int SensorChange11 = 0;
int SensorChange12 = 0;

void setup()
{
  // initialize the sensor pin 24 as an input:
  pinMode(SENSOR1, INPUT);
  digitalWrite(SENSOR1, HIGH); // turn on the pullup  // initialize the sensor pin 25 as an input:
  pinMode(SENSOR2, INPUT);
  digitalWrite(SENSOR2, HIGH); // initialize the sensor pin 26 as an input:
  pinMode(SENSOR3, INPUT);
  digitalWrite(SENSOR3, HIGH); // initialize the sensor pin 27 as an input:
  pinMode(SENSOR4, INPUT);
  digitalWrite(SENSOR4, HIGH); // initialize the sensor pin 28 as an input:
  pinMode(SENSOR5, INPUT);
  digitalWrite(SENSOR5, HIGH); // initialize the sensor pin 29 as an input:
  pinMode(SENSOR6, INPUT);
  digitalWrite(SENSOR6, HIGH);  // initialize the sensor pin 30 as an input:
  pinMode(SENSOR7, INPUT);
  digitalWrite(SENSOR7, HIGH);  // initialize the sensor pin 31 as an input:
  pinMode(SENSOR8, INPUT);
  digitalWrite(SENSOR8, HIGH);  // initialize the sensor pin 32 as an input:
  pinMode(SENSOR9, INPUT);
  digitalWrite(SENSOR9, HIGH);  // initialize the sensor pin 33 as an input:
  pinMode(SENSOR10, INPUT);
  digitalWrite(SENSOR10, HIGH);  // initialize the sensor pin 34 as an input:
  pinMode(SENSOR11, INPUT);
  digitalWrite(SENSOR11, HIGH);  // initialize the sensor pin 35 as an input:
  pinMode(SENSOR12, INPUT);
  digitalWrite(SENSOR12, HIGH);   // initialize the LED pin as an output:

// initialize the LED pin as an output:
  pinMode (LEDPIN, OUTPUT);

// initialize the SWITCH pin as an output:
  pinMode (SWITCH, INPUT);

// setpin 19 as high (5V) and 18 as low
  pinMode(19, OUTPUT);
  pinMode(18, OUTPUT);
  digitalWrite(19, HIGH);
  digitalWrite(18, LOW);

  Serial.begin(9600);
  Serial.println(F("Initializing Card"));

 //CS pin, and pwr/gnd pins are outputs
  pinMode(CS_PIN, OUTPUT);

  //Initiate the I2C bus and the RTC library
  Wire.begin();
  RTC.begin();

  //If RTC is not running, set it to the computer's compile time
  if (! RTC.isrunning())
  {
    Serial.println(F("RTC is NOT running!"));
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

  //Initialize SD card
  if (!SD.begin(CS_PIN))
  {
    Serial.println(F("Card Failure"));
    return;
  }
  Serial.println(F("Card Ready"));

  //Read the configuration information (speed.txt)
  File commandFile = SD.open("speed.txt");
  if (commandFile)
  {
    Serial.println(F("Reading Command File"));

    while(commandFile.available())
    {
      refresh_rate = commandFile.parseInt();
    }
    Serial.print(F("Refresh Rate = "));
    Serial.print(refresh_rate);
    Serial.println(F("ms"));
    commandFile.close();
  }
  else
  {
    Serial.println(F("Could not read command file."));
    return;
  }

}

void loop()
{
  SWITCHSTATE = digitalRead(SWITCH); //read input value
  if (SWITCHSTATE == LOW)
 {
   digitalWrite(LEDPIN, LOW);
 }
  else
 {
   digitalWrite(LEDPIN, HIGH);

// read the state of the sensor value:
  sensorState1 = digitalRead(SENSOR1);
  sensorState2 = digitalRead(SENSOR2);
  sensorState3 = digitalRead(SENSOR3);
  sensorState4 = digitalRead(SENSOR4);
  sensorState5 = digitalRead(SENSOR5);
  sensorState6 = digitalRead(SENSOR6);
  sensorState7 = digitalRead(SENSOR7);
  sensorState8 = digitalRead(SENSOR8);
  sensorState9 = digitalRead(SENSOR9);
  sensorState10 = digitalRead(SENSOR10);
  sensorState11 = digitalRead(SENSOR11);
  sensorState12 = digitalRead(SENSOR12);

  //Get the current date and time info and store in strings
  DateTime datetime = RTC.now();
  year  = String(datetime.year(),  DEC);
  month = String(datetime.month(), DEC);
  day  = String(datetime.day(), DEC);
  hour  = String(datetime.hour(), DEC);
  minute = String(datetime.minute(), DEC);
  second = String(datetime.second(), DEC);

  //Concatenate the strings into date and time
  date = year + "/" + month + "/" + day;
  time = hour + ":" + minute + ":" + second;

  if (sensorState1 == HIGH)
  {
   SensorChange1 = 1;
  }
  else
  {
   SensorChange1 = 0;
  }
  if (sensorState2 == HIGH)
  {
   SensorChange2 = 1;
  }
  else
  {
   SensorChange2 = 0;
  }
  if (sensorState3 == HIGH)
  {
   SensorChange3 = 1;
  }
  else
  {
   SensorChange3 = 0;
  }
  if (sensorState4 == HIGH)
  {
   SensorChange4 = 1;
  }
  else
  {
   SensorChange4 = 0;
  }
  if (sensorState5 == HIGH)
  {
   SensorChange5 = 1;
  }
  else
  {
   SensorChange5 = 0;
  }
  if (sensorState6 == HIGH)
  {
   SensorChange6 = 1;
  }
  else
  {
   SensorChange6 = 0;
  }
  if (sensorState7 == HIGH)
  {
   SensorChange7 = 1;
  }
  else
  {
   SensorChange7 = 0;
  }
  if (sensorState8 == HIGH)
  {
   SensorChange8 = 1;
  }
  else
  {
   SensorChange8 = 0;
  }
  if (sensorState9 == HIGH)
  {
   SensorChange9 = 1;
  }
  else
  {
   SensorChange9 = 0;
  }
  if (sensorState10 == HIGH)
  {
   SensorChange10 = 1;
  }
  else
  {
   SensorChange10 = 0;
  }
  if (sensorState11 == HIGH)
  {
   SensorChange11 = 1;
  }
  else
  {
   SensorChange11 = 0;
  }
  if (sensorState12 == HIGH)
  {
   SensorChange12 = 1;
  }
  else
  {
   SensorChange12 = 0;
  }

  File dataFile ;
  dataFile = SD.open("log1.csv", FILE_WRITE);
  if (dataFile)
    {
      dataFile.print(date);
      dataFile.print(F(","));
      dataFile.print(time);
      dataFile.print(F(","));
      dataFile.print(SensorChange1);
      dataFile.print(F(","));
      dataFile.print(SensorChange2);
      dataFile.print(F(","));
      dataFile.print(SensorChange3);
      dataFile.print(F(","));
      dataFile.print(SensorChange4);
      dataFile.print(F(","));
      dataFile.print(SensorChange5);
      dataFile.print(F(","));
      dataFile.print(SensorChange6);
      dataFile.print(F(","));
      dataFile.print(SensorChange7);
      dataFile.print(F(","));
      dataFile.print(SensorChange8);
      dataFile.print(F(","));
      dataFile.print(SensorChange9);
      dataFile.print(F(","));
      dataFile.print(SensorChange10);
      dataFile.print(F(","));
      dataFile.print(SensorChange11);
      dataFile.print(F(","));
      dataFile.print(SensorChange12);
      dataFile.println( );
      dataFile.close(); //Data isn't actually written until we close the connection!

      //Print same thing to the screen for debugging
      Serial.println();
      Serial.print(date);
      Serial.print(F(","));
      Serial.print(time);
      Serial.print(F(","));
      Serial.print(SensorChange1);
      Serial.print(F(","));
      Serial.print(SensorChange2);
      Serial.print(F(","));
      Serial.print(SensorChange3);
      Serial.print(F(","));
      Serial.print(SensorChange4);
      Serial.print(F(","));
      Serial.print(SensorChange5);
      Serial.print(F(","));
      Serial.print(SensorChange6);
      Serial.print(F(","));
      Serial.print(SensorChange7);
      Serial.print(F(","));
      Serial.print(SensorChange8);
      Serial.print(F(","));
      Serial.print(SensorChange9);
      Serial.print(F(","));
      Serial.print(SensorChange10);
      Serial.print(F(","));
      Serial.print(SensorChange11);
      Serial.print(F(","));
      Serial.print(SensorChange12);

    }
    else
    {
     Serial.println(F("Couldn't open log file"));
    }

  lastState1 = sensorState1;
  lastState2 = sensorState2;
  lastState3 = sensorState3;
  lastState4 = sensorState4;
  lastState5 = sensorState5;
  lastState6 = sensorState6;
  lastState7 = sensorState7;
  lastState8 = sensorState8;
  lastState9 = sensorState9;
  lastState10 = sensorState10;
  lastState11 = sensorState11;
  lastState12 = sensorState12;

  delay(refresh_rate);
  }

  }

you can streamline your code by using arrays  .... sensorState[1] ,  SensorChange[1] , etc.  ... then use a for loop to iterate over the sensors and update values

This has nothing to do with your question, but that long string of repeated .print()/.println() calls could be moved into a separate function e.g. void printRecord(Print &p) {, which could be called on both dataFile and Serial.  printRecord would contain a sequence (or as jsotola said, array)  of  p.print(....

I couldn't stand looking at the non-loops so I rewrote it as an example for you to look at here. I found a bug when doing so, you update the change variables without looking at the previous value. I didn't compile the code, but it might work anyway!

Why all those "lastState" variables. You don't seem to do anything with them.

I don't have certain answer for you, but a deep suspicion.  If I get bored I'll confirm it. Confirmed below.
In each pass of loop(), you have:
  dataFile = SD.open("log1.csv", FILE_WRITE);

In short, finding the end of the file is linear operation in a FAT filesystem.  It must follow the allocation chain to find (or create), the last cluster of the file.  The allocation chain is sort like a linked list with the links themselves being the only thing in linked list structure; their numbers are mapped onto the cluster numbers.  So you're traversing a linked list, except you may be doing it across multiple sectors of an SD card, which is comparatively expensive.
So by reopening repeatedly in loop(), you're forcing it to perform this lengthening process each time, apparently because of:
dataFile.close(); //Data isn't actually written until we close the connection!

The part of .close(); that does this is made available to you as .flush();, without needing to close the file and forget where the current cluster is.
In other words, you should be able to open() the file once in setup() and replace your .close() in loop() with a .flush().
That said, you needn't and probably shouldn't flush on every record write.  If you're doing this so that you can shut the device down, you might want to just add a push-button that does the closing or flushing and then waits in the tight loop until it's power cycled.
Confirmation Test  Results
In short, yes, there's a measurable, file-size related cost to opening the file for write and seeking to the end. And it's just a fact about the FAT filesystem and noticeable because it's impractical to load the whole allocation table into memory on a small Arduino.  It would normally (e.g on the desktop) be loaded into memory and you'd scarcely notice the difference in opening files of different sizes.
In my one tested scenario for my setup the numbers predict that when the file grows to approximately 155 Meg, it will take about a tenth of a second to open.
This test involved:

An Arduino UNO.
2 GB FAT16 formatted card.
Arduino AVR core version 1.8.3
SD card library version 1.2.4.

Your results will probably vary widely with MCU type and filesystem block size, but so long as you're using a Arduino with a SD library that minimizes memory footprint, you'll have a noticeable increasing open time with larger file sizes.
The below is going to be a bit nerdy, but since people seem to be interested in it, I'm giving some detail.  Arduino code follows at the bottom for what was used to collect the data that produced the graph.
I emptied a 2 GByte SD card.  This included removing the "System Volume Information" that windows (or perhaps the card maker) had put on there, and
confirmed that were were no allocated clusters, no file chains.  Under these conditions the file should just grow in consecutive sectors on the card; at
least as presented by the card, as in: if we ignore anything the card might be doing for wear-leveling.  The pattern used in the program makes it pretty easy
to just look at a raw image of the card and see that this is what happened.
Anyway, with my setup these are some results:

The 98304 sector count on the right refers to a file of roughly 50 Meg.
This SD card is FAT16 formatted, something I hadn't noticed until I ran the numbers on that staircase pattern and found them defying expectations by a factor of 2.
Being FAT16, each FAT table sector, has 512/2 = 256 entries in it.  Each entry number corresponds to one cluster (block), which for my SD card's filesystem happens to be 32 kByte, or 64 count of 512-byte sectors.   So every FAT table sector (in my case) is responsible for locating 64 * 256 = 16,384 file sectors.  In other words, the staircase pattern appears to reflect the fact that following the allocation chain for our consecutive file means reading another FAT table sector for every 16,384 sectors of the file, hence the jumps at those intervals.

If you used a fragmented file it would need to do this more often and the performance would look worse.  I did inspect the SD card to confirm that it was written sequentially.

If you use FAT32, you can expect it to take longer because each FAT sector will store half as many cluster references.

If you use smaller cluster (block) size, then it will take longer because each enter in the FAT sector covers less file content.

Test code
//
// Tested on an UNO with Arduino Core version 1.8.3
// 2 GByte SDCard
//

#include <SD.h> // Version 1.2.4 as of test.
#include <SPI.h>

static constexpr int PIN_SDCARD_SHIELD_CHIP_SELECT = 10;
static constexpr int PIN_HALT_TEST                 =  2;

static const char test_filename[] = "testfile.txt";

struct test_state : Printable {
  uint32_t      sector_counter = -1;
  unsigned long open_duration  =  0;

  size_t printTo(Print& p) const override {
    auto r = p.write('[');
    r     += p.print(sector_counter);
    r     += p.write(':');
    r     += p.print(open_duration);
    r     += p.write(']');
    return r;
  }

  void update(unsigned long new_open_duration) {
    open_duration = new_open_duration;
    ++sector_counter;
  }
};

//
//
//
void write_numbered_sector(
  Print &p,
  const test_state &state
) {
  static constexpr size_t SECTOR_SIZE            = 512;
  static constexpr size_t CR_LF_SIZE             =   2;

  const auto printed_test_state_len = p.print(state);

  const auto xs_to_write =
      SECTOR_SIZE
    - printed_test_state_len
    - CR_LF_SIZE;

  for (size_t i = xs_to_write; i != 0; --i) {
    p.write('X');
  }

  p.write('\r');
  p.write('\n');
}

//
//
//
void setup() {
  pinMode(PIN_HALT_TEST, INPUT_PULLUP);

  Serial.begin(9600);

  if (!SD.begin(PIN_SDCARD_SHIELD_CHIP_SELECT)) {
    Serial.println(F("Card initialization failed."));
    halt_test();
  }

  SD.remove(test_filename);
}

//
//
//
void blink_forever() {
  pinMode(LED_BUILTIN, OUTPUT);
  while (true) {
    static bool led_state = false;

    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    delay(100);
  }
}

//
//
//
void halt_test() {
  SD.end();
  SPI.end();
  Serial.end();

  blink_forever();
}

//
//
//
void loop() {
  static test_state state;

  Serial.flush();
  const auto started_opening = micros();
  File testfile = SD.open(test_filename, FILE_WRITE);
  const auto done_opening = micros();

  const auto open_duration = done_opening - started_opening;

  state.update(open_duration);

  write_numbered_sector(
    testfile,
    state
  );
  testfile.close();
  Serial.print(micros());
  Serial.print(' ');
  Serial.println(state);

  const auto user_requested_halt = (digitalRead(PIN_HALT_TEST) == LOW);
  if (user_requested_halt) {
    Serial.println(F("Test halt requested."));
    halt_test();
  }
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:

If you're worried about unattended power loss, you can flush periodically, e.g. every 400 records for a nominal 10s interval - nominal because with a 25ms delay your loop will always take longer than 25ms

Ah yes, the old "doing a resource-intensive operation that should be done only once, but doing it every iteration" problem :)

It is also possible that close instead of flush will cause more writing to the SD card - specifically to the directory sector holding the file entry - causing extra wear (and extra time for the card's controller to load balance sectors (unless flush also touches file entry, if an SD card controller load balances sectors).  Does anyone know?

If I dig through the code again later, I'll check.  My gut reaction is that both will have the same effect on the sectors when called.  But I don't know that.

@mishan it's called a Shlemiel the painter algorithm

Some other useful advice may be found in this answer as well. In particular, using multiple files which can offer some benefits. If I have real cause to edit this again, I'll probably incorporate the link.


text:
Error message while trying to burn bootloader onto atmega 328p
I have tried to burn bootloader onto an atmega 328p chip onto a breadboard using another arduino uno , I am not using an external clock but I am doing all the steps to make this thing which are given on this site - https://create.arduino.cc/projecthub/techmirtz/arduino-without-external-clock-crystal-on-atmega328-d4fcc4
the error code I am receiving is this :
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\DELL\Desktop\arduino ide\arduino-nightly\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.```

A device signature of 0x000000 usually means you've wired it wrong.

"I am not using an external clock" I take this to mean that you didn't attach a crystal or clock to it.  Or that you don't want to.  What it doesn't tell me is whether or not the ATMega328P you're using has previously been fused for an external clock or crystal.  So, where/what did you get the ATMega328P from?  Or alternately do you know that it is not currently configured for something other than internal RC oscillator?

@timemage Its totally new and has not yet been programmed for anything, I didnt take it out of any arduino or anything - bought it separately

source: Stack Exchange

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

sort: votes


text:
ATTINY13A, Servo only makes half a sweep
I have been trying to get a servo to sweep using an attiny13A. And i managed to get the servo to (kindoff) work by the help of a previous thread. But i'm now getting an issue. The servo only goes to 180 degrees and does not return to 0 degrees, instead it just keeps trying to go further then 180 degrees eventhough its not mechanicly capabel of doing so. Anyone have any idea how i can solve this? ( I need it for a small animatronic part) (also the servo is a generic 9gram servo and i have tested it on multiple servos, its the same result) thanks in advance
#define F_CPU 9600000
int servo = PB1;  //connect servo to PB1
long angle;
int pwm;
int counter = 0;
int LED = PB3;
#include <avr/io.h>
void adc_setup (void)
{
    // Set the ADC input to PB2/ADC1
  ADMUX |= (1 << MUX0);
  ADMUX |= (1 << ADLAR);
  // Set the prescaler to clock/128 & enable ADC
  // At 9.6 MHz this is 75 kHz.
  ADCSRA |= (1 << ADPS1) | (1 << ADPS0) | (1 << ADEN);
}
int adc_read (void)
{
  // Start the conversion
  ADCSRA |= (1 << ADSC);
  // Wait for it to finish
  while (ADCSRA & (1 << ADSC));
  return ADCH; // return the value
}
void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(servo, OUTPUT);  // set servo as output pin
  digitalWrite(LED, HIGH);
  delay(3000);
  pinMode(LED, LOW); //blink LED

}
void loop ()
{
 for(counter = 0; counter < 180; counter++)  //scan fril 0 degrees to 180 degrees
  {
    servoPulse(servo, counter);  // call the servoPulse function.
    delay(15);
  }

delay(1000);

 for(counter = 180; counter > 0; counter--)  // now scan back from 180 to 0 degrees
  {
    servoPulse(servo, counter);  // call the servoPulse function.
    delay(15);
 }
}
void servoPulse (int servo, int counter)
{
  pwm = (angle * 11) + 500;    // Convert angle to microseconds
  digitalWrite(servo, HIGH);
  delayMicroseconds(pwm);
  digitalWrite(servo, LOW);
  delay(50); // Refresh cycle of servo
}

I’m a little confused; servos require a pulse every 20ms (this depends on the servo; there’s a fair amount of variability) but you’re pulsing with a 65ms delay (delay in loop + delay in servoPulse) so my first guess would be the PWM signal is bogus—your overall pulse width is > 65ms, with the HIGHS signal a tiny fraction of that. I don’t see angle changed anywhere in the code, or initialized, and servoPulse ignores what I think you meant to use, counter.

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


text:
Help needed with driving multiple stepper motors on arduino UNO
I am brand new to Arduino but have good experience with Raspberry Pi's and Microchips.
My problem is that I am having trouble driving many stepper motors at once. I am using the AccelStepper library(https://www.airspayce.com/mikem/arduino/AccelStepper/index.html). The code is pretty simple and I got it to work perfectly for a long time with three motors, however it had trouble running more than three motors, I have 5 motors hooked up right now and all of them vibrate or skip steps.
Can anyone help me get the 5 motors working.
Here is the code I'm running:
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <Stepper.h>

AccelStepper stepper1(AccelStepper::FULL4WIRE, 8, 10, 9, 11);
AccelStepper stepper2(AccelStepper::FULL4WIRE, 4, 5, 6, 7);
AccelStepper stepper3(AccelStepper::FULL4WIRE, 12, 13, 2, 3);
AccelStepper stepper4(AccelStepper::FULL4WIRE, A0, A1, A2, A3);
AccelStepper stepper5(AccelStepper::FULL4WIRE, 0, 1, A4, A5);

void setup()
{
    //Serial.begin(9600);
    pinMode(0, OUTPUT);
    pinMode(1, OUTPUT);
    pinMode(A0, OUTPUT);
    pinMode(A1, OUTPUT);
    pinMode(A2, OUTPUT);
    pinMode(A3, OUTPUT);
    pinMode(A4, OUTPUT);
    pinMode(A5, OUTPUT);
    Serial.print(" a0:");
    Serial.print(digitalRead(A0));
    stepper1.setMaxSpeed(600.0);
    stepper1.setAcceleration(50.0);
    stepper1.moveTo(3240);

    stepper2.setMaxSpeed(50);
    stepper2.setAcceleration(1);
    stepper2.moveTo(800);

    stepper3.setMaxSpeed(300.0);
    stepper3.setAcceleration(200.0);
    stepper3.moveTo(1500);

    stepper4.setMaxSpeed(300.0);
    stepper4.setAcceleration(200.0);
    stepper4.moveTo(1500000);

    stepper5.setMaxSpeed(300.0);
    stepper5.setAcceleration(200.0);
    stepper5.moveTo(1500000);
}
void loop()
{
    // Change direction at the limits

    if (stepper1.distanceToGo() == 0)
        stepper1.moveTo(-stepper1.currentPosition());
    if (stepper2.distanceToGo() == 0)
        stepper2.moveTo(-stepper2.currentPosition());
    if (stepper3.distanceToGo() == 0)
        stepper3.moveTo(-stepper3.currentPosition());
    if (stepper4.distanceToGo() == 0)
        stepper4.moveTo(-stepper4.currentPosition());
    if (stepper5.distanceToGo() == 0)
        stepper5.moveTo(-stepper5.currentPosition());
    stepper1.run();
    stepper2.run();
    stepper3.run();
    stepper4.run();
    stepper5.run();
}

I don't think it is the code that is the problem because as I stated before it worked with three motors just fine and the code for 4 and 5 is just copy paste.
I think it could be a power problem, I have a wall outlet that can convert to a range of dc voltages between 3 and 12, at 5V the motors are clearly lacking the power to run. At 6V they do turn on but dont work well at all(as I stated above) and at 7.5V the Arduino seems to continually restart: the motors start for just a second.
Here are the 28BYJ-48 motors with drivers I bought from amazon: https://www.amazon.com/gp/product/B01CP18J4A/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1
Can anyone explain to me why it restarts at 7.5 volts? I've read that the minimum power should be around 7 volts so this doesn't make sense to me.
Appreciate any help I can get, please remember I'm new to this. Thank you.

How is this all wired up? How much power can your supply deliver and how much do the motors need?

@Mat The motors connect to the drivers plug-and-play and the wiring from the drivers to the board can be seen in lines 4-7 of the code. The power to the boards is gotten from the 5V pin of the Arduino and the ground  is also from the Arduino. Amazon states that the motors are rated at 5V. Finally Mat if you read my paragraph above you can see how my power supply works

You're only talking volts. That's not enough, you need amps too to deliver watts (i.e. power).

pins 0 and 1 are used for Serial

@jsotla, they are only used for serial if you have a serial begin statement in your code

@Mat Do I have enough amps to run both the Arduino and the motors?


text:
nodemcu EEPROM corrupting
Platform

Hardware:                 [nodemcu amica ESP8266MOD]
Core Version:         [nodemcu-master-21-modules-2018-03-17-17-09-10]
Development Env:      [Arduino IDE|]
Operating System:     [Windows|]

Settings in IDE

Module:           |Nodemcu]
Flash Mode:           [qio|dio|other]?
Flash Size:       [1MB]
lwip Variant:   [v2 Lower Memory]
Reset Method:     [nodemcu]
Flash Frequency:  [40Mhz]
CPU Frequency:        [80Mhz]
Upload Using:     [SERIAL]
Upload Speed:   [115200] (serial upload only)

Problem Description
hi, in my code i did a simple thing. i get the data from jSon object and write them to the EEPROM. once i write them to eeprom i can read the relevant data from that writing function handleFinishWizard()  (i have put reading functions here n there to find where is the problem) .When i write data and finish it i can read the data.once its over when the program moved to the loop, eeprom data are corrupted and it doesnt display anything. i attached the output in debug message. whats the problem here?
[MCVE] Sketch
code in github CODE LINK
Debug Messages
```
add 1
aid 1
station: c0:ee:fb:ed:3b:0e join, AID = 1
value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM ADD:
OnePlus 3T
test123@abc
test.com

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM saveBefore:
⸮?

⸮?

value on EEPROM save:

value on EEPROM save:

value on EEPROM save:

```

use SPIFFS with 8266, so much better than EEPROM

@dandavis yes after the problem i moved to SPIFFS. saved data in json format.easy

EEPROM has 100K cycles of recording data and then it will probably stop.  Have you written to this EEPROM more than 100K times?

@tonygil no, this happened because of I wrote pointers instead of values

Look at this code:
void setupCredentials(const char *ssid, const char *password,
                      const char *link) {
  int addr = 0;

  EEPROM.begin(512);
  addr = sizeof(int);
  EEPROM.put(addr, ssid);
  delay(10);
  addr += sizeof(st_ssid);
  EEPROM.put(addr, password);
  delay(10);
  addr += sizeof(st_password);
  EEPROM.put(addr, link);
  delay(10);
  EEPROM.commit();

You are calling EEPROM.put(addr, ssid) with ssid being a const char*. A pointer to some memory location. Notice that you only give it a start address and a pointer, not the length of your data.
Have a look at the implementation of the put function:
  template<typename T>
  const T &put(int const address, const T &t) {
    if (address < 0 || address + sizeof(T) > _size)
      return t;
    if (memcmp(_data + address, (const uint8_t*)&t, sizeof(T)) != 0) {
      _dirty = true;
      memcpy(_data + address, (const uint8_t*)&t, sizeof(T));
    }

    return t;
}

What it essentially does is copy your given object const T &t into its internal _databuffer. The size of the data saved is determined by sizeof(T).
In your example t = ssid, T = const char* and sizeof(T) = sizeof(char*) = 4 and addr= sizeof(int) = 4.
What you are doing here is not to save the string that ssid points to in memory but the pointer value of ssid. After you leave the function the data pointed to by ssid will be de-allocated at some point and the memory will be overwritten by something else.
When you do a print directly in the function you are retrieving the pointer value of ssid 3 times and print that value. At that point the data is still there and everything is okay. Then if you print it again after leaving the function you get garbage because the local data is gone after the function call handleSetup is left.
What you want here is to not use a const char* in your second argument to a  EEPROM.put(address, object) call but a char [20], for example. This way the put will work correctly.
Example:
// Assume EEPROM.begin() was called already
void EEPROM_SaveSSID(const int address, const char* str) {
    char ssid_buf[20];
    strncpy(ssid_buf, sizeof(ssid_buf) - 1, str);
    EEPROM.put<char[20]>(address, ssid_buf[0]); //sizeof(ssid_buf) = 20
    //don't forget to EEPROM.commit(); and EEPROM.end()
}

/* read SSID into a pre-allocated buffer */
void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
    EEPROM.get(address, ssid_buf); //sizeof(ssid_buf) = 20
}

If you do not like the semantics of these C++-templates auto-determining the size of read/write calls, you can always use bytewise read and write calls:
void EEPROM_SaveSSID(const int address, const char* str) {
    for(size_t i = 0; i < strlen(str)) {
        EEPROM.write((int)(address + i), str[i]);
    }
}

/* always read 20 bytes starting from given address into buffer */
void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
    for(size_t i = 0; i < sizeof(ssid_buf); i++) {
        ssid_buf[i] = EEPROM.read((int)(address + i));
    }
}

See "EEPROM" (actually: Flash-emulated EEPROM) implementation code at https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM.

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


text:
Using two references in the same ADMUX
I'm making a project and I neee to use 2 different references on the same ADMUX. One reference is 0-5V and the other is 0-2.5V. I'm aware that I can use the reference of the Arduino to the 5V sensor. But how I put a 2.5V reference while using the 5V at the same time?

You can try to read 2.5V sensor twice, sum it and divide by two. Or you can double the input voltage by using non-inverting OP AMP with amplification factor 2. Or if you don't mind half resolution, you can use 5V reference voltage and just read it.

Do you really need 10-bit precision on both voltages?

First of all a reference is just a voltage, not a range.
If you use a reference of say 5V than your analogRead(...) calls will return a 10 bit number where 0 stands for 0V and 1023 stands for 5V.
Second, the AREF pin is there for that purpose: feed your 2.5V reference to that pin and use:
analogReference(EXTERNAL);
analogRead(...);

when you want to read using the 2.5V reference (0 stands for 0V and 1023 stands for 2.5V in this case), or
analogReference(DEFAULT);
analogRead(...);

when you want to read using the 5V reference (supposing your Arduino is powered by 5V).
UPDATE
Nothing can be done at the exact same time on an Arduino/ATmega328 because it has one single processing unit. In case of analog to digital conversion you can not even perform two conversions on two pins too fast because you have only one ADC which is multiplexed (shared) among all the analog pins.
You have no choice to perform one reading, wait, then perform the other reading. You can change the voltage reference between the two conversions though, but you need to ensure the internal ADC capacitor is properly discharged: if you read a 5V line and then read a 2.5V line without discharging the internal ADC you are more than probably going to always read the maximum value.
How long you will have to wait depends on the impedance of the line you are sampling: higher the impedance, longer the time you have to wait for the ADMUX capacitor to discharge/charge up (Arduino/ATmega328 ADC is a store and sample comparator).

But how? In the ADMUX, one pin needs to be configured to 5V and other is configured to 2.5, and I need to do the conversion at the same time. And also I need the code in AVR.

Are you using the ATmega328 internal ADMUX or an external component? In case it's an exaternal component, which is the EXACT part number?

If you have a 2.5 V reference connected to the AREF pin, then calling analogReference(DEFAULT) will short that to +5V, possibly destroying your voltage reference or the Arduino. C.f. the warning in the documentation of analogReference().

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


text:
Arduino chip family
This is a very basic question but I cannot find answer for this. I have a couple of Arduino Nano boards lying with me. With keen scrutinizing I found that a few chips on board where numbered as Atmega 328P-AU 1645 and some were numbered Atmega 328P-AU 1644. Can somebody please tell me the difference the number after AU makes ? I know the difference between an AU and PU chip.

Looks to me like a date code: YYWW, where YY are the last two digits of the year and WW is the ISO week number.

I hope it has got nothing to do with functionality and is only a sort of batch number.

They were made one week apart. That is the only difference.


text:
Can I make delayMicroseconds more accurate?
I'm trying to bit bang DMX data and that requires 4us pulses. Not having much luck with the results I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.
Here's a quick little test I did:
unsigned long ptime;

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

void loop() {
  ptime = micros();
  delayMicroseconds(4);
  Serial.println(micros() - ptime);

  delay(1000); //just to keep the serial monitor from going nuts
}

And the results:

8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

I was kinda shocked at just how bad it's accuracy is. It's double the time I wanted to delay, but it's not even consistent to where I could just divide by 2!
Is there anything I can do to get correct, consistent results?

Why are you bit-banging instead of accessing the UART directly?

So I can have more than one output.

The Mega has four UARTs. Even if you hold one permanently for programming that still gives you three universes.

I'm just testing with the mega because that's what I currently have available, the final project will have an ATMEGA328

The ATmega328PB has two UARTs.

Also, bit-banging more than one serial port, especially at 250kbps, needs more grunt than any AVR has.

micros() has a resolution of four microseconds.

The problem here is how you measure.

As explained in the previous answers, your actual problem is not the
accuracy of delayMicroseconds(), but rather the resolution of
micros().
However, to answer your actual question, there is a more accurate
alternative to delayMicroseconds(): the function _delay_us() from
the AVR-libc is cycle-accurate and, for example
_delay_us(1.125);

does exactly what it says. The main caveat is that the argument has to
be a compile-time constant. You have to #include <util/delay.h> in
order to have access to this function.
Note also that you have to block the interrupts if you want any kind of
accurate delay.
Edit: As an example, if I were to generate a 4 µs pulse on PD2
(pin 19 on the Mega), I would proceed as follows. First, notice that the
following code
noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

makes a 0.125 µs long pulse (2 CPU cycles), because that's the
time it takes to execute the instruction that sets the port LOW. Then,
just add the missing time in a delay:
noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
_delay_us(3.875);
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

and you have a cycle-accurate pulse width. It is worth noting that this
cannot be achieved with digitalWrite(), as a call to this function
takes about 5 µs.

Your test results are misleading.  delayMicroseconds() actually delays fairly precisely (for delays of more than 2 or 3 microseconds).  You can examine its source code in file /usr/share/arduino/hardware/arduino/cores/arduino/wiring.c (on a Linux system; or on some similar path on other systems).
However, the resolution of micros() is four microseconds. (See, eg, the garretlab page about micros().) Hence, you will never see a reading between 4 microseconds and 8 microseconds.  The actual delay might be just a few cycles over 4 microseconds, but your code will report it as 8.
Try doing 10 or 20 delayMicroseconds(4); calls in a row (by duplicating the code, not by using a loop) and then report the result of  micros().

With 10 delays of 4 I'm getting a mixture of 32's and 28's... but 4*10 = 40.

What do you get with, say, 10 delays of 5 ?  :)  Also note, for bitbanging you might need to use fairly direct port accesses, ie, not digitalWrite(), which takes several microseconds to execute.

40 & 44... But shouldn't it be rounding up? What am I missing here?

By  “rounding up” do you mean delayMicroseconds() ? I don't see that as any better than rounding down.  ¶  Regarding the source of inaccuracy, if the routine gets inlined then timing depends on surrounding code.  You could read assembly or disassembly listings to see.  (See  “Making assembly listings” section in my answer to question Equivalent for PORTB in Arduino Mega 2560, which may anyway be relevant to your bitbanging project

I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.

micros() has a well-documented resolution of 4 µs.
You could improve the resolution by changing the prescaler for Timer 0 (of course that throws out the figures, but you can compensate for that).
Alternatively use Timer 1 or Timer 2 with a prescaler of 1, which gives you a resolution of 62.5 ns.

 Serial.begin(9600);

That's going to be slow anyway.

8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

Your output is exactly consistent with the 4 µs resolution of micros() coupled with the fact that sometimes you would get two "ticks" and sometimes one, depending on exactly when you started the timing.

Your code is an interesting example of measurement error. delayMicroseconds(4); will delay for close to 4 µs. However your attempts to measure it are at fault.
Also, if an interrupt occurs then it will stretch the interval a bit. You need to turn interrupts off if you want an exact delay.

When measured with an oscilloscope, I found that:
delayMicroseconds(0) = delayMicroseconds(1) = 4 μs real delay.
So, if you want a 35 μs delay you need:
delayMicroseconds(31);

Is there anything I can do to get correct, consistent results?

The Arduino implementation is quite generic thus may not be as effective in some applications. There are a few ways for short delays, each with its own shortfalls.

Use nop. Each is one instruction so 16th of a us.
Use tcnt0 directly. Each is 4us as the prescaler is set to 64. You can change the prescaker to achieve 16th us resolution.
Use ticks, you can implement a clone of systick and use it as basis of the delay. It offers finer resolution plus accuracy.

edit:
I used the following block to time the various approaches:
time0=TCNT0;
delay4us();             //65
//t0delayus(4*16);          //77
//_delay_us(4);             //65
//delayMicroseconds(4);     //45
time1=TCNT0 - time0;        //64 expected

before that, I had reset the timer0 prescaler to 1:1 so each TCNT0 tick is 1/16th of a microsecond.

delay4us() is built up from NOP(); it produced a delay of 65 ticks, or just over 4us;
t0delayus() is built up from timer0 delays. it produced a delay of 77 ticks; slightly worse than delay4us()
_delay_us() is a gcc-avr function. performance on par with delay4us();
delayMicroseconds() produced a delay of 45 ticks. the way arduino implemented its timing functions, it tends to under-count, unless in an environment with other interrupts.

hope it helps.

Note that the expected result is 65 ticks, not 64, because reading TCNT0 takes 1 CPU cycle.


text:
Save highlighted text as int variable
I build a macro keyboard and one thing I do alot is add a set amount to numbers mostly in 3d modeling programs. I add and remove 0.25 and 0.125 all the time. I want to make a macro that copies selected text, adds or subtracts a value then pastes it back.
I known the simple copy and paste commands but how do I get my arduino program to grab that copied value?
Can this even be done?

What keys does it have, what is the current sketch (or related parts),  how is text selected, can it handle multiple keys simultaneously? I miss the actual requirements and current code you have.

My keyboard has 9 keys and mutable modes I can put it in for different programs. How I want it to work is I select text on my screen its normal an z x or y I need to move by a set amount. I push one key on the arduino macro keyboard and it copies that text imports it as an int adds or subtracts the needed amount then pastes the edited value back.

You can't. A keyboard is a one-way device.

"Can this even be done?" Not without help from the PC side.  It's not like the clipboard stored in the keyboard.  And there are no scan/codes or USB-HID messages that will cause the host to send a copy of the clipboard to the device.

You have to write an application for your PC that

reads a number from the clipboard
adds some constant
puts the result back in the clipboard
quits

Then you have to configure you desktop environment in order to have this
application launched from a keyboard shortcut.
Once you have done that, you can do the whole operation from a regular
keyboard: Ctrl-C + Launcher shortcut + Ctrl-V.
If you can do it from a regular keyboard, you can do it from the Arduino
emulating a regular keyboard.
Edit: The way you do the first two steps is very dependent on the OS
running on your PC. On Linux, for example, the mentioned “application”
can be a minimal shell script:
#!/bin/bash

x=$(xclip -o -selection clipboard)
xclip -i -selection clipboard <<< $(bc <<< "$x + 0.25")

These steps are, however, outside the scope of this site.

I guess I will see if I can make a blender plugin that does what I want and just have it bind to a key combo I can have they macro keyboard do

Well, as long as we're just doing tech support: For what it's worth, in Blender you can click into the number, hit END and type +0.25 and ENTER or whatever other expression you want to do, * pi or / 2 etc.


text:
Arduino due temperature reading shows random temperatures
I am using an Arduino Due board to read three temperatures from three separate smt160-30 digital sensors but the program is behaving very randomly. the code I am using is one I got from arduino official site and changed the structure to get three temp readings and display them on a 16x2 lcd. The problem is when I use one sensor the output is reasonable but when I use all three the temperature showing are all off by 4 degrees. also I tried removing the line lcd.print(temperature1, 1) and the output temperatures changed. Is this odd behavior because of SRAM issues ? if so how can I find out about it and fix it ?
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

unsigned long now;
unsigned long lastSample;
unsigned int sampleSize;

unsigned int highCount1;
unsigned int highCount2;
unsigned int highCount3;

unsigned long lastOutput;

float temperature1;
float temperature2;
float temperature3;
float hcf1, hcf2, hcf3;
float ssf;

int sensorPin1 = 23;
int sensorPin2 = 24;
int sensorPin3 = 26;

void setup(){

    pinMode(sensorPin1, INPUT);
    pinMode(sensorPin2, INPUT);
    pinMode(sensorPin3, INPUT);

    digitalWrite(sensorPin1, LOW);
    digitalWrite(sensorPin2, LOW);
    digitalWrite(sensorPin3, LOW);

    lastSample = 0;
    sampleSize = 0;

    highCount1 = 0;
    highCount2 = 0;
    highCount3 = 0;

    temperature1 = 0;
    temperature2 = 0;
    temperature3 = 0;

    lastOutput = 0;

    delay(2000);
    lcd.setCursor(0, 0);

}

void loop() {
    now = micros();
    if (now - lastOutput > 3000000) {
        lcd.clear();

        hcf1 = highCount1;
        hcf2 = highCount2;
        hcf3 = highCount3;

        ssf = sampleSize;

        temperature1 = ((hcf1 / ssf) -0.32)/0.0047;
        temperature2 = ((hcf2 / ssf) -0.32)/0.0047;
        temperature3 = ((hcf3 / ssf) -0.32)/0.0047;

        lastOutput = now;
        sampleSize = 0;

        highCount1 = 0;
        highCount2 = 0;
        highCount3 = 0;

        lcd.print(temperature1, 1);
        lcd.print(" ");

        lcd.print(temperature2, 1);
        lcd.print(" ");

        lcd.print(temperature3, 1);

    }
    if (now - lastSample > 50) {
        sampleSize++;
        highCount1 = highCount1 + digitalRead(sensorPin1);
        highCount2 = highCount2 + digitalRead(sensorPin2);
        highCount3 = highCount3 + digitalRead(sensorPin3);
        lastSample = now;
    } else {
        delayMicroseconds(10);
    }
}

Thank you!

Did you read about this smt160 sensor ? It relies on the calculation of duty cycle of the square wave output from the sensor, to calculate the temparature.

temperature = (dutyCycle) -0.32)/0.0047

The square wave output has to be sampled at 8KHz or at 125us for no loss of information. This block samples that data.

if (now - lastSample > 50) {
sampleSize++;
highCount1 = highCount1 + digitalRead(sensorPin1);
highCount2 = highCount2 + digitalRead(sensorPin2);
highCount3 = highCount3 + digitalRead(sensorPin3);
lastSample = now;
      }
else {
          delayMicroseconds(10);
      }

when you increased the number of code lines , information loss also increased, cz more number of instructions have to be executed now , till reaching the corresponding digital reads.

So if I put it in a for loop to guarantee the needed sample it should work right ? is there better way to do this ? thank you for responding

I don't think so. This is already running in loop under void loop(). So It may still have the same problem.

One solution is to shift the start of sampling of three sensors. Divide the time frame into 3 parts. First time frame only for sampling and displaying the temp of sensor 1, second one only for second sensor, first sensor would be idle. Like that. But the temperature update interval will increase.

I don't understand how to divide it into different time frames. Is it possible to create a function for getting temperature and call it three times for each sensor ? if so how do I write the function where is the exit point of it ?

You have to code some logic using if conditions and  a variable to keep track of time passed. Based on the value of that variable , call functions for processing sensor 1, 2 or 3.

I ran the code for 1 sensor without any adding additional code and the temp seemed to be stable and pretty accurate with a sampleSize of 31600 so I wrote this function with 31600 sample rate with 10 microsecond intervals and it does work can I just go with this ?

float GetTemp(int pinN){
for(int i =0; i < 31600; i++){
highDuration = highDuration + digitalRead(pinN);
delayMicroseconds(50);
}
hcf = highDuration;
dutyCycle = highDuration / (float) 31600;
temp = (dutyCycle - 0.32)/0.0047;
highDuration = 0;
return temp;
}

yea if this worked, you can write the same function for the next two sensors too...And just call this function one by one from the main code


text:
How to move Servo in between three positions
I want my tower pro 9g servo to start from pos=0, wait there for 1 second, then reach pos=90 wait for 1 second, then reach pos=180 and wait for 1 second. Now it goes back to pos=0 and repeats this cycle. I have written the following code for this purpose:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(12);  // attaches the servo on pin 9 to the servo object
}

void loop() {

  for (pos = 0; pos <= 180; pos += 90) { // goes from 0 degrees to 180 degrees
    // in steps of 90 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

  for (pos = 180; pos >= 0; pos -= 90) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

}

But the behavior of the servo is not correct. It moves few degree from  initial position and then comes back.
What is wrong with the logic in my code ?

remove the second for loop ... the first loop already does what you want

The logic looks OK to me. But be aware that these servos don't perform well at or close to their limits - mine tend to jitter there but there may be other issues as well. I have 10 of these hobby servos; each has a different jitter-band at the ends of its travel. You may have better success driving them to 10, 90, and 170 degrees.

I think that the servo is too slow. When you ask it to go 90 degrees it starts, than after one second (while it maybe reaches 5 degrees) you ask it to go to 180 degrees it is probably reaching 10 degrees. There it waits again one second.
Than you ask it to go back to 0 (which it does in the same 2 seconds as it moved from 0 to 10 degrees).
Try to adjust the delay times, or use a faster servo.
Also note that in your example (if you wish it would behave like coded), it will end 2 seconds at 0 and 180 degrees, and 1 second at 90 degrees).
Try:
void move_servo(int pos)
{
    myservo.write(pos);
    delay(30000);
}

void loop()
{
    move_servo(  0);
    move_servo( 90);
    move_servo(180);
    move_servo( 90);
}

It will wait 30 seconds between each step, make this less when possible.
To make the servo wait not more than needed, check the old and new servo position and wait as needed, it's probably reasonably linear.


text:
Http Client requests
I am working on a project where the ESP 8266 sends a very long string about 3000 chas over http as client. Likewise sensor data are determined. The loop repeats itself every 250ms. Now I noticed that my server gets the data of the ESP often slower. In rare cases it takes up to a minute until the server receives something.
How do these delays occur and why are they not constantly the same?
Does the length of the string have something to do with it or how much does it affect the delay?
Are calculation and sensors processed only after sending?
The ESP works with this function.
String http_GET(String value){
  String payload = "non_Message";
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
    //WiFiClient client;
    HTTPClient http;  //Declare an object of class HTTPClient
    String send_data = "http://" + web_conect + value;
    //http.begin(client, send_data);
    http.begin(send_data);
    //http.begin("http://" + address + ":" + port + "/" + path +"?" + param + "=" + value);  //Specify request destination
    int httpCode = http.GET();                                  //Send the request

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

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

    }

    http.end();   //Close connection

  }
  return payload;
}

I suspect it could be Strings fragmenting your heap, making it take longer to find free slots as time goes on. Don't use String for long-running or repeatedly-running operations. Take the String usage out and see if it stop slowing down, if so, you found the problem.

I tried it once. Unfortunately, the problem is still there. For me it is not bad, but I would still be interested where these delays come from.


text:
Arduino Yun not getting response from Azure API
I posted this on StackOverflow but figured I'd post it here too. Sorry in advance if thats not allowed.
I'm trying to get my Arduino Yun to talk to an API that I'm hosting on Azure. I would like to do more complex things in the future, but at the moment I'm just trying to make a GET request over wifi with a single integer as a parameter.
I'm basically just using the example found here with the url changed. The example works fine, so as far as I'm aware the issue isn't with my board, its with the interaction with Azure.
HttpClient.get() returns an int as a response (not the regular HTTP response codes, its unique for the library). I got 60 initially, and changing my API to accept http calls (instead of just https) fixed this and made me get a response of 0 instead. 0 is the same response that I get from the working Arduino example, but for some reason I'm not actually getting anything in the body of my response, as the client.available() loop is never entered.
The API works as intended when I go to the url in chrome, so the issue arises somewhere due to how the arduino and azure talk to each other, but I don't know enough about either to figure it out and nowhere that I look seems to point me in the right direction.
Any help would be greatly appreciated, thanks.

Found the problem, even though I set azure to accept http requests, it was still redirecting to https which the arduino couldn't handle. I've written a python script to offload the requests to the linux processor, and now it works.


text:
Getting 0 cm from ultrasonic sensor when nothing is in front
My Ultra sonic sensor (HC-SR04) is returning these types of values when it has nothing in front:
Ping: 144cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 105cm
Ping: 105cm
Ping: 94cm
Ping: 0cm
Ping: 378cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 106cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 250cm
Ping: 0cm
Ping: 108cm
Ping: 0cm
Ping: 108cm
Ping: 0cm

I am not able to understand why I am getting 0 cm. This value is critical in the program that I am using. Here is a test code which gives me these output:
#include <NewPing.h>

#define TRIGGER_PIN  A5
#define ECHO_PIN     A4
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN);

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

void loop() {
  delay(1000);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Because  of these 0s my robot is making turns which are not expected.
Any idea why this might happen ?

The documentation for the NewPing library states:

Constructor
NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);

and

max_cm_distance is optional [default = 500cm].

Then:

sonar.ping_cm(); - Send a ping, returns the distance in centimeters or
  0 (zero) if no ping echo within set distance limit

So it would seem that if there is nothing in front of your sensor closer than 500cm, this library returns 0cm. Probably not the best design, but at least it is disclosed.
Thus, you need to write your code such that a 0cm measurement is treated as no obstruction visible; more like an infinite cm measurement.

The library defines NO_ECHO as 0 so you check sonar.ping_cm() == NO_ECHO for clarity.


text:
Arduino Micro draws too much power from iPhone. How can I change that?
I'm building a USB keyboard that has two buttons - space and enter. The plan is to use this USB keyboard (with an Apple Lightning connector to USB) with the built in iOS switch control. I bought the lightning to USB dongle, and hooked it up to a normal keyboard, and it works fine.
Next, I took an Arduino Micro (ATMEGA32u4) and programed it to act as a keyboard with the two keys I need (space and enter). On a PC, it works just fine, but when I hook it up to my iPhone, I get the message:
Arduino Micro: The connected device requires too much power.

I've done quite a bit of research on this, and I found this post. In a nutshell, that post said that when you connect a device to an iOS device, one of the first things it does is tell the iDevice how much current it could potentially draw. This number (about 200mA for the Arduino Micro) is what decides whether the iDevice will support the device or not, when in truth, the device will not come close to its max current draw, at least not in my case.
I hooked up a meter to the normal keyboard, and it draws just over 4mA. When I hook up the Arduino, it is drawing almost 40mA. While the Arduino is drawing much more than the keyboard, it should be okay, because when I plugged in a flash drive, it was drawing 50mA, but the iPhone didn't complain.
There is my story, here is my question:
Is there any way to change it so that the Arduino Micro doesn't request so much power? In other words, is there a way to reset the value that is causing the iPhone to not use the device?

do not use an arduino for this ..... take apart a regular USB keyboard ..... discard the switches and install a couple of push buttons to replace the two keys

Did you get this to work? I am working on a keyboard I need to connect to iPhone and I can't get it to work. Please help

The power consumption is part of the exchange with the PC when it is plugged in. You can change that. Find the file USBCore.h in your Arduino install directory. In my case (under Linux) it was:
./hardware/arduino/avr/cores/arduino/USBCore.h

Inside that file, at around line 269 (depending on the distribution) you should see these lines:
#define D_CONFIG(_totalLength,_interfaces) \
    { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

On the right of the second line is the requested power consumption in milliamps (currently 500). Change that to (say) 100:
That is, change USB_CONFIG_POWER_MA(500) to USB_CONFIG_POWER_MA(100).
Save and recompile.
You may find that the bootloader initially requests 500 mA even with this change (as it initially runs the bootloader). However when the sketch starts it should re-establish a USB connection and only request 100 mA. To fix that you would need to recompile the bootloader with the same fix, and reinstall it, a somewhat more complex task.
Another possible approach would be to tweak the fuses so that it doesn't run the bootloader, if you have finished debugging your code. Only do that if you are confident with playing with the fuses.

Majenko beat me to it while I was testing my answer. :)

I have a simple Arduino keyboard and it works great on all other devices then iPhone. Did you guys get this to work on iPhone?

@ErikAndershed This sounds like a new question to me. Feel free to make one.

Yes, but it requires manual modification of the Arduino core software.

Find the file USBCore.h within your AVR boards installation (it could be in the data storage folder wherever that is on your OS, or within the actual IDE software)
Look for the line #define D_CONFIG(_totalLength,_interfaces) \
The next line has the power setting.  Change USB_CONFIG_POWER_MA(500) to what you require (for example USB_CONFIG_POWER_MA(50)

I did test with 50. But it do not work. When I plug it in to my iPhone with a adapter (from usb-c to lighting and it’s supports both power and data). My Arduino chip don’t wake up. Did you get this to work?


text:
What are the correct techniques for implementing functional client access to an asynchronous serial interface?
This is not a question for beginners.
I am implementing a functional interface to an asynchronous serial device connected to the Serial1 port on a mega.
To ensure clarity, I want to implement a series of functions thus:
    {param} CallInterface({param1},{param2},...) {
        sendRequestPacket();
        ....{await Response or timeout}....
        return Response;
     }

Obviously, when "awaiting Response" we are blocking the operational thread and have to allow an additional thread processor access in order to retrieve and parse the response.
On a multithreaded platform, this would be trivial to implement using semaphores and other multi-threading techniques, but on Arduino,AVR the solution is possibly less obvious, or not.
So, the question is, what is the best and most effective way to implement a pattern such as this on the Arduino platform?

Obviously, when "awaiting Response" we are blocking the operational thread ... actually, that is not obvious ... you could use non-blocking code

It's hard to tell what's the “best and most effective” without knowing the exact requirements of your project. I once faced a similar situation when I needed my code to be non-blocking. I then added a “callback” parameter to CallInterface, to which the response is to be delivered, and an update() method to the object implementing the interface, in order for it to catch the response and deliver it to the callback.

@jsotola can you please follow this up with an example of a non-blocking code pattern That would work on the Arduino platform?

@EdgarBonet Thanks Edgar, yes this is a similar model to Async Javascript / Node. Initial impressions are that I would need to implement a callback array in the receiver code to capture any and all potential requests for this data that need to be fulfilled when and if the response arrives. The only issue I foresee with this is that there is no "linkage" between the request and response other than the fact that the response happens soon after the request.

There is no way of linking a specific request with a specific response other than to block requests until all pending requests are fulfilled, or a timeout occurs.

one of the parameters of the call can be forwarded to the callback. or with lambdas you can capture parameters

The typical way I handle this kind of thing is to have one "master" function that controls everything using a finite state machine in a non-blocking way.
That function could contain all the logic to do things, or it could be simpler and just handle the basic communication and then pass details on to a callback function that is specified in the action function call.
So the flow could be:

You call a function that just sets up things:

It stores details of the request to be made
It records the address of a "callback" function

You execute your "run" function repeatedly from loop()

It sends the command to the target
It receives and parses the response storing it internally somewhere
When the response is complete it executes the callback function passing it the response

Not all of 2 would happen each iteration of loop(), so write it in a non-blocking way (using .available() etc) and only call the callback when everything is complete.
So in that way you can set up a chain of things to happen:

You submit request 1 with callback A.
Callback A submits request 2 with callback B.
Callback B submits request 3 with callback C.

... etc ...
As an example this is how a modem control could look:
Modem.command("AT+CREG?", testRegistration);
>>> send         AT+CREG?
<<< store        +CREG: 0,2
<<< store
<<< identify     OK
--- Execute testRegistration(true, "+CREG: 0,2\n\n");

Or maybe if it goes wrong:
Modem.command("AT+CROG?", testRegistration); // Oops, made a typo...
>>> send         AT+CROG?
<<< identify     ERR
--- Execute testRegistration(false, "");


text:
Midi Timecode Fails to Send
I have an ATMEGA 2560 platform running HIDUINO and a sketch based on the stock MIDI library. I'm intending to use it to convert Linear Timecode (LTC) to MTC. Got a long way through the project - LTC decoding working fine, timer configuration OK, and Midi output working fine. It's just that as soon as I try and generate MTC messages, they are being dropped before they land on the computer USB interface.
Equipment to hand: Macbook Pro running El Cap/Reaper and Protools., ATMEGA2560 MEGA R3 (With 16u2 for HIDUINO) and small audio interface circuit.
Using Timer 4 for LTC Decoding and Timer 5 for MTC generation (4 messages per LTC Frame).
Midi Monitor on the OSX box.
Sees Note on/Note off packets quite happily, but no MTC messages are registering.
I do note the TX LED is active during MTC Message generation, indicating that the sketch is actually generating messages and sending them to the 16u2 chip.
Specifically, my question is how do I get the MTC messages through HIDUINO into the computer?
https://pastebin.com/pAXyq04s

The code should be included inside the post, not via a link.

The HIDUINO library supports only some MIDI message correctly; most System Common and System Real-Time message are buggy, and SysEx messages are not handled at all.
Try some other library, e.g., mocoLUFA.

Already there. sysEx much better in mocoLUFA but still no System Common. Working on modding mocoLUFA as we speak.

If you clone my fork of the code, I have got this working.
https://github.com/mwr9uk/mocolufa
I have generated a pull request to merge it with mainline.

Is this really an answer?  Please add some more explanation

Yes. The OP experienced the problem of MTC messages not being passed through Hiduino. A subsequent poster suggested using MocoLUFA which also doesn't pass System Common messages, including MTC. I have added that support in a fork in the code of MocoLUFA as I needed it too. This will solve the OP's problem.


text:
Change Arduino Clock Speed
I want to run an arduino board at a slower - but more accurate - clock speed. What (if anything) needs to be changed in the arduino code/libraries in order to achieve this? Normally the boards I use run at 16MHz, but I wish to derive a 10MHz clock from a GPS timing module and run the ATMEL processor off the 10MHz timing clock.

What kind of timing facilities do you need? Would millis() be enough? Would you need micros() or delay() as well? millis() could be easily reimplemented on top of Timer 1, if you can spare it for this use. Depending on your needs, you could also have single-cycle timing resolution by taping directly on the hardware timers.

You have to change F_CPU only - You can add new board into the boards.txt with correct clock speed.
EDIT: Aparently millis counter will be drifting much more then expected due to "rounding" errors.
The bootloader on the other side needs to be recompiled with correct F_CPU and  reflashed, if you want it working at the same baud rate (plus it's possible to change fuses to use external clock source instead of crystal). Otherwise you have to try reduced speed (also configured in board config).
You can use MCUdude/MiniCore as inspiration. It supports many clock speeds (but 10MHz doesn't)

Note that all the timing functions will be off, as the implementation of millis() relies on some arithmetic that does not work well for arbitrary clock speeds. See this comment in the source: “for the clock speeds we care about - 8 and 16 MHz - this doesn't lose precision.” Since the OP seems to care about accuracy, this could be a deal breaker.

Looking at that source code, it turns out that, with F_CPU set at 10 MHz, millis() will assume a frequency of 512/51 ≈ 10.039 MHz. It will then run about 3900 ppm slow, which is a huge error: more than 5 min/day.

@EdgarBonet I'm not sure about this, but ISR handler is adding 1ms and 638us every interrupt instead of 1ms and 638.4us (those values are counted from F_CPU). Somehow it gives me about 21.1s every day:  (1 - (1/0.0016384)*0.001638) * 24* 3600. But maybe I'm calculating this completely wrong.

Okay, I've missed that bitshift... Well, then it will be much worst (337.5s)


text:
How can I wire a 12V LED switch so that it is powered, but my Arduino only receives a 5V signal?
My arduino is powered by 12V.  I am getting some cool looking 12V led switches from amazon, but they need 12 volts to light up. My arduino will perform an override function when it detects the switch is closed. the digital pins can only handle 5V. How can I step down the 12V signal that powers the switch to the 5V that the pin can handle.
12V supply -> 12V led switch -> reduce 12V to 5V -> arduino digital pin

What is a "12V led switch"?

Could you provide a link to the switch in question, please? Depending on how it's made, you may not need to do anything.

you can power the switch's LED with only 5v, it will be dimmer but should work.

You need a voltage divider:
The formula is:
V1 = 12V
R2 = 5V max
R1 = The rest (V1-R2)
And then you have to calculate max current. If you use 1/4watt resistors, you have to convert watt to current, P = U x I.
Pmax = 0,25W
R1volt = 7 volt
Imax for R1 = P/U = 0.25/7
Imax for R2= P/U = 0.25/5
Now you have the current and voltage for R1 and R2
And the relation between R1 and R2 is:
R1 = 7/12 x Rtotal
R2 = 5/12 x Rtotal
Rtotal = R1 + R2

simulate this circuit – Schematic created using CircuitLab


text:
How to keep a 24 hour maximum and minimum temperature
I am keeping a simple weather station to monitor humidity and temperature in my greenhouse. I have a ds18b20 and dht probes.  everything works great and I even used a little trick to hold my maximum and minimum values, but I would like them to reset every 24 hours. Is there anyway i can code the arduino to reset itself. i tried several examples of connecting digital pins to the reset pin and i couldn't get any of those to work.  i tried to reset the values of my max and min to 0 and 99 respectively after my millis() reached the equivalent of a day, but they just stuck at 0 and 999. I understand fully why it does this i just don't know how to fix it. all i want to do is reset my minimum and maximum temperatures after 24 hours.
//       Green HAUS Version 1 by Kent Scipione 9/3/2017
//       Monitors temperature and humidity
long timenow;
long day = 86400000; // 86400000 milliseconds in a day
long hour = 3600000; // 3600000 milliseconds in an hour
long minute = 60000; // 60000 milliseconds in a minute
long second =  1000; // 1000 milliseconds in a second

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
#define ONE_WIRE_BUS 10
double temp;  // sensor is precise to .1 degree.
//Double gives smoother serial graph, byte doesn't overflow oled screen
Adafruit_SSD1306 display(OLED_RESET);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#include <Adafruit_Sensor.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

int maxtemp=0;
int mintemp=999;

void setup() {

  Serial.begin(9600);
  Serial.println("green HAUS Version 1 by Kent Scipione 9/3/2017");
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  display.setTextColor(WHITE);
  sensors.begin();
  dht.begin();

}

void loop() {
  timenow = millis();
  sensors.requestTemperatures();
  temp = sensors.getTempFByIndex(0);
  int humid = dht.readHumidity();
  float dtemp = dht.readTemperature(true);
  if (temp > maxtemp) {
    maxtemp=temp; }
  if (temp < mintemp) {
    mintemp=temp; }

  if (timenow >= day){
      digitalWrite(4, HIGH);
      pinMode(4, OUTPUT);       //*************************this is the part where I'm trying to reset the mintemp and maxtemp**********

    }

  Serial.print("Probe Temperature: ");
  Serial.println(temp); Serial.println("*F");
  display.setCursor(0,0);  //refreshes display
  display.clearDisplay();
  display.setTextSize(1); display.print("Probe "); display.println(temp);  //line 1 of text
  display.print("DHT  "); display.print(dtemp); display.print("  "); display.print(humid); display.println(" %");  //line 2 of text
  display.print("HIGH "); display.println(maxtemp);           //line 3 of text
  display.print("LOW  "); display.println(mintemp);   //line 4 of text
  display.display();

}

Thank you so much for your help this is driving me mad haha

At first glance, a small typo in your reset section -- you have set the pinMode to OUTPUT after you try to write. You should call pinMode() before you try to call digitalWrite().

if(millis()>day) ...

Consider using #define for your constants day,hour, minutes, seconds rather than variables. While on the subject.... if you're not going to keep decimals for your temperatures then you can use byte (or unsigned byte depending on if you'd ever have negative degrees F) rather than int for your min,max and current temperatures saving a few more bytes. Finally dtemp isn't used so you can delete that line.

You should also keep a timestamp of the last time you reset the min and max otherwise the arduino will keep thinking it's a new day:
//add to globals
unsigned long lastDay = 0;

and inside loop()
  if (timenow-lastday >= day){

      maxtemp=0;
      mintemp=999;
      lastDay = timenow;
  }

unsigned long. long will fail after about 25 days.

But when it rolls over it will still work correctly so it doesn't matter that much

You'll find unsigned long rolls over ok when compared to another unsigned long that's rolled over. A signed long won't when compared to an unsigned long in the >= comparison in the if loop.


text:
Integer array definitions: Length
I'm defining a variable as integer and want to use thati
int specLength = 17;
int spec[specLength-1];

When I do this, I get the following error message:
 TestProgram:34: error: array bound is not an integer constant before  ']' token
 int spec[specLength-1];

But when I set it up as
int specLength = 17;
int spec[16];

it all works fine.
What is the magic here?
Many thanks


text:
Speed measurement from lidar sensor for automatic braking system
For a school project I have been working on a system that will automatically brake when there is danger. Only the requirements are more strict (safety) than just using a ping sensor and detecting a fixed distance. I am going to implement the speed of an incoming object a swell.
On the internet I found this awesome 100Hz sample Lidar module that's very cheap. It uses UART with 2 header frames (0x59), after that a data Lowbyte and a data Highbyte.
So I've started inputting coffee and outputting code (in C) on the atmega328P (Arduino). Only I'm stuck for a few days now.
As you can see here I've set up the code to read the sensor and process the data. The problem is that it gives back weird readings, like a distance difference when I'm moving further away AND when moving closer even though I stated it not to.
Does anyone have experience using this module? Or maybe I misread something of the datasheet.
//Includes
//============================================================================================//
#include <avr/io.h>
#include <avr/interrupt.h>
#include <math.h>
//============================================================================================//

//Defines
//============================================================================================//
#define F_CPU 16000000                                          //CPU frequency
#define Baudrate 115200                                         //UART Baudrate
#define UBRR_VALUE (((F_CPU / (Baudrate * 8))) - 1)             //UART Baudrate set in Arduino
// #define SafetyRating 8
// #define sampleTime 0x65                                          //Time between 2 samples in 10^-4. This value comes from testing (its 1,01ms)
//============================================================================================//

//Enums
//============================================================================================//
enum {Safe, Warning, Danger}State;                              //Possible States
//============================================================================================//

//Global variables
//============================================================================================//
uint8_t distanceL;                                              //Distance (low value) data taken from the UART buffer coming from Lidar
uint8_t distanceH;                                              //Distance (high value) data taken from the UART buffer coming from Lidar
uint16_t Distance;                                              //Distance combined
uint8_t frameByteCount = 0;                                     //To count which byte in the frame is current
uint16_t Speed;                                                 //Speed variable
//volatile uint8_t DangerLevel;                                 //Danger indicator

//Function prototypes
//============================================================================================//
void calcSpeed(uint16_t Measurement);                       //Function to calculate the speed out of distance readings
void UART_Transmit(uint8_t data);                               //Funtion to send data via uart
//============================================================================================//

//Interrupts
//============================================================================================//
/*UART receive complete interrupt*/
ISR(USART_RX_vect)                                              //Data taken from the UART buffer
{
    uint8_t sample;

    sample = UDR0;                                              //Read a sample from the receiver buffer

    if(frameByteCount == 3)                                     //If its the 4th byte of the frame
    {
        frameByteCount = 0;                                     //Reset the counter
        distanceH = sample;                                     //Read the distance data high byte
        Distance = (8 << distanceH);                            //Combine the data low and data high
        Distance |= distanceL;

        calcSpeed(Distance);                                //Send the data to laptop for debugging purposes

    }

    if(frameByteCount == 2)                                     //If its the 3rd byte in the frame read the distance data low byte
    {
        distanceL = sample;
        frameByteCount++;                                       //Increment the counter
    }

    if (sample == 0x59)                                         //If a sample is a header increment a counter
    {
        frameByteCount++;
    }
    else if (frameByteCount != 2 && frameByteCount != 3)        //If its not a header or distance data byte reset counter
    {
        frameByteCount = 0;
    }
}
//============================================================================================//

//Timers and Counters
//============================================================================================//
/*Timer0 Counter, this decreases the danger level periodically so a really slow approach will not keep incrementing the danger level*/
ISR(TIMER0_OVF_vect)
{
//  if (DangerLevel > 0)
//  {
//      DangerLevel--;
//  }
}
//============================================================================================//

//Main
//============================================================================================//
int main(void)
{
    DDRB    |=      0x02;                                       //For debugging purposes LED pin PB1 (pin 9) as output

    UBRR0H = (UBRR_VALUE >> 8);                                 //Setting the Baudrate register high value
    UBRR0L =  UBRR_VALUE;                                       //Setting the Baudrate register low value
    UCSR0A |= (1<<U2X0);                                        //Setting the data sample to double speed to make Baudrate error less
    UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00);                        //Initializing UART, setting frame to 8 data bits
    UCSR0B |= (1<<RXCIE0) | (1<<TXEN0) | (1<<RXEN0);            //Setting receiver interrupt enable, transmitter enable and receiver enable... Transmitter for debugging purposes

    TCCR0A = 0x00;                                              //Timer0 Setup
    TCCR0B |= 0x05;                                             //Timer0 clock prescaler to 1024
    TIMSK0 |= 0x01;                                             //Timer0 overflow interrupt enable

    sei();                                                      //Set interrupts

    State = Safe;                                               //Set state to safe

    while (1)
    {
        //checkState(DangerLevel);
    }
}
//============================================================================================//

//Functions
//============================================================================================//
/*Calculate the danger level out of distance readings*/
void calcSpeed(uint16_t Measurement)
{
    static uint8_t samplenumber = 0;                                //Sample tracker
    static uint16_t value0 = 0;                                         //First sample
    static uint16_t value1 = 0;                                         //Second sample

    switch(samplenumber)                                            //To store the measurements alternately
    {
        case 0:
            value0 = Measurement;                                   //Store first measurement
            samplenumber = 1;                                       //So next measurement goes to a different variable
        break;
        case 1:
            value1 = Measurement;                                   //Store 2nd measurement
            samplenumber = 0;                                       //So next measurement goes to a different variable
        break;
        default:
        break;
    }

    if (samplenumber == 0 && value1 < value0)                       //When value0 is first and value1 is second and the object is closing in
    {
        Speed = value0 - value1;
    }
    else if (samplenumber == 1 && value0 < value1)                  //When value1 is first and value0 is second and the object is closing in
    {
        Speed = value1 - value0;
    }
    else
    {
        Speed = 0;
    }
    UART_Transmit(Speed);       //I think sending an uint16_t over uint8_t uart is possible because 'Speed' is never greater than 255 when i'm testing it
}

/*Send data over UART when buffer is empty*/
void UART_Transmit(uint8_t data)
{
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    ;
    /* Put data into buffer, sends the data */
    UDR0 = data;
}
//============================================================================================//

The datasheet for the module: Datasheet Lidar module

I forgot to add the link to datasheet Datasheet Lidar Module

All #defined numbers should be enclosed in brackets to prevent against misunderstandings as a result of precedence rules.  i.e. #define Baudrate (115200)

I found it!
Can't believe I was stuck for two days on this.
Distance = (8 << distanceH);                            //Combine the data low and data high
Distance |= distanceL;

Should be:
Distance = (distanceH << 8);                            //Combine the data low and data high
Distance |= distanceL;

Thanks all for taking the effort, and i'm definately going to do the experiment above to test the accuracy.

I don't know how, because I asked the question with an guest account. And I made an account right after.

I think you are either getting interference that is corrupting the serial data or reflections from the scattering of the light off the object.
If you are certain that your code is right, which it seems to be, then I think you need to ascertain if the unit is giving you constant readings or not.  Can you set up a test that puts the unit at a fixed distance from a reflector and get readings for a minute.  The raw readings should all be identical, absolutely no variation.  They won't be they will waver around a tiny amount so work out what the percentage variation is for this distance.
Now repeat the test but at double the distance, you should get the same accuracy. Now again at double the distance again and you should have the same level of accuracy.
If the accuracy is varying "significantly" then you will need to generate a calibration table.  'At distance x the accuracy is y', etc.
Reflections will give you intermittent wildly inaccurate results. To combat this you might want to filter the data to remove any data that is more than n times the accuracy away from the previous reading.  n has to be a value large enough to cover the maximum distance the reflector (car) can cover in the time between samples.  I would guess assuming a maximum speed of 300MPH would be enough for most cases.


text:
M0 pro: SPI communication, code works on Uno, but not in M0. Using ICSP port
I am trying to establish a communication between a sensor and a M0 -pro using SPI. The code :
    #include <SPI.h>

    unsigned int result  = 0;
    void readAngle();

    void setup() {
      Serial.begin(9600);
      SPI.setBitOrder(MSBFIRST);
      SPI.setClockDivider(SPI_CLOCK_DIV8); //sets the clock speed for data transfer, slowed down 8 times
      SPI.setDataMode (SPI_MODE1);

      digitalWrite(11,HIGH);
      pinMode(11,OUTPUT);

      SPI.begin();
      SerialUSB.println("First Try");
}

    void loop() {
      readAngle();
      SerialUSB.println(result);
      delay(500);

}

    void readAngle(){
        digitalWrite(11,LOW); //Turn SS on, start communication
        result = SPI.transfer16(0xFFFF); // the read command and the response received
        result = (result << 2) >> 2; // get rid of the last 2 bits, error(14) + parity(15)
        digitalWrite(11,HIGH); //Turn SS of

}

The code works perfectly with an UNO, but with M0, it event doesnt print the first SerialUSB.println("First Try");. The moment i erase the lines that have SPI commands in it, the serial monitor starts working again. As i said in the titel i am using the ICSP port on M0. I use the native usb port to programm.
I think i am missing something very basic. I checked many different forum posts, but there is no indication of M0 requiring other SPI commands. Any help is much appriciated.
PS: i didnt go into detail with the sensor and its datasheet because since it works fine with uno, the cause of the problem should be it.

Which version of the Arduino IDE are you using ? If its an older one, try to get the latest one, sometimes that solves issues like the one you have.

You must declare that the pin as an output before you use it.
Do this by using the pinMode() function, like this:
pinMode(11, OUTPUT);          // sets the digital pin 11 as output

Add the above line at the beginning of your setup() function.


text:
Can i supply the AREF pin with an Analog pin from the same board?
I guess its a dumb question but couldnt find anything about it online. I know its possible to supply the AREF pin with 3.3 V to increase the ADC resolution.
For the project i am working on the analog voltage i will be reading will be between 0 and 2.2 and the increased resolution is a must.
I know i can use another board that has a 12 bit resolution but i really would like to make do with Uno. So i wonder if i can set an analog pin to output 2.3 V and feed it to the Aref pin.
If thats not possible please let me know why, so i can increase my knowledge

With an input voltage between 0 and 2.2 V, you can use a 2:1 voltage divider to cut the voltage in half.  In your code, use analogReference(INTERNAL) to set the analog reference voltage to 1.1 V.  The 1.1 V internal reference voltage is created by a bandgap circuit so is reasonably accurate.
To make the voltage divider, put two equal resistors (eg 10KΩ each) in series; connect one end of the series to your input voltage, the other end to ground, and the mid-point to an analog input pin.

Once you set the analog voltage to the internal bandgap voltage source, you can measure the actual voltage on the AREF pin using a multimeter. You can use that voltage to "calibrate" that arduino.

@Gerben That seems like easiest option, thanks for the further explanation. I also checked the oversampling, which i have never heard of before. It also seems quite valid. Again thanks for the heads up

The output voltage of the "analog outputs" (which are actually PWM) are dependent on supply voltage and so are not a good choice where precision is required. Consider using either an integrated voltage reference (e.g. TL431) or a constant-current source feeding a zener diode instead.

Thanks for the quick reply! The things is i really try to refrain from using another circuit, allthough its relatively easy to use, the target users will have no idea how to set it up. The resolution i need is not that much, just 2.5 V /1024 instead of 5 V / 1024. sadly 3.3 V wouldnt do. Is the way i suggested still too unreliable in these conditions ? And if it is do you have any other suggestion that would not require another component ? thanks in advance!

@Firat.Berk.Cakar You could try oversampling to get better resolution.


text:
Arduino Mega 2560 from .org- which IDE works?
My personal choice is to purchase from the .cc (or adafruit) for new boards. YMMV.  Craigslist locally of course has generic and .org boards now and then.
If I get a .org board on craigslist, will I need to use their fork of the IDE for the board to be recognized by the IDE?
My feeling is "yes" but I wanted to confirm.
A board there just now is Arduino mega 2560 from the .org.  Would I have to use their flavor of the IDE?
Thank you for your thoughts- photo of the board I am considering is attached.

Have you compared the schematics yet?

Yes, That doesn't look different that I can see.
I was thinking more about the IDE6 not recognizing the vendor or board ID due to all the things going on between .cc and .org.

Then you can use any IDE you like as long as you use the appropriate firmware.

Perfect timing on your reply, thank you for your help.

Arduino.org and arduino.cc have come to a agreement.
As such all incompatibilities that exist (I don't think they exist for this mega board) will be solved with next version of the Arduino IDE as if it is a board of their own.


text:
EEPROM: managing address mapping between firmware versions
Is there a common way to handle changes in the mapping between eeprom addresses and variables between firmware versions? It's not about the eeprom memory to survive the update, but to be(come) compatible with future sketches with a possibly different set of variables.
To make it clearer consider the following fictional scenario:
A coffee machine has been programmed to measure water_temperature and the firmware is supposed to stop heating within a temperature_hysteresis
 below set_temperature. set_temperature is a persistent parameter that has been individually optimized be the user and must therefore survive any firmware update. As a configuration parameter also temperature_hysteresis is stored in the eeprom.
Now the manufacturer decides to update his machine with a PID-controller, making the parameter temperature_hysteresis obsolete while he introduces some new parameters for the controller's gains (pid_gains). How can he manage that the firmware keeps values that haven't been touched by the update (like set_temperature) while the additional parameter pid_gains is added.
I assume that obsolete parameters should be removed as there could be more updates with new parameters in the future. That's why simply incrementing the eeprom address and ignoring deprecated addresses probably won't work.
On the other hand, when re-using old addresses I wonder how a fragmentation of the eeprom can be avoided.
I came up with the idea of putting all configuration data into a json in the eeprom and to handle the problem a layer above by parsing the json for configuration data. But anyhow, that feels so wrong and might be too complicate.
Does anyone have experience with this kind of problem and knows how this routine is commonly implemented?

There's lots of ways you could handle this.
Two thoughts right off the top of my head:

Have a "Version" identifier in the EEPROM.

The firmware then needs to know the EEPROM layout of all versions up to the current one. It can then read the EEPROM from the old version and write back a new format for the current version.

Have each entry in the EEPROM tagged with a "meaning".

This is not too different to your JSON idea (which you are right is horrible), but instead of lots of words you just use a simple number to identify the meaning of the value it is associated with.  Assuming that each stored value is an 8-bit byte (though it doesn't have to be), you could allocate "1" as "set_temperature", "2" as "temperature_hysteresis", "3" as "pid_gains", etc, Then the EEPROM might contain the bytes 1,96,2,5 and the firmware would know that the second byte is the set_temperature because it has a 1 in the first byte.
You can think of it as a "key / value" pair, but both the key and the value are just numbers.
To find the temperature_hysteresis you just scan through all the even EEPROM entries until you find 2, then read the next entry. If you don't find a 2 then you use the default value.
Your firmware can then choose to either update an existing cell that is tagged with the right type (scan for type, update next cell), or it could erase all the values and replace them with just the ones it cares about - the choice is yours.
Any values that your firmware no longer cares about will be ignored, and potentially erased.

Thanks for your immediate answer! I don't know if I have fully undestood your first solution, but it sounds like I could still run out of memory after a limited number of updates. But the idea is to do all previous changes in eeprom mapping one after another until the latest version (in case that one has missed some updates in the meantime), isn't it?

your second solution is quite clear in general, but I wonder how to handle datatypes of different size. Do I have to store the size of each value after its "key"-byte or how would you do that?

You could infer the data type from the key.

Yes, wrapping a routine around it to achieve this is another story, but at least that's no mystery to me. Thx

I also have things like look-up tables (not entirely predictable size/structure) that need to be stored. What are the disadvantages of using my json approach in spiffs? I mean, it's in the flash anyway...

Seems straight forward to me: having a config.json and a config_updated.json (which gets updated via ota) and at the very first boot the firmware merges those files.

Looks to me like almost unavoidable that the newer firmware will need at least some understanding of what the old versions stored in the EEPROM. In such a situation, solution 1 seems like the most straightforward.