text:
Wire library compatibility Arduino Pro Mini - nodeMCU (I2C/TWI) problem
I'm writing PortExtender, a library to convert an Arduino Pro Mini in a port expander and I ran into what seems to be a compatibility problem between Arduino and nodeMCU: I got different answers depending on who is the master (Arduino or nodeMCU).
This is my test configuration:

At the center, the Slave Arduino, with buttons, leds, and ldr for testing pin access.
I have two master, but only one is used at a time. The inactive one is powered off and disconected from the two others. The slave get its power from the master.
I compiled and ran the same Master program in the two master, while the slave remains the same. This is the Master test program:
#include <Wire.h>
#include <PortExtender.h>

const int SLAVE_ADDRESS = 42;

PortExtender port = PortExtender(SLAVE_ADDRESS);

void setup ()
{
  Serial.begin(9600);
  delay(1000);
  Serial.println("Master");
  Serial.println("-----");

  Wire.begin();
  int r;
  do {
    r = port.reset();
    Serial.print("Resetting Port Expander. Status=");Serial.println(r);
    delay(100);
  } while(r != SLAVE_ADDRESS);
}

void loop() {
}

The test just sent a soft-reset to the slave. The slave answers with its own address (42), just to check that the command works.
Master 1 execution
This is the correct result from Master 1 (Arduino Pro Mini):

In fact, I can run a complete test suit with no problems, testing the button, controlling the LED and reading the LDR.
Master 2 execution
This is the result from Master 2 (nodeMCU):

Response is some random value that change from run to run. Slave, however, receive the command and return the right response, as checked thru Serial Monitor connected to the slave.
Everything seems to work fine, but answer from slave looks like it changed "in the wire".
PortExtender library code
The relevant methods involved are:
int PortExtender::reset() {
    return send(CMD_RESET);
}

int PortExtender::send(byte cmd) {
    Wire.beginTransmission(slave);
    Wire.write(cmd);
    Wire.endTransmission(false); // Also tested with true.
    return readAnswer();
}

int PortExtender::readAnswer() {
    short answer;

    Wire.requestFrom(slave, sizeof(answer));
    PortExtender::read((byte*) &answer, sizeof(answer));
    return (int) answer;
}

void PortExtender::read(byte* p, int len) {
    while (len > 0 && Wire.available() > 0) {
        *p++ = Wire.read();
        len--;
    }
}

Arduino ints are 2 bytes, nodeMCU ints are 4 bytes. Data from slave is send as short (Arduino, 2 bytes), received as short (nodeMCU, 2 bytes) and then promoted to int (nodeMCU, 4 bytes).
PortExtender.h
#ifndef PortExtender_h
#define PortExtender_h
/*
 *
 */
#include <Arduino.h>
#include <inttypes.h>

#define NO_CMD             0
#define CMD_DIGITAL_WRITE  1
#define CMD_DIGITAL_READ   2
#define CMD_ANALOG_WRITE   3
#define CMD_ANALOG_READ    4
#define CMD_PIN_MODE       5
#define CMD_SET_WATCHDOG   6
#define CMD_START_WATCHDOG 7
#define CMD_STOP_WATCHDOG  8
#define CMD_RESET          9
#define CMD_PLAY          10
#define CMD_PLAY_STEP     11
#define CMD_DEBOUNCE      12
#define CMD_TONE          13
#define CMD_TONE_LEN      14
#define CMD_NO_TONE       15

#define ERROR_NO_RESET    -1
#define ERROR_PARAMETER   -2

struct PAR_TONE {
    byte pin;
    unsigned int freq;
};

struct PAR_TONE_LEN {
    byte pin;
    unsigned int freq;
    unsigned long len;
};

class PortExtender
{
  private:
      short slave;
      int send(byte* b, int len);
      int send(byte cmd);
      int send(byte cmd, byte arg1);
      int send(byte cmd, byte arg1, byte arg2);
      int readAnswer();

  public:
      PortExtender(int slaveAddress);

      /*
       *     All same as Arduino, except as noted.
       */
      int pinMode(int pin, int mode);
      //    Set debouncer.
      int debounce(int pin, short debounce);

      int digitalWrite(int pin, int value);
      int digitalRead(int pin);
      int analogWrite(int pin, int value);
      int analogRead(int pin);
      int tone(int pin, unsigned int freq);
      int tone(int pin, unsigned int freq, unsigned long len);
      int noTone(int pin);

      /*
       * Watchdog functions
       */
      //    Designate the output pin and watchod parameters.
      int setWatchdog(int pin, unsigned long time, unsigned long pulse);
      int startWatchdog();
      int stopWatchdog();

      /*
       *    Timed switching of a pin, with a giving set of intervals.
       */
      int play(int pin, unsigned int score[]);

      /*
       *    Reset Port Extender.
       */
      int reset();
      static void read(byte*, int len);
};

#endif

Slave PortExtender (Arduino Pro Mini)
This is work in progress. Digital/Analog read/write completed, other methods (play, watchdog and tone still to be tested).
/*
   Programable Port Extender by Look Alterno.

   Convert your Arduino in a I2C slave that extends
   the number of pin for your master Arduino.

   Your master Arduino will be able to:
   - Read/Write digital/analog pins.
   - Program one-shot pulses of any length.
   - Program PWM with arbitrary period and duty cycle.

   Applications:
   - Make timers for external appliances.
   - Implement watchdogs for resetting things.
*/

//  ---- Change this address to a suitable value if needed ----
#define MY_ADDRESS  42

#include <Bounce2.h>
#include <Wire.h>
#include <PortExtender.h>

//  A CMD_RESET has been received from master.
boolean bReset = false;

//  These port are programmables.
struct {
  byte pin;
  byte exp;
} pins[] = {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0},
  {8, 0}, {9, 0}, {10, 0}, {11, 0}, {12, 0}, {13, 0},
  {A0, 0}, {A1, 0}, {A2, 0}, {A3, 0}
};

const short nPins = sizeof(pins) / sizeof(pins[0]);

struct {
  Bounce debouncer;
  short pin;
  short interval;
} debouncer = {Bounce(), 0, 0};

#define WD_NORMAL 0
#define WD_PULSE  1

struct {
  int pin;
  int state;
  boolean active;
  unsigned long lastBeat;
  unsigned long time;
  unsigned long pulse;
  unsigned long wait;
  unsigned long startPulse;
} watchdog;

#define SCORE_MAX_STEP 50
struct {
  boolean active;
  int pin;
  unsigned long time; // start time of current step.
  int freeStep;       // for filling the array.
  int currentStep;    // for playing the array.
  unsigned int step[SCORE_MAX_STEP];
} score;

typedef void (*fcnptr)();

void cmdBeat();
void cmdDigitalWrite();
void cmdDigitalRead();
void cmdAnalogWrite();
void cmdAnalogRead();
void cmdPinMode();
void cmdWatchdog();
void cmdStartWatchdog();
void cmdStopWatchdog();
void cmdReset();
void cmdPlay();
void cmdPlayStep();
void cmdDebounce();
void cmdTone();
void cmdToneLen();
void cmdNoTone();

struct {
  byte  cmd;
  fcnptr fcn;
} commands[] = {
  { NO_CMD,             cmdBeat},
  { CMD_DIGITAL_WRITE,  cmdDigitalWrite},
  { CMD_DIGITAL_READ,   cmdDigitalRead},
  { CMD_ANALOG_WRITE,   cmdAnalogWrite},
  { CMD_ANALOG_READ,    cmdAnalogRead},
  { CMD_PIN_MODE,       cmdPinMode},
  { CMD_SET_WATCHDOG,   cmdWatchdog},
  { CMD_START_WATCHDOG, cmdStartWatchdog},
  { CMD_STOP_WATCHDOG,  cmdStopWatchdog},
  { CMD_RESET,          cmdReset},
  { CMD_PLAY,           cmdPlay},
  { CMD_PLAY_STEP,      cmdPlayStep},
  { CMD_DEBOUNCE,       cmdDebounce},
  { CMD_TONE,           cmdTone},
  { CMD_TONE_LEN,       cmdToneLen},
  { CMD_NO_TONE,        cmdNoTone}
};

unsigned long now = millis();
byte  lastCommand;
short answer;

void setup() {
  Serial.begin(9600);
  Serial.println("--- Port Extender ---");

  initAll();
  Wire.begin(MY_ADDRESS);
  Wire.onReceive(receiveCommand);
  Wire.onRequest(sendAnswer);
}

void loop() {
  now = millis();

  checkDebouncer();
  checkWatchdog();
  checkPlay();
}

void checkDebouncer() {
  debouncer.debouncer.update();
}

/*
   Start playing a score on pin.
   The pin start at the last value set by master (HIGH or LOW)
*/
void startPlay() {
  noInterrupts();
  score.active = true;
  score.time   = millis();
  score.currentStep = 0;
  digitalWrite(score.pin, !digitalRead(score.pin));
  interrupts();
}

void checkPlay() {
  noInterrupts();

  if (score.active) {
    unsigned long stepEnd = score.time + score.step[score.currentStep];

    if (now >= stepEnd) {
      score.currentStep++;

      if (score.currentStep >= score.freeStep) {
        score.active = false;
      } else {
        digitalWrite(score.pin, !digitalRead(score.pin));
        score.time = now;
      }
    }
  }

  interrupts();
}

/*
   Each if is time to reset the master.
   After resetting the master, soft-reset the slave.
*/
void checkWatchdog() {
  if (watchdog.active) {

    switch (watchdog.state) {
      case WD_NORMAL:
        if (now - watchdog.lastBeat > watchdog.time) {
          pinMode(watchdog.pin, OUTPUT);
          digitalWrite(watchdog.pin, HIGH);
          watchdog.startPulse = now;
          watchdog.state = WD_PULSE;
        }

        break;

      case WD_PULSE :
        if (now - watchdog.startPulse > watchdog.pulse) {
          digitalWrite(watchdog.pin, LOW);
          cmdReset();
        }

        break;
    }
  }
}

/*
    Receive a command from Master
*/
void receiveCommand(int howMany) {
  lastCommand = Wire.read();
  //  Serial.print("command="); Serial.println(lastCommand);
  answer = 0;

  if (!bReset && lastCommand != CMD_RESET) {
    //  The first command received must be a CMD_RESET.
    answer = ERROR_NO_RESET;
  } else {
    fcnptr f = commands[lastCommand].fcn;
    f();

    watchdog.lastBeat = now;
  }
}

  // called by interrupt service routine when outgoing data is requested
  void sendAnswer() {
    Wire.write((byte *) &answer, sizeof(answer));
    lastCommand = NO_CMD;
  }
  void cmdBeat() {
  }

  void cmdReset() {
    //  Make a soft reset.
    initAll();
    bReset = true;
  }

  /*
     Initialize all variables and pins.
  */
  void initAll() {
    score.active = false;
    watchdog.active = false;
    debouncer.pin = -1;

    int size = sizeof(pins) / sizeof(pins[0]);

    for (int i = 0; i < size; i++) {
      int pin = pins[i].pin;
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
    }

    answer = MY_ADDRESS;
  }

  void cmdPinMode() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();
      pinMode(pin, val);
    }
  }

  void cmdDebounce() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();
      debouncer.pin = pin;
      debouncer.interval = val;
      debouncer.debouncer.attach(pin);
      debouncer.debouncer.interval(val);
    }
  }

  void cmdDigitalWrite() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();

      digitalWrite(pin, val);
    }
  }

  void cmdDigitalRead() {
    if (Wire.available() == 1) {
      byte pin = Wire.read();

      if (pin == debouncer.pin) {
        answer = debouncer.debouncer.read();
      } else {
        answer = digitalRead(pin);
      }
    }
  }

  void cmdAnalogWrite() {
    if (Wire.available() == 2) {
      byte pin = Wire.read();
      byte val = Wire.read();

      analogWrite(pin, val);
    }
  }

  void cmdAnalogRead() {
    if (Wire.available() == 1) {
      byte pin = Wire.read();

      answer = analogRead(pin);
    }
  }

  void cmdTone() {

  }

  void cmdToneLen() {

  }

  void cmdNoTone() {
    if (Wire.available() == 1) {
      byte pin = Wire.read();
      noTone(pin);

    }
  }

  void cmdPlay() {
    if (Wire.available() == 1) {
      score.active = false;
      score.pin = Wire.read();
      score.freeStep = 0;
    }
  }

  void cmdPlayStep() {
    unsigned int val;

    if (Wire.available() == 2) {
      val = Wire.read() << 8 | Wire.read();

      if (val > 0) {
        Serial.print("val=");
        Serial.println(val);
        score.step[score.freeStep++] = val;
      } else {
        startPlay();
      }
    } else {
      answer = ERROR_PARAMETER;
    }
  }

  void cmdWatchdog() {
    PortExtender::read((byte *) &watchdog.pin, sizeof(watchdog.pin));
    PortExtender::read((byte *) &watchdog.time, sizeof(watchdog.time));
    PortExtender::read((byte *) &watchdog.pulse, sizeof(watchdog.pulse));
    watchdog.active = false;
  }

  void cmdStartWatchdog() {
    watchdog.active = true;
  }

  void cmdStopWatchdog() {
    watchdog.active = false;
  }

  int searchPin(int pin) {
    int i = 0;

    while (i < nPins && pins[i].pin != pin) {
      i++;
    }

    return (i < nPins) ? i : -1;
  }

The question
What is going wrong here?

Please show a working sketch with a complete PortExtender.h and the code of the slave. I can not recognize a pattern: 22272 = 0x5700 = 0b0101.0111.0000.0000, 47 = 0x2A = 0b0010.1010. You don't even know if you are reading something at all. Could you test if Wire.available is not zero ?

@Jot. Remember: an Arduino Master can control LED, read buttons, read analog input, but nodeMCU fails.

Thanks. You should add that test to check if Wire.requestFrom actually received some bytes. Does the nodeMCU support I2C clock pulse stretching ? The Slave code working with the Arduino as Master does not matter. The code could have some details that makes the nodeMCU fail. The slave code does not set 'lastCommand' and 'answer' as volatile and the interrupt routine 'receiveCommand' can be long. If the nodeMCU does support I2C clock pulse stretching does it allow a very long stretch by the Slave 'receiveCommand' code ? Do you have a logic analyzer ?

@Jot. I added "volatile". Same result. And reset() is short and fixed-time. I printed requestFrom() and available() and both returns "2". And clearly the slave is receiving the requestFrom() because it's executing the callback. I don't have a logic analyzer.

I can not pinpoint the problem. The 0x5700 is very suspicious, there must be something in it. What is the Endian Byte Order for Arduino and nodeMCU ? Is everything running at 3.3V ? A 5V Arduino board needs 3.5V on the I2C bus to see it as a valid high. My best advice is to add more tests. For example send in the slave 0x33 instead of 'answer'. Check in the master the error return of Wire.endTransmission. And so on.

@jot. port.reset() return a random value (different in each run). nodeMCU and Arduino Pro Mini are both 3.3v. I also tested with master and slave both connected to USB for power. In first iteration, commands like reset() returns byte, but it also fails. Wire.endTransimission() works, because slave did receive the command and executed it, and, yes, I also checked the return code and it was OK.

How random is random ? Is the lower byte always zero ? It could be a bug in the ESP8266 Wire library, then you need a logic analyzer.

Hardware problem!
The nodeMCU I'm using fails (mostly resets and garbage in the Serial Monitor) when inserted in the breadboard. That is. Them run OK when I let them just hanging from the USB cable.
I tested two of them in different breadboards. I also tested the breadboard for shorts and failed connections with an ohmmeter.
These are culprits:


text:
PS2 Keyboard and sending keystrokes between a Leonardo and several pro micros
I am working on a project where I am taking the the key presses from a PS/2 keyboard and passing them to several pro micro boards so I can type the same commands on multiple computers at the same time. I have a master board that is a Leonardo that is connected to a keyboard. Using the TX pin I am connecting to a pro micro and trying to receive keystrokes on the micro and output them to a computer. I can get a the keyboard to work with the Leonardo connected to computer but not the pro micro. What do I have wrong about communication between these devices.(I get maybe every other key correctly on the computer but a also other keys or even function keys.)  Code for the "Master":

#include <PS2Keyboard.h>
#include <Keyboard.h>

const int DataPin = 8;
const int IRQpin =  3;

PS2Keyboard keyboard;

void setup() {
  delay(1000);
  keyboard.begin(DataPin, IRQpin);
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial.println("Keyboard Test:");
}

void loop() {
  if (keyboard.available()) {

    // read the next key
    char c = keyboard.read();

    // check for some of the special keys
    if (c == PS2_ENTER) {
      Serial.println();
    } else if (c == PS2_TAB) {
      Serial.print("[Tab]");
    } else if (c == PS2_ESC) {
      Serial.print("[ESC]");
    } else if (c == PS2_PAGEDOWN) {
      Serial.print("[PgDn]");
    } else if (c == PS2_PAGEUP) {
      Serial.print("[PgUp]");
    } else if (c == PS2_LEFTARROW) {
      Serial.print("[Left]");
    } else if (c == PS2_RIGHTARROW) {
      Serial.print("[Right]");
    } else if (c == PS2_UPARROW) {
      Serial.print("[Up]");
    } else if (c == PS2_DOWNARROW) {
      Serial.print("[Down]");
    } else if (c == PS2_DELETE) {
      Serial.print("[Del]");
    } else if (c == PS2_F1) {
      Serial.print("[F1]");
      //Serial1.print("[F1 ]");
    } else {

      // otherwise, just print all normal characters
      Serial1.print(c);
    }
  }
}

Code for the "Slave":
#include <HID.h>
#include <Keyboard.h>

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

void loop(){
   if (Serial1.available() > 0) {
   // read incoming serial data:
   char c = Serial1.read();
   Keyboard.print(c);
  }
}

Could you try to use Serial1.write with a fixed byte. For example remove the Serial1.print(c); and before or after char c = keyboard.read(); a Serial1.write('H');

Interesting, I actually tried Serial1.write but where my keyboard.print(c) was located, but that actually is kind of making sense. I thought I needed to convert the data to a byte instead of a Serial1.print. No changes are necessary on the slave device correct?

Correct for normal characters, like 'a', 'b', 'A', 'B', '?'. The PS2 library returns those normal ASCII characters, they are transmitted over the serial line and send to the computer. Everything as normal ASCII characters. You need to translate the function-keys and other special keys. Is this good enough for you ? Or do you need to simulated a key being pressed for a long time and also the Alt, Ctrl and media keys as well ?

I am going to need to use the alt, Ctrl and function keys as well. I was hoping to get the regular keys working first as it seemed that special or modifier keys might be more difficult. The PS2Keyboard.h file is missing the bits for the function keys but I was able to get those working and I found the if else statements in an example to test the functions keys. What would be the best way to go about this?

Instead of the if-else-statements you can use a table. However, nothing is wrong with the if-else-statements. Try to make it work with the Arduino Keyboard library. Perhaps you have to detect the pressing down and releasing a key as two seperate events. To create a keyboard that can do everything, you might need https://github.com/NicoHood/HID/wiki If you are going to use that, start by reading about the three different types of keyboard. Perhaps the keyboard leds can be added as well, but I'm not sure of that. How is the problem going, can you get normal characters in the computers ?

I seem to be having the same issue with serial1.write.I put Serial1.write after keyboard.read and it spits out random keys. Here is an example if I hold down the k key: kkkJkkJk[JJJJkkkkJJkJk

Very strange, I don't know what could be the cause. Test every part one by one. For example the Micro running at its own sending keys. Does everything have enough voltage ? Could you try a different computer ?

source: Stack Exchange

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

sort: votes


text:
Infinite "while" statement
I am building a robot that is both obstacle-avoiding and remote-controlled. The robot uses an infrared remote.  When the front button is pressed the robot moves front, when the right button is pressed the robot turns right, and so on...
When a certain button is pressed the robot switches to obstacle-avoiding mode and starts to drive around. When the ultrasonic sensor detects an object 15cm away the robot turns right, reverses, and then continues moving forward. the obstacle-avoiding code has a problem, though. Here is the code:
#include <EEPROM.h>
#include <IRLib.h>
#include <AFMotor.h>
int frontlights = A1;
int backlights = A2;
int buzzer = A3;
int pingPin = A4; //setup pingpin as A4

//ir variables
int RECV_PIN = A0;
IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
unsigned int Buffer[RAWBUF];

void obstacle_avoiding(){
   while (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){  // when the automatic mode button is pressed and the stop button is not pressed do...

 motor4.setSpeed(230);
 motor3.setSpeed(230);
 motor2.setSpeed(230);
 motor1.setSpeed(230);

    long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(90);

      if(cm>15){          // if an object is greater than 10cm move forward
      motor_forward();
      Serial.println("forward");
      digitalWrite(backlights, LOW);

      }

     else if (cm<=15)     // if an object is less than or equal 10cm move backward then turn right
     {
      motor_stop();
      digitalWrite(frontlights, HIGH);
      digitalWrite(backlights, HIGH);
      digitalWrite(buzzer, HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      delay(2000);
      motor_backward();
      digitalWrite(backlights, HIGH);
      Serial.println("backward");
      delay(500);
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(900);
      motor_right();
      digitalWrite(backlights, LOW);
      Serial.println("right");
      digitalWrite(frontlights, LOW);
      delay(400);

   }
   if (My_Decoder.value==0xFF0AF5){   //the stop button is pressed break the "while" loop and stop the robot
   break;
   motor_stop();
   }
 }
}

void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();

    //automatic code here
            else if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

The code is working however when the "while" statement becomes true it will loop infinitely not stopping even when the condition has become false. I thought while statements should loop until the condition becomes false. Am I misinformed?

side note: (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5) if My_Decoder.value is 0xFF807F then it's a fairly safe bet that it's not 0xFF0AF5 which means the condition can be simplified to (My_Decoder.value==0xFF807F)

@Andrew I had been working previously with the simplified condition you offered but with no different results.

Yes, the reason for the infinite loop is exactly what Look Alterno pointed out, the value of My_Decode.value never changes within the while loop so if the condition is true at the start then it'll remain to be true forever.  You need to fix that by somehow including updating My_Decoder within the loop. You can do that by either adding code within the while or by changing the while into an if and relying on the loop() function to create your loop. This was just a minor tidy up to remove redundant logic.

My_Decoder.value doesn't change inside obstacle_avoiding(). Hence, while is running infinitely.
I think you have to delete the while, and let loop() take care of controlling the execution.
Addendum
The intent of the loop() is to read some IR data in value. I under the impression that getResults() sometimes block, acording to this:

However the IRrecvLoop is not interrupt driven and so when you call
  GetResults it sits in a tight loop and does not release control back
  to you until the complete signal has been received.

I also want to check that value doesn't change if getResults() return nothing with this loop()
void loop() {
bool r = My_Receiver.GetResults(&My_Decoder)
Serial.print("getResults()=");
Serial.print(r);
Serial.print(" value=");
Serial.println(My_Decoder.value);

if (r) {
    //Restart the receiver so it can be capturing another code
    //while we are working on decoding this one.
    My_Receiver.resume();
    My_Decoder.decode();
} else {
    if (My_Decoder.value == 0xFF807F && My_Decoder.value != 0xFF0AF5) {
        obstacle_avoiding();
        }
    }
}

I hope this works!

When I delete the "while", and let "loop()" take care of controlling the execution, if I press the obstacle-avoiding button, the code only runs once.

@Matthew. Read my answer new version.

Copy/paste this part only:
void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();
        }
    //automatic code here
           if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

Please explain your solution and fix the code indentation.

I tried the above code and found that the "while" loop still runs infinitely.

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


text:
Are global variables evil in Arduino?
I'm relatively new at programming and many of the coding best practices I'm reading effectively state that there are very few good reasons to use a global variable (or that the best code has no globals at all).
I've done my best to keep this in mind, when writing software to make an Arduino interface with an SD card, talk to a computer and run a motor controller.
I currently have 46 globals for about 1100 lines of "beginner level," code (no line having more than one action). Is this a good ratio or should I look at reducing it more? Also what practices can I employ to reduce the number of globals further?
I'm asking this here because I'm specifically concerned with best practices for coding on Arduino products rather than computer programming in general.

In Arduino you can't avoid global variables. Every variable declaration outside the scope of a function/method is global. So, if you need to share values between functions, they have to be globals, unless you want to pass every value as an argument.

@LookAlterno Err, can you not write classes in Ardunio, since it's just C++ with weird macros and libraries? If so, not every variable is global. And even in C, it's usually considered best practice to prefer passing variables (perhaps inside structs) into functions rather than having global variables. Might be less convenient for a small program but it usually pays off as the program gets larger and more complex.

@Muzer. I use C++ classes only for library development, and, well, larger programs. I avoid C++ for reasons.

@LookAlterno: "I avoid" and "you can't" are very different things.

@LookAlterno That's a mundane truism of C/C++ (namespaces notwithstanding), which is not specific to Arduino at all, and as you then yourself indicated, does not by any means lead to the conclusion that global variables cannot be avoided; they can, and often should. Where the answer to this question might differ when the platform is an Arduino is not on the level of the language, but rather in the design patterns that make sense on the platform and whether they make globals desirable.

Actually, some embedded programmers ban local variables and require global variables (or function scoped static variables) instead.  When the programs are small, it can make it easier to analyze it as a simple state machine; because variables never overwrite each other (ie: as they do stack and heap allocated variables).

Static and global variables offer the advantage of knowing memory consumption at compile time. With an arduino having very limited memory available, this can be an advantage. It quite easy for a novice to exhaust the available memory and experience untraceable failures.

Global variables on an Arduino are less evil that on a PC.  I have seen people declaring a loop variable, i, as a global variable.  TBH I try and avoid them, but they do have their place in memory management.

@LookAlterno - The biggest issue with global variables is poor programmers.  You should pass every value as an argument (try to keep it less than 5), because that compartmentalises your code and allows for reuse.  Copy and pasting functions together into programs is really easy, but only if you avoid globals as much as possible.  It also prevents monolithic functions, if you are passing in 20 args into a 2000 line function then you should be refactoring it.

@Muzer huh, always thought it was Processing. TIL

related: https://electronics.stackexchange.com/questions/97241/use-of-global-variables-in-embedded-systems

Hey All: This got a lot more popular than expected. I've learned a lot in the last 9 months and would like to make this as useful to "other me's" as possible. Would people appreciate it if I appended this post with links to tutorials/ideas that helped me as a beginner improve my code? I'm still not 100% confident on stack exchange's edicate, so I thought I'd ask 1st.

They aren't evil per se, but they do tend to get overused where there is no good reason to use them.
There are plenty of times when global variables are advantageous. Especially since programming an Arduino is, under the hood, vastly different to programming a PC.
The biggest benefit to global variables is static allocation. Especially with large and complex variables such as class instances. Dynamic allocation (the use of new etc) is frowned upon due to lack of resources.
Also you don't get a single call tree like you do in a normal C program (single main() function calling other functions) - instead you effectively get two separate trees (setup() calling functions, then loop() calling functions), which means that sometimes global variables are the only way to achieve your goal (i.e., if you want to use it in both setup() and loop()).
So no, they're not evil, and on an Arduino they have more and better uses than on a PC.

Ok, What if it's something I'm only using in loop() (or in multiple functions called in loop())? would it be better to set them up in a different way than defining them at the beginning?

In that case I would probably define them in loop() (maybe as static if I needed them to retain their value across iterations) and pass them through the function parameters down the call chain.

Ok, I think I can do that. If I have (for example) static var n defined in loop(). If I pass n to foo(var) and in foo(var) I set n=[new value]. Will I need to have  return [new value] and have n=[new value] in loop()?

That is one way, or pass it as a reference: void foo(int &var) { var = 4; } and foo(n); - n is now 4.

Classes can be stack-allocated. Admittedly, it's not good to put large instances on the stack, but still.

@JAB Anything can be stack allocated.

Right, I skimmed over too quickly and conflated some of the comments on the question regarding non-use of classes.

The fact no communication is possible between setup() and loop() is, by itself, an excellent reason to use a more standard toolsuite and have a good old main() or _main() entry point.

One of the reasons I've heard to avoid global variables has more to do with a system other than an Arduino, Global variables can be exposed external to, or outside of the program itself. This C++ statement states it best.
"The C language does not have a global keyword. Variables declared outside a function have "file scope," meaning they are visible within the file."
This exposes the variable space to being modified outside of the program's scope before running, as in the case of statics where the file variable space can be edited before running, creating potential security risks

It's very difficult to give a definitive answer without seeing your
actual code.
Global variables are not evil, and they often make sense in an embedded
environment where you typically do a lot of hardware access. You have
only four UARTS, only one I2C port, etc. So it makes sense to use
globals for variables tied to specific hardware resources. And indeed,
the Arduino core library does that: Serial, Serial1, etc. are global
variables. Also, a variable representing the global state of the program
is typically a global.

I currently have 46 globals for about 1100 lines of [code]. Is this a
  good ratio [...]

Is not about the numbers. The right question you should ask yourself is,
for each of these globals, whether it makes sense to have it in global
scope.
Still, 46 global seems a bit high to me. If some of these hold constant
values, qualify them as const: the compiler will usually optimize out
their storage. If any of those variables is only used inside a single
function, make it local. If you want its value to persist between calls
to the function, qualify it as static. You could also reduce the
number of “visible” globals by grouping variables together inside an
class, and having one global instance of this class. But only do so when
it makes sense to put stuff together. Making a big GlobalStuff class
for the sake of having only one global variable will not help make your
code clearer.

Ok! I didn't know about static if I have a variable that is used only in one function but get a new value every time a function is called (like var=millis() ) should I make that static ?

No. static is only for when you need to keep the value. If the first thing you do in the function is set the value of the variable to the current time there is no need to keep the old value. All that static does in that situation is wasting memory.

This is a very well-rounded answer, expressing both points in favour of, and scepticism about, globals. +1

The main issue with global variables is code maintenance. When reading a line of code, it is easy to find declaration of variables passed as parameter or declared locally. It is not so easy to find declaration of global variables (often it requires and IDE).
When you have many global variables (40 is already a lot), it becomes difficult to have an explicit name that is not too long. Using namespace is a way to clarify role of global variables.
A poor way to mimic namespaces in C is:
static struct {
    int motor1, motor2;
    bool sensor;
} arm;

On intel or arm processor, access to global variables is slower than other variables. It is probably the opposite on arduino.

On AVR, globals are on RAM, whereas most non-static locals are allocated to CPU registers, which makes their access faster.

The problem isn't really finding the declaration; being able to quickly understand the code is important but ultimately secondary to what it does - and there the real problem is finding which varmint in which unknown part of your code is able to use the global declaration to do weird things with an object you left out in the open for everyone to do whatever they want with.

As with everything (other than gotos which are truly evil) globals have their place.
e.g. If you have a debug serial port or a log file that you need be to able to write to from everywhere then it often makes sense to make it global. Similarly if you have some critical piece of system status information then making it global is often the easiest solution. There is no point in having a value that you have to pass to every single function in the program.
As others have said 46 seems a lot for only just over 1000 lines of code but without knowing the details of what you are doing it's hard to say if you are over using them or not.
However for every global ask yourself a few important questions:
Is the name clear and specific so that I don't accidentally try to use the same name somewhere else? If not change the name.
Does this need to ever change? If not then consider making it a const.
Does this need to be visible everywhere or is it only global so that the value is maintained between function calls? Is so consider making it local to the function and using the keyword static.
Will things really screw up badly if this gets changed by a piece of code when I'm not being careful? e.g. if you have two related variables, say name and ID number, that are global (see previous note on using global when you need some information almost everywhere) then if one of them gets changed without the other nasty things could happen. Yes you could just be careful but sometimes it's good to enforce carefulness a little. e.g put them in a different .c file and then define functions that set both of them at the same time and allow you to read them. You then only include the functions in the associated header file, that way the rest of your code can only access the variables through the defined functions and so can't mess things up. This is basically a pure c way of doing what a c++ class would allow but without having to learn how to define and create classes so you aren't learning too much at once.
-- update -- I just realized that you had asked about Arduino specific best practice rather than general coding and this is more of a general coding reply. But honestly there isn't much difference, good practice is good practice. The startup() and loop() structure of Arduino means that you have to use globals a little more than other platforms in some situations but that doesn't really change much, you always end up aiming for the best you can do within the limitations of the platform no matter what the platform is.

I know nothing about Arduinos but do a lot of desktop and server development. There is one acceptable usage (IMHO) for gotos and that's to break out of nested loops, it's much cleaner and easier to understand than the alternatives.

If you think goto's are evil, check out Linux code. Arguably, they are just as evil as try...catch blocks when used as such.

gotos aren't evil. They are used in production, professional C code all the time for error handling, including in safety-critical real-time software for life-saving devices, aircraft, etc. They just have to be used properly is all, and their usage pattern is limited and well-defined. Additionally, to keep the project MISRA-compliant, if that's something the project cares about, the usage pattern of gotos in the project must be documented as an exception, which is commonly done in MISRA-compliant software.

Here's some examples I wrote showing reasonable goto usage: https://stackoverflow.com/a/54488289/4561887. I've added additional references to justify their usage at the bottom of the answer. Of course, no code cannot be done without goto (ie: all code can be done withOUT goto), but many instances of code are greatly benefited and made more readable by properly using goto. Some professional teams even mandate the usage of goto in a standardized way in order to have cleaner, more-readable code. It's all about tradeoffs.

Although I wouldn't use them when programming for a PC, for the Arduino they have some benefits. Most if it has already been said:

No dynamic memory usage (creating gaps in the limited heap space of an Arduino)
Available everywhere, thus no need to pass them as arguments (which costs stack space)

Also, in some cases, especially performance-wise it can be good to use global variables, instead of creating elements when needed:

To decrease gaps in heap space
Dynamically allocating and/or freeing memory can take substantial time
Variables can be 'reused', like a list of elements of a global list that are used for multiple reasons, e.g. once as a buffer for the SD, and later as a temporary string buffer.

Are they evil? Maybe. The problem with globals is that they may be accessed and modified at any point in time by any function or piece of code being executed, without restrictions. This may lead to situations that are, let's say, difficult to trace back and explain. Minimizing the amount of globals, if possible bringing the amount back to zero, is therefore desirable.
Can they be avoided? Almost always yes. The problem with Arduino is, that they force you into this two function approach in which they assume you setup() and you loop(). In this particular case you have no access to the scope of the caller function of these two functions (probably main()). If you had, you would be able to rid yourself of all globals and use locals instead.
Picture the following:
int main() {
  setup();

  while (true) {
    loop();
  }
  return 0;
}

This is probably more or less what the main function of an Arduino program looks like. Variables you need in both the setup() and the loop() function would then preferably be declared inside the scope of the main() function rather than the global scope. They could then be made accessible to the two other functions by means of passing them as arguments (using pointers if necessary).
For example:
int main() {
  int myVariable = 0;
  setup(&myVariable);

  while (true) {
    loop(&myVariable);
  }
  return 0;
}

Note that in this case you also need to change the signature of both functions.
As this might not be feasible nor desirable, I see really only one way to remove most globals from an Arduino program without modifying the forced upon program structure.
If I recall correctly, you're perfectly able to use C++ while programming for Arduino, rather than C. If you're not familiar (yet) with OOP (Object Oriented Programming) or C++, it might take some getting used to and some reading.
My proposal would be to create a Program class and create a single global instance of this class. A class should be considered the blueprint for objects.
Consider the following example program:
class Program {
public:
  Program();

  void setup();
  void loop();

private:
  int myFirstSampleVariable;
  int mySecondSampleVariable;
};

Program::Program() :
  myFirstSampleVariable(0),
  mySecondSampleVariable(0)
{

}

void Program::setup() {
  // your setup code goes here
}

void Program::loop() {
  // your loop code goes here
}

Program program; // your single global

void setup() {
  program.setup();
}

void loop() {
  program.loop();
}

Voilà, we've rid ourselves of almost all globals. The functions in which you would start adding your application logic would be the Program::setup() and Program::loop() functions. These functions have access to the instance specific member variables myFirstSampleVariable and mySecondSampleVariable whereas the traditional setup() and loop() functions do not have access as these variables have been marked class private. This concept is called data encapsulation or data hiding.
Teaching you OOP and/or C++ is a bit out of scope of the answer to this question so I'll stop here.
To summarize: globals should be avoided and it's almost always possible to drastically reduce the amount of globals. Also when you're programming for Arduino.
Most importantly I hope my answer is somewhat useful to you :)

You can define your own main() in the sketch if you prefer. This is what the stock one looks like: https://github.com/arduino/Arduino/blob/1.8.3/hardware/arduino/avr/cores/arduino/main.cpp#L33-L51

A singleton is effectively a global, just dressed up in an extra confusing way. It has the same downsides.

@patstew Do you mind explaining me how you feel it has the same downsides? In my opinion it doesn't since you're able to use data encapsulation to your benefit.

@per1234 Thanks! I'm definitely no Arduino expert, but I suppose my first suggestion could work also then.

Well, it's still global state that can be accessed anywhere in the program, you just access it through Program::instance().setup() instead of globalProgram.setup(). Putting related global variables into one class/struct/namespace can be beneficial, especially if they're only needed by a couple of related functions, but the singleton pattern doesn't add anything. In other words static Program p; has global storage and static Program& instance() has global access, which amounts to the same as simply Program globalProgram;.

@patstew I didn't think of it that way. I think you're right. I'll modify my post. It will make it more easy to understand also.

As a long-time embedded coder, I fairly regularly have to train people out of the cast-iron rule of "Global Variables Bad".  Passing arguments always makes code slower.  On a PC this is pretty much immaterial, but in the embedded world this is still a very big deal.  The accessor/mutator pattern is a way to guarantee sound encapsulation at the cost of processing time.  It's perfectly possible to write well-encapsulated code with global variables - but you do have to apply discipline to how you design it, and specify clearly how other people should use it.

@Graham I'm curious to find out what kind of discipline you're talking about? I think I have an idea what you're talking about, but discipline isn't going to create 'well-encapsulated code'. The accessor/mutator pattern will sometimes come with a slight performance cost, depending on how you setup your code, agreed. However, lots of expensive operations may be optimized out by a compiler.

Global variables are never evil. A general rule against them is just a crutch to let you survive long enough to gain the experience to make better decisions.
What a global variable is, is an inherent assumption that there is only one of a thing (it doesn't matter if we're talking about a global array or map that might contain multiple things, that still contains the assumption that there is only one such list or mapping, and not multiple independent ones).
So before you make use of a global, you want to ask yourself: is it conceivable that I will ever want to use more than one of this thing? If it turns out to be true down the line, you will have to modify the code to un-globalize that thing, and you'll probably find out along the way that other parts of your code depend on that assumption of uniqueness, so you'll have to fix them as well, and the process becomes tedious and error-prone. "Don't use globals" is taught because usually it's a pretty small cost to avoid globals from the beginning, and it avoids the potential of having to pay a large cost later on.
But the simplifying assumptions that globals allow also make your code smaller, faster, and use less memory, because it doesn't have to pass around a notion of which thing it's using, doesn't have to do indirection, doesn't have to consider the possibility of the desired thing maybe not existing, etc. On embedded you're more likely to be constrained for code size and/or CPU time and/or memory than you are on a PC, so these savings can matter. And many embedded applications also have more rigidity in the requirements — you know that your chip only has one of a certain peripheral, the user can't just plug another one into a USB port or something.
Another common reason for wanting more than one of something that seems unique is testing — testing the interaction between two components is easier when you can just pass a testing instance of some component to a function, whereas trying to modify the behavior of a global component is a trickier proposition. But testing in the embedded world tends to be very different from elsewhere, so this may not apply to you. As far as I know, Arduino has no test culture whatsoever.
So go ahead and use globals when they seem worthwhile. The code police won't come and get you. Just know that the wrong choice could lead to a lot more work for you down the road, so if you're not sure...

Are Global Variables Evil in Arduino?

nothing is inherently evil, including global variables. I would characterize it as a "necessary evil" - it can make your life much easier but it should be approached with caution.

Also what practices can I employ to reduce the number of globals further?

use wrapper functions to access your global variables. so you at least are managing it from the scope perspective.

If you use wrapper functions to access global variables, you may as well put your variables inside these functions.

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


text:
polynomial change of LED brightness arduino
I try to change the brightness of an LED following the formular in out1. I'm pretty sure that something is going wrong because it doesn't really change its brightness and it never stops lightening. Can pleas somebody help me. It should basically do the same than a sin wave but instead of the sin I try to use my equation!
const int LED = 11;
const int LED1 = 10;
const int LED2 = 9;

void setup()
{
}

void loop()
{
float in1, out1, out2, out3;

for (in1 = 0; in1 < 10; in1++)
{
out1 = 8.8 * pow(10,-4) * pow(in1,4) - 0.0034 * pow(in1,3) +0.37* pow(in1,2) -6.7 *in1 +1.7 *pow(10,2);
//out2 = 1.207*pow(in1,4)-0.0011*pow(in1,3)+0.16*pow(in1,2)-5.5*in1+2,0763;
//out3 = 4.829*pow(in1,4)-0.034*pow(in1,3)+0.37*pow(in1,2)-6.7*in1+2,076;

analogWrite(LED,out1);
delay(10);
//analogWrite(LED1,out2);
//analogWrite(LED2,out3);

}

analogWrite(LED,LOW);

/*analogWrite(LED,out1);
analogWrite(LED1,out2);
analogWrite(LED2,out3);
//analogWrite(LED1,LOW);*/
delay(500);

You wrote: “8.8 * pow(10,-4)”. You mean 8.8e-4. And you should implement Horner's method instead of using the (very expensive) pow() function.

Don't cross post. You already asked this on SO.

You wrote: “The formula [...] comes from data I've plottet in Matlab”. Why don't you tell us what you actually want to achieve? Your code is probably working just fine, and the Arduino is doing what you asked for. Only you know what you actually want it to do.

Here is the proper way to implement a polynomial function. It's a direct
application of Horner's
method:
// Polynomial function for output 1.
static float f1(float x)
{
    return (((8.8e-4 * x - 0.0034) * x + 0.37) * x - 6.7) * x + 1.7e2;
}

You would use it like this:
void loop()
{
    for (int x = 0; x < 10; x++) {
        analogWrite(LED, f1(x));
        delay(10);
    }
    digitalWrite(LED, LOW);
    delay(500);
}

Thank you for your help.It's hard for me to tell if it's working but the plot of the function looks like this : link I'm not quite sure but i think the brightness should not fall down at a certain point. Do you have any idea what the issue could be? I was also wondering if I could do more steps with the brightness....

The most likely issue is your poor choice of polynomial. You are varying the brightness over a tiny range: the variation will be hardly visible.

anlogWrite uses 0...255, that is only 8 bit. A led intensity with a curve into a 8 bit intensity resolution ? That is not very useful. The first 10 steps are far too coarse. The Neopixels and other RGB leds often have more bits, and those can be programmed with a nice visual brightness curve. As far as I know, all led PWM modes are linear, but the human eye is not linear. Therefor you need more bits for finer steps when the led is dim.

@Jot: The Neopixels (and the WS2811, WS2812 and SK6812) are 8-bits per channel.

@EdgarBonet, thanks, so the most common 5050 RGB leds are still 8-bits per color. That's disappointing. Even the 5050 RGBW leds are 8 bits (times four for each 'color'). Some PWM led driver chips are 12 or 16 bits. Sometimes I use two digital outputs with different resistors to get more resolution.

You should make sure that your code works with known good values for out1.
After dthat, try to make sure that your formula produce values in a valid range - check analogWrite to see what values it expects.
Then you should make sure that your code formula is what you want. Aka the code reflects your intent correctly.
edit: here is what I use to calculate polynomial functions.
//return poly functions
//x: independent variable
//degree: degree of the polynomial function
//p[]: array for the coefficients
double poly(double x, int degree, double p[]) {
  double tmp=0;  //temp variable

  while (degree--) tmp = tmp * x + p[degree];

  return tmp;
}

by providing different "degree" and "p[]/coef", you can calculate any polynomial function with one call to poly().
I generally use a set of macros to further simplify the calling to that function.

The formular is a little bit strange but it comes from Data I've plottet in Matlab and afterwards I did cirve fitting. Is there no easy way to have more steps? Maybe by doing a fourrier transformation?

Think simple. Your problem isn't the lack of complexity. So adding more complexity will not get you where you want to go. Instead, focus on the basics

Ok first of all my possible maximum vallue is 255. So everything above will not be displayed right? I've normalized the values with Matlab so no value is above 1. Is there a way to do the same thing with ardouino? Because in this case I could Multiplay the normalized Vector by 100. I'm probably thinking to complex, you're right! So could you give me an instruction I can follow to solve this? It would really help me a lot! Thanks!

Your problem doesn't require Fourier transformation to solve. It only requires common sense and basics, as laid out to you earlier.

In poly(), you should increment degree before the while loop, otherwise you fail to add the leading term. Alternatively, you could rename degree and document that this parameter is the length of the p array, which is not the same as the degree of the polynomial.

Ok so here is what I did: I multiplicated my function with 10^-1 so I have a bigger range. Afterwards I changed the range of my loop up to 245 because for this number the result is 244.33 so it's a possiple value. By changeing the steps to 2.47, I have exactly 100 steps.
for (int x = 0; x < 245; x++) {
analogWrite(LED, f1(x));
delay(100);
}
analogWrite(LED, 0);
  delay(10000);

What do you say? Is ther any mistake?


text:
433Mhz receiver only get values of 0, 1, 2
I have two Arduino Uno and a few sets of transmitters and receivers. I followed some guide on the internet to make them work and that's what I did so far but I still get random values of 0 or 1 or 2, no matter what signals I am trasmitting.
I connected the receiver's VCC to 5v on Arduino; the receiver's data to A0 on the Arduino; the receiver's GND to the Arduino's GND.
I connected the transmitter's VCC to 5v on Arduino; the transmitter's data to  on Arduino; the transmitter's GND to the Arduino's GND.
This is the transmitter code:
#define dataout 12
#define ledPin 13
unsigned int temp = 0;

void setup() {
  pinMode(dataout, OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {

  digitalWrite(dataout, HIGH);
  digitalWrite(ledPin, HIGH);
  delay(5000);
  digitalWrite(dataout,LOW);
  digitalWrite(ledPin, LOW);
  delay(5000);
}

This is the recriver code:
const int datain=A0;
#define ledPin 13

int temp = 0;
const unsigned int upperThreshold = 500;
const unsigned int lowerThreshold = 100;

void setup() {
  pinMode(datain, INPUT);
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  temp=analogRead(datain);
  Serial.println(temp);
  delay(300);
  if(temp<lowerThreshold) {
    digitalWrite(ledPin, HIGH);
  }

  if(temp>upperThreshold) {
    digitalWrite(ledPin, LOW);
  }
}

I tried to change the transmitter and receivers. I tried to change Arduino boards. I tried to change analog to digital, nothing worked...
Suggestions?
Update:
Here are some pictures of my gear:

This is the output of the receiver when both Arduinos work near each other, there no sync between the signals transmitting and receiving.

0 1 0 0 0 0 1 1 0 2 1 2 1 0 1 362 0 1 1 1 1 1 0 2 0 314 2 2 1 0 0 2 1
  0 1 2 1 1 2 0 1 1 0 1 1 2 1 0 0 0 0 2 1 0 1 0 0 1 0 1 0 1 1 1 2 2 1 1
  2 1 1 1 1 1 0 211 2 0 2 0 0 1 2 0 0 759 1 2 1 1 2 1 2 0 1 16 0 0 1 1 0
  0 2 1 1 0 1 2 1 2 0 2 1 0 2 0 1 2 1 1 2 2 1 2 0 0 1 0 1 1 2

This is the output when I tried to disconnect the GND and VCC from the receiver:

433 426 431 422 379 367 362 394 405 412 406 394 399 388 356 258 193
  438 507 507 499 486 478 473 449 442 431 428 427 424 425 423 422 419
  417 414 413 413 409 410

I thought the typical 433 device used a modulation of the carrier signal to transmit the data.  You end up using it like a Morse code system.  Your code needs to be a lot more complex than that, or use a library.  Of course I might be wrong, because I don't know what gear you are using (post a picture/part number/data sheet).

The receivers probably don't receive a DC voltage, only a stream of bits. You probably need a library and digital pins and interrupts. Please tell which transmitter and receivers you have, and give a link to that guide,

I updated my post,
Code Gorilla - how can i use a library? i tried to use virtual wire but failed...
Jot - the receiver do receive DC voltage as you can see in the outputs i got

Those cheap 433 MHz RF modules require a (good) library to work. The VirtualWire/RadioHead library is the best.
The VirtualWire library it outdated, but still used.
The RadioHead library has a few bugs fixed, but uses more memory.
Use it in RH_ASK mode, see the included 'ask' examples.
[Update: better quality]
Most cheap 433 MHz ASK transmitters work with 3.5 to 12V. They have the longest range at 12V. About 20 meters is no problem with 5V, but if longer range is needed then transmitters that are only made for 5V are better.
The cheap 433 MHz receivers use a coil to tune the frequency. They are very sensitive and they do work well. However, when such a module is placed near metal or close to the Arduino, the frequency might change. Modules that use a crystal for the frequency are better. Sometimes a sensitivity is mentioned (for example -112dBm) but I don't know how reliable that is. When an antenna of 16 cm does not work well, try an antenna of more than a meter.
The transceivers are better for wireless data transfer, but that depends on the use.
Sparkfun has Wireless Buying Guide.
RadioHead has a list of supported transceivers.
The nRF24L01+ are very cheap. I read that every one of them on Ebay or Aliexpress is counterfeit, but the counterfeit chips do work. They work at 3.3V, and are 5V tolerant.
The CC1101, CC2500 and so on are good, but not often used with an Arduino. The same for Si4432, Si4436 and so on. If you know a good library, they are very good transceiver chips.
Adafruit is using the RFM69 a lot. For example the Feather Packet Radio board.
Last but not least: don't forget Wifi and Bluetooth.

can you please recommend me on some good transmitters and recievers?

@user35399, I have added a "Update: better quality" section.


text:
Rotary encoder I2C LCD menu
I am trying to make a menu for a monitoring/control system.  I am not sure how to make this without interrupting my current code which needs to be monitoring my system at all times to shut off if it reads overload. It is mostly swtich () and case x: stuff. I have looked into attachInteruupt and rotary encoder examples, but none have really helped me figure out how to display a multiple layer menu where I can select to see the system readings as well as edit outputs.
There are a lot of posts here on rotary encoders with LCDs, but I can't seem to find a good skeleton menu code that works well and uses current libraries.  My biggest problem right now is making the menu layers without interrupting my monitoring code running in the background.

I don't think you should do both tasks on the same microprocessor.  Detach the UI an put it on a second processor that sends messages to the control processor over I2C or similar.  This way the user can 'accidentally' use the UI is a way the blocks the control processor.

you might want to consider timed routines or interrupts.
For timers https://playground.arduino.cc/Code/Timer1 or similar can help.
When using interrupts be sure to be minimalistic because atmegas do not behave well when interrupts take too long to process.
About menus there are several, most of them dynamic and some requiring user display + nav code.
This open-source menu lib (https://github.com/neu-rah/ArduinoMenu) is static, that is good for bigger projects because it stores a lot on flash.

(-) you can not change menu at runtime (however it support value fields)
(+) requires no user code base
(-) setup involves several parts (inputs/output)
(+) non blocking polled mode. Just call the poll function on your code loop, the menu will just return if it has no input or output
(+) supports a lot of display devices, including i2c lcd
(+) supports encoder (interrupts (PCINT) or timed driver)
(-) atmega2560 interrupts (PCINT) only on 3 ports, PCINT might require pin mappings (not sure), but if needed the PCINT library examples can print one for you.


text:
Lifespan of a hot microchip
I'm currently building my own Home Automation System with a bunch of Arduinos and Relais, all of them wired to Ethernet "Shields". The casing I am printing on a 3D printer.
The Arduinos work great with those Ethernet "Shields", but the ENC28J60 chip on those Ethernet boards get quite hot. I am measuring 79.5°C approx.
In the plastic casing, I expect that they reach higher temperatures (because it's closed and has no ventilation whatsoever).

Since I am building this as a permanent solution (House wiring is now all newly adapted and I have no way back), which lifespan can I expect from those Ethernet boards?
The datasheet of that chip is saying that it's rated up to 85°C, but what does this upper rating mean? Will it stop working at this point, or only begin to degrade it's lifetime at this point?
EDIT: I have no space to put a dissipation block on those chips, because the casing is so tight.

I'm voting to close this question as off-topic because it is entirely about the ENC28J60 and not about Arduino at all.

This would appear to be a malfunction, either due to past damage or miswiring, for example mishandling of the Ethernet transformer bias.  With full engineering detail included, on a site like Electronics Stack Exchange it could perhaps be addressed, but doesn't belong here.

At the outset, you wrote “The casing I am printing on a 3D printer”, and at the end, “I have no space to put a dissipation block on those chips, because the casing is so tight”.  So, redesign the case with either more room or an opening for a heat sink to protrude.

I agree this is not about Arduino.  Remember the rule of thumb about chips, though:  Every 18 degrees F cuts their lifetimes in half.

FALSE POSITIVE... Sorry and thanks to all the suggestions given, but the meter was not calibrated. The calibrated one shows 46°C... I think that's acceptable. (Today I noticed something was wrong when the floor was 50°C and I was like wtf?!?

The reliability data is typically not in the product datasheet but in pen whitepapers. Generally speaking life span goes down exponentially as temperature rises. For some high temperature semi conductors ( designed specifically for high temperature applications) you are talking about hubdreds or thousands of hours at rated temperatures.
That should give you some sense as to what to expect.


text:
Why is the GSM shield so expensive?
I've been doing some Googling for GSM shields and their prices and frankly I don't understand why they are so expensive on average.
The official one sold by Arduino is 71 euros for me (I live in Europe), and third party ones have similar prices.
A cheap dumb-phone is usually 30 euros and those phones have become really impressive these days, they have even a camera. When they are locked with the carrier the price can go as low as 20 euros. How is it even possible that a single part of what is supposed to make up a phone is more expensive than the phone itself? :(
Thanks in advance!

Economies of scale?

Both my dumb-phone and Arduino's GSM shield are sold on a global scale. And I don't think my dumb-phone sells more than the shield, it's a quite crappy brand.

@AlbertoLaRocca no, the GSM shield is sold on a global scope, the scale (number of units sold) is miniscule compared to phones.

@SmartHead You should also read the help center yourself, because edits are not for flagging something as off-topic.

@Michel Keijzers you approved an utterly improper title edit to this question.  NEVER DO THAT AGAIN.

@Hasan you approved an utterly improper title edit to this question. NEVER DO THAT AGAIN.

If you are ready to wait a month for delivery and also giving up flexibility by restricting yourself to just sending and receiving SMS, then you can go as low as €2 for a DIY kit on AliExpress.
By adding more money, you also get more features. Just sarch for "gsm arduino" or "SIM800", "SIM900".

Sorry but that doesn't answer at all. All right, I can go as low as 2 euros, and why such a crazy difference? Just because I can't make voice calls? My 30 euro dumb-phone actually CAN make voice calls.

Some of these probably can make voice calls on a suitable network, and some probably won't work on the current network in your country at all.  A big part of the cost difference is not having a local distributor standing behind their suitability.

I thougt you was just complaining about the price. Well the reason is simple. Those devices are produced in small batches. Non of those suitable for use with arduino are used in actual phones. Phones have SoCs so the modem is integrated into the CPU. Just take a look at a Qualcomm Snapdragon. Those have built in LTE modems. Also iPhone CPUs have integrated modems. So you would have to pay a lot more if a manufacturer used those for Arduino Shields. Also you would get more than you asked for. Like a CPU, GPU and system memory.

However Flash storage is external. so those would be even more expensive if you want run them with pre configured firmware/software/operating system or such. The development of those will likely also take a bunch of money. Not to mention licensing fees.

@Kwasmich - it may be that some of the modules are simply low-end feature phone SoCs with a serial port brought out.  Or at least, that seems like it could be the most economical way to make a module.


text:
What is the difference between python and arduino programming?
I am a Python programmer and want to learn Arduino programming so want to know what are the main differences between Python and Arduino C++ programming?
Is Arduino C++ more complex than Python programming?
Are there any similarities that will help me?
Are there any formatting  restrictions like in Python?
Etc...
According to this page(printing hello), Aurdino programming looks easy to me.

What is the difference between python and arduino programming? -- Everything.

Heh.  As usual, @Majenko is correct.  This is like asking what the difference is between FORTRAN and COBOL.  From this question it sounds like you don't really know either Python nor C++

@SDsolar I know python but not C++

@ShopiMacros - If you know one language learning a second is easier than learning a first.  Start with small examples and work up.

@CodeGorilla , Got It

I agree with the Gorilla.  If you really want to have fun, look at this link.  It shows how to say "Hello, World" in 28 different languages..  It is interesting to see the similarities and differences.  Both Python and C++ are in there.   https://excelwithbusiness.com/blog/say-hello-world-in-28-different-programming-languages/

Python works great on everything except Arduino, where you use C++.  It is amazingly easy to use Arduinos.   Start with the built-in examples, like Blink.  Here is an article on that subject:  https://www.arduino.cc/en/Tutorial/BuiltInExamples

@SDsolar Its interesting alot.

Have fun with it!   The best thing about programming is that you have the freedom to control everything.  The worst thing about programming is that you have to control everything.  That was the joke when I was in CS school.

btw, please edit your question here and make it very clear that you are a Python programmer and want to know how hard of a leap it might be to use C++ on Arduino.  You have said plenty in the comments that, if included in the question, might even get the hold released.

@SDsolar is there anything missing now?

Your edit only makes this question worse.  Fundamentally, it does not fit here.

Arduino uses a language that is derived from Processing, which looks like C++.
Python is a different language, although both have similarities (both Object Oriented for example).
What is 'complex' depends on what your background is. C++ is in general more complex than Arduino, but most people using Arduino program in C++, so most examples can be found in C++, which makes support from other users easier.
If you are new to programming, I suggest using the 'standard' Arduino IDE.
To be complete, Arduino is not a programming language, it is a platform. In general, every language can be used to write Arduino code, but only a few have compilers for creating Arduino (machine) code.

Arduino uses the gcc compiler which is 100% 'c++'. The 'c++' includes automatically 'c' (although some would say that is is no longer pure 'c' because there are very tiny differences for example with keywords that are needed in 'c++'). On top of the 'c++' the Arduino platform has put an extra sauce. That extra layer can be a blessing or a curse or just confusing. In my opinion it is a little of each of those three things. Newer Arduino boards have faster processors and more memory, so there is no more holding back to use 'c++' to the full.

@Jot> well, there are C constructs that do not exist in C++. C++ doesn't include C, only a subset of it.

It sure is easy to get sidetracked by discussions about languages.  For Arduino I say just do what @Michael says and use the Arduino IDE (and the built-in examples) to get into the mindset.

I tried to make my answer suitable to the one who asked ... Jot is right mostly that C++/C and the Arduino 'language'  are similar, but from a start point of view, it's best to start simple (which is the Arduino IDE).

Understood.  I like your answer so upvoted.  It was a challenge to answer it as asked.  @Chris improved the body but I still think the title is not compelling enough for people to find this one after it is not new and goes inactive.

@SDSolar Thanks ... and also it's partly opinion-based (what is complex or not). E.g. for me electronics is more complex than programming, since I have more experience in the latter. Some people like OO, others prefer non-OO etc.


text:
Very bright cursos positions

As you may can I see on the picture. I try to display the word "goodbye". Yet the problem is that the cursor positions are to bright. I hooked up a 10k ohm potmeter to the Anode. To change the backlight. Is there a way to make the cursos positions less visible?
Kind Regards,
Q

Adjust the contrast pot that you should have wired in?

as the brightness of the blue backlight changes so do the cursos positions. In the end the cursor positions are equally as bright as the backlight

Which pot are you adjusting?

connected to the Anode (pin 15)

No, you should be adjusting the other pot. The contrast pot.

that one goes to ground on my setup

Well, there's your problem then. If you created the circuit properly you'd be able to adjust the contrast. As it is you have no control. Every tutorial I have ever seen has specified a pot for the contrast. They don't do that just for fun - they do it for a reason.

issue fixed: I adjusted the Anode (pin15) instead of the contrast (pin3).
Look at the conversation between me and Majenko to see the realisation.


text:
Using Thinger.io Wifi together with HX711 library soft resets ESP8266 (NodeMCU)
I'm trying to get my NodeMCU v1.0 board to read from a load cell connected to a HX711 amplifier and send the data through Wifi to Thinger.io. I managed to make the readings from HX711, works perfectly. I also managed to send data to Thinger.io separately (ran the example without problems). However putting these together just doesn't work for me, the board soft resets:
[NETWORK] Starting connection...
[NETWORK] Connecting to network xxxxxxx

Soft WDT reset

ctx: cont
sp: 3fff0c60 end: 3fff0ec0 offset: 01b0

>>>stack>>>
3fff0e10:  4021e91f 00000001 3ffefe64 3ffefd48
3fff0e20:  3fff18dc 40203d38 3ffefe64 40203f0c
3fff0e30:  3ffe8e7f 3ffefcd8 3ffefe64 402023fc
3fff0e40:  3ffe8e81 00000015 3ffefe64 402051c0
3fff0e50:  00005173 3ffefcd8 3ffefe64 402051e4
3fff0e60:  3fffdad0 3ffefcd8 3ffefe64 3ffefe90
3fff0e70:  3fffdad0 00000001 3ffefcd8 402034b9
3fff0e80:  feefeffe 3ffefcd8 3ffefe88 40203768
3fff0e90:  3fffdad0 00000000 3ffefe88 402037e0
3fff0ea0:  feefeffe feefeffe feefeffe 40205824
3fff0eb0:  feefeffe feefeffe 3ffefea0 40100718
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

And if I wrap the thing.handle(); with
  ESP.wdtDisable();
  thing.handle();
  ESP.wdtEnable(0);

Then I get hard reset after few seconds.
This is minimal code where I reproduce the issue:
#define _DEBUG_

#include <HX711.h>
#include <ESP8266WiFi.h>
#include <ThingerESP8266.h>

#define USERNAME "zink"
#define DEVICE_ID "xxxxxxxx"
#define DEVICE_CREDENTIAL "xxxxxxxxx"

#define SSID "xxxxx"
#define PASSWORD "xxxxxx"

ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

HX711 scale;

void setup() {
  // put your setup code here, to run once:
  thing.add_wifi(SSID, PASSWORD);
  scale.begin(D6, D5);
}

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

While this sketch works perfectly:
#define _DEBUG_

#include <ESP8266WiFi.h>
#include <ThingerESP8266.h>

#define USERNAME "zink"
#define DEVICE_ID "xxxxxx"
#define DEVICE_CREDENTIAL "xxxxxxx"

#define SSID "xxxxxxx"
#define PASSWORD "xxxxxxx"

ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

void setup() {
  // put your setup code here, to run once:
  thing.add_wifi(SSID, PASSWORD);
}

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

And also this one:
#include <HX711.h>

HX711 scale;

void setup() {
  // put your setup code here, to run once:
  scale.begin(D6, D5);
}

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

But combining them triggers a soft reset. What am I doing wrong here?

When an ESP resets its usually a segmentation fault.  The first area I would look at is string manipulation, but you aren't doing any.  So maybe reversing the order of:
thing.add_wifi(SSID, PASSWORD);
scale.begin(D6, D5);

might stop it, but it will only be temporary.
If it isn't you, and I can't see anything in your code that would cause it, then it must be the libraries.  I think you will have to sit down and look at those two functions and see if you can see any string manipulation that might be causing it.
My money (£1) is on the add_wifi function and the cause being because it wants variables passing to it rather than #defines, but that's just a pure guess.


text:
Why would digital outputs on Arduino Due be less than 3.3V?
We are working on a project that requires a temperature sensor to tell the Arduino Due to turn a digital pin to HIGH (3.3V) to active a relay so a heating pad can be powered on.
We have diagnosed all possibilities and the only explanation as to why the switch will not active is the digital pins are only reading 1.8 V on the relay.
We are using a JQC-3F(T73) relay. We are using two digital pins to give it plenty of voltage and amps to switch on and off when needed.
so any explanation as to why it isnt working? thanks.

It sounds like you are directly wiring the relay to the due. Bye bye due...

Also posted at http://forum.arduino.cc/index.php?topic=488837. And indeed they had the relay directly connected to the Due's pin.

volts go down as you run out of omph

The output impedance for the MCU used in the Due is about 46ohm. Along with the relay's impedance this forms a voltage divider that results in a final voltage that is lower than the unloaded voltage from the output.
In any case, do not connect an inductive load directly to a MCU; use a driver such as a ULN2803 instead, being certain to connect the flyback connection of the driver chip properly.


text:
Digispark Serial Port Communication
I am using Digispark ATTiny85 and i need to send and receive data through the serial port of my computer.
Does anyone have an idea as to how do i proceed with sending STRINGS and NUMBERS through the serial port ??
I have read that the ATTINY 85 does not have a serial port.
If that is the case is there any alternative ??

use digikeyboard and your notepad will act as a serial monitor
just burn the program using digikeyboard in digispark examples and connect the attiny to pc and open notepad and it will start acting as a serial monitor.
link to tutorial
https://www.youtube.com/watch?v=Wj7i1fQDeTk

You may use DigiCDC to virtually create a serial device. It's slow but does the job as mentioned in this article.
A serial-echo program would look something like this:
#include <DigiCDC.h>

void setup() {
  SerialUSB.begin();
}

// the loop routine runs over and over again forever:
void loop() {

  if (SerialUSB.available()) {
    SerialUSB.write(SerialUSB.read());
  }

   //SerialUSB.delay(10);
   /*
   if you don't call a SerialUSB function (write, print, read, available, etc)
   every 10ms or less then you must throw in some SerialUSB.refresh();
   for the USB to keep alive - also replace your delays - ie. delay(100);
   with SerialUSB.delays ie. SerialUSB.delay(100);
   */
}

Welcome to Arduino:SE. You might want to summarise the main points from that article in your answer. Links do go dead, which is why (as with other SE sites) link-only answers are often removed.

have read that the ATTINY 85 does not have a serial port.

It depends on your definition of serial port.
From a hardware perspective it has a usi. That can be configured as a uart. Whether it fits your need or not is up to your application. Read the datasheet to be sure.

The ATTiny85 does not have a hardware serial port, but you can use the Arduino SoftSerial library to implement a serial port in software. Have a look at SoftSerial. Or for better performance, including full duplex operation (transmit and receive at the same time) this may be better.

could you help me even further as to how to implement the software serial on the DIGISPARK ATTINY 85 module and use a serial port.

You have a number of options.

Go the DigiCDC/SerialUSB path. Or whatever replaces it.
(harder), use an I2C to serial bridge, SC16IS750. This has a 64 byte buffer limit so input should be short, typically [Esc] or "U" (for firmware update), but basic menu control is possible.
Use SendOnlySoftwareSerial, on a free pin as Tx and hook up an FTDI cable or a serial to USB adapter. This is good for PuTTy, Screen, MiniCom etc.

NB. I have no issues with blowing away the bootloader and just using the usb for power to get option 3 to work.

Its quite simple, you need a program on your PC that will send data (that you type) to the serial port.
If you are on Windows then you want a 'Terminal Emulator' program, I don't know what its called on Linux but it will be along the same lines.
If you are using the Arduino IDE then there is already something built in, the Serial Monitor will do the job.  You don't even need to be using the IDE for programming you should be able to use the monitor anyway.
Also you can write your own application to do it, but don't do that unless you really have to.

the serial monitor is not accessible when using the digispark attiny85 and it gives the error that "COM port is not available" even when the module is connected to the pc

OK, I can see the problem with that plan then. :)

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


text:
Sizeof variables and Due's RAM
I set out to see how much space some arrays have. I used this test code
bool state = false;

uint16_t BuffA[46000];
uint16_t BuffB[20000];
uint16_t BuffC[20000];
uint16_t all = 0;

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

void loop(){
if (state==false){
Serial.println(sizeof(BuffA));
Serial.println(sizeof(BuffB));
Serial.println(sizeof(BuffC));
all = sizeof(BuffA) + sizeof(BuffB) + sizeof(BuffC)
Serial.println(all);
state = true;
  }
}

I got this answer from the serial:
92000
40000
40000
40928

Why are the results doubled from those i initiated? Shouldn't the first one be 46kb and the other two 20kb?
Why is the last value only 40928?
The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?
If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

sizeof doesn't return the number of elements. It returns the number of bytes. Since they are uint16_t arrays each element is 2 bytes - hence twice the size.
The reason your last number is only 40928 is because of integer wraparound. You only provide a 16-bit unsigned variable to store it in, so all you get is the lower 16 bits of the answer.
92000 + 40000 + 40000 = 172000

172000 in hex is 0x29FE0

0x29FE0 truncated to 16 bits is 0x9FE0

0x9FE0 in decimal is 40928.

The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?

It would, but you aren't actually using the arrays for anything, so the compiler threw them away.

If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

There are ways of interfacing the SAM3X with external RAM, but I don't thing the Due exposes all the signals you need. I would change to a chip with more RAM, such as the PIC32MZ with 512kB of RAM and 200MHz operation.

OP should be extremely careful with using nearly all RAM for data on embedded systems. One won’t get a nice error when things overflow. Instead, the stack will grow into the data section, overriding data there and getting overwritten by write access’ to the data. One will be seeing erratic misbehaviour, including freezes, NMIs and incorrect data.

Also known as "stack smashing" ;)

The sizeof operator's result is number of bytes, not number of array elements.  Your arrays in the program above have two bytes per element, hence twice as many bytes as elements.
If you want to report the number of elements, divide the total size by the number of bytes per element.  For example:
nElements = sizeof BuffA /  sizeof BuffA[0];

As uint16_t variables have 16 bits, the total all will exceed the maximum (65535) that all can hold.  Consider using uint32_t type for that variable. For example:
uint32_t all = sizeof BuffA/sizeof BuffA[0] + sizeof BuffB/sizeof BuffB[0] + sizeof BuffC/sizeof BuffC[0];

Because the type of sizeof is size_t, a “type able to represent the size of any object in bytes”, one need not cast any of addends to uint32_t for the result to not overflow.

A variable of uint16_t has 16 bits, thus two bytes, so for e.g. BuffA[46000] this means 46000 * 2 = 92000 bytes.
The variable all is also 16 bits and can contain only as max value 65,535.
92000 + 40000 + 40000 = 172000 bytes but that does not fit in 16 bits.
Therefore the value is clipped ... make it a uint32_t variable.
The total is 172.000 bytes, this mean it will not fit in 96KB. What are the value ranges you want to store? If the values are max 255
You can use extra RAM. DRAM is very hard to use, EEPROM is only usable when you don't have to write it too often. Otherwise use SRAM, e.g. the 23LC1024's which can store 128 KB RAM and are only DIP8.

Thanks! About the external SRAM.. I am doing real time audio applications. Will the external RAM introduce delays to the output audio?

I did some timing tests on the 23LC1024 ... a page read/write of 32 byte costs about 100 us. Reading other amount cost relatively more, like 1 byte read or write: 23 us, 8 bytes 30 us, 1024 bytes 4000 us.
I also tested another SRAM, but that was much slower and more DIP pins, but cheaper.

32 byte is pretty small, so maybe the time for read/write is high! To put this into perspective, do you know how much time it would take for 32 byte r/w on the arduino due? Is there some benchmarking info on this?

True, but for 1024 bytes its relatively larger (note that 1024 bytes / 32 * 100 ns = 3200 us. Of course you can read multiple times 32 bytes.
I also am interested about a bench mark for the Arduino (Uno/Mega). But I don't know if it can be found.

I will ask for further info on this and i will answer here if i know something. Thanks for everything!

I'm also curious!

Let us continue this discussion in chat.


text:
Time to read/write memory on the DUE
I am onto a project where a need more memory. I saw the 23LC1024 chips are very popular with the Arduino DUE.
A very helpful person told me he did some timing tests on the 23LC1024 and a page read/write of 32 bytes costs about 100 μs.
I am interested in real time audio manipulation application (using the Arduino Due's ADCs and DACs).
This time of 100μs per 32 bytes seems a lot for the application, though i am not sure.
Are there benchmarking tests of the Arduino DUE for the time it takes to read/write to its memory, so i can compare with this chip and decide what to do?

You really don't want to use an external SPI memory for that.  Switch instead to either a processor with more on-chip RAM (maybe another SAM series part, or maybe the top end Teensy), or even more appropriately for such a task, switch to an SoC which uses a variety of external parallel DRAM and likely has on-chip caches to further speed access to it.  These don't necessarily cost any more today, though they do add some system complexity.

Personally I use the PIC32MZ with an external I2S DAC or CODEC chip. 200MHz 512kB RAM, 2MB flash... And programmable in the Arduino IDE...

Besides, using DMA to read from the ADC and write to the DAC leaves plenty of CPU time for shuffling memory around between internal and external RAM blocks.

I didn't know this chip was programmable from the arduino IDE! Does it follows the same code structure (setup, loop)? Also the chip is available in bulk form. I would have to build a circuit and solder components to program it right? Any references on the circuit?

Also, could you please mention the I2C DAC chip you were using?


text:
Why is Wire.onReceive() called during requests?
I'm building a complex I2C-based networking protocol and have noticed that the Wire.onReceive() handler is called both for I2C read and write operations. When the master writes to the slave, it is called as you'd expect. But it also seems to be invoked when the master reads from the slave which is unexpected.
Ideally, I'd like a transaction with both a read and a write - e.g. the master writes a value (for instance a variable argument) and then reads back from the slave the result (for instance, the lookup of that variable.)
Compiled on the SAMD21 ArduinoCore, the following programs generate this result:
1400,700
>>> x is
<<< hello
>>>
>>> x is
<<< hello
>>>
1404,702
>>> x is

Showing that the onReceive is called twice as often as onRequest.
I don't see this behavior documented anywhere.
Master:

    #include
void setup()
{
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop()
{
  Wire.beginTransmission(4); // transmit to device #4
  Wire.write("foobar");        // sends five bytes
 // Wire.write(3);              // sends one byte
  Wire.endTransmission(true);    // stop transmitting

  Wire.requestFrom(4, 6);    // request 6 bytes from slave device #2

  while(Wire.available())    // slave may send less than requested
  {
    char c = Wire.read(); // receive a byte as character
    Serial.print(c);         // print the character
  }

  delay(500);
}

Slave
#include <Wire.h>

void setup()
{
  Wire.begin(4);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent);
  Serial.begin(9600);           // start serial for output
}

long inCount = 0;
long outCount = 0;

void loop()
{
  char c[200];
  snprintf( c, 200, "%d,%d\n", inCount, outCount );
  Serial.print( c );
  delay(1000);

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
inCount++;

  Serial.print( ">>> ");
  while(1 < Wire.available()) // loop through all but the last
  {
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }

  Serial.println();         // print the integer
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
  Serial.println( "<<< hello ");

  outCount++;
  Wire.write("hello "); // respond with message of 6 bytes
                       // as expected by master
}

The Wire.onReceive is not called when the Master is reading data. If you encounter that, it is a bug, write a minimal sketch and start an issue at Github. Please don't use any Serial function inside receiveEvent or requestEvent. In the receiveEvent you can use 'howMany' for the number of received bytes, there is no need for the strange while(1 < Wire.available()). I know that is in an example, but that is a terrible example. The 'inCount' and 'outCount' should be volatile. The sprintf format should perhaps use %ld a long, but I suppose that is also 32-bit for a SAMD21.

@jot: +1 for the hint, not to use any Serial function within the event handler.


text:
Fastest way to read an array of numbers from python
I'm trying to send an array of numbers from python to Arduino over the serial connection. I can reliably read a small incoming set of numbers (for example 123435678) from python, which I can then parse since I know how many digits are supposed to be in each number (for example, 1, 23456, 78). I do this with my Arduino code:

void getInput() {
     char buff[9];
     int field1;
     char field2[6];
     char field3[3];

  Serial.readBytes(buff, 8); //read 8 bytes from the Serial port
  buff[9] = '\0'; //null terminate the string we just read
  Serial.println(buff); //check that we got it
  for(int i=0; i<buff_len;i++) { //now we divide up the string into separate numbers
    if(i==0) {
      field1 = buff[0] - 48; //turn it into an int using ASCII
    }
    if(i>=1 && i<6) {
      field2[i-1] = buff[i];
      field2[5] = '\0';
    }
    if(i>=6) {
      field3[i-6]=buff[i];
      field3[2] = '\0';
    }
  }
  for(int i=0;i<buff_len;i++) { //clear the buffer
    buff[i]=0;
  }
}

But if I wanted to send a whole array whose contents I don't know in advance, for example like this:
for i in range(200):
    ser.write(i)

What's the best way to get these numbers to Arduino and file them away in an int array? Should I make the array in python first as a numpy.linspace() and send that?

While it's probably not your only issue, you invoke undefined behavior when you write to the 10th element (index 9) of the 9-element buff[9].

If you don't know the length of the data then you need to be sending start and end markers so your other code can tell where the transmission starts and ends.  I usually use < and >, so the data packet might look like <12345678>.  You don't have to use those particular characters, just pick something that you know won't show up in your data.

Yes. Putting a newline at the end of each is even more common, and plays well with many traditional computing tools.  Since there seem to be multiple fields in each entry, putting a space or comma between them would also help.


text:
Use a Unicode surrogate pair character in Arduino IDE
I'm writing a sketch for a Wemos D1 Mini to display a web page. This works and I can get Unicode characters to display, but if I try to use ones with surrogate pairs like 🔊 I get a compile error;
  s += "\uD83D\uDD0A";

Error

\uD83D is not a valid universal character

How can I get this character in my code?

Google the error message "\uD83D is not a valid universal character" and you fill find lots of answers.

There is a nifty new feature in C++11 called string literal, this example shows how to use it with any single line or multi line or utf8 text. You just define starting and ending sequence, in following case --- (starting sequence becomes R"---( and ending sequence )---") and make sure that this sequence does not appear in encapsulated text. This is great for integrating websites into arduino projects:
static const char _index_html[] PROGMEM = R"---(
<html>
<head>
<link rel="icon" type="image/png" href="/favicon.png"/>
</head>
<body>
...
</body>
</html>
)---";

Okay, but what does that have to do with the SMP? Or anything outside ASCII for that matter?

If he had used any unicode capable editor, he could just copy/paste any unicode symbols without caring how to encode them - no need to use escaping sequences. Also this answers shows how to easily integrate mutliline HTML code into arduino project

After some trial and error, I got it using the python style u"\U0001F50A" without the leading u of course
  s += "\U0001F50A";

Too bad I didn't think about googling the error msg, would have saved me some time.

Can you use pure UTF-8 characters in the source code ? It is a risk, because everything should be able to handle them. I think it should work. At least this forum can handle pure UTF-8 characters: ±10 °C, 10 µm, 1 kΩ, ¿

Actually, you can. I didn't even try that.


text:
Arduino Mega - I2C pins (20/21) unreliable
Has anybody else noticed that the Arduino Mega pins 20/21 are exceedingly unreliable over long periods of time? It has been the case four times now where I have hooked up no more than 3 I2C devices to these pins and had them fail after approx. 10 days of light use on average.
For example, my team and I had 3 sensors hooked up and were successfully running tests for about two weeks, then right before our launch, I2C stopped working entirely, returning completely incorrect (all zero) data every time.
Again, I have had this issue four separate times in the past, some where pull-up resistors are present, others not.
I seem to be unable to find related information on the web.
Has anyone else noticed this?

If you mean a lasting failure, this may be indicative of electrical abuse.  Are you running these to off-board sensors?  I2C in its everyday form really isn't intended for that.  What sort of environment and power situation are you operating in?  And what do you mean by without pull-up resistors - those are absolutely required...

then right before our launch, I2C stopped working entirely, - have you changed absolutely nothing in that time (including code)? I find it exceedingly hard to believe that the I2C circuit "wears out".

Your question would be better by including the sensors part numbers, and your code and schematic. As it is, your question is really "some unidentified sensors, connected in a way we haven't disclosed, using code we haven't posted, fails after two weeks".

That's because it has a built-in "crisis detector" and you made the mistake of talking about your presentation where it could hear you.  ;-)

Welcome to Arduino Stack Exchange.  Please take the tour to see how to get the most out of this site:  https://arduino.stackexchange.com/Tour - you will notice that it is best to show us what you have tried (photos, code, etc.) then post a specific question about where you have a problem.  Then put your question in the title.

The I2C pins on the Arduino Mega 2560 board are 100% reliable, but you have to use them correctly.
The Wire library could halt when something is wrong with the hardware I2C bus. In that case the sketch stops. The Wire library should have timeouts programmed in case something is wrong with the hardware, but sadly it doesn't have timeouts.
Hardware
The hardware I2C bus on the Arduino Mega 2560 board is a 5V I2C bus, because the Arduino Mega 2560 has 10k pullup resistors to 5V for SDA and SCL.
The wires for I2C can only be short. Long wires will not work.
The worst thing is when SDA and SCL are in a flat ribbon cable next to each other. The crosstalk between SDA and SCL will make the I2C very unreliable.
Because it is a 5V I2C bus, you may not connect 3.3V sensors to that 5V I2C bus. In that case you need a level converter.
The total value of all pullup resistors in parallel should not be too high (more sensitive for electrical noise, longer wires are not possible) and not be too low. The I2C specificiation is maximum 3 mA pulling of down current to get the signal low.
Everything that is connected to the I2C bus must have proper power supply. If one sensor has a power supply that fails, then that sensor will probably pull down the SCL and SDA signals.
A test with a breadboard might fail, due to bad contacts of the breadboard.
Software
The Arduino Wire library is often used in a wrong way.
If one of the sensors is an Arduino board as a I2C slave, then the code for the slave must be done right, because there are many ways to do it wrong.
You could check the return value of every Wire.endTransmissions for an error, and check every return value of Wire.requestFrom for the amount of data that is received.
If you tell us everything about the sensors, the wires (with photos), the logic level converters, the sketch, and so on, then we can tell you what the problem is.