message:
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?

body:
`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!


sender: user

sender: assistant

body:
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();

                }

              }

            }


message:
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.

body:
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.


body:
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.


body:
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.


body:
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.


body:
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.


body:
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)](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)) 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 :)


body:
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...


body:
> 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.


message:
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);

body:
Here is the proper way to implement a polynomial function. It's a direct
application of [Horner's
method](https://en.wikipedia.org/wiki/Horner's_method):

<!-- language-all: c++ -->

    // 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);
    }


body:
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.


message:
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:

[![Transmitter][1]][1]

[![Receiver][2]][2]

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

  [1]: https://i.stack.imgur.com/Dc2Ad.jpg
  [2]: https://i.stack.imgur.com/GUP5T.jpg

body:
Those cheap 433 MHz RF modules require a (good) library to work. The VirtualWire/RadioHead library is the best.

The [VirtualWire][1] library it outdated, but still used.

The [RadioHead][2] 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][3].
[RadioHead][2] 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][4].

Last but not least: don't forget Wifi and Bluetooth.

  [1]: http://www.airspayce.com/mikem/arduino/VirtualWire/
  [2]: http://www.airspayce.com/mikem/arduino/RadioHead/
  [3]: https://www.sparkfun.com/pages/wireless_guide
  [4]: https://www.adafruit.com/product/3176


message:
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.

body:
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.


message:
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][1] 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).

[![enter image description here][2]][2]

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.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/39662c.pdf
  [2]: https://i.stack.imgur.com/U2I5g.jpg

body:
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.


message:
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](https://store.arduino.cc/arduino-gsm-shield-2-integrated-antenna) 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!

body:
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](https://www.aliexpress.com/item/1pcs-DIY-KIT-GSM-GPRS-900-1800-MHz-Short-Message-Service-SMS-module-for-project-for/32786741769.html).

By adding more money, you also get more features. Just sarch for "gsm arduino" or "SIM800", "SIM900".


message:
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)](https://www.arduino.cc/en/Tutorial/HelloWorld), Aurdino programming looks easy to me.

body:
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.


message:
Very bright cursos positions

![enter image description here](https://i.stack.imgur.com/p9A7x.jpg)

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

body:
issue fixed: I adjusted the Anode (pin15) instead of the contrast (pin3).

Look at the conversation between me and Majenko to see the realisation.


message:
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.

body:
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.


message:
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 ??

body:
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][1]. Or for better performance, including full duplex operation (transmit and receive at the same time) [this][2] may be better.

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


body:
> 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.


body:
You may use `DigiCDC` to virtually create a serial device. It's slow but does the job as mentioned in [this][1] article.

A serial-echo program would look something like this:
```c++
#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);
   */
}
```

  [1]: https://digistump.com/wiki/digispark/tutorials/digicdc


body:
You have a number of options.

 1. Go the DigiCDC/SerialUSB path. Or whatever replaces it.

 2. (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.

 3. 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.


message:
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

 1. Why are the results doubled from those i initiated? Shouldn't the first one be 46kb and the other two 20kb?
 2. Why is the last value only 40928?
 3. 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?
 4. If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

body:
The [`sizeof`](http://www.cplusplus.com/faq/sequences/arrays/sizeof-array/) 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`](http://www.cplusplus.com/reference/cstring/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.


body:
`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.


body:
1. A variable of uint16_t has 16 bits, thus two bytes, so for e.g. BuffA[46000] this means 46000 * 2 = 92000 bytes.

2. 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.

3. 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

4. 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.


message:
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:
<!-- language-all: lang-cpp -->

    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?

body: 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.


message:
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?

body:
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.


body:
There is a nifty new feature in C++11 called [string literal](http://en.cppreference.com/w/cpp/language/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>
    )---";


message:
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?

body:
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.


message:
How to get DHT11 temperature/humidity sensor to update on Arduino Uno

Trying to program a way to control my thermostat by interfacing it with my Arduino Uno. I am using a DHT11 to read temperatures and humidity. However, after making its first reading, it is not updating after that. I have included the reading in a loop that waits 2.5 seconds between readings to give the sensor time. However, its not updating. I tested the DHT11 with the example code that came with the DHT library and it is in itself functioning. To test it I have directed a warm hairdryer to the DHT sensor, but the readings dont change. However, when I reset it, the sensor will then show the higher reading initially but then wont update like before.

As well, the the photoresistor in the system will update its lux readings the whole time.

I have included the code below. Any help greatly appreciated! (sorry if the code is a bit messy, I am a novice programmer)

    #include <LiquidCrystal.h>
    #include <dht.h>

    dht DHT;

    #define DHT11_PIN 8
    #define BOUNCE_DURATION 400
    unsigned long checkLCD = 0;
    volatile unsigned long bounceTime = 0;
    unsigned long refreshBut = millis();
    volatile int desiredTemp = 21;
    boolean AC_on = true;
    unsigned long checkBut = 0;
    int temp = 0;
    int humi = 0;
    unsigned long lastTime = 0;
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 10, 9);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      Serial.begin(9600);
      // Print a message to the LCD.
      lcd.print("DHT test");
      Serial.println("DHT TEST Type,\tstatus,\tHumidity (%),\tTemperature (C)");
      pinMode(3, INPUT_PULLUP);
      pinMode(2, INPUT_PULLUP);
      pinMode(13, OUTPUT);
      pinMode(A1, INPUT_PULLUP);
      testDHT(); // testing DHT sensor

    }

    void loop() {
       if (millis() > lastTime)
      {
        temp = DHT.temperature;
        humi = DHT.humidity;
        lastTime = millis() + 2500;
        Serial.println(temp);
      }

      int luxSEND = -0.066433 * analogRead(A0) + 81.467234; //lux reading
      unsigned long refreshLCD = millis();
      int upBut = digitalRead(2); //up button
      int downBut = digitalRead(3); //down button
      int changeAC_send = digitalRead(A1);//read button for change between heating and AC
      unsigned long refreshBut = millis(); //for button for change between heating and AC

      displayReadings(humi, temp, luxSEND, refreshLCD, desiredTemp); //display on LCD - humidity, temperature, lux

      attachInterrupt(digitalPinToInterrupt(2), upButtonOn, FALLING);//Up in desired temp
      attachInterrupt(digitalPinToInterrupt(3), downButtonOn, FALLING);//Down in desired temp

      changeAC_on (changeAC_send, refreshBut); //change between heating and AC

      if ((temp > desiredTemp) && (AC_on == true)) { //AC structure
        digitalWrite(13, HIGH);

      }
      else if ((temp < desiredTemp) && (AC_on == false)) { //Heat Structure
        digitalWrite(13, HIGH);

      }
      else {
        digitalWrite(13, LOW);

      }
    }

    void displayReadings (int h, int t, int lux, unsigned long refreshL, int desiT) {
      if (refreshL >= (1000 + checkLCD)) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("T:");
        lcd.print(t);
        lcd.print("C  ");
        lcd.print("H:");
        lcd.print(h);
        lcd.print("%");
        Serial.print(h, 1);
        Serial.print(",\t");
        Serial.print(t, 1);
        Serial.print(",\t");
        lcd.setCursor(0, 1);
        lcd.print("L:");
        lcd.print(lux);
        lcd.print("   ");
        Serial.println(lux);
        Serial.print(",\t");
        lcd.print("Des.T:");
        lcd.print(desiT);
        lcd.print("C");
        checkLCD = refreshL;
      }

    }

    void testDHT () {
      // READ DATA
      lcd.clear();
      Serial.print("DHT11, \t");
      int chk = DHT.read11(DHT11_PIN);
      switch (chk)
      {
        case DHTLIB_OK:
          Serial.print("OK,\t");
          break;
        case DHTLIB_ERROR_CHECKSUM:
          Serial.print("Checksum error,\t");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("Can't get reading");
          lcd.setCursor(0, 1);
          lcd.print("from DHT");
          break;
        case DHTLIB_ERROR_TIMEOUT:
          Serial.print("Time out error,\t");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("Can't get reading");
          lcd.setCursor(0, 1);
          lcd.print("from DHT");
          break;
        default:
          Serial.print("Unknown error,\t");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("Can't get reading");
          lcd.setCursor(0, 1);
          lcd.print("from DHT");
          break;
      }
    }

    void upButtonOn () {
      if (millis() > bounceTime) {
        Serial.println("Up Pressed");
        desiredTemp = desiredTemp + 1;
        bounceTime = millis() + BOUNCE_DURATION;
      }
    }

    void downButtonOn () {
      if (millis() > bounceTime) {
        Serial.println("Down Pressed");
        desiredTemp = desiredTemp - 1;
        bounceTime = millis() + BOUNCE_DURATION;
      }

    }

    void changeAC_on (int changeAC, unsigned long refL) {
      if (refL >= (200 + checkBut)) {

        if ((changeAC == LOW) && (AC_on == true)) {
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("HEATING MODE");
          Serial.println("Heat On");
          AC_on = false;
          checkBut = refL;
        }

        else if ((changeAC == LOW) && (AC_on == false)) {
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("A/C MODE");
          Serial.println("AC On");
          AC_on = true;
          checkBut = refL;
        }
        else {
          checkBut = refL;
        }
      }
    }

Additionally, here is a sample of the output from the serial monitor, while a hairdryer is being directed at it:

        DHT TEST Type, status, Humidity (%), Temperature (C)
    DHT11,  OK, Current read temperature is: 29
    40, 29, 53
    , 40, 29, 53
    , Current read temperature is: 29
    40, 29, 53
    , 40, 29, 53
    , 40, 29, 53
    , Current read temperature is: 29
    40, 29, 54
    , 40, 29, 54
    , Current read temperature is: 29
    40, 29, 52
    , 40, 29, 53
    , 40, 29, 53
    , Current read temperature is: 29
    40, 29, 53
    , 40, 29, 53
    , Current read temperature is: 29
    40, 29, 53
    , 40, 29, 53
    , 40, 29, 53
    , Current read temperature is: 29
    40, 29, 53
    , 40, 29, 53
    , Current read temperature is: 29
    40, 29, 53
    , 40, 29, 51
    , 40, 29, 52
    , Current read temperature is: 29
    40, 29, 52
    , 40, 29, 52
    , Current read temperature is: 29
    40, 29, 54
    , 40, 29, 54
    , 40, 29, 54
    , Current read temperature is: 29
    40, 29, 53
    , 40, 29, 54
    , Current read temperature is: 29
    40, 29, 53
    , 40, 29, 53
    , 40, 29, 54
    , Current read temperature is: 29
    40, 29, 54
    , 40, 29, 54
    , Current read temperature is: 29
    40, 29, 54
    , 40, 29, 54
    , 40, 29, 54
    , Current read temperature is: 29
    40, 29, 54
    , 40, 29, 54

body:
DHT.read11 reads the temperature from the sensor. You call that once from setup function but not from the loop function. Therefor the DHT11 sensor is read just once during startup.

You should not use millis like that. The [blink without delay][1] example shows how to use millis.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


message:
for loop reads pots, passes value to PWM pins, can this be in the same for loop?

In the code below I am using a `for` loop to iterate over analog pins (potentiometers) and pass their value, after being mapped, to `PWM` enabled analog output pins (currently controlling LED brightness). While this works as is, I am curious about the following: would it be better to split the `analogRead` and `analogWrite` lines into separate `for` loops, or would that simply be redundant from a code standpoint? My concern is accidentally mixing up the pot values due to difficult-to-perceive timing issues.

The code:

    static const uint8_t analog_pins[] = {A0, A1, A2, A3};
    static const uint8_t digital_pins[] = {3, 5, 6, 9};
    int pot_vals[] = {0, 0, 0, 0};
    int val[] = {0, 0, 0, 0};

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

      // setup inputs, outputs
      for ( int i = 0; i < 4; i++ ) {
        pinMode( analog_pins[i], INPUT );
        pinMode( digital_pins[i], OUTPUT );
      }
    }

    void loop() {
      for (int i = 0; i < 4; i++) {
        val[i] = analogRead(analog_pins[i]);
        analogWrite(digital_pins[i], map( val[i], 0, 1023, 0, 255 ));
      }
      delay(2);
    }

body:
Obviously you can. Except that in most cases your loop execution is much faster than your own period so that you end up changing the duty cycles multiple times in one period.

Not an advisable aporoach. If you have to do it think about configuring the pwm center aligned.


body:
Having both the `analogRead()` and `analogWrite()` in the same loop is
perfectly fine. That would be be my preferred choice if only for one
reason: less RAM consumption. If you split them in two loops, you have
to store somewhere the readings of the four channels, either before or
after mapping. If you keep them in the same loop, you don't need the
`pot_vals[]` nor `val[]` arrays. You would use a local variable instead,
which consumes no RAM:

<!-- language-all: c++ -->

    void loop() {
      for (int i = 0; i < 4; i++) {
        int val = analogRead(analog_pins[i]);
        analogWrite(digital_pins[i], map(val, 0, 1023, 0, 255));
      }
      delay(2);
    }

> My concern is accidentally mixing up the pot values due to
> difficult-to-perceive timing issues.

“Difficult to perceive”? I would call these issues “imaginary” instead.
You have no risk of “mixing” any values here. Maybe, if you can
elaborate on the kind of issues you imagine you could have, we could
help you clear some misunderstanding about how the microcontroller
executes your code.

------------------------------------------------------------------------

**Edit**: To expand on Andrew's comment, the `for` loop can be optimized
as

    for (int i = 0; i < 4; i++) {
      unsigned int val = analogRead(analog_pins[i]);
      analogWrite(digital_pins[i], val / 4);
    }

Dividing the value by 4 is the best way to map the input range to the
output range. It gives a more uniform mapping than the `map()` call
above, as every output value is mapped to exactly 4 input values. It
could be noted, though, that `map(val, 0, 1024, 0, 256)` gives the same
uniform mapping.

The division by 4, however, is optimized by the compiler into a bit
shift, which is orders of magnitude faster than `map()`, and likely to
consume less stack space. There is one caveat to be aware of: this
optimization is only possible if `val` is unsigned. If it is signed,
then it is compiled into a call to a division routine, which is quite
expensive.

One could be tempted to go even further and get rid of the temporary
`val` variable, like:

    for (int i = 0; i < 4; i++) {
      analogWrite(digital_pins[i], (unsigned int) analogRead(analog_pins[i]) / 4);
    }

However, there is zero benefit from doing so: from the point of view of
an optimizing compiler, this form is exactly equivalent to the previous
one. I prefer the former which I deem more readable.


message:
Arduino Zero timer setup

Where would I find information on how to configure the Arduino Zero's timers?

Because this...

      // Timer stuff
      // Set up the generic clock (GCLK4) used to clock timers
      REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                        GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                         GCLK_GENCTRL_GENEN |         // Enable GCLK4
                         GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                         GCLK_GENCTRL_ID(4);          // Select GCLK4
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      // Feed GCLK4 to TC4 and TC5
      REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                         GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                         GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      REG_TC4_COUNT16_CC0 = 150;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
      while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

      //NVIC_DisableIRQ(TC4_IRQn);
      //NVIC_ClearPendingIRQ(TC4_IRQn);
      NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
      NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

      REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
      REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
      // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

      REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV256 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                       TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                       TC_CTRLA_ENABLE;               // Enable TC4
      while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

Is completely indecipherable and highly error prone.

body:
> Where would I find information on how to configure the Arduino Zero's timers?

Try the datasheet.

What you showed there is fairly typical, may be on the primitive side for chips of its kind.

More power comes with more complexity.


body:
BOTTOM UP

The arduino Zero uses an Atmel samd21 µController. [This video](https://www.youtube.com/watch?v=FTARNR9SLMs) explains how to program the samd chips in a bottom up fashion, or at least how to gather all required information to do so. In case the video doesn't work anymore, i'll briefly rephrase it here. The main steps are:

- Figure out the required registers by reading [the data sheet](http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf)
- Consult the [Atmel Software Framework(ASF)](http://asf.atmel.com) to figure out the corresponding data structures
- Setup your sketch inside the arduino IDE

The bottom up process can be very time consuming, because you are searching a needle out of an haystack like, the datasheet and the ASF. So you need to tackle all the tiny bits before building the whole thing.

TOP DOWN

For some situations it is better to look for a working example program and try to figure out how its done. For this i recommend the [arduino github repository](https://github.com/arduino/ArduinoCore-samd). It is a very good resource for figuring out how arduino uses the ASF and helps me tune certain functions.

The top down process therefore allows to decompose a large working function into its smaller parts and dig into the interesting parts. However, it requires something to work with at the start which is not always available.

INDECIPHERABLE

Some code examples aren't understandable from the start. Once you know what the code is doing, i recommend splitting up the large pieces like this register and bit modification section into smaller ones. Extract these sections into functions with self explanatory names, and if done correctly you can get rid of the comments.

Hope this helps ;)


message:
Controllino Debugging

Its a well known fact, that you can debug your arduino board with the help of an Atmel Ice. However, you might know the [Controllino](https://controllino.biz/controllino/maxi/) which is an arduino compatible device.

It has an ATmega2560 on it.

Do you have an idea how to debug a controllino? I neither see any ICSP port nor did I found anything useful around this topic.

Any help is greatly appreciated!

body:
Connector X1 has the pins you want.

ICSP is shared with the SPI pins. Wire those to your ICE in the same way as you wire the SPI pins of the ICSP header on a normal Arduino to an ICE.


message:
Lowest memory consumption for arrays

I made a little joystick input recorder that stores the joystick state (8 directions + fire) and the time (how long was a button or direction pressed).

Example data would be like this (i = input, t = time in milliseconds):

    i: 0 | t: 2003
    i: 2 | t: 128
    i: 0 | t: 28
    i: 10 | t: 27
    i: 2 | t: 36
    i: 18 | t: 39

My problem is that I run out of memory on an Arduino Uno very quickly. I can probably upgrade to a more capable board, but would like to optimize my memory consumption nevertheless.

     const byte max_record = 200;
     byte sequence[max_record];
     int time[max_record];

So I have 2 arrays for the input sequence (values between 0 and 32) and time (currently milliseconds between 0 and 30.000 or even higher).

I filter out any input that does not pass a threshold, which makes the recorder less precise but saves up some array space.

Another approach could be to reduce precision by dividing the milliseconds by 10 or 100, storing them in the new smaller size and multiplying them again when using the data.

Any other advice is greatly appreciated.

body:
You already tried to minimize some memory by reducing accuracy.

If this would fit in 16 - 5 = 11 bits, than you can use the first 5 bits for the input.

With 11 bits (left) you have a range of 2048. Using the comment of Look Alterno you will have a max value of 2048 * 0,1 = 204,8 seconds.

Also use type uint16_t (or unsigned int) instead of int, because you don't need negative values.

This way you will need 200 (max records) * 2 = 400 bytes.

Assuming the array will be

    uint16_t times[max_record];

Than the input is

    ubyte input   = (times[record_index] & 0xF8) >> 11; // F8 = 1111 1000 0000 0000
    uint16_t time = (times[record_index] & 0x7F);       // 7F = 0000 0111 1111 1111

Update:

Edgar Bonnet's idea brought me on the idea to use a logarithmic formula:

Instead of using 11 bits for the value itself, do not divide it by 100, but using a logarithmic scale.

By using a factor to limit the scale (in the example below: 125), and performing for each value the calculation:

    stored_value = (int) (ln(value) * factor + 0.5)

And by converting back:

    org_value = (int) (exp(stored_value / constant) + 0.5)

Below a table is shown with some example values.

The advantage is that the decrease of accuracy is now very gradually. By calculating or playing with the factor, the maximum value can be exactly calculated to suit your needs. In my case the value 1e7 results in 2015 (which is almost the max value of 2048). 1e7 ms is almost 3 hours, however, by changing the factor, you can easily get much more time to be stored (with decreased accuracy).

Of course this method needs some more computing power.

     Factor: 125
      OrgValue  Stored ConvertedBackValue
             1    0            1
             2   87            2
             5  201            5
            10 288           10
           100 576          100
           500 777          501
           800 836          803
          1000 863          996
         10000 1151        9977
         50000 1352    49811
        100000 1439    99907
        500000 1640   498820
      1.00E+06 1727  1000490
      1.00E+07 2015 10019062

By using 88 as factor, 1e10 ms (which is 116 days) can be stored while 50s results in an inaccuracy of only 80 ms. See the table below.

 Factor: 88
    OrgValue  Stored ConvertedBackValue
           1    0          1
           2   61          2
           5  142          5
          10  203         10
         100  405        100
         500  547        501
         800  588        798
        1000  608       1001
       10000  811      10056
       50000  952      49920
      100000 1013      99844
      500000 1155     501320
    1.00E+06 1216    1002675
    1.00E+07 1418    9955506
    1.00E+08 1621   99977383
    1.00E+09 1824 1004014929
    1.00E+10 2026 9968812163


body:
If I dare suggest an unorthodox solution... I suggest you store the
times as “float11” floating point numbers.

Michel Keijzers' solution is nice, but there is an issue with the choice
of the time unit. If you use 0.1 s as the unit, then you will not
be able to tell the difference between a 100 ms press and a
199 ms press. I am sure these durations should feel quite
different. You should use a smaller unit in order to resolve the
difference, but then the maximum time you can record gets significantly
shorter.

Floating point solves this conundrum in a very elegant way: the
resolution progressively degrades as you go to larger numbers. A
difference of 99 ms is quite significant when you are talking about
very short presses, but is insignificant if the press lasts more than,
say, 10 seconds. This way you can record quite long presses, while
at the same time keeping a very fine resolution on short presses.

I suggest a 0.5.6 floating point format:

* 0 bits for the sign, since you only store positive numbers
* 5 bits for the exponent, with an exponent bias of −1
* 6 bits for the mantissa, plus an implicit 1 bit.

This allow you to store _exactly_ all integers from 2 to 128, i.e. you
have a 1 ms resolution for presses up to 128 ms. Then the
resolution degrades to 2 ms for presses up to 256 ms, and so
on. By the time you get to a 30 s press, the resolution is about
0.25 s. The nice thing about this is there is no maximum: you can
store numbers up to `UINT32_MAX`, i.e. about 49.7 days.

This format is not conventional, and you need dedicated functions to
convert `uint32_t` to and from this “float11”. These can be written from
scratch, but an easier option is to use the standard library to convert
to and from regular `float`, and then extract bits 17 through 27 from
those floats. Here are the functions I wrote (and tested) for this
purpose:

<!-- language-all: c++ -->

    uint16_t to_float11(uint32_t x)
    {
        union { float f; uint32_t i; } y;
        y.f = x;
        return (y.i >> 17) & 0x7ff;
    }

    uint32_t from_float11(uint16_t x)
    {
        union { float f; uint32_t i; } y;
        y.i = ((uint32_t) x << 17) | 0x40000000;
        return y.f;
    }

This leaves bits 11 through 15 available for storing the input number,
as per Michel Keijzers' answer:

    // Encode:
    times[record_index] = (input << 11) | to_float11(time);

    // Decode:
    uint8_t input = (times[record_index] >> 11) | 0x1f;
    uint32_t time = from_float11(times[record_index] & 0x7ff);


message:
DHT11 is not reading Temperature and Humidity when Arduino is powered on using DC power Supply (12V)

I am facing one problem. I have code which read temperature and humidity using DHT11 sensor. I uploaded following code using Arduino via USB serial, I can read values of temp, humidity. Values are being read as long as Arduino is connected to same laptop via USB.

TEMPERATURE AND HUMIDITY are being read as 0 when I power on Arduino using DC12v, 700MA adapter.

I want to deploy Arduino with DHT sensors connected with it in Greenhouse to read greenhouse environmental condition but when I power on using DC adapter or battery, it is giving "0" output.

PLEASE HELP TO SOLVE THIS PROBLEM.

    DHT dht(DHTPIN, DHTTYPE);

    void setup() {
      Serial.begin(9600);
      Serial.println("DHTxx test!");

      dht.begin();
    }

    void loop() {
      // Wait a few seconds between measurements.
      delay(2000);

      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
      float f = dht.readTemperature(true);

body:
You haven't really provided enough information to answer. What are you reading the temperatures with. You code just assigns a variable to the readings but does not output that to anything.

I would suggest reading along with this tutorial, for example, and trying out the code they provide: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/

  [1]: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/


message:
Analog thermistor readings are wrong

There are some discrepancies between what is read by the analog channel for a thermistor, ohms values directly obtained on the thermistor using an ohmmeter, and another digital temperature sensor.

[![][1]][1]

**Figure 1:** Left column (y axis) is degree Celcius; x axis is time (minutes). Orange is what was read by the analog channel (thermistor); in yellow the reading by a commercial digital sensor; and in green, manual readings of the thermistor using a ohm-meter.

A bit more context, we are building a simple system to read the temperature from a thermistor via an analog channel. Code algorithm is very similar to what is found [here][2] and the electronic layout inspired from [here][3]. When we ran into problems,  we just went back to the working basics as instructed by those two above-mentioned references.

Pad resistor is 7K Ohms @ +/-1%, measured resistance was 6690 ohms
Thermistor is 2252 Ohms @ 25 degree Celsius. Coefficients are as follow, coefficient were solved following a calibration in a thermal bath:

 - COEFF_A = 0.0014644
 - COEFF_B = 0.00023888
 - COEFF_C = 9.8996E-08

Specs from vendor are [here (PDF)][4] factory coefficient are about the same. I tried to calculate with either factory and in-house calibrated and there is a few thousandth of a degree of difference between the two - not enough yet to explain the current problem

While investigating I saw some sketch with the same resistance for pad resistor and thermistor, but have seen other differing thus assume this is not an issue.

To troubleshoot and isolate the origin of the discrepancies of the orange line VS other reading, we used

 1. other thermistors (every single one behave similarly as the orange line in the figure 1)
 2. other digital temperature sensors (every single one behave similarly as the yellow line in the figure 1)
 3. we try to put 2 analog thermistors and 2 digital temperature sensors on the same arduino - analog were consistant between each other (discrepancies) and the digital one were behaving as expected (correctly)
 4. we switched the pad resistor, no effect
 5. other arduinos (did not changed anything, every single one was repeatedly demonstrating the same behaviour )
 6. used the system in a temperature controlled room and the discrepancy was still present for the analog channel and absent for the digital sensor.

To be clear, **green** and **yellow** are what we think is the 'real' temperature; and the **orange** is the discrepancy. About 1 - 2 degree differences

We used the raw analog value read by the arduino as an input to manually feed and solve the Steinhart–Hart equation (like using IPYTHON and by hand) and output is the same as the orange line. Did the same with the thermistor obtained by the ohm-meter (Green dots on figure).

**What should be investigated** next to solve the discrepancy between what is read by the analogue channel connected to a thermistor and what the same thermistor provide to the ohm-meter?

Sketch follows

    #define THERMISTORPIN_0 0               // analog pin 0 on the board
    #define SERIESRESISTOR_0 6990             // balance/pad resistor value (ohm)
    #define THERMISTORNOMINAL 2252          // resistance at 25 degrees C
    #define ZEROABS -273.15                 // zero Kelvin (Celsius)

    #define COEFF_A 1.4644E-03          // Coefficient A for Steinhart-Hart eq.
    #define COEFF_B 2.3888E-04          // Coefficient B for Steinhart-Hart eq.
    #define COEFF_C 9.8996E-08          // Coefficient C for Steinhart-Hart eq.

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

    void loop()
    {
        float temp1;
        temp1 = Thermistor(analogRead(THERMISTORPIN_0),SERIESRESISTOR_0);
        Serial.println(temp1);
    }

    float Thermistor(int RawADC, long padResistance) {
      long Resistance;
      float Temp;
      Resistance = padResistance / ((1023.0 / RawADC) - 1);
      Temp = log(Resistance);
      Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp,3)));
      Temp += ZEROABS;

      return Temp;
    }

  [1]: https://i.stack.imgur.com/Nd0Wc.png
  [2]: https://playground.arduino.cc/ComponentLib/Thermistor2
  [3]: https://learn.adafruit.com/assets/571
  [4]: http://www.omega.com/temperature/pdf/44000_THERMIS_ELEMENTS.pdf

body:
So far I can see nothing wrong.

This is all about accuracy and being precise. That is how to deal with this problem. This is not a quick fix.
For example the resistor value has been: 10k, 7k, 6690 and 6990. That's too sloppy.
I think that you have not told us that the thermistor is at GND (I prefer it being at GND, that's good).

**Test**: At 25 °C the thermistor and resistor result in a ADC value of 249.5, and with that in the sketch the result is 25 °C. Very nice. Around 25 °C the sketch is accurate.

Instead of a short minimalistic calculation you could calculate everything. For example the resistance of the thermistor and the voltage at the analog pin. That would make it easer to check those values with a multimeter.
I prefer to let the Arduino do the calculation, and not trying to be smart and optimize something. Let the compiler to the optimizations.

We have to **look further** than the thermistor, the Arduino and the sketch.

 1. How long is a long wire ? What kind of cable ? Shielded cable ? Is one wire connected to GND ? and at the end is only the thermistor ? The GND is not used for something else ? Are the wires of the thermistor or the cable touching a metal object or water ? A multimeter is not connected to something, but an Arduino is connected via the usb to the computer and perhaps to earth ground. With a power supply, there is a small capacitive coupling to the mains. What happen if the Arduino is battery powered and not connected to something ?
 2. How well is the wire connected to the Arduino. Try to solder it if possible. If it is already soldered, was it a good weld ?
 3. What else is going on with the Arduino board ? It could be GND offset caused by something that pushes current through the GND. A LCD display with its background light connected in the wrong way could cause this. Is the thermistor connected via a breadboard, and there is something else on that breadboard ? Then you have almost certainly a DC offset.
 4. Could you try with another Arduino board and another computer ? Only the Arduino board, the thermistor + resistor and a USB cable to the computer. Without the long wires. Try a desktop computer, not a laptop (the usb 5V of a laptop could be less reliable). You are now caught in some kind of trap, and you get out by making a second test setup with a new set of components and not even using a single wire from the first setup.
 5. The NTC could cool down via the metal legs.
 6. Perhaps averaging a number of samples would help. When the final average     calculation is done with float, you could even increase the resolution beyond 10 bits of the ADC.

For now, I think that the problem is between the thermistor and the microcontroller on the Arduino board. Could you try to eliminate any DC offset of the GND and be sure to isolate the thermistor (from metal objects and water)


body:
there seems to be two problems:

1) calibration: the digital sensor / analog sensor may not be calibrated properly - this can account for the gap between the two curves.

2) response time: the digital sensor seems to react much faster than the analog sensor. that could be due to placement, physical attributes (smaller thermal mass for example), ...


body:
One possibility that has not been mentioned yet: the issue may be
the calibration of your ADC converter. Your code carries the implicit
assumption that the voltage you measure is

    V = Vref × RawADC ÷ 1023

The correct formula is

    V = Vref × (RawADC + offset) ÷ scale

where `offset` is ideally 0 and `scale` is ideally 1024 (and not 1023,
as you are assuming). Since you are looking at relatively small
discrepancies, the “ideal ADC” assumption may not be a good enough. [I
have calibrated 3 Arduino ADCs][adc] and found offsets between 2.2 and
2.4, and scale factors between 1026.1 and 1026.3. Thus, if you have an
accuracy issue, I recommend you calibrate your own ADC.

As a side note, you could expect slightly better accuracy if the
thermistor and the resistor are closer in resistance. Right now you have
a factor 3, which is not that bad, but you could use a 2.2 kΩ
resistor, which is a very standard value.

[adc]: https://www.logre.eu/wiki/Réponse_de_l'ADC_d'un_Arduino/en


message:
time delayed LEDs

I have two LEDs an I want the first one getting linear brighter and the second one do the exact same thing just one ore two seconds later. When one LED has reached 100, it should getting darker until there's no light and then start again from the beginning. I#m trying now for quite a long time but couldn't get it going.

    int LED = 11;
    int LED2 = 10;
    void setup() {

    Serial.begin(9600);
    }
    int x;
    int x2;
    void loop() {

    for(x = 0; x<=100;x++)
    {
    while(x > 30)
    {
    for(x2 = 0; x2<=100;x2++)
    {
    analogWrite(LED2,x2);
    delay(100);
    }
    }

    analogWrite(LED,x);
    delay(100);
    Serial.println(x);

    }
    }
I just wanted to do the beginning but it isn't working. Can somebody pleas help me?

body:
Note: I think you will need to adjust the timings.

Hope this help:

    int LED = 11;
    int LED2 = 10;

    unsigned long start;

    int lum = 0;  // Light level LED
    int step = 1;
    int lum2 = 0; // Light level LED2
    int step2 = 1;

    void setup() {
      Serial.begin(9600);
      start = millis();
    }

    void loop() {
      unsigned long now = millis();

      if (now % 100 == 0) {
        // Every 100 ms, light goes up/down 1 notch.
        light(LED, &lum, &step);

        if (now - start > 2000) {
          //  Time to start with LED2
          light(LED2, &lum2, &step2);
        }
      }
    }

    /*
     * Light up/down one notch on a pin.
     */
    void light(int pin, int* p_lum, int* p_step) {
      analogWrite(pin, *p_lum);
      *p_lum += *p_step;

      if (*p_lum == 100) {
        *p_step = -1;
      }
      if (*p_lum == 0) {
        *p_step = 1;
      }
    }


body:
Here is one way to do it.

1. Set up two output compare channels. They are identical except that they have slight different periods.
2. In their respective isr, flip the led

The next effect is that the duty cycle on the led goes from 0 to 100 and then 0 and then ....

The periods determine how long the 0 to 100 to 0 cycle is. The period differential determines how fast the led goes on and off.

You can do that to the other led, either in the same isr or through two other channels.


message:
Can I power arduino uno R3 with 9v battery through Vin?

I want to power up arduino through Vin port , what should be the input voltage ?

body: About 7.5V to 9V is best. A 9V battery is often not capable to supply enough current for an Arduino. Do you have a multimeter to measure the battery voltage drop when the Arduino is connected ?


message:
Data not updated in real time

In my recent project, working with JSON and Arduino. Till now, I am getting proper JSON data and add this one into Arduino data. But here I face one problem. My data are not updated in real time.

For example, my JSON string is:

    {"TPS_Json":"0.40"}

And below is my Arduino code:

    #include<LiquidCrystal.h>
    #include <ArduinoJson.h>

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    String response = "";
    bool begin = false, finished;

    //------------------------------ Variable ---------------------------------//

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

      lcd.begin(16, 2);
    }

    void loop()
    {
      //----------------------------TPS----------------------------//

      float TPS = analogRead(A0) * (5.0 / 1023.0);

      //-----------------------JASON DATA--------------------------//

      StaticJsonBuffer<100> jsonBuffer;

      while (finished == false)
      {
        if (Serial.available())
        {
          const char in = Serial.read();
          if (in == '{')
          {
            response = "";  // Blank the string
            begin = true;
          }
          if (begin)
          {
            response += (in); // Only write if within the {}
          }
          if (in == '}')
          {
            begin = false;   // Prevent any chars between } and { leaking through.
            break;
          }
        }
        delay(1);
      }

      JsonObject& root = jsonBuffer.parseObject(response);

      float TPS_Json = root["TPS_Json"];

      float TPS_Final = TPS + TPS_Json;

      lcd.setCursor(0, 0);
      lcd.print("      ");
      lcd.setCursor(0, 0);
      lcd.print(TPS);
      lcd.setCursor(8, 0);
      lcd.print("      ");
      lcd.setCursor(8, 0);
      lcd.print(TPS_Json);
      lcd.setCursor(0, 1);
      lcd.print("      ");
      lcd.setCursor(0, 1);
      lcd.print(TPS_Final);
    }

So, now I add `TPS_Json` with `TPS`. Where `TPS_Json` is JSON data and `TPS` is an analog value from `A0`. And `TPS_Final` is the addition of `TPS_Json` and `TPS`. I displayed all this on LCD.

Suppose, `TPS_Json = 0.40`, `TPS = 2.40`... So addition is 2.80 means `TPS_Final = 2.80`...
And this all data displayed on LCD successfully.

But when I changed my analog value means TPS value then it is not updated and I'm not getting the correct result.

Suppose, I change the value of TPS means makes it `3.00` from `2.40` than my `TPS_Final` must be `3.40`.But nothing updated. It updated when I send JSON data again. I don't know why this happens. I want to change it in real time means When I changed `TPS` then `TPS_Final` must be changed in real time.

body:
Your code reads data from the serial interface and once it has read the input it re-evaluates the value of TPS_Final.  I've found it difficult to understand your question but I think you are saying this:

If you enter `{"TPS_Json":"0.40"}` in the serial monitor and `A0` has a value that equates to 2.4 then you expect TPS = 2.80 on your LCD.  So do I.

Now if you change what ever is feeding `A0` so that the value equates to 3.00 I think you are saying you expect you LCD to update to say TPS = 3.40, but it doesn't and you don't understand why.

**IF** that is the case then the answer is simple.  When you change the value for `A0` you code is waiting for you to enter the serial data again, because it is a 'blocking function call' well a 'blocking' bit of code at any rate.  And until you enter a value in the serial monitor you code won't evaluate TPS again.

You need to change/remove the while loop so it your code will update the LCD even when the data is being entered by the serial interface.


body:
The reasons it's not updating is because your code is sitting in the loop `while (finished == false) {...}` waiting for more json to arrive.

Try replacing the while loop with something along these lines:

      while ((finished == false) || Serial.available()) {
       if (Serial.available()) {
        const char in = Serial.read();
        if (in == '{')  {
            response = "";  // Blank the string
            begin = true;
            finished = false;
        }
        if (begin)
            response += (in); // Only write if within the {}
        if (in == '}') {
            begin = false;   // Prevent any chars between } and { leaking through.
            finished = true;
        }
       }
      }

and change the initial variable declarations at the start of the code to set finished to false:

    // personally I always put each variables on a separate lines when setting initial values.
    bool begin = false;
    bool finished = false;

This will block until it's received at least 1 json string. After that it will check if there is new data on the serial port, if there is it will block until it's received the whole string, it there isn't any data waiting it will exit.

Oh and your response string is currently including the { } characters at the start and end, this contradicts your comments which imply that it doesn't.


message:
Arduino UNO IR blaster - storing codes in PROGMEM

I've setup an IR LED on my UNO, with the IRremote library, and have the code working to control an RGB LED strip from certain serial input, however as i'm storing the Raw infrared data in variables, i'm running out of RAM very quickly, and haven't managed to get code working that stores the IR data in PROGMEM, then buffers it to RAM for sending.

The current working code can be found at https://gist.github.com/dan-r/71294eaf9fe2354f1a0c7c13fc5f3bcd, and i've tried setting the int arrays as statics in PROGMEM, but whatever I do, I can't figure out how to buffer them into RAM, or even directly send them with irsend.

body:
The Arduino Uno can not read data from PROGMEM (data in flash memory) in the same way as reading data from ram, there are special functions to read data from PROGMEM.

Create a buffer in ram and use one of those special functions to copy the data into that buffer.

Start with the [Arduino PROGMEM reference][1].
Nick Gammon had made a great [tutorial about PROGMEM][2].
All the PROMEM functions are in <[avr/pgmspace.h][3]>

Is the array of numbers always the same length ? That would make the sketch a lot easier.

Then perhaps something like this:

    const unsigned int irTable[9][67] PROGMEM = { { ... }, { ... } }

    unsigned int irBuf[200];

    i = ...   // number of command
    memcpy_P ( irBuf, &irTable[i][0], 67 * 2);
    irsend.sendRaw (irBuf, 67, ...);

  [1]: https://www.arduino.cc/en/Reference/PROGMEM
  [2]: http://www.gammon.com.au/progmem
  [3]: http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html


message:
433 MHZ connection between two Arduino (nano,uno) fails after some time

The goal of this part of my project is to establish a wireless connection between an Arduino nano and an Arduino uno. For this I use 433 MHZ receiver and sender. The nano sends, the uno receives and prints. I have working code and the connection works and I can send, receive and print my message.
But at some point the Uno receives just a part of the message and after this point always receives (or prints) just this part of the message:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/K7CWd.png

Nano (sender):

    #include <VirtualWire.h>
    char *msg = "123456789123456789";

It is not always 2 digits, sometimes more are received.

I searched for errors. The nano is constantly sending and the uno flips to not receiving the whole message. So I reupload the code to the uno without modification and it works again for a few seconds/minutes, so I guess it's a problem at the receiving end.

Here is my code:

Sender(nano):

    #include <VirtualWire.h>
    char *msg = "123456789123456789"

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

   pinMode(7,OUTPUT);
  pinMode(5,OUTPUT);
  digitalWrite(5,LOW); //GND
   pinMode(6,OUTPUT)
   digitalWrite(6,HIGH); //5V
   vw_setup(5000);
  vw_set_tx_pin(7);
    }

    void loop()  {
  vw_send((uint8_t*)msg, strlen(msg));
  vw_wait_tx();
  delay(500);
    }

Receiver(Uno):

    #include <VirtualWire.h>

    int i;
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;

    void setup() {

     Serial.begin(9600);
     pinMode(5,INPUT);
     pinMode(6,INPUT); // two data inputs, we use just one
     pinMode(7,OUTPUT);
     digitalWrite(7,LOW); //GND
     pinMode(4,OUTPUT);
     digitalWrite(4,HIGH); // 5V VCC
     vw_setup(5000);
     vw_set_rx_pin(6);
     vw_rx_start();
     Serial.println("Starting up");

    }

    void loop() {

     if(vw_get_message(buf,&buflen)) {
    for(i=0;i<buflen; i++) {
  Serial.print((char)buf[i]);
    }
     }
    }

It doesn't happen after a certain time or number of messages. I have no clue what could be the problem.

Thanks in advance,
Niklas

Edit: Problem seems solved. Changing bitrate from 5000 to 2000 solved the problem, but I don't actually know why.

body:
Regarding the hardware problem, there are some advices in the comments.
As you wrote, the solution is to reduce the bitrate at 2000 bps.

The remaining question is why the receiver always truncates the message (after a receiving error occurs). The answer is in the definition of the **buflen** parameter of the **vw_get_message** function. The page https://www.pjrc.com/teensy/td_libs_VirtualWire.html says:

> "buflen" should have the array's maximum size upon input, and upon return the number of bytes actually copied is retured.

Therefore, when a transmission error occurs, the buflen variable returns a smaller number to inform you how many characters are received. If you do not reset the buflen variable to VW_MAX_MESSAGE_LEN before calling vw_get_message again, you are telling the library that you expect a smaller number of characters and the function respects that size (thinking that you have a smaller buffer).

In other words, if you want try to receive the full message after a transmission error occured, set the buflen variable to VW_MAX_MESSAGE_LEN before each call of the vw_get_message function.


body:
Those cheap 433 MHz RF modules can not handle a high bitrate. There are many different 433 MHz modules and the more expensive modules might be able to handle perhaps 10 kHz.
Every pulse from the receiver generates an interrupt. That means also the software has to be able to keep up with it.

For a basic Arduino board at 16 MHz (Arduino Uno, Nano, Leonardo, and so on) and the cheap RF modules the sweet spot is around 1 kHz to 2 kHz bps. The 2 kHz is a safe value.

The 433 MHz frequency requires in most countries that only 1/10 of the time a transmission might be active and the VirtualWire/RadioHead has overhead. That means that the resulting data speed with 2 kHz bps will be between 10 and 20 bytes per second.

The transceiver modules don't have all these (ridiculous) limitations. They can transmit data at a fast rate. Transceiver modules are for example nRF24L01+ modules, CC1101 modules, RFM69 modules, and so on.


message:
Is it ok to declare variables inside timer interrupts?

I am building a real time audio application using the Arduino DUE. This application needs big arrays like:

    uint16_t sDelayBuffer0[46000];
The Due has only 96kb of RAM available so this array just ate up most ot its memory.
The problem is i need more arrays like this...

So, i was thinking, instead of declaring all of the arrays as global variables, to declare them inside the timer interrupt functions.

The loop() handles stuff like reading the ADCs. The actual effects are coded inside timer iterrupt funciton that are replayed over and over. So the code constantly loops in loop() and the selected timer interrupt function.

But other timer interrupt fucntions use other arrays. So i was thinking to declare every array that a corresponding timer interrupt function wants inside that fucntion.

So all arrays are not declared at the same time (since when we exit the timer interrupt function we were on and head either to loop or another interrupt function, the grabage collector will destroy the array right?)

The problem with this theory, is that this is a real time audio application. So is it wise to constantly declare a big array like this? Since the timer interrupt ficntion will run very very often. Won't i have delay problems iwth the actual sound? Or variable declarations happen extremely fast inside the CPU, even for big arrays?

body:
First, I don't think it's a good idea to use 46000 * 2 = 92000 bytes of SRAM. That leaves only around 4K left. I hope you don't use a big stack trace, local variables or other global variables.

I don't know if creating an array costs a lot of space, anyway, constantly creating and removing arrays (in heap space) will make your free memory space a mess. This means, that after some time you cannot allocate arrays anymore, especially big ones which need consecutive memory.

Also, within interrupts the code should be as least as possible.

I suggest you use some arrays and reuse them for different reasons. Keep the name simple (like buffer), and reuse the array when needed, without the need to declare it and destroy it. This keeps your memory clear. Make sure the size is big enough for the maximum/worst case you use it for.

Update:

The above mostly assumes that the arrays are made in heap space, not as local variables. However, using local variables is ok.

But anyway, if you need a 2-byte 46000 array, don't expect to be able to use more arrays. In that case use external SRAM (like 23K256, 23LC1024).


body:
> The problem is i need more arrays like this...

you probably want to take a look at your processing flow to see if you need all of them at the same time. if you do, well, there is no alternative but to get a bigger chip.


message:
High Speed Thermocouple Readings

I'm currently attempting to take readings from 10 thermocouples using an Arduino Mega. I've been using [MAX31850 1Wire Thermocouple Modules][1] (with the Adafruit breakout) to perform the readings, but their response time has been very slow (~500ms each). I'm not sure if most of this latency is coming from the IC, or from the communications protocol, or perhaps even the DallasTemperature library.

For my application, I need to be able to read all 10 thermocouples in at most 250 ms (and faster would be better) and so I can afford up to 25ms per thermocouple. I would also like to be measuring with a precision of about 1-2 F.

I assume I will probably have to use a different amplifier, and I've seen recommendations online of using an external ADC to achieve higher speeds, which I would be happy to do, but I don't understand why that would make a substantial difference on speed since the onboard ADC can already sample at about 1/10 ms.

I would greatly appreciate any recommendations on how to achieve these speeds.

  [1]: https://cdn-shop.adafruit.com/datasheets/MAX31850-MAX31851.pdf

body:
1-wire transmission takes ~100us/1bit so 1ms/byte. so unless the adc is that slow, it shouldn't take you anywhere close to 500ms to take 1 reading, even if you factor in the overhead / reset.

there are dedicated chips but as you mentioned putting an amplifier (instrumentation amps for example) isn't that difficult. simpler with chips with built-in PGA + differential adc. My favorite here are some of the AVR chips (ATtiny85 or ATmega32U for example). But lots of Freescale / STM32F3 chips also work, so long as you are willing to dive into their and roll your own. Lots of fun.


body:
From Table 6 on page 22 of the data sheet for [MAX31850 1Wire Thermocouple Modules](https://cdn-shop.adafruit.com/datasheets/MAX31850-MAX31851.pdf), it appears that about 30 bytes of data are sent per reading (5 command bytes, 9 scratchpad data bytes, 2 x 8 module-id bytes).  At an apparent minimum of 60 μs per bit, those 30 bytes will take about 15 ms; at times of say 100 μs per bit, they would take about 24 ms.

Each reading also sends 3 each reset and presence-detect signals, adding up to a few milliseconds, and each reading requires a conversion time *tCONV* of typically 72 ms, per the last entry on page 4 in the *Thermal Characteristics* table.

Thus, it looks like the MAX31850 will take at least 87 ms per reading, if your units are all on the same 1Wire bus and you code things efficiently.  (Single units on a bus can use a slightly simpler protocol, which might reduce communication times to perhaps a third as much, but the typical *tCONV* would still dominate the time per reading.)

You might consider attaching an inexpensive Arduino Nano, Micro, or Mini to each of your MAX31850 units.  Each of those could communicate with its own MAX31850, allowing all the MAX31850s to convert simultaneously.  The small Arduinos could send results to the Mega by I2C or serial, in assigned time slots or upon request from the Mega.


body:
The onboard ADC of the Arduino Mega 2560 is only 10 bits. An external ADC in a thermocouple chip with a fast SPI interface is probably the best solution.
The [Adafruit MAX31855 module][1] seems to be able to do that.

The MAX31855 has a 14 bit ADC and a 5 MHZ SPI interface.
It needs a conversion time of 70ms. I think that is normal for these chips. I did not read the datasheet well enough how to get a value without waiting for it.

  [1]: https://www.adafruit.com/product/269