text:
Arduino parsing Double is incorrect
Im having some problems with parsing gps coordinates with the arduino ide.
To be honest I want to process the data without a library.
From my sensor I get this String: 4815.98450
The result of String.toDouble(): 4815.9843750
I also parsed it on my own, but i got the same result: (yes this code is not nice ;))
char buf[10];
  msg.toCharArray(buf, 19);
  double num = 0.0;

  int c;

  c = buf[0] - '0';
  double num0 = (c * 1000);
  c = buf[1] - '0';
  double num1 = (c * 100);
  c = buf[2] - '0';
  double num2 = (c * 10);
  c = buf[3] - '0';
  double num3 = (c * 1);
  c = buf[5] - '0';
  double num5 = (c * 0.1);
  c = buf[6] - '0';
  double num6 = (c * 0.01);
  c = buf[7] - '0';
  double num7 = (c * 0.001);
  c = buf[8] - '0';
  double num8 = (c * 0.0001);
  c = buf[9] - '0';
  double num9 = (c * 0.00001);
  num = num + num0;
  num = num + num1;
  num = num + num2;
  num = num + num3;
  num = num + num5;
  num = num + num6;
  num = num + num7;
  num = num + num8;
  num = num + num9;

Does somebody have a solution for my problems?
Thank you very much :=)

There is no easy solution. The Arduino you are using does not support
double precision floating point. The type double is just an alias for
float, which has 24-bit accuracy.
Your program is actually giving you the correct result, as the float
closest to 4815.98450 is exactly 4815.984375.

Thank you for your answer! You helped me a lot because now i know it is no bug. But now im searching for a workaround :)

@Benjamin_Ellmer: Maybe store the integer and fractional parts separately?

double (or float) is just an inappropriate data type.
Perhaps you take int(4815) and float(0.98450) as two numbers?

And BTW, I bet from your sensor you don't get a String object.

Im reading the output from the TX of my sensor, so im pretty sure this is a string ;)      i figured out that i can do my calculation without the first 2 digits of the number.   there are some cases where it does not work but those cases are very unlikely

You can convert this to a long, do your arithmetic, and convert it back to an ASCII-Decimal number:
Remove the decimal point from the string. Convert the remaining string of digits to a long. Now you have the coordinate in binary, in units of the least significant decimal digit; 1 lsb == 0.00001, if you used 5 decimal places.
Manipulate your data however you need to using long integer arithmetic.
Divide the value by 10^ -(# of fraction digits you used). The quotient is the whole number part; the remainder is the fractional part. Print the quotient and a decimal point. Print the remainder padding with zeros to the left as necessary to result in your printing (# of fraction digits you used) total fraction digits.
The output conversion is even easier if you're willing to use sprintf():
Divide the value by 10^ -(# of fraction digits you used), as above. Let's assume 5 places as in your example:
char buffer[BIGENOUGH+1];
sprintf(buffer, "%ld.%05ld", value/100000, value%100000);

Note that I made two divisions to get the quotient and the remainder and assumed you could tolerate the performance hit. If you're expecting to crank out a lot of values and speed is a factor, you could look up or write a division routine that can return both the quotient and the remainder results from a single division.
Update: @edgar_bonet points out that the compiler is smart enough to notice this fragment uses both results of the numerically same division and avoids dividing twice after all.

Re the “routine that can return both the quotient and the remainder results from a single division”: this is exactly what avr-gcc does when compiling the example you provided.


text:
Possibility of clean the code?
Good night! Based on stuff I get a bit here and there, came up with a program for an Arduino Audio Selector with shift registers and some features. Working as expected, only missing connecting the relay boads, but that's for future. Since I have a few devices, instead of having to write all, is there anyway of I change for instance a line and then on display show that line?
Thanks. Here's my code, realy big, try to short the part of the shift registers but seems to me it was unstable.
Arduino selector 4x20

Please explain what you mean when you say "is there anyway of I change for instance a line and then on display show that line?". Which line are you talking about?

Sorry, forgot to mention... i was thinking in something like: line1 = mp3 player, cd 1 = sony, cd2 =pioneer, and when writing the sources, only need tho change at the begginning instead of having to scroll trough entire code. 73’s CT1JQJ

In traditional C they use #define / #ifdef . In C++ there are more possibilities but interpreting/guessing your question's background that might help already.

I see a lot of 'almost' repetitions like :
  if (RelaySourceDigi == 7) {
    shifter.setPin(16, LOW);
    shifter.setPin(17, LOW);
    shifter.setPin(18, LOW);
    shifter.setPin(19, LOW);
    shifter.setPin(20, LOW);
    shifter.setPin(21, LOW);
    shifter.setPin(22, HIGH);
    shifter.setPin(23, LOW);
    shifter.write();
    lcd.setCursor(0, 2);
    lcd.write(8);
    lcd.setCursor(2, 2);
    lcd.print("Coaxial 3");
  }

Move this to a separate function, and make an argument (or more) of items that vary.
This will greatly reduce your code, making it more managable/maintainable.
Below I changed the entire program. Note I didn't check for runtime errors, and it is highly possible I made some copy/paste errors, but it will give you a clue what you can change. As you can see, the program is radically shortened (and more maintainable).
What you need to do is:

Check each change
Check for copy/paste errors
Read a little bit about pointers (e.g. the &RelaySource and *t constructs)
Also I highly suggest not to use so many constants, but use enums, to denote the value for each different mode you have. So instead of case 1, you can write case TAPE_1.
Split loop in smaller functions (e.g. one function per mode).
I didn't install your libraries but used e.g. #include "LiquidCrystal_I2C.h" and stubbed all functions (meaning I can call them but they don't do anything, just to check for compiler errors in the main program).
Also instead of Aux, use a boolean (true, false).
You see I use a lot of (state - 1) constructs. It's common practice to start counting at 0, not at 1, it will make your life easier. Only when displaying a value for a user, add +1.
Below the program.
//Libraries
#include "LCD.h"
#include "LiquidCrystal_I2C.h"
#include "Shifter.h"

#define SER_Pin 8 //SER_IN 14 on 74HC595
#define RCLK_Pin 9 //L_CLOCK 12 on 74HC595
#define SRCLK_Pin 10 //CLOCK 11 on 74HC595
#define NUM_REGISTERS 3 //how many registers are in the chain
//initaize shifter using the Shifter library
Shifter shifter(SER_Pin, RCLK_Pin, SRCLK_Pin, NUM_REGISTERS);

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

const int ButtonPinUp = 2;
int ButtonPinUpState = 0;
const int ButtonPinDn = 3;
int ButtonPinDnState = 0;
const int MuteButtonPin = 5;
int MuteButtonPinState = 0;
const int AuxButtonPin = 4;
int AuxButtonPinState = 0;
const int fbutton = 6;
int RelaySource = 1;
int RelaySourceDigi = 1;
int RelayRec = 1;
int RecDigi = 1;
int Mute = 0;
int Mode = 0;
int Aux = 1;
int state = 0;
int old = 0;
int ButtonPoll = 0;

byte opt[8] = {
  0b00000,
  0b01110,
  0b11011,
  0b10001,
  0b10001,
  0b10001,
  0b11111,
  0b00000
};

byte coax[8] = {
  0b00100,
  0b01110,
  0b11111,
  0b10001,
  0b10001,
  0b01110,
  0b00100,
  0b00100
};

byte mut[8] = {
  0b00001,
  0b00011,
  0b00111,
  0b11111,
  0b11111,
  0b00111,
  0b00011,
  0b00001
};

byte outp[8] = {
  B00000,
  B00100,
  B00110,
  B11111,
  B11111,
  B00110,
  B00100,
  B00000
};

byte upp[8] = {
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111
};

byte inpp[8] {
  0b10000,
  0b10000,
  0b10100,
  0b10110,
  0b11111,
  0b00110,
  0b00100,
  0b00000
};

byte ann[8] {

  0b11111,
  0b10001,
  0b10101,
  0b10101,
  0b10001,
  0b10101,
  0b10101,
  0b11111
};

byte dnn[8] = {
  0b11111,
  0b10011,
  0b10101,
  0b10101,
  0b10101,
  0b10101,
  0b10011,
  0b11111
};

byte too[8] = {
  0b00000,
  0b00100,
  0b00110,
  0b11111,
  0b00110,
  0b00100,
  0b00000,
  0b00000
};

void printAtCursor(int a, int b, const char* c)
{
  lcd.setCursor(a, b);
  lcd.print(c);
}

void setup() {
  lcd.begin(20, 4);
  lcd.backlight();

  byte* list[] = {outp, coax, mut, opt, upp, inpp, ann, dnn, too };
  for (int n = 0; n < 9; n++)
  {
    lcd.createChar(n + 1, list[n]);
  }

  pinMode(fbutton, INPUT);
  pinMode(ButtonPinUp, INPUT);
  pinMode(MuteButtonPin, INPUT);
  pinMode(ButtonPinDn, INPUT);
  pinMode(AuxButtonPin, INPUT);

  for (int n = 11; n < 14; n++)
  {
    pinMode(n, OUTPUT);
  }

  printAtCursor(3, 0, "Digital/Analog");
  printAtCursor(3, 1, "Audio Selector");
  printAtCursor(4, 2, "Built-In DAC");
  printAtCursor(2, 3, "V2.0f (23052020)");
  delay(4000);
  lcd.clear();
}

void setPin(int first, int last, int pin)
{
  for (int n = first; n < last + 1; n++)
  {
    shifter.setPin(n, pin == n ? HIGH : LOW);
  }

  shifter.write();
}

void setLines(int a, int b, const char* t, int x = -1, const char* u = "")
{
    lcd.setCursor(0, a);
    lcd.write(b);
    lcd.setCursor(2, a);
    lcd.print(t);
    if (x != -1)
    {
      lcd.write(x);
      lcd.print(u);
    }
}

void loop()
{
  // shifter.clear(); //set all pins on the shift register chain to LOW
  shifter.write(); //send changes to the chain and display them
  //check button states
  ButtonPinUpState = digitalRead(ButtonPinUp);
  ButtonPinDnState = digitalRead(ButtonPinDn);
  MuteButtonPinState = digitalRead(MuteButtonPin);
  AuxButtonPinState = digitalRead(AuxButtonPin);
  ButtonPoll = digitalRead(fbutton);

  if (AuxButtonPinState == HIGH && RelaySource == 1 && state == 1) {
    lcd.clear();
    Aux           = ~Aux;
    digitalWrite(13, Aux == 0 ? LOW : HIGH);
  }

  if (ButtonPoll == HIGH) {
    state = old + 1;
  }

  lcd.clear(); // Happens in all cases
  switch (state) {
    case 1: // Fall through
    case 2: // Fall through
    case 3: // Fall through
    case 4:
      lcd.setCursor(1, state - 1);
      lcd.write(5);
      old = state;
      break;

    default:
      old = 0;
      break;
  }

  // Assuming state = 1..4
  if (ButtonPinUpState == HIGH)
  {
    lcd.clear();
    int* t = NULL;
    int maxValue = -1;

    switch (state)
    {
      case 1: t = &RelaySource;     maxValue = 8; break;
      case 2: t = &RelayRec;        maxValue = 5; break;
      case 3: t = &RelaySourceDigi; maxValue = 8; break;
      case 4: t = &RecDigi;         maxValue = 4; break;
      default: break;
    }

    *t = min(1, max(maxValue, *t + (ButtonPinUpState == HIGH ? 1 : 0) + (ButtonPinDnState == HIGH ? -1 : 0)));
  }

  if (MuteButtonPinState == HIGH) {
    lcd.clear();
    Mute = (Mute == 0 ? 1 : 0);
    digitalWrite(12, Mute == 0 ? HIGH : LOW);
  }

  // RelaySource
  setPin(0, 7, RelaySource - 1);
  if (RelaySource == 1 && Aux == 0)
  {
    setLines(0, 7, "D", 9, "A:");
  }
  else
  {
    const char* rs1[] = { "Line 1", "Line 2", "CD 1", "CD 2", "Tape 1", "Tape 2/DCC", "Tape 3/DAT", "MD", "MD" };
    setLines(0, 7, rs1[RelaySource - 1]);
  }

  if (RelaySource == 8)
  {
    shifter.setPin(0, LOW); //set pin 1 in the chain(second pin) HIGH
  }

  // RelayRec
  int         rr1[] = { 8      , -1   , 9       , 10      , 11       };
  const char* rr2[] = {"Source", "OFF", "Tape 1", "Tape 2", "Tape 3" };
  const int   rr3[] = { -1     , -1   , 9       , 9       , 9        };
  const char* rr4[] = { ""     , ""   , "2,3"   , "1,3"   , "1,2"    };

  setPin(8, 11, rr1[RelayRec - 1]);
  setLines(1, 6, rr2[RelayRec - 1], rr3[RelayRec - 1], rr4[RelayRec - 1]);

  // RelaySourceDigi
  setPin(16, 23, 17 - RelaySourceDigi);
  if (RelaySource == 1 && Aux == 0)
  {
    lcd.setCursor(7, 0);
    const char* t[] = { "Optical 1", "Optical 2", "Optical 3", "Optical 4", "Coaxial 1", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
    lcd.print(t[RelaySource - 1]);
  }

  const char* t1[] = { "Sony 5-CD", "Sony MD[", "Optical 3", "Optical 4", "Philips CD-R [", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
  const int   t2[] = { 4          , 4         , -1         , -1         , 2               , -1        , -1         , -1          };
  const char* t3[] = { "]"        , "]"       , ""         , ""         , "]"             , ""        , ""         , ""          };
  setLines(2, 8, t1[RelaySourceDigi - 1], t2[RelaySourceDigi - 1], t3[RelaySourceDigi - 2]);

  // RecDigi
  const char* t[] = { "Optical Out1", "Optical Out 2", "Coaxial Out 1", "Coaxial Out2" };
  setPin(12, 15, 11 + RecDigi);
  setLines(3, 6, t[RecDigi - 1]);

  delay(150);
}

Update
I wanted for myself to see how to clean it fully, so I tried below.
Still check for copy/paste problems, as I didn't execute the sketch (but it compiles without warnings).
Original sketch: 2746 bytes (8%) program storage space, 142 bytes (6%) of dynamic memory
Sketch below   : 1546 bytes (4%) program storage space,  40 bytes (2%) of dynamic memory.
Conclusion:

25% less program storage space used
67% less dynamic memory used
Less lines of code
Better readability
Better maintainability
No (or less) code duplication
Smaller function complexity
Less statements (added more to initialization)

Code:
//Libraries
#include "LCD.h"
#include "LiquidCrystal_I2C.h"
#include "Shifter.h"

const uint8_t SER_Pin = 8; //SER_IN 14 on 74HC595
const uint8_t RCLK_Pin = 9; //L_CLOCK 12 on 74HC595
const uint8_t SRCLK_Pin = 10; //CLOCK 11 on 74HC595
const uint8_t NUM_REGISTERS = 3; //how many registers are in the chain

Shifter _shifter(SER_Pin, RCLK_Pin, SRCLK_Pin, NUM_REGISTERS);
LiquidCrystal_I2C _lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

enum EMode
{
  RELAY_SOURCE,
  RELAY_REC,
  RELAY_SOURCE_DIGI,
  REC_DIGI,
  LAST_MODE
};

static const uint8_t _buttonPinUp = 2;
bool _buttonPinUpState = false;
static const uint8_t _buttonPinDown = 3;
bool _buttonPinDownState = false;
static const uint8_t _muteButtonPin = 5;
bool _muteButtonPinState = false;
static const uint8_t _auxButtonPin = 4;
bool _auxButtonPinState = false;
static const uint8_t _forwardButton = 6;
uint8_t _relaySource = 0;
uint8_t _relaySourceDigi = 0;
uint8_t _relayRec = 0;
uint8_t _recDigi = 0;
bool _mute = false;
bool _aux = true;
EMode _mode = RELAY_SOURCE;
bool _buttonPoll = false;

static const byte OPT[8]  PROGMEM = {  0b00000,  0b01110,  0b11011,  0b10001,  0b10001,  0b10001,  0b11111,  0b00000 };
static const byte COAX[8] PROGMEM = {  0b00100,  0b01110,  0b11111,  0b10001,  0b10001,  0b01110,  0b00100,  0b00100 };
static const byte MUT[8]  PROGMEM = {  0b00001,  0b00011,  0b00111,  0b11111,  0b11111,  0b00111,  0b00011,  0b00001 };
static const byte OUTP[8] PROGMEM = {  B00000 ,  B00100 ,  B00110 ,  B11111 ,  B11111 ,  B00110 ,  B00100 ,  B00000  };
static const byte UPP[8]  PROGMEM = {  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111 };
static const byte INPP[8] PROGMEM = {  0b10000,  0b10000,  0b10100,  0b10110,  0b11111,  0b00110,  0b00100,  0b00000 };
static const byte ANN[8]  PROGMEM = {  0b11111,  0b10001,  0b10101,  0b10101,  0b10001,  0b10101,  0b10101,  0b11111 };
static const byte DNN[8]  PROGMEM = {  0b11111,  0b10011,  0b10101,  0b10101,  0b10101,  0b10101,  0b10011,  0b11111 };
static const byte TOO[8]  PROGMEM = {  0b00000,  0b00100,  0b00110,  0b11111,  0b00110,  0b00100,  0b00000,  0b00000 };

static const byte* const CHAR_LIST[] PROGMEM = {OUTP, COAX, MUT, OPT, UPP, INPP, ANN, DNN, TOO };
static const uint8_t PINS[] PROGMEM = { _forwardButton, _buttonPinUp, _muteButtonPin, _buttonPinDown, _auxButtonPin };

static uint8_t* const    MODE_VALUES[] PROGMEM = { &_relaySource, &_relayRec, &_relaySourceDigi, &_recDigi };
static const uint8_t     MAX_VALUES[] PROGMEM = { 7             , 4         , 7                , 3         };

static const char* const RELAY_SOURCES[] PROGMEM = { "Line 1", "Line 2", "CD 1", "CD 2", "Tape 1", "Tape 2/DCC", "Tape 3/DAT", "MD", "MD" };

static const char* const RELAY_SOURCE_DIGI_1[] PROGMEM = { "Sony 5-CD", "Sony MD[", "Optical 3", "Optical 4", "Philips CD-R [", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
static const int         RELAY_SOURCE_DIGI_2[]         = { 4          , 4         , -1         , -1         , 2               , -1        , -1         , -1          };
static const char* const RELAY_SOURCE_DIGI_3[] PROGMEM = { "]"        , "]"       , ""         , ""         , "]"             , ""        , ""         , ""          };

static const int         RELAY_REC_1[] PROGMEM = { 8      , -1   , 9       , 10      , 11       };
static const char* const RELAY_REC_2[] PROGMEM = {"Source", "OFF", "Tape 1", "Tape 2", "Tape 3" };
static const int         RELAY_REC_3[] PROGMEM = { -1     , -1   , 9       , 9       , 9        };
static const char* const RELAY_REC_4[] PROGMEM = { ""     , ""   , "2,3"   , "1,3"   , "1,2"    };

static const char* const DIGI_RELAY_SOURCES[] PROGMEM = { "Optical 1", "Optical 2", "Optical 3", "Optical 4", "Coaxial 1", "Coaxial 2", "Coaxial 3", "Coaxial 4" };

void printAtCursor(int a, int b, const char* c)
{
  _lcd.setCursor(a, b);
  _lcd.print(c);
}

void setup()
{
  _lcd.begin(20, 4);
  _lcd.backlight();

  for (int n = 0; n < 9; n++)
  {
    _lcd.createChar(n + 1, (byte*) CHAR_LIST[n]);
  }

  for (int n = 0; n < sizeof(PINS) / sizeof(uint8_t); n++)
  {
    pinMode(PINS[n], INPUT);
  }

  for (int n = 11; n < 14; n++)
  {
    pinMode(n, OUTPUT);
  }

  printAtCursor(3, 0, "Digital/Analog");
  printAtCursor(3, 1, "Audio Selector");
  printAtCursor(4, 2, "Built-In DAC");
  printAtCursor(2, 3, "V2.0f (23052020)");
  delay(4000);
}

void setPin(int first, int last, int pin)
{
  for (int n = first; n < last + 1; n++)
  {
    _shifter.setPin(n, pin == n ? HIGH : LOW);
  }

  _shifter.write();
}

void setLines(int a, int b, const char* t, int x = -1, const char* u = "")
{
    _lcd.setCursor(0, a);
    _lcd.write(b);
    _lcd.setCursor(2, a);
    _lcd.print(t);

    if (x != -1)
    {
      _lcd.write(x);
      _lcd.print(u);
    }
}

void ResetShifter()
{
  // _shifter.clear(); //set all pins on the shift register chain to LOW
  _shifter.write(); //send changes to the chain and display them
}

void ReadButtons()
{
  _buttonPinUpState = digitalRead(_buttonPinUp) == HIGH;
  _buttonPinDownState = digitalRead(_buttonPinDown) == HIGH;
  _muteButtonPinState = digitalRead(_muteButtonPin) == HIGH;
  _auxButtonPinState = digitalRead(_auxButtonPin) == HIGH;
  _buttonPoll = digitalRead(_forwardButton) == HIGH;
}

void HandleAuxButton()
{
  if (_auxButtonPinState && (_relaySource == 0) && (_mode == EMode::RELAY_SOURCE))
  {
    _aux = !_aux;
    digitalWrite(13, _aux ? HIGH : LOW);
  }
}

void HandlePollButton()
{
  if (_buttonPoll)
  {
    _mode = (EMode) ((_mode + 1) % EMode::LAST_MODE);
  }
}

void StartLcd()
{
  _lcd.clear(); // Happens in all cases
  _lcd.setCursor(1, (int) _mode);
  _lcd.write(5);
}

void HandleButtonPinUp()
{
  if (_buttonPinUpState)
  {
    static uint8_t* const modeValue = MODE_VALUES[_mode];
    static uint8_t maxValue = MAX_VALUES[_mode];
    *modeValue = min(0, max(maxValue, *modeValue + (_buttonPinUpState ? 1 : 0) + (_buttonPinDownState ? -1 : 0)));
  }
}

void HandleMuteButton()
{
  if (_muteButtonPinState)
  {
    _mute = !_mute;
    digitalWrite(12, _mute ? HIGH : LOW);
  }
}

void ProcessRelaySource()
{
  // RelaySource
  setPin(0, 7, _relaySource);
  if (_relaySource == 0 && !_aux)
  {
    setLines(0, 7, "D", 9, "A:");
  }
  else
  {
    setLines(0, 7, RELAY_SOURCES[_relaySource]);
  }

  if (_relaySource == 7)
  {
    _shifter.setPin(0, LOW); //set pin 1 in the chain(second pin) HIGH
  }
}

void ProcessRelayRec()
{
  setPin(8, 11, RELAY_REC_1[_relayRec]);
  setLines(1, 6, RELAY_REC_2[_relayRec], RELAY_REC_3[_relayRec], RELAY_REC_4[_relayRec]);
}

void ProcessRelaySourceDigi()
{
  setPin(16, 23, 17 - _relaySourceDigi);
  if (_relaySource == 0 && !_aux)
  {
    _lcd.setCursor(7, 0);
    _lcd.print(DIGI_RELAY_SOURCES[_relaySource]);
  }
  setLines(2, 8, RELAY_SOURCE_DIGI_1[_relaySourceDigi - 1], RELAY_SOURCE_DIGI_2[_relaySourceDigi - 1], RELAY_SOURCE_DIGI_3[_relaySourceDigi - 2]);
}

void ProcessRecDigi()
{
  static const char* const t[] PROGMEM = { "Optical Out1", "Optical Out 2", "Coaxial Out 1", "Coaxial Out2" };
  setPin(12, 15, 12 + _recDigi);
  setLines(3, 6, t[_recDigi]);
  delay(150);
}

void loop()
{
  ResetShifter();
  ReadButtons();

  HandleAuxButton();
  HandlePollButton();
  StartLcd();
  HandleButtonPinUp();
  HandleMuteButton();

  ProcessRelaySource();
  ProcessRelayRec();
  ProcessRelaySourceDigi();
  ProcessRecDigi();
}

Hello. Still trying to figure that, newbbie to arduino, thanks for the info

upvote for a very nice answer ... you can further simplify your code ...
lcd.setCursor(0, 2);
lcd.write(8);
lcd.setCursor(2, 2);
lcd.print("Sony MD [");
lcd.write(4);
lcd.print("]");
.... is same as this ....
lcd.setCursor(0, 2);
lcd.print("\x08 Sony MD [\x04]");

@jsotola thanks ... however, in my optimized code I'm not sure if I can use it as positions for the cursor are variable.

Thank you very much, after seeing this I realized I’m in fact a newbbie! I’ll try it tomorroy, meanwhile tried with a rotary encoder and menu but dont like that much.

I'm a professional software engineer, so this is kind of 'normal stuff' fo rme, although I still don't know much about many Arduino specific details. (btw the sketch can be improved more, but these are the 'low hanging fruit' items. If you next time try to make your loop as simple as I did know,  your overall design will be much easier in general.

source: Stack Exchange

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

sort: votes


text:
Serial Read Data Loss With Arduino Nano
I am trying to use Serial reading from a python serial code (which is running on my Jetson Nano) in my project, but in some loop in my code, my data is receiving wrong.

I use Serial.readBytesUntil() function for interrupt-like reading.
I use standart blue mini-USB cable for communication.
My Arduino Nano also connected a nRF24L01 module with SPI.
Baudrate is 9600 for both devices. I tried 115200 but there is no difference.
The data loss is about %10 of all loops with both test codes (image-1, image-2).
There is no positive difference when I use RX/TX pins on both boards with level shifter.
When I use the test code in my main code with USB connection, the data loss increases %50 of all loops. But Arduino serial monitor is fine like image-3.
When I use the test code in my main code with RX/TX pins, Arduino serial monitor looks like image-4 and Arduino IDE gives error like image-5.

Here is my receiver test code on my Arduino Nano.
void setup() {

  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  while (!Serial) {}

}

void loop() {
  char buffer[4];
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 4);

    if (size == 4) {
      Serial.print("deger: ");
      Serial.write(buffer);
      Serial.print("  size: ");
      Serial.print(size);

      // Bytes to integer
      deger = (buffer[1] - 48) * 100 + (int(buffer[2]) - 48) * 10 + (buffer[3] - 48);
      if (buffer[0] == '1') {
        deger = -1*deger; }

      Serial.print(" Sayi: ");
      Serial.println(deger);
      }

    if (deger < 0) {
      digitalWrite(LED_BUILTIN, HIGH);
    }
    else {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
}

And the python serial transmitter test code.
import serial

ser = serial.Serial('/dev/ttyUSB0',baudrate=9600,timeout=10)
while True:
    hata = -58

    if hata > 0:
        hata = str(hata)
        if len(hata) == 2:
            hata = '00' + hata
        elif len(hata) == 1:
            hata = '000' + hata
        else:
                hata = '0' + hata    #Pozitive, Added 0
    elif hata < 0:
        hata = -1 * hata
        hata = str(hata)
        if len(hata) == 2:
            hata = '10' + hata
        elif len(hata) == 1:
            hata = '100' + hata
        else:
            hata = '1' + hata    #Negative, Added 1
    else:
        hata = str(hata)
        hata = '000' + hata

    # For every loop, sends 4 character and "\n"  Example: 1058\n
    gonder = hata + '\n'       # For readBytesUntil function
    ser.write(gonder.encode('utf-8'))
    print(gonder.encode('utf-8'))

image-1: Arduino test code serial monitor screenshot

image-2: Python test code serial terminal screenshot

image-3: Arduino main project code monitor with USB cable screenshot

image-4: Arduino main project code monitor with RX/TX pins on GPIO screenshot

image-5: Arduino main project code IDE error

So, what did i do wrong?
Thank you!

Already answered on the Arduino forum here

You are overflowing your buffer, and also allowing garbage reads.
First you need 5 bytes for your buffer not 4, and you need to ensure it is zeroed out before using it. This is because you are treating it like a C string, which means it must b zero terminated.
Secondly your use of Serial.readBytesUntil() is flawed.  From the manual:

The function terminates (checks being done in this order) if the determined length has been read, if it times out (see Serial.setTimeout()), or if the terminator character is detected (in which case the function returns the characters up to the last character before the supplied terminator).

You are sending 5 bytes (1058\n) but telling it to read up to 4. Which leaves the \n in the buffer. The next time through you read another 4 bytes, which gives you \n which is the terminating character.
If you must use readBytesUntil then you need to specify a buffer that is bigger than the whole string including the terminator so that the terminator always occurs before the maximum number of bytes read. Including the trailing zero you would thus need at least 6 bytes in your buffer, maybe a couple more "just in case" (one can never tell with Arduino API functions...)
So to roll it all up:
  char buffer[8]; // <- Bigger buffer
  memset(buffer, 0, 8); // <- Clear it out
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 7); // <- Tell it to read more leaving room for the terminating NULL
    ... etc ...

if (size == 4) {

readBytesUntil doesn't put the terminating character in the buffer. but it is read.

@Juraj Not if it's the 5th character and you're only telling it to read up to 4...

Thank you! I will try to code like you said. What do say about the second problem (image-4, broken serial monitor) ?

That is most likely buffer overflow from your unterminated buffer.

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


text:
How do you remove an item from array arduino?
Is there a way that can change {3, 5, 3, 6} to {3, 5, 6} with a function? I checked all the arduino forums but they don't give the answer i need (just delete 1 item from an array with a function like delete(myArray, 2)).

There is no such concept in C. Arrays are a fixed size and that size can never be changed. You can't "delete" an entry. You can replace one with something else, and you can introduce the concept of a variable that says how many entries the array has, but you can't delete one.
So you could:

Keep a count of how many entries are in the array
Shuffle down all the entries one space so the unused one is at the end
Decrement the count of entries

So in your example {3, 5, 3, 6} becomes {3, 5, 6, 6} and your "count" holds 3 to say the first three entries are valid and to ignore the last.
Alternatively you can introduce the concept of "end of array". C strings do this with the NULL character (0). Anything before that character is valid, and anything from that character onwards is ignored.  So say you nominated the value -1 to be "end of array" you could have, after again shuffling down the values: {3, 5, 6, -1}.
You could also have -1 (or whatever you chose) indicating an "invalid" entry, so your array would be {3, 5, -1, 6} and you would ignore the -1 entry in your code.

Using an invalid value (vs. an end-of-array value) saves shuffling values to over-write the vacated space, but adds some overhead in that array indexing would no longer work as expected but would require walking the array and counting valid values until the i-th one. Some applications may benefit (those that just store data but don't index to it, or not often, anyway), vs. those that do a lot of indexing but not much deleting.

In C++, arrays are fixed-length data structures. There is no way you could remove an item. You could replace it with an invalid item, though.

So is there a data array-like type witch can be modifiable?

Dynamic objects are not a good idea on a memory-starved device like an Arduino. Come up with a "this space intentionally left blank" value and store that into a location to remove an item. (0 and -1 are common choices for an empty entry, as Majenko mentions in their answer.)


text:
Arduino glitches and makes 240 < 7 and -240 > 7
I'm experimenting with the joystick and the MAX7219 module (8x8 LED display) and i made this program:
#include "LedControl.h"

LedControl lc=LedControl(11,13,10,1);

int Xo = 36;
int Yo = 34;

int xPin = A1;
int yPin = A0;
int buttonPin = 7;

int xPos = 0;
int yPos = 0;

int Xvel = 0;
int Yvel = 0;

int lastMapX = -1;
int lastMapY = 0;

void setup() {
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
  lc.shutdown(0,false);
  lc.setIntensity(0,8);
  lc.clearDisplay(0);
}

void loop() {

  Xvel = joystickMap(xPin, Xo);
  Yvel = joystickMap(yPin, Yo);

  if (Xvel == 0 and Yvel == 0) {
    Xvel = lastMapX;
    Yvel = lastMapY;
  }

  yPos = yPos + Xvel;
  xPos = xPos + Yvel;

  if (xPos < 0) {
    xPos = 0;
  }else if (yPos < 0) {
    yPos = 0;
  }else if (xPos > 7) {
    xPos = 7;
  }else if (yPos > 7) {
    yPos = 7;
  }

  lc.clearDisplay(0);
  lc.setLed(0,xPos,yPos,true);

  Serial.print("x=");
  Serial.print(yPos);
  Serial.print(" y=");
  Serial.print(xPos);
  Serial.print(" buttonpress=");
  Serial.print(digitalRead(7)==0);
  Serial.print(" x>7=");
  Serial.println(xPos > 7);

  lastMapX = Xvel;
  lastMapY = Yvel;

  delay(100);
}

int joystickMap(int in, long offset) {
  int firMap = map(analogRead(in), 0, 1023, -102, 100)+offset;
  if (firMap == 0 or firMap == 1 or firMap == -1) {
    return 0;
  }else if (firMap > 0) {
    return 1;
  }else if (firMap < 0) {
    return -1;
  }
}

it should make it for the player impossible to stop. But there is a glitch witch allows you to go off-screen. If you are in any corner and you go diagonally to the opposite corner you just go through. Here  is a screenshot with the program and the serial monitor:

My Arduino is a UNO R3. How can i fix this glitch?

Read your code where you are printing your values. Read it carefully. It's behaving exactly as you are telling it...

don't you think, that tying the conditions for x and y together with else if is incorrect? x and y are independent coordinates, so why should the limitations on y being only imposed, if the limitations on x weren't imposed? Split your if conditions up into one set for x and one set for y


text:
ESP32-POE/ISO unstable after 10 days of power up
i have one ESP32-POE and ESP32-POE and i'm using the Olimex RS485 module to read a power meter that is placed near the ESP32 (5 meters of CAT5 cable - 9600 8N1).
My device has this workflow (it's powered via PoE using a Cisco 2960x switch):

Boot and acquire a DHCP address
Connect to the server and check if there is a new ota package to download
Read via modbus (Using ModbusMaster library) the power meter
Prepare the data in JSON format using ArduinoJson library and send it to the broker using PubSubClient
Wait for five minutes using Millis and start over with the loop

This is the main logic that "blocks" the loop and wait for some minutes:
void loop() {
  wdt_reset();
  MQTT_connect();

  client_subscriber_loop(); // loop subscriber mqtt

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillisTaskDataPublisher > MQTT_PUBLISH_EVERY) {
    if (DEBUG == 1)
      Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());
    //  OTA Check
    trueverit_ota_check_update();
    wdt_reset();

    publish_data();
    if (DEBUG == 1)
      Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());

    previousMillisTaskDataPublisher = currentMillis;
  }
}

As you can see, i've also have Watchdog timer enabled and it is feeded in the loop or function that have to feed it (Modbus read, etc...)
Now, here comes the issues, this works exactly for 10 days and after that the MCU goes in loop, the LAN green led will flash indefinitely and nothing work, leaving the ESP32 in a undefined state.
This is the debug message that i see on arduino console:

There is no way to make it work a part of power off and power on the device.
This is extremely uncomfortable...in my case i have 25 of those devices placed far away from my office (600km) and i can't go every time to reboot them every ten days.
Maybe is hardware related issue? a software issue on ModbusMaster library?
Any toughts?

please, no pictures of text ... include the debug message as text ... format it the sane as code

You could have the watchdog timer timeout if you get a network error. Then the MCU will just reset. It would be interesting to see if  lowering MQTT_PUBLISH_EVERY also make the problem occur faster than 10 days.

Is the console output from right before the ESP malfunctions? There is no way to make it work a part of power off and power on the device. does that include pressing the reset button?

Have you considered performing a software reset every 24h as a workaround?

Tomorrow I'll remove the publish delay and test it. - about what asked from Gerben, yes, this is the console output right before the ESP malfunction, it doesn't include the reset pressing button (if I reset the device with reset button it will start working).

HTTP_UPDATE_FAIL_ERROR (-104) means that the server disconnected for some reason, and your code went into a trap state without the ability to establish a reconnect. The code you posted doesn't provide any clue on how you handle the reconnect when it happened.


text:
Connect Arduino + WiFi Shield to Raspberry Pi
I want to send collected data (temperature sensor) from my Arduino via the WiFi shield to my Raspberry Pi. Can I do that with the WiFi library that exists in Arduino IDE ?

Yes.  You could do something like run a simple TCP server on the pi, or perhaps something more complex like an MQTT-based setup, either with the pi itself as the broker or through a traditional broker either on the local network or the cloud.  At present your question lacks specifics, perhaps you should look at existing examples first.  Also keep in mind that an ESP8266 by itself may be preferable to an ATmega - based Arduino plus a shield.

I would just want it as simple as possible. Collect temperature from my balcony and send it via the local network to my Pi while I execute a python script on my Pi which waits to receive data from a local port (say 8088) and print out the data it received. To be more specific I would like to send the collected data from my Arduino to the IP address of my Pi.

Good, a web search should readily find you plenty of examples.  Questions should generally be asked after you search and find something specifically confusing or that does not work as expected, not as a substitute for research.

Yes, all right. I also searched but haven't found until now exactly what I wanted and I want to be sure before I buy certain things. However, hank you for your time and help!

Do you have power on the balcony? Cause if you have to run of batteries, using wifi isn't very energy efficient.

@Gerben Yes, I have power at the balcony!

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


text:
Arduino MKR GSM 1400 project - Establish call - Wait and hang call
I am implementing a GSM project using the Arduino MKR 1400 GSM board and I would like to achieve the following:
Establish a call to a specific number, wait for a certain amount of seconds and then hag the call. I have written the following test code in order to see how to manage it.
#include <MKRGSM.h>

// PIN Number
#define PINNUMBER ""

GSM gsmAccess;
GSMVoiceCall vcs;

void setup()
{

  Serial.begin(9600);

  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized.");

  if (vcs.voiceCall(char_array_number)) {
    Serial.println("Call established");
    delay(10000);
  } else {
    Serial.println("Something is going wrong");
  }

}

void loop()
{

}

Well, the call is established, the phone rings but the instructions inside the if statement won't get execute. Instead I get the following Serial Monitor output.

I don't really understand why that happens because since the call is stablished the first if statement would be executed. I would really appreciate any help, since this is like the final step of my project and been struggling for some time.


text:
Using an esp8266, how can I create a circuit to measure 2 different analog inputs (not simultaneously) with only one ADC pin available (A0)
I'm currently using a circuit with 2 separate transistors that can be switched on or off to measure 2 separate voltage inputs.
The reason for this is because I'm using an esp8266 which has only one ADC input at pin A0 and I need to measure light intensity from an LDR as well as voltage from a solar panel.
The LDR is wired with a voltage divider. The voltage input from the solar panel is 0 - 5v, so I have that wired with a voltage divider to output a max of 3.3v (pin A0 is 0 - 3.3v). The problem is that in complete darkness, the ADC is still reading the LDR with a value of around 260 (should be close to zero) and with bright light reading around 850 (should be close to 1023). Also, the voltage measured from the solar panel (divided to 3.3v) is returning anywhere from 600 (0v) to around 840 (3.3v).
I've tried these input measurements separately with expected results. It's having the option to switch inputs is what is tripping me up.
So, is my approach correct or is there another way to do this?
Note: I would have included a circuit diagram if I knew anything about circuits and making diagrams.

you can measure resistance quite accurately with a digital pin and some passive components using RC timing. I have a reisistor finder sketch that uses this, as it works better than a voltage divider for identifying unknown values on a large range of ohms, not just ones that work well as voltage dividers when close to the known resistor.... you can also use a plain old relay to switch between two analog inputs.

Could use a multiplexer to switch analog input.  You connect one pin to youe esp, and then you can connect 4-16 inputs/output depending on the chip.  Use  2-4 control pins to select the pin you want to read/write on.

Can anyone explain what's up with the down vote? Was my question too detailed?

For what it's worth, I solved the problem by simply condensing the range of values with the light and voltage readings in my script along with adding a higher ohm resistor to the base of both transistors. The resolution isn't as high, but still very accurate.

There's two basic solutions, both of which require the addition of an external chip:

Use an analog multiplexer to select the different devices to connect to the ADC input
Use an external (I2C or SPI) ADC chip. These can give you higher resolutions than the internal ADC and many more inputs (depending on the chip you choose).

My recommended solution would be to get an external ADC chip.

Thank you, I'll look into those solutions. So, why wont simple transistors work in this scenario? Isn't a transistor just a switch?

I can be done with transistors but you have to select the right kind of transistors and wire them in the right way. A transistor is not just a switch - certainly a BJT isn't just a switch.

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


text:
Receiving message from arduino through wifi
I am new to arduino . I went through the basics . I want to receive message from arduino uno r3 in my laptop(ubuntu) . I have esp8266 wifi module . Arduino and esp8266 connection done . How do I proceed further ?

the simplest way is probably a running web server on your laptop, or perhaps mqtt/sockets, or a common cloud-based sever.

Download the ESP8266 extension for the Arduino board in Arduino IDE,desktop. Then select the example code for ESP8266, use the Server example. If you wanna access your board outside your home then you need to open a port in your router.

authors: ยอดชาย ขุนสังวาย์


text:
The working of a MFRC522 and its Interface protocols?
I've actually messed up and posted into the stackoverflow site, even though I'm probably not meant to. I've been given this datasheet, but even though it does explain somewhat how each host interfaces works, it does not fully answer the questions I have at the moment and I probably don't even know what I'm doing in the first place, hence I'm giving this question another shot in the right place.
I've enrolled recently into a programming course, and one of the subject seems to be embedded software development revolving around an Arduino. Now, I'm tasked with explaining to the class how the MFRC522 works and where it might be applicable, but before all that, I probably am lacking the basic knowledge before I can proceed with my work.
I have here the image of the pinout from a MFRC522 and I have the following questions:

Theres UART, I2C and SPI. Are they all separate communication protocols or are they all involved somehow with each other on this device? If I plan to use only UART for example, is it possible that I just only use the RX and TX?
Are there restrictions as to which pins on the Arduino or the MFRC522 I could possibly use, depending on the protocol or circumstances? I can see in the datasheet the pins D1 to D7 being referenced, but I cannot find it anywhere on the MFRC522 itself.
In case they are separate protocols, I would like to know how each protocol is applicable for this specific device? Like a general idea as to why a protocol is suited for a certain every day device we have been using.
The device itself uses only 3.3V, but is it also 5V resistant? Like, will plugging it into a 5V fry the circuit board or will it work just as fine?

Thanks everyone for your time.

Let's have a look at the datasheet of that chip:
Paragraph 8.1 says

The MFRC522 supports direct interfacing of hosts using SPI, I2C-bus or serial UART interfaces. The MFRC522 resets its interface and checks the current host interface type automatically after performing a power-on or hard reset. The MFRC522 identifies the host interface by sensing the logic levels on the control pins after the reset phase. This is done using a combination of fixed pin connections.

But it seems that on this specific board the control pins are preconfigured for SPI. But, the supporting library only supports SPI so I guess that's OK. For other applications the control pins will be connected differently, and the pins will take up an i2c or serial async role. Applications for the other interfaces include microcontrollers without an SPI interface but with an i2c interface, or eg general purpose computers that have easy access to serial async interfaces, like PC's

the pin names D1-D7 in the datasheet are not related to the Arduino's pins with the same names, that's just a coincidence. If you use the aforementioned library, the Arduino pins to use are documented:

     * Pin layout should be as follows:
     * Signal     Pin              Pin               Pin
     *            Arduino Uno      Arduino Mega      MFRC522 board
     * ------------------------------------------------------------
     * Reset      9                5                 RST
     * SPI SS     10               53                SDA
     * SPI MOSI   11               51                MOSI
     * SPI MISO   12               50                MISO
     * SPI SCK    13               52                SCK

what the device will tolerate in terms of voltage on its pins is documented in chapter 11. Absolute max on most pins is 4.5 V, so the chance that 5V will fry the component is so high you probably don't want to try.

I think this is your board, and luckily they include a schematic on that page:

Here's it clearly visible that pin 1 is connected to ground, and pin 32 is connected to 3.3V, which shows that it's indeed hardcoded to SPI mode.

Thanks for helping out again, after helping me provide these informations. :)
As the device is hardcoded to SPI mode, I guess I do not need to worry about the other compatible host interfaces. I understand how Pin 1 being connected to GND would rule out the possibility of I2C mode, but how does EA being connected to 3.3V rule out the possibility that it uses UART communication?

@Tsubakura the communication mode is decided by the combination of pins 1 and 32, and UART needs pins 1 AND 32 tied to 0. That's explained in 8.1.1


text:
Creating a queue in Arduino?
Does anyone know if there is a way to create a queue of some sort for arduino?
My project consists of simulating multiple traffic lights with crossing pedestrians on an Arduino breadboard. Since I need to assume the situation where on all sides are cars waiting + pedestrians having pressed the button, I needed to figure out a way to store these inputs into an array of some sort.
However, the problem with array I believe is that it doesn't allow me to shift the data to the left, so that the next one will be selected in the queue. Deleting the data inside an array would only merely make it null, which doesn't work.
Greatly appreciated if someone can help me by pointing to the right direction.

This is a pure programming question: the answers would be no different if you were running the same code on a PC instead of an Arduino. You need to ask this on stackoverflow.com. (Well, actually you need to search there for the no doubt many existing questions asking things similar to this. :-))

Oh, so things purely related to Arduino should be posted here, while anything related to coding itself should be done in stackoverflow. Alright, i guess I finally know how this works, time to re-post this in the right place. :)

you can't shift array to left but you can move your pointer to right it will work similarly. for eg. your array array=[1,2,3,4,5,\0], you can denote any array element by array[i] and you can increment value of i by i++.

Actually, coding related specifically to the Arduino (e.g., "I have a problem when using this Arduino library") should be posted here. But what you've described is a generic programming problem. A good rule of thumb is to think, "would this application work just as well on a PC as on an Arduino, and the code I'm asking about be unchanged or almost unchanged?"

Hmm, I guess it then belongs in here? I mean, when it comes to other programming languages like Java, I would have no problem creating an ArrayList instead to do the job. I was actually unsure as to how to do this in arduino, hence why I thought about adding this here instead. I wasn't really used to a different language and the low amount of available memory. xD

Maybe this will be useful for you
http://playground.arduino.cc/Code/QueueArray

Template Queue class from Cosa; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Queue.hh used in the Event class https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Event.hh

Alternatively a double linked cyclic list (queue) with fast insert and remove at any position; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Linkage.hh used in Job/Scheduler queues; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Job.hh

You wrote: “the problem with array I believe is that it doesn't allow me to shift the data to the left”. No, that's not the problem: you can shift the data if you wish with memmove(). The problem is that doing so is inefficient, as you would be copying all the data each time you shift out one element. That's why the answers you got suggest implementing the queues as circular buffers.

@Tsubakura: The reason it still belongs in SO rather than here is because what you're asking is a pretty generic question about doing something in C. It's useful to say, when posting problems like this, "I know how to do this in Java" and perhaps even provide a small fragment of Java code so we can see how you're thinking and explain just the stuff you don't understand, rather than the stuff you do.

I wrote a simple queue library some weeks ago, you can find it in the arduino library manager, or here:
Queue
I think you need FIFO implementation, but LIFO is also implemented in the lib & possibility to overwrite previous records when full.
It can handle any structure or data type (as long as it's size is fixed for memory allocation), defining a number of records in the queue, then you're good to go.
2 methods are implemented to interact with the queue, push() & pull().
I'll probably add a peek() later on if needed.
I also noticed this other FIFO only queue lib in the library manager when I commited mine: MD_CirQueue
Hope this can help!

Regarding how to “create a queue of some sort for Arduino”, about the first thing to settle is how many items may need to be queued.  On a typical personal computer with gigabytes of RAM, queue size often is not much of an issue ... one just allocates a few more megabytes whenever necessary.  On an typical Arduino, however, with a few kilobytes or few tens of kilobytes of RAM, use of dynamic (heap) allocation is risky unless you carefully analyze possible execution paths.
If you are ok with a fixed queue size, the next issue is what kind of queue, eg FIFO, LIFO, priority, etc.  The question's concern about a “shift the data to the left, so that the next one will be selected in the queue” issue suggests a FIFO (first in first out) queue is desired.  For this, a circular buffer or circular queue is a relatively-low-overhead method often used.  Using terms from the wikipedia article, Start and End pointers are maintained, marking next-data-out and last-data-in positions.  Via modular arithmetic or if tests, each of these pointers wraps to array front whenever it goes past the array end.   The queue is empty if Start == End (modulo N, if queue size is N) and full if Start == End+1.
If an interrupt-driven process can modify pointers asynchronously to the main thread of execution, then synchronization methods need to be used to ensure atomic updates of pointers.  (This is true for all kinds of queues, not just circular ones.)
If instead of a FIFO queue you need a priority queue, a binary heap is easy to implement. Usually Fibonacci heaps and binomial heaps are not worth the extra trouble of implementing, except when you need efficient heap merging or secondary operations like decreasing keys of elements.  The Summary of running times section of wikipedia's binomial heap article shows the complexity of different operations across different heap structures.  Note that with Arduino RAM being so limited, a complexity difference like Θ(log n) vs Θ(1) is negligible; simplicity of code, leading to a compact implementation, is more important.
Note, also see QueueList Library For Arduino at arduino.cc.  This library apparently uses dynamic allocation.  It provides methods push(), pop(), peek() et al.  Also see QueueArray Library For Arduino at arduino.cc, which provides the same methods as QueueList, plus enqueue and dequeue() as synonyms for push() and pop().  Where QueueList uses lists to build its data structures, QueueArray uses arrays.
OsWrap at arduino.cc is a heavy package (eg 15KB flash, 1.5KB RAM) that supports various message and priority queue structures.
Depending on your rationale for using a queue, Task Scheduler Library may also be of interest.
As noted in Mikael Patel's comments above, Cosa platform software includes a Queue class, which is a “Template class for ring-buffer for queueing data elements”, with usage of the class illustrated in an Event class, which in turn is used in a Job class.

I had an arduino project that I needed to build a queue for.
You can download the source code and copy into a file called Queue.h next to your arduino project.ino file.
Here is a simple interactive example (with the Serial monitor) to see how its used, make sure you set the baud rate to 115200 and No new line.
#include "Queue.h":

Queue<char> queue(10);

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

void loop() {
  while(Serial.available()) {
    queue.push(Serial.read());
  }

  Serial.print(millis() / 1000);
  Serial.print(": ");
  int count = queue.count();
  if (count > 0) {
    Serial.print("Found ");
    Serial.print(count);
    Serial.print(" items.. '");
    Serial.print(queue.pop());
    Serial.print("' is the oldest. Next is.. '");
    Serial.print(queue.peek());
    Serial.println("'.");
  } else {
    Serial.println("Nothing to process...");
  }
  delay(2000);
}


text:
Trying to move a stepper motor back and forth
So, I am trying to move a stepper motor through a halfway revolution (1024 steps), and once that is completed, have it move back and forth by about 100 steps in either direction.
I am having some trouble with this though, because while it will move in one direction, it will not move in the other.
void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      forthMotion(stepper1.currentPosition());
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

So, when I call the forthMotion function right after the backMotion function, it will just move forward. Which makes no sense to me. Shouldn't it be moving backwards, and then forwards in an infinite loop?
Because it will hit 1024, go back to 824, hit 1024 again, and so on and on...
Also, when I call the backMotion function, isn't the Arduino code supposed to be blocking in that, nothing else gets executed while that is running?
Edit: The code seems to work when I uncomment the if statement in the loop function.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Your current snippet does not reveal which libraries you are using or how you declared and initialized the stepper1 object.  Anyhow, please edit your question to include that information via an MCVE.

Looks like you are missing a few  stepper1.runSpeedToPosition();

@MikaelPatel - why do I need the runSpeedToPosition function?

The manual says "Runs at the currently selected speed until the target position is reached". You might want to give the stepper some time to complete the operation. http://www.airspayce.com/mikem/arduino/AccelStepper/MultiStepper_8pde-example.html

You also need to define what "stepper1" is in your scope.

I guess the solution might be this:
in back motion
void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

In forward motion
void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}

In loop
void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    stepper1.moveTo(1024);
    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

Your main code will be like this
void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    delay(3000); // wait till stepper gets to destination
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}

Steppers don't typically have feedback about their position (as opposed to servos). Normally you're just telling a stepper how much and how quickly to rotate. As opposed to servos, which you tell which position to rotate to.
Are you sure you're using a stepper?

Nothing in the posted question supports your theory.


text:
ModbusMaster - Read 64 Bit integer
i'm using ModbusMaster library (Repo) to read from a device some registers.
Many of them are float and i've no problem to read them using the following code:
  //for float conversation
  union
    {
      uint32_t i;
      float f;
    }u;
    uint8_t result = node.readInputRegisters(address, 2); // for 3000xx registers
    Serial.println("Result : " + String(result));// to get error type
    if (result == node.ku8MBSuccess)
    {
         u.i=(((unsigned long)node.getResponseBuffer(0x01)<<16) | (node.getResponseBuffer(0x00)));// shifting 2nd register to left & stiching with 1st register
    }
    Serial.println("Reading is "+String(u.f));

But i have the energy registers that are 64 Bit unsigned int and i can't figure out how to adapt the above code in order to read them.
Anyone has a solution?

64bit must be stored in two registers. so (r1 << 32) | r2 or (r2 << 32) | r1


text:
Reading SNMP V2 OID from ESP8266/ESP32
i need to read from my ESP32/ESP8266 some SNMP V2 OID values from my home printer: it exists a library/method that can do that?
I've seen some SNMP agents, but they works only with the devie as server and not as SNMP client.
Any thoughts?

SNMP agents are servers. In the SNMP world, clients are called managers.

Not sure if you found it, but there I created an SNMP Manager: https://github.com/shortbloke/Arduino_SNMP_Manager
There is also an SNMP Agent: https://github.com/0neblock/Arduino_SNMP
I know this is a bit later than when you requested this info. But posting here in case it's still helpful to you or others that stumble over this question.


text:
Atmega328 and ADXL335 - is the right choice for vibration analysis?
I'm planning to use the ATMEGA328 and the ADXL335 accelerometer to monitor the bearing and gears vibration of a industrial extractor that works at maximum speed of 3000rpm at 380VAC - 50Hz .
The main scope of this monitoring is to get continuously the vibration readings and apply the FFT transform in order to identify if there is something that is not running well.
My primary concerns are regarding the sampling speed of the ATMEGA328P: i've tried to identify the needed sampling speed but i'm a little bit confused about the relation of motor/gear speed and the ADC sampling speed of the ATMEGA...also, the ADXL is the right choice?

According to nyquist-shannon you have to sample at 2x your maximum interesting frequency. That's probably the same as your max RPM, so 6000sps. You need to take 6000 readings per second from the ADXL, and if you want all three axes that's 18,000sps (if you want the values concurrently). The Arduino can (from a quick google) manage about 9615sps.

You could just about manage 1 axis with that. You could cycle through the three axes and take a sample block from each one and FFT it in turn I guess.

However, the ADXL335 can only go up to 1600Hz, so won't be able to get anywhere near your needed sample frequencies. You may be better thinking about audio instead of vibration.

I would say that depends on how you identify that "something is not running well". What frequencies do you expect to find then. Did you some research?  Also, the ADXL335 is a device with radiometric analog output with negative voltages. Did you plan how to read that with a arduino?

And, where do perform the FFT? On the Arduino? ;-)

Actually the ADXL is only one candidate sensor, something like that may be better: https://www.pcb.com/products?m=639a91

@PeterPaulKiefer, my initial purpouse is to get the "vibration fingerprint" when the extractor is okay and works well and then monitor it during time and correlate the result of the frequency analysis with the typical frequency fingerprint of the monitored components (bearings, for example)

I fear the arduino approach is not the best, as long as you are fishing in the dark. You don't know what frequencies (fingerprints) you should expect. For research purposes you should use equipement with a wider and deeper view into the domain. Let's say an error leads to overtone frequencies of 23.000 HZ. Then none of the sensors you mentioned would suffice the pcb one would even get in resonance. And the arduino would be out of the race. Finding out what you need means finding the condition you have to search for. You may find some research results. Standing on the shoulders of giants. ;-)

@Majenko, the ATmega328 can sample up to 50Ksps by speeding up the ADC at the cost of slightly reduced resolution. I do it in my library in this switch case here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_analogReadXXbit/blob/Version_2/eRCaGuy_NewAnalogRead.cpp#L66. 50ksps is kind of the "sweet spot" where you get 5x faster than normal sampling speed with very little loss in resolution. You can sample faster still by further speeding up the ADC ckock, but resolution losses increase more and more, eventually down to something like 7 bits vs the Arduino's default 10 bits.

For anyone wondering about how analog sampling can affect the voltage on the line being sampled, when sampling too fast, see my answer here under the section I titled "Which ADC sampling time should I choose?", near the end of my answer.

Gabriel, about the sensor and the desired measurements, you have some advices to give?

@Symon, can you post a link to the ADXL datasheet? I don't know anything about it. As for sample rate, any sample rate > 2x the maximum vibrational frequencies you care about it enough to do post analysis FFT, as Nyquist says. So, what vibrational frequencies do you care about? If the ADXL is analog, the fastest you can do a single channel ADC sampling in the ATmega328 is about 10kHz by default or about 50kHz if you speed up the ADC clock. If the ADXL is digital, it's different. You also have to consider how you will log or transmit the data stream live.

Lastly, you may need to set up the ADC to do jitter free continuous sampling rather than blocking sampling which is the Arduino default when you call analogRead(). I'm sure @nickgammon has some examples of this (jitter free continuous sampling) on his website. The low level details will all be in the ATmega328 datasheet, but expect to read it for days to understand it, and get an experienced embedded systems developer to walk you through it for an hr or two to start.

@Symon, I left an answer. Please remember to always leave purchase links, datasheet links, etc, for any specific device you are asking about in the future. Hopefully my answer sheds some light on the situation. A sound card could potentially be a great way to go, as they are designed to sample up to the hundreds of kilohertz usually, to sample high-quality voice, music, and audio.

Thanks for the support @GabrielStaples, for completeness, this is the sensor that i've picked: https://www.analog.com/media/en/technical-documentation/data-sheets/adxl335.pdf

My primary concerns are regarding the sampling speed of the ATMEGA328P

The ATmega328 can sample up to ~10ksps (kilo-samples-per-second) in normal configuration and at 10-bit ADC resolution, or reliably and with good (near 10-bit) resolution up to ~50ksps if you speed up the ADC clock. You can get even faster if you want to sacrifice a lot on sample resolution, but at faster speeds this processor is too slow to even reliably grab the data and transmit it or store it, so you should go to a much much beefier and better microcontroller, such as a 32-bit Arduino Zero, Portenta, or non-Arduino STM32 or something.
Example of speeding up the ATmega328 to sample up to ~50kHz:
See my library here, and my initial article on it here.
#include <eRCaGuy_NewAnalogRead.h>

void setup()
{
    adc.setADCSpeed(ADC_FAST); // now analogRead() will operate up to ~50 kHz
}

void loop()
{
    // these readings can now be done up to ~50 kHz
    uint16_t reading = analogRead(A3);
}

I don't remember the exact details of configuring the ADC clock, but it's all in the ATmega328 datasheet, and in my code--which you can study at the library link above, and you can look at Nick Gammon's website on it here: https://www.gammon.com.au/adc.
How fast do you need to sample? Only you can answer that question.
Perhaps you read some academic paper that says that vibrations of 102kHz on a 5cm diameter motor made of material X can cause microfractures in the material if exposed for 100 hours. Well, in this case, you need to sample at at least 204kHz (2x the frequency of interest) to see if 102kHz vibrations exist.
Or, perhaps you just want to use FFT to determine the RPMs of the motor since it will almost certainly have a dominating frequency at its rotational frequency due to imperfect balance of the motor. In that case, sampling at 2x the max RPM (but in samples per second, not minute) is sufficient. You stated a max rotational speed of 3000 RPM, so that's 3000 rot/min x 1 min/60 sec = 50 Hz. To detect your RPM, therefore, by sampling vibration, you need to sample at least 2x as fast as this, or 100 Hz or higher.
Remember, this is all Nyquist frequency stuff. All that the Nyquist frequency says is [in my own words]:

you can only detect a frequency up to 1/2 as high as your sampling rate

...or otherwise stated [in my own words]:

you must sample at 2x whatever frequency it is you are trying to measure

Any sample rate lower than this, and you get aliasing and it is mathematically and physically impossible to determine if a higher frequency exists. Any frequencies higher than 1/2x your sample rate which appear to exist in your FFT analysis must be thrown out, as they are invalid.
So, what max vibrational frequency do you need to measure? That's for you to find out. If you're looking to find gear tooth wear (ex: a broken, cracked, or missing gear tooth), you can come up with some estimations based on number of teeth per rotation, and knowing your motor's max rotational speed in rotations per second.
Example: assuming 32 teeth per revolution, you will be rotating at 3000 rot/min / 60 sec/min = 50 rot/sec x 32 teeth/rot = 1600 teeth/sec. But, to identify a broken tooth maybe you need to do a waveform analysis of the shape of the wave over that broken tooth, so you should sample at 5x to 10x that rate, or perhaps 1600 teeth/sec x 10 samples/tooth = 16000 samples/sec = 16 kSps. But...5 samples per tooth might be enough, or only 8 kSps...
See how some of this analysis might work? You have to figure out what it is you're trying to figure out, and sample accordingly. If you don't know what you're trying to figure out, just sample as fast as you can and then with that data try to see what you can figure out from what you just sampled! Such are the ways of engineering and curious minds! :)

With that being said, assuming you use my library's adc.setADCSpeed(ADC_FAST); trick, you can sample 1 channel up to 50kHz or 3 channels up to 50/3 = ~16kHz, meaning the max vibrational frequency you can detect with FFT for 3 channels is ~8kHz with an ATmega328. Is that enough?
BUT, you will have jitter problems unless you put the ADC into continuous sample mode at a fixed interval, and you cannot sample all 3 channels at once, so there will naturally be an offset between them all, as they happen in sequence one after the other.

How fast can the ADXL335 sample? (ie: what's its "bandwidth", or frequency response?)
As for the ADXL335, its datasheet reveals it to be an analog 3-axis accelerometer, not a digital one, so you are limited by:

how fast the ADC you have on your microcontroller can sample the sensor (we already came up with ~16khz (kSps)/channel, for 3 channels, above) and
what the ADXL335's bandwidth, or max frequency response, is.

The datasheet (see image below) says you get a bandwidth of 0.5 Hz to 1600 Hz for the X and Y axes, and 0.5 Hz to 550 Hz for the Z axis, all depending on the chosen bypass capacitors, cx, cy, and cz you choose for it. See the image and highlighting below.

Bandwidth means simply [in my own words]:

Bandwidth is the maximum frequency at which a device can respond to changes in the thing is it measuring (ex: an accelerometer to changes in acceleration).

By definition, a bandwidth for a low-pass filter, or a sensor responding to a high-frequency input, is equal to the frequency at which point the measurement of the thing being measured is attenuated by 3 db, or in other words, is 1/sqrt(2) = 0.707 times as big as the actual thing being measured. So, if the bandwidth of an accelerometer is 50 Hz, then that means if it tries to measure a 50 Hz vibration, then the measurement it outputs at that frequency is attenuated to 0.707x as large as the actual amplitude of that vibration. Therefore, it is said that this sensor cannot be reliably used to measure higher frequencies than this. Note that since Power = V^2/R, and the 0.707 rule applies to voltage, the attenuation is 0.707^2 = 0.5 for power.
If you bought your ADXL335 sensor from Adafruit here for $15 (https://www.adafruit.com/product/163), they state:

The XYZ filter capacitors are 0.1uF for a 50 Hz bandwidth

...which means they chose capacitors to give it a 50 Hz bandwidth, or frequency response. This means the sensor is limited to reliably measuring vibrations only up to 50Hz. You should sample at least 2x this bandwidth then in order to adequately capture frequencies up to that value, again, based on Nyquist. This means for this Adafruit version of the device and with these chosen bypass capacitors you can sample at 100 Hz or higher to detect vibrations up to 50 Hz (that's Hertz, not kiloHertz!). Even if you sample much much faster, the maximum reliable frequency this device can measure is only up to 50 Hz before attenuation of its measurements becomes a significant concern. Whether sampling at 100 Hz or 1000 Hz, the frequency this sensor can measure, in this configuration, is only up to 50 Hz, which is only 50/sec x 60sec/min = 3000 RPM if your goal is to just detect the rotational frequency, but not any higher-frequency vibrating modes, for your device.
A 50 Hz bandwidth (max frequency response), FYI, is optimized to reduce sample noise for handheld tilt-based game controllers, as it intentionally attenuates any frequencies above 50 Hz, and 50 Hz input from a human is a good expectation for human control signals. You might sample this sensor for such a game controller anywhere from 50 Hz to 1 KHz, but again, it can't detect vibrations any faster than about 50 Hz. So, the Adafruit version of the ADXL335 is optimized to be used to make home-made tilt-based hand controllers for games, toys, smart devices, radio control devices, etc.
Extra note on sampling frequency
Even though the Nyquist frequency says you only need to sample 2x the frequency of interest to detect the frequency of interest through FFT or similar, you need to realize that if you ever want to plot a given signal or inspect its shape or waveform, you should sample at least 5x to 10x as fast as the frequency of the signal you are trying to record and inspect.
This is how oscilloscopes are rated. A "100 Mhz" bandwidth oscilloscope will have a sample rate of at least 5x to 10x that, or 500 MSps (Mega-samples-per-second) to 1 GSps (Giga-samples-per-second). This makes sense because the purpose of an oscilloscope is to plot waveform shapes, and that requires at least 5 to 10 points per period, or 5x to 10x the sample rate of the rated bandwidth in order to display a reasonably-nice picture of the waveform.
For pure FFT or frequency analysis, where you just want to know the frequency of the thing being measured, but don't need to know how the waveform looks, a sample rate exactly 2x or higher than the frequency of the thing being measured is physically and mathematically sufficient.

Thanks Gabriel, this is one of the most complete answer that everyone gave me in my entire life! have a good day man! thanks!
Now, the only remaining question is: looking at commercial MEMS sensors, you have some recommendations about where i need to point in order to sample also higher frequencies...maybe this sensor is the right choice: http://static6.arrow.com/aropdfconversion/c9b572888f3b1329b19ec85b0ef62a2d2c923af5/adcmxl3021.pdf

@Symon, yeah, that looks like a great sensor! It is a digital sensor with its own built-in ADC up to 220 kSps, FIR filters, internal FFT capability, etc. I see a it uses CS (Chip Select), SCLK (Serial Clock), DIN (Data In--MOSI (Master Out Slave In)), DOUT (Data Out--MISO (Master In Slave Out) pins, meaning it communicates over SPI. You'll have to figure out how to do that. Will be a learning curve for sure, but absolutely, go get one and get to it!

First of all, 3000 RPM is only 50 Hz, so sampling is not a problem for the fundamental frequency.  But you usually want to see harmonics, to pick up gear tooth issues, etc.
I suggest using my Daqarta software with a sound card to do your initial testing.  It already does everything you need, including waveform, spectrum, and spectrogram displays plus a lot more.  You can use it free for 30 sessions or 30 days, then the sound card inputs are no longer supported.  By that time you should have a good idea about what you need.  As it turns out, Daqarta also supports Arduino, and that does not end with the trial period.  So you may be able to do everything with an Arduino, for free.  The Daqarta site also has a contact page, and I am glad to answer questions and provide specific help for any issues that arise.  That include free users.


text:
Matrix and State Space Arduino Implementation
I wrote an Arduino Matrix class. Then I used this class to implement State Space on Arduino.
During tests I stomped upon a problem. After starting the program it stops at some point. I have no idea why this is happening. There are no error messages.
Can you please tell me what im doing wrong?
Here is my code:
//"Matrix.h"
#ifndef _Matrix_h
#define _Matrix_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif
class Matrix
{
private:
    unsigned row_number = 0;
    unsigned column_number = 0;
    double* elems;

public:

    //Constructors + Destructor
    Matrix();
    Matrix(double, unsigned row_number = 1, unsigned column_number = 1);
    Matrix(double*, unsigned row_number = 1, unsigned column_number = 1);
    Matrix(const char*);
    Matrix(const Matrix&);
    void operator=(Matrix);
    ~Matrix();

    //Comunication Methods
    unsigned get_rows() const { return row_number; };
    unsigned get_columns() const { return column_number; };
    double& operator()(const unsigned row, const unsigned column);
    double valueAt(unsigned row, unsigned column) const ;
    void print() const;
    bool mRead2();

    //Matrix Operations
    Matrix operator+(Matrix);
    Matrix operator-(Matrix);
    Matrix operator*(Matrix);
    Matrix transpose();

    //Scalar Operations
    Matrix operator+(double);
    Matrix operator-(double);
    Matrix operator*(double);
    Matrix operator/(double);

};
Matrix mRead(unsigned row,unsigned column);
#endif

//"Matrix.cpp"

#include "Matrix.h"
Matrix::Matrix() {
  row_number = 0;
  column_number = 0;
  elems = new double[0];
}
Matrix::Matrix(double val, unsigned row_number, unsigned column_number) {
  this->row_number = row_number;
  this->column_number = column_number;
  elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i < row_number * column_number + 1; i++)
    elems[i] = val;

}

Matrix::Matrix(double* elems, unsigned row_number, unsigned column_number)
{
  this->column_number = column_number;
  this->row_number = row_number;
  this->elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i < row_number * column_number + 1; i++)
    this->elems[i] = elems[i - 1];
}

Matrix::Matrix(const char*)
{

}

void Matrix::operator=(Matrix A){
  this->column_number = A.get_columns();
  this->row_number = A.get_rows();
  this->elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i <= row_number; i++)
    for (unsigned j = 1; j <= column_number; j++)
      this->elems[(i - 1) * (column_number) + j] =  A.valueAt(i, j);

}

Matrix::Matrix(const Matrix& A) {
  this->column_number = A.get_columns();
  this->row_number = A.get_rows();
  elems = new double[row_number * column_number + 1];
  for (unsigned i = 1; i <= row_number; i++)
    for (unsigned j = 1; j <= column_number; j++)
      this->elems[(i - 1) * (column_number) + j] =  A.valueAt(i, j);

}

Matrix::~Matrix()
{
  delete[] elems;
}

double& Matrix::operator()(const unsigned row, const unsigned column)
{

    return this->elems[(row - 1) * (column_number) + column ];

}

double Matrix::valueAt(unsigned row, unsigned column) const
{

    return this->elems[(row - 1) * (column_number) + column ];

}

void Matrix::print() const
{
  for (unsigned i = 1; i <= get_rows(); i++) {
    for (unsigned j = 1; j <= get_columns(); j++) {
      Serial.print(this->valueAt(i, j));
      Serial.print(" ");
      Serial.flush();
    }
    Serial.print("\n");
  }
}
Matrix mRead(unsigned row, unsigned column) {
  int sizeM = row * column;
  double m[sizeM];
  char buffor[64];
  for (int i = 0; i < 64; i++) {
    buffor[i] = 0;
  }
  for (int i = 0; i < sizeM; i++) {m[i]=0;}
  for (int i = 0; i < sizeM; i++) {
    while (!Serial.available()) {
      Serial.write(32);
    }
    int j = 0;
    while (Serial.available() > 0) {
      Serial.println(Serial.available());
      buffor[j] = Serial.read();
      j++;
      Serial.flush();
    }
    m[i] = (double)atof(buffor);
    Serial.flush();
    //for (int i = 0; i < 64; i++) {
    //  buffor[i] = 0;
    //}
  }
  return Matrix(m, row, column);
}
bool Matrix::mRead2() {
  int sizeM = row_number * column_number;
  double m[sizeM];
  char buffor[64];
  for (int i = 0; i < 64; i++) {
    buffor[i] = 0;
  }
  for (int i = 0; i < sizeM; i++) {m[i]=0;}
  for (int i = 0; i < sizeM; i++) {
    while (!Serial.available()) {
      Serial.write(32);
    }
    int j = 0;
    while (Serial.available() > 0) {
      Serial.println(Serial.available());
      buffor[j] = Serial.read();
      j++;
      Serial.flush();
    }
    m[i] = (double)atof(buffor);
    Serial.flush();
    for (int i = 0; i < 64; i++) {
      buffor[i] = 0;
    }
  }
  *this=Matrix(m,row_number,column_number);
  return true;
}
Matrix Matrix::operator+(Matrix A)
{
    Matrix sum = Matrix(0.0, row_number, column_number);
    for (unsigned i = 1; i <= row_number; i++)
      for (unsigned j = 1; j <= column_number; j++)
        sum(i, j) = A.valueAt(i, j) + this->valueAt(i, j);

    return sum;
}

Matrix Matrix::operator-(Matrix A)
{
    Matrix diff = Matrix(0.0, row_number, column_number);
    for (unsigned i = 1; i <= row_number; i++)
      for (unsigned j = 1; j <= column_number; j++)
        diff(i, j) = A.valueAt(i, j) + this->valueAt(i, j);
    return diff;

}

Matrix Matrix::operator*(Matrix A)
{
  Matrix mult = Matrix(0.0, row_number, A.get_columns());
    double temp;
    for (unsigned i = 1; i <= row_number; i++) {
      for (unsigned j = 1; j <= A.get_columns(); j++) {
        temp = 0.0;
        for (unsigned k = 1; k <= column_number; k++)
          temp += this->valueAt(i, k) * A(k, j);
        mult(i, j) = temp;
      }
    }

    return mult;
}

Matrix Matrix::transpose() {
  Matrix transpose = Matrix(0.0, row_number, column_number);
  for (unsigned i = 1; i <= row_number; i++) {
    for (unsigned j = 1; j <= column_number; j++) {
      transpose(i, j) = this->valueAt(j, i);
    }
  }
  return transpose;
}

Matrix Matrix::operator+(double x)
{
  Matrix A = Matrix(x, row_number, column_number);
  return *this + A;
}

Matrix Matrix::operator-(double x)
{
  Matrix A = Matrix((-1) * x, row_number, column_number);
  return *this + A;
}

Matrix Matrix::operator*(double x)
{
  Matrix A = Matrix(*this);
  for (unsigned i = 1; i <= row_number; i++)
    for (unsigned j = 1; j <= column_number; j++)
      A(i, j) = this->valueAt(i, j) * x;
  return A;

}

Matrix Matrix::operator/(double x)
{
  if (x != 0) {
    Matrix A = Matrix(*this);
    for (unsigned i = 1; i <= row_number; i++)
      for (unsigned j = 1; j <= column_number; j++)
        A(i, j) = this->valueAt(i, j) / x;
    return A;
  }
  else {} //throw "Dividing by zero";
}

//"StateSpace.h"

#ifndef _StateSpace_h
#define _StateSpace_h
#include "C:\Users\Wojciech Trybulec\Desktop\Test\Matrix.h"
class StateSpace
{
private:
    Matrix State;
    Matrix A;
    Matrix B;
    Matrix C;
    Matrix D;
    Matrix Out;
public:

    //Constructors + Destructor
    StateSpace();
    StateSpace(Matrix A, Matrix B, Matrix C, Matrix D);
    StateSpace(Matrix A, Matrix B, Matrix C, Matrix D,Matrix InitState);
    StateSpace(const StateSpace&);
    StateSpace operator=(StateSpace);
    ~StateSpace();

    //Comunication Methods
    Matrix get_states() const;
    Matrix get_output() const;
    Matrix* get_all() const;
    void calculate(Matrix Signal);
    void print_states() const;
    void print_output() const;
    void print_matrices() const;

};
#endif

//"StateSpace.cpp"
#include "C:\Users\Wojciech Trybulec\Desktop\Test\Matrix.h"
#include "StateSpace.h"
StateSpace::StateSpace() {
    A = Matrix();
    B = Matrix();
    C = Matrix();
    D = Matrix();
    State = Matrix();
    Out = Matrix();
}
StateSpace::StateSpace(Matrix A, Matrix B, Matrix C, Matrix D) {
    this->A = A;
    this->B = B;
    this->C = C;
    this->D = D;
    this->State = Matrix(0.0,A.get_columns(),1);
    this->Out = Matrix(0.0, C.get_rows(), 1);
}
StateSpace::StateSpace(Matrix A,Matrix B, Matrix C, Matrix D,Matrix InitState){
    this->A = A;
    this->B = B;
    this->C = C;
    this->D = D;
    this->State = InitState;
    this->Out = Matrix(0.0, C.get_rows(), 1);
}
StateSpace::StateSpace(const StateSpace& ss) {
    this->A = ss.get_all()[0];
    this->B = ss.get_all()[1];
    this->C = ss.get_all()[2];
    this->D = ss.get_all()[3];
    this->State = ss.get_all()[4];
    this->Out = ss.get_all()[5];
}
StateSpace StateSpace::operator=(StateSpace ss) {
    this->A = ss.get_all()[0];
    this->B = ss.get_all()[1];
    this->C = ss.get_all()[2];
    this->D = ss.get_all()[3];
    this->State = ss.get_all()[4];
    this->Out = ss.get_all()[5];
}
StateSpace::~StateSpace() {
    delete this;
    //A.~Matrix;
    //B.~Matrix;
    //C.~Matrix;
    //D.~Matrix;
    //State.~Matrix;
    //Out.~Matrix;
}

Matrix StateSpace::get_states() const {
    return this->State;
}
Matrix StateSpace::get_output() const{
    return this->Out;
}
Matrix* StateSpace::get_all() const {
    Matrix all[6];
    all[0] = A;
    all[1] = B;
    all[2] = C;
    all[3] = D;
    all[4] = State;
    all[5] = Out;
    return all;

}
void StateSpace::calculate(Matrix Signal) {
    State = ((A * State) + (B * Signal));
    Out = ((C * State) + (D * Signal));
}
void StateSpace::print_states() const {
    State.print();
}
void StateSpace::print_output() const {
    Out.print();
}
void StateSpace::print_matrices() const {
    A.print();
    B.print();
    C.print();
    D.print();
}

And this Arduino sketch that im using for testing:
#include "Matrix.h"
#include "StateSpace.h"
double a[4]={-0.5,0,0,0.7};
double b[2]={1,2};
double c[4]={1,0,0,1};
double d = 0;
Matrix A=Matrix(a,2,2);
Matrix B=Matrix(b,2,1);
Matrix C=Matrix(c,2,2);
Matrix D=Matrix(d,1,1);
Matrix x=Matrix(0.0,2,1);
Matrix U=Matrix(1.0,1,1);
StateSpace ss=StateSpace(A,B,C,D);
void setup()
{
  Serial.begin(9600);
}
void loop() {
  ss.calculate(U);
  x=ss.get_states();
  Serial.print(x.valueAt(1,1));
  Serial.print("\t");
  Serial.println(x.valueAt(2,1));

  delay(100);
}

I really hope that you can help me

I would say the dynamic memory allocation is the culprit. Everytime you create a Matrix, you are allocating dynamic memory. And you are creating a lot of matrices. Even when deleting everthing correctly, you are making swiss cheese out of your memory, aka heap fragmentation. Rewrite your code to not use dynamic allocation

What the hell is this: delete this;? Are you trying to make recursion inside of destructor? Also forget this->, there is no need for it - it's not PHP

Btw, after longer look at that code - it's really bad. It could be much shorter, also bit faster as it's doing lots actions twice and even more.

This is not a solution (meaning to pinpoint the exact problem), but to find out yourself.
There are mainly two ways to debug this:

On Arduino: Try placing Serial.print statements to see where it stops (like putting them on the beginning of every function, or on other 'strategic' places. When you found which function stops, try putting print statements within. So within two 'runs' you can find which line is causing the problem. What I normally do is just number the print statements, e.g. function 1 you print values 100..200, next function 200.300 etc. So you can easily leave them for later reusage (just comment them out).
Unit test on PC: If you didn't already do, test your class on a PC... this will give you much better debugging tools than an Arduino. When you know the class itself work, create a small test sketch on the Arduino (but high likely it will work, unless you made a mistake in the test sketch). For a PC, consider writing a so-called unit-test ... so even later when you change something, you can test you didn't break anything else.

In both cases (if you start on PC also do this), check for memory usage. The Arduino has only 2 KB SRAM, on a PC you can already check how much is used. The SRAM usage shown during compiling only takes into account global variables. It does not take into account:

Local variables
Dynamic variables (made with new, malloc)
Stack (passed parameters).

During PC debuging I noticed that it keeps using more and more memory. It probably doesnt destroy created objects. Could you please tell me how to fix this or at least give me some tips?

I didn't look good enough, I see a lot of new statements which create dynamic variables. These are not counted. I don't have a quick fix, but for an Arduino with only 2 KB SRAM it's very unrecommendable to use dynamic memory (there are a few exceptions). Also when you assign or pass parameters, maybe those (copy?) constructors are used, creating a copy (maybe temporarily).  But sometimes you might need a copy (if you want to keep the original). That's hard to say, since I don't know  your requirements.

I added delete [] elems in operator=. It solved my problem. Thanks a lot for help.

Great you found it (yourself) ... wonder why this didn't show up in Windows ... however, stay warned for memory issues.

@sanX you should read something about Rule of Three / Rule of Five. You'll find out adding delete into copy assigment operator and destructor is not enough.


text:
Arduino emulator to create virtual 3d printer farm
I'm building a system to monitor several 3d printers, but I just have 1 printer. I'm thinking if there is any opensource tool to launch several virtual Arduino based boards running with Marlin firmware to accomplish my task. I'm planning to use Ocoprint for monitoring every board, so I need one serial port to communicate with the virtual printer.
I already modified the firmware in such a way that it runs on a clean ArduinoMEGA (without any shield) and it worked as I need.
I check the suggestions on this related thread but I'm not sure if any of them will work as I need.

Have you tried any of them? I would say it would be a far fetch to think, that any of them can really run the Marlin firmware (which is rather complex). Though you only need idle serial communication, so it might work. You should really try it first, because it is very difficult and complex to answer this. To write an answer without trying it, we would need to know the Marlin firmware and the simulators (not emulators) in detail, with all their requirements and caveats. It is just easier to try it first.

@chrisl I have tried the simulide, simavr, simultron none of them give an answer for serial communicaction


text:
Connect k-type termocouple using o-amp
first of all I have to say that this is my first Arduino thing. I'm trying to connect a k-type termocouple to my Arduino using an LM2904 Oamp, Yes I know that this is not the best solution but is the only that I have right now due to the pandemic situation, that I can't get a dedicated module as an MAX6675
This is what I have done:

note: The Grnd symbol next to 2.6k resistor is a handwritten error, its not connected in the circuit
my problem is that with this circuit I'm having 3.7V on the arduino analog input even before connect the termocouple. After connect it, the read is about 2.6V and it starts to increase as expected when heat is applied.
My problem is if I have 2.6V for 32°C for temperatures over 200°C I will have more than 5V. Any help with this?

Do you need to measure temperatures over 200°C? If not, thats ok. The opamp cannot output a higher voltage than its supply voltage, thus it cannot exceed 5V in your circuit. If you need to measure also that range, you need to change the amplification of your circuit by changing the resistor values

The MAX6675 is obsolete. You should be considering the MAX31855 or MAX31856 instead.

@chrisl, thanks for yours suggestions, I know that I wold have to change the values of my resistors, but, its normal to have 3.7V in the output even with no inputs? with my current setup I have expect to have near .5V not 2.6V I dont know what is wrong here

Why do you think, that you get 0.5V without anything connected? The pin would be floating then, so the opamp will be amplifying the noise, thats flying around.

@chrisl no I spect to have near 0.5V for on 32°C which is 1.2mV on the K thermocouple table


text:
Having some trouble incrementing counters
So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.
I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.
The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.
Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?
void loop()
{
    stepper1.run();
    int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      ctr++;
      Serial.println(ctr);
    }
    Serial.println(ctr);
    if(stepper1.currentPosition() == 824 && ctr > 0){
      forthMotion(stepper1.currentPosition());
    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

@KingDuken I'll correct you because you are wrong. Normally you are right, but the Arduino IDE inserts function prototypes automatically for you which allows you to be lazy with your function ordering.

Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.
The line:
int ctr = 0;

literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens every time loop() is executed.
Instead making it static will change it so that it only happens the first time loop() is executed so it retains its value across successive executions of loop().
static int ctr = 0;

Agreed. A declaration int ctr = 0; inside a function tells the compiler to assign 0 to ctr every time it passes that line.

loop() != main()
when declaring a variable inside a function, it is cleaned up when returning from the function.
if cnt was in a main() function, it would have worked (as it's the only function that may have an infinite loop in a program. In the arduino world, it's not the case. The main() function is hidden, but loop calls the loop() function.
Workaround is to use the static quelifier when you declare variables inside loop() (or in any other function if you want the variable to remain inside the function scope, but don't want it to be initialized each time you enter the function).


text:
Chromebook/chromebox IDE/compiler option?
My daughter has a chromebox she uses for all her email/homework/etc.  We've started to get into making ADABOX projects and I was looking for best options for chromebook users.  I saw that codebender was shutting down.  And Chromeduino looks like it might have problems with libraries.  Currently I am looking to just set her up with a Raspberry Pi she can connect to with her chromebox and use it to connect to the Arduinos/Feathers, since I know she will need libraries and things from adafruit.  But I was hoping there might be newer options I haven't found yet.

Arduino Create?

@Majenko from what I can tell it does not have a way to connect USB to Chromebook like codebender.

Ah well. Maybe the pi is the best way. She'll learn Linux too then.

authors: Роман Скверис


text:
How do i fix the "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header"
I have an AI Thinker ESP32-CAM and I've had issues uploading the CameraWebServer sketch, every time I hit upload it says "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header" and I've tried everything that I can think of, I disconnected and reconnected all the connections on my FTDI board and I've done all sorts of button presses during the connection, I've switched the voltage and I've bought a whole new board and I don't know what the issue is or how to fix it.

Did you connect IO0 to Ground?

ESP32 only works with 3.3 V serial do not switch the FTDI voltage to 5 V
Watch out for the serial connections too
U0R-->TX
U0T-->RX
If you mixed it up it won't work!
First of all you need to connect two pins only when uploading
It is all ready fixed for you need to press the rest button when uploading
and seeing these dots as below image.

ESP32-CAM on-board RST button Press and hold until you see uploading

After a few seconds, the code should be successfully uploaded to your board.
I hope this helped for you!
You can reffer to this link for more info
https://randomnerdtutorials.com/esp32-cam-take-photo-display-web-server/

Good info about ESP32. In addition, I think some confusion comes from the ESP32-CAM, which does have +5V option. And you have to ground GPIO0 in order to program that board. But other than that they are very similar. Again, this comment and link applies to ESP32-CAM, as the original question asked about. https://randomnerdtutorials.com/program-upload-code-esp32-cam/

I have had the same problem / error message with a different board. I did not realise that during upload you must make sure that any GPIO pins that the board uses to talk to the flash chip are NOT connected to other devices. The upload process should be:

Disconnect any GPIO pin connectors.
Upload your code.
Reconnect any GPIO pin connectors.

(In your question, you say "I disconnected and reconnected all the connections" but you do not say whether all your connections were disconnected while you were trying to upload your code.)
I found this information here (the text in that post says "This message normally means that the ESP32 can't talk to its attached flash chip (the flash chip may be in the module). Check the GPIO pins 6,7,8,9,10 & 11 (which are shared with the flash chip) are not connected to anything external or shorted together, etc.")
HTH.


text:
Stereo audio Arduino MKR Zero
I am doing a project in which I need to have a stereo audio output in Arduino MKR Zero. The quality of the audio is not important: 8 bit, 44 kHz would be enough. Is it possible to use two combined PWM outputs to do that, maybe with the library TMRpcm (is it supported by MKR?)? Or is it a better solution to interface it with a I2S stereo DAC?
Thank you
Alessandro


text:
Replacing BT module with 433 MHz transreceiver module
I have made a prototype where I can send data from one arduino to another via Bluetooth(hc-05), they are working fine, but now I want to replace the BT module with RF module, how can I do that???

Yes, use VirtualWire or RadioHead. You might need to "evolve" your protocol to handle message fragmentation and loss. RadioHead has support for that.
Cheers!

OK, I'm gonna try it.