text:
Unable to parse my JSON Data in Arduino IDE
i want to get my thingSpeak channel data into arduino by performing GET request every things works fine.Further i used Arduinojson lib to parse the JSON but i am getting failed every time when i try to parse it.I used arduinojson assistant to calculate the parsing program but still i am getting error.
Below is my JSON and Failure message that i got every time in serial monitor.
{"channel":{"id":421932,"name":"remote_car","description":"Nothing up to this point !","latitude":"0.0","longitude":"0.0","field1":"MOTOR ONE","field2":"MOTOR TWO","field3":"MOTOR THREE","field4":"MOTOR FOUR","created_at":"2018-02-07T17:32:09Z","updated_at":"2018-03-17T07:08:49Z","last_entry_id":7},"feeds":[{"created_at":"2018-03-17T06:53:48Z","entry_id":4,"field1":"0"},{"created_at":"2018-03-17T06:59:22Z","entry_id":5,"field1":"0"},{"created_at":"2018-03-17T07:03:59Z","entry_id":6,"field1":"2"},{"created_at":"2018-03-17T07:08:49Z","entry_id":7,"field1":"1"}]}

Parse Failed...

this is my arduino code(i used arduino plus esp8266 to get my thinkSpeak channel data).
#include "WiFiEsp.h"
#include <ArduinoJson.h>
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2,3); // RX, TX
#endif
char ssid[] = "M T G";            // your network SSID (name)
char pass[] = "androidGUII";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
// Initialize the Ethernet client object
WiFiEspClient client;
static const char* host = "api.thingspeak.com";
static const char* apiKey = "H359MYV0P0KFG2VS";
const unsigned long HTTP_TIMEOUT = 10000;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }
  // you're connected now, so print out the data
  Serial.println("You're connected to the network");
//  printWifiStatus();
  Serial.println();
}

void loop()
{
      const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }

 client.print("GET /channels/421932/fields/1.json?api_key=");
client.print(apiKey);
client.println("&results=4 HTTP/1.1");
client.print("Host:");
client.println(host);
client.println();
  while (client.available() == 0);
  while (!skipResponseHeaders());  // wait till something comes in; you may want to add a timeout here
while (client.available()) {                         // Now receive the data
    String line = client.readStringUntil('\n');
    if ( line.indexOf('{',0) >= 0 ) {                  // Ignore data that is not likely to be JSON formatted, so must contain a '{'
      Serial.println(line);                            // Show the text received
      parseData(line);
     }
  }
  client.stop();
  delay(10000);
}

void parseData(String data){
     const size_t bufferSize = JSON_ARRAY_SIZE(4) + JSON_OBJECT_SIZE(2) + 4*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(12) + 520;
     DynamicJsonBuffer jsonBuffer(bufferSize);
     const char* json = data.c_str();
     JsonObject& root = jsonBuffer.parseObject(json);
      if(!root.success()){
        Serial.println("Parse Failed...");
      }
     JsonObject& channel = root["channel"];
long channel_id = channel["id"]; // 421932
const char* channel_name = channel["name"]; // "remote_car"
const char* channel_description = channel["description"]; // "Nothing up to this point !"
  Serial.println(channel_name);
  Serial.println(channel_description);
}

bool skipResponseHeaders() {
  char endOfHeaders[] = "\r\n\r\n"; // HTTP headers end with an empty line
  client.setTimeout(HTTP_TIMEOUT);
  bool ok = client.find(endOfHeaders);
  if (!ok) { Serial.println("No response or invalid response!"); }
  return ok;
}

Any one have any idea how i am getting parsing failed message.
Any help would be appreciated.

It is a memory allocation failure. Your Arduino Uno has 2KB ob RAM and I found out, via a binary search on the size of the StaticJsonBuffer<size> object, that for this specific 566 byte long JSON string you need a JSON buffer of at least 785 bytes to parse it.
Use this minimal sketch to test the size:
#include <Arduino.h>
#include <avr/pgmspace.h>
#include <ArduinoJson.h>

#define stringToParse  \
        "{\"channel\":{\"id\":421932,\"name\":\"remote_car\",\"description\":\"Nothing up to this point !\",\"latitude\":\"0.0\",\"longitude\":\"0.0\",\"field1\":\"MOTOR ONE\",\"field2\":\"MOTOR TWO\",\"field3\":\"MOTOR THREE\",\"field4\":\"MOTOR FOUR\",\"created_at\":\"2018-02-07T17:32:09Z\",\"updated_at\":\"2018-03-17T07:08:49Z\",\"last_entry_id\":7},\"feeds\":[{\"created_at\":\"2018-03-17T06:53:48Z\",\"entry_id\":4,\"field1\":\"0\"},{\"created_at\":\"2018-03-17T06:59:22Z\",\"entry_id\":5,\"field1\":\"0\"},{\"created_at\":\"2018-03-17T07:03:59Z\",\"entry_id\":6,\"field1\":\"2\"},{\"created_at\":\"2018-03-17T07:08:49Z\",\"entry_id\":7,\"field1\":\"1\"}]}"

StaticJsonBuffer<785> jsonBuffer;
void parseData(const __FlashStringHelper* json){
    //const size_t bufferSize = JSON_ARRAY_SIZE(4) + JSON_OBJECT_SIZE(2) + 4*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(12) + 520;
    //DynamicJsonBuffer jsonBuffer(bufferSize);
    //const char* json = data.c_str();
    JsonObject& root = jsonBuffer.parseObject(json);
    if(!root.success()){
        Serial.println("Parse Failed...");
        return;
    }
    JsonObject& channel = root["channel"];
    long channel_id = channel["id"]; // 421932
    const char* channel_name = channel["name"]; // "remote_car"
    const char* channel_description = channel["description"]; // "Nothing up to this point !"
    Serial.print("Channel name: "); Serial.println(channel_name);
    Serial.print("Channel description: "); Serial.println(channel_description);
    Serial.print("Channel id: ");
    Serial.println(channel_id);
}

void setup() {
    Serial.begin(9600);
    //We use the F() macro to create a flash string helper
    //this way, that huge JSON string is held in FLASH and not in precious RAM..
    parseData(F(stringToParse));
}

void loop() { }

If you decrease the buffer size by even 1 byte, parsing will fail.
Since you are using a DynamicJsonBuffer initially, your memory allocation will surely fail, since the heap can be really fragmented due to your other libraries (WiFiEspClient) and you are not able to find a continous 785 byte fragment on the heap. If the libraries tries to allocate memory object-wise (that is, not a continious segment), you might still get an out-of-memory error because

the heap induces overhead per allocated object because of house-keeping information
you fragment your heap over time, essentially leaving holes in it; this causes big allocations to fail because no continous segment could be found, although maybe in sum there is enough memory free
other libraries / part of your program is also using the heap and you are actually out-of-memory no matter what your allocation strategy is

You have various options:

decrease the length of JSON string received by the Uno for it to be able to parse it.

For example, instead of huge JSON string have it receive a binary-formatted message with the information being as compactly packet in there as possible. You don't need to send "id\":421932, instead just make a field "id" in your packet format for a 32-bit integer. That decreases it from 11 bytes to 4 bytes.

use StaticJsonBuffer with fixed maximum size instead of DynamicJsonBuffer to make sure you can always parse the longest message (that is, if you have enough RAM free)
program the ESP8266 directly.

Really, your ESP8266 has about ~40KByte of user-usable RAM at startup and is at least an order of magnitude more powerful than your Uno. I wouldn't bother strapping a Arduino Uno to a mighty ESP8266 just for it to do JSON parsing.
Depending on what ESP8266 you have (ESP8266-01, ESP12F, NodeMCU board, ..) you should start looking for tutorials for programming it using the Arduino-ESP8266 framework.

Hi sir thank you for your precious time...i modified the code according to your instruction but but now i am getting this..strange info...

Con¬B
Parse Failed.

Does the above sketch work on its own? Edit your question to include the full code and runtime error.

the above code works fine when use stand alone but when i modified it for my own purpose then it throws the above error...my main goal is to received the json from thingspeak and then parse it...

you can look up into my main arduino code sir.

That is your old code before updating .You have modified it, so please edit to include the new version

this is my modified code sir..it shows half JSOn..when i increased the buffer size its hows memory overflow.    http://textuploader.com/dg625!

Did you check the link sir.

Instead of doing parseData(totalR); do parseData(line.c_str()); and change function signature to parseData(const char* json) @mtg

again i received parsed failed sir in serial monitor

this is my updated code sir. http://textuploader.com/dgjtg!

@mtg move the line StaticJsonBuffer<787> jsonBuffer; outside the function as a global variable. Maybe increase buffer size even further.

Global variables use 2520 bytes (123%) of dynamic memory, leaving -472 bytes for local variables. Maximum is 2048 bytes.    by increasing the memory of static Json buffer and placing it as a global variable

Then you're officially out of memory on your Uno.

So what i have to do next sir.

You have still 2 options left from above.


text:
Advice needed, commercializing an Arduino Due project
We have a project using an Arduino Due, and we are looking to commercialize the project. How would one typically proceed? Would you use the Arduino Due inside the project? This seems very amateur.
Using another Arduino is not an option due to the number of interrupts, number of pins, and processing power required.
Thanks!

What kind of project?

Depends on the kind of project you are doing. If the Due is just minor part (say you are producind 3D printer) and you plan to do like tens of the devices, I would consider using it, but probably would solder it in for good contact reliability. Maybe put it inside a box too, so nothing can short anything on the board. (And then the Due is not in plain sight).
If it is mainly Due with some sensors around and you want to sell thousands of them, then I would make extra PCB for it, containing everything what is possible on one board. (Like @Majenko suggested.)
Anyway I made a lot of PCB in my kitchen (yes, literally) for my "Arduino" projects, even when I made only 1 or 2 devices just for me. Every of them worked just fine. It is not so dificult to do if you are not pushing some limits too hard. Even Due small chip can be soldered by hands and with some basic tools on your eating table.
But if you lack the skills, hiring contractor (or found company, which does that) may be cheaper in terms of your time and number of devices destroyed before getting the skill and customers complaining about devices broken after short time use.

There's two routes you can take.
First route:

Get the Due schematics.
Remove the parts you don't need.
Add to it the new components for your product.
Lay out the PCB design.
Get the PCB manufactured.
Solder all the components on.
Test it and go back to step 2/3 as required.

Second route:

Hire a contractor that knows the SAM3X and can do it all for you.

source: Stack Exchange

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

authors: Орлов Александр

sort: votes


text:
Serial LCD has like a "rolling shutter"
I've attached my LCD Display (AV1624YRB-SJ) to my Arduino Nano on the following pins:
#define LCD_RS 7
#define LCD_ENABLE 8
#define LCD_D4 9
#define LCD_D5 10
#define LCD_D6 11
#define LCD_D7 12
#define LCD_CONTRAST 6 //PWM Wave with capacitor for contrast

and im initializing it this way:
LiquidCrystal lcd(LCD_RS, LCD_ENABLE, LCD_D4, LCD_D5, LCD_D6, LCD_D7);

byte arrow[8] = {
    B00000, B00100, B00010, B11111, B00010, B00100, B00000,
};

void setup() {
  pinMode(LCD_CONTRAST, OUTPUT);
  pinMode(LCD_D4, OUTPUT);
  pinMode(LCD_D5, OUTPUT);
  pinMode(LCD_D6, OUTPUT);
  pinMode(LCD_D7, OUTPUT);
  analogWrite(LCD_CONTRAST, STARTCONTRAST); // Set LCD Contrast

  lcd.begin(16, 2);
  lcd.createChar(CHAR_ARROW, arrow);
  lcd.setCursor(3, 0);
  lcd.print("Welcome To");
  lcd.setCursor(1, 1);
  lcd.print("My Test");
  delay(2000);
}

The Problem is, that there is nothing to see on the display.
If i crank up the contrast slightly you can see something like a rolling shutter effect.
http://i.imgur.com/FOIEwVj.gif
The display worked just fine 3 days ago.
Where could be a mistake. I don't remember changing something, but i tried rewiring.

Your method of handling the contrast is unusual. Normal is a potentiometer as in this diagram http://codb.coocox.org/component/doc/coocox-master/1602IIC/bef8ac476249c994b8ac544091c7f424a33c0796/index.html

The Potentiometer just produces a given voltage. PWM plus Lowpassfilter equals a voltage too. This way i can adjust the contrast digitally.

I'd temporarily replace it with a pot to rule out that this is the problem. Also, try pressing down on the black border of the LCD. It could be a connection problem between the glass and the pcb of the display.

As I noted in a comment to the question  Arduino LCD is displaying gibberish, sometimes,  a PWM's sharp-cornered waveform might introduce a lot of noise into the LCD.  If you have to use PWM, you probably should put a good low-pass filter between PWM and LCD pin 3.
Check whether using a fixed voltage (from a voltage divider or pot) fixes the problem.  That fixed the problem in the case of the linked question.
If you need programmable control of contrast, and can't get PWM to work without heroic measures involving op-amp based filters, you could use a digital pot or a DAC.

The contrast works pretty fine. As stated my Display used to work and with an Encoder i could set the contrast digitally.
PS: I've added some imformation

If this is set up on a breadboard, maybe one of the wires is loose; try reinserting them.

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


text:
Using rotary encoders with pin change interrupts
I'm using an Arduino Uno and two (3-pin) rotary encoders for a project. Since the loop takes a bit long and accuracy is important, I'd like to use interrupts to read the values from the rotary encoders. Also, pins 2 and 3 are occupied so I can't use hardware interrupts.
I'm using the Rotary library (github link) for the rotary encoders and the EnableInterrupt library (github link) for external interrupts. The Rotary library includes an interrupt example, but I couldn't manage to modify it to work with pin change interrupts. This is my current state (test code):
#include <EnableInterrupt.h>
#include <Rotary.h>

Rotary r = Rotary(2, 3);

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

  /* Original interrupt setup:
  PCICR |= (1 << PCIE2);
  PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
  sei();
  */

  enableInterrupt(2, interruptFunction, CHANGE);
  enableInterrupt(3, interruptFunction, CHANGE);
}

void loop() {

}

void interruptFunction() {

  Serial.println("Int. called");

  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }
}

Everytime I turn the encoder for one step, the interruptFunction gets called a bunch of times (about 2~4) but the r.process() call never returns a value.
My current guess is that this has something to do with the rotary encoder outputting gray code, but I'm not quite sure how my approach differs from the Rotary interrupt example using hardware interrupts.
Hope you can help!

Avoid Serial in an ISR. Check the online documentation.

I'm aware of that, i just used the provided (and working) example as a base to eliminate possible sources of failure. I will of course change it for my production code.

The function process() of the Rotary Library is not a blocking function and only read the state of the 2 pins and compute an output. How you can say "but the r.process() call never returns a value." ?

Code Correction 7th October - Tidy code as per comments
Code Correction 7th October - proper reading of rotary encoder
Uses the Pin Change interrupts to allow increment and decrement of the 2 rotary encoders within an interrupt service routine using arduino (in my case nano) with ATMEGA328P chip. Need to add 2 x 104 (0.1uF caps) at the rotary encoder between each pin and the centre ground pin to stop the debounce, doesnt work without the capacitors added. Does not need any library. Watched the Tutorial: Pin Change Interrupts on the Arduino by makecourse which helped understand the Pin change interrupts, will help to watch this if have a different version of arduino so know what digital pins relate to what interrupts.
          //*******************************************  rotary encoder ************************************************************
          #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))    //shortcut way to clear a bit in a register
          #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))     //shortcut way to set a bit in a register

          #define Encoder1pin 3 //corresponds to PCINT19
          #define Encoder2pin 4 //corresponds to PCINT20
          #define Encoder3pin 5 //corresponds to PCINT21
          #define Encoder4pin 6 //corresponds to PCINT22
          #define Encoder5pin 7 //corresponds to PCINT23

          unsigned long encoderPos1 = 100;
          unsigned long oldEncPos1 = 0;
          unsigned long encoderPos2 = 100; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
          unsigned long oldEncPos2 = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)

          volatile byte portDstatus;

          volatile bool readingEncoder1pin = 0;
          volatile bool readingEncoder2pin = 0;
          volatile bool readingEncoder3pin = 0;
          volatile bool readingEncoder4pin = 0;
          volatile bool lastreadingEncoder1pin = 0;
          volatile bool lastreadingEncoder2pin = 0;
          volatile bool lastreadingEncoder3pin = 0;
          volatile bool lastreadingEncoder4pin = 0;

          void setup() {

            Serial.begin(9600);

          //*************************************************** rotary encoder ******************************************************************************
            pinMode(Encoder1pin, INPUT);//define pin as INPUT
            digitalWrite(Encoder1pin, HIGH);//connect the internal pull-up resistor - this will yield a HIGH readout if the switch is open.
            pinMode(Encoder2pin, INPUT);
            digitalWrite(Encoder2pin, HIGH);
            pinMode(Encoder3pin, INPUT);
            digitalWrite(Encoder3pin, HIGH);
            pinMode(Encoder4pin, INPUT);
            digitalWrite(Encoder4pin, HIGH);
            pinMode(Encoder5pin, INPUT);
            digitalWrite(Encoder5pin, HIGH);

            //setting up the interrupt pins:   //I needed to set all of these otherwise the serial monitor does not read the byte correctly -
                                               // and it doesnt work.

            sbi (PCICR, PCIE2); // enable interrupt PCI2);
            sbi (PCMSK2,PCINT23); // set the interrupt control bits for pins 7-3. These bits control whether the pins can trigger the interrupt or not.
            sbi (PCMSK2, PCINT22);
            sbi (PCMSK2, PCINT21);
            sbi (PCMSK2, PCINT20);
            sbi (PCMSK2, PCINT19); // we do not want to set interrupt control for pins 0 or 1 since this is serial reading .

          //******************************************************************* LED *********************************************************************
          }

          void loop()

              {
               }

          ISR(PCINT2_vect) // Interrupt Service Routine. This code is executed when a state change occurs on a pin
          {

                portDstatus=PIND;
               readingEncoder1pin = bitRead(portDstatus,3);
               readingEncoder2pin = bitRead(portDstatus,4);
             if(lastreadingEncoder1pin == 1 && lastreadingEncoder2pin == 0 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
              {
                  encoderPos1 ++;
                   lastreadingEncoder1pin = readingEncoder1pin;
                   lastreadingEncoder2pin = readingEncoder2pin;
              }

              else if(lastreadingEncoder1pin == 0 && lastreadingEncoder2pin == 1 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
              {
                encoderPos1 --;
                  lastreadingEncoder1pin = readingEncoder1pin;
                  lastreadingEncoder2pin = readingEncoder2pin;;
              }
              else
                {
                   lastreadingEncoder1pin = readingEncoder1pin;
                   lastreadingEncoder2pin = readingEncoder2pin;
                }

    //  reading the second encoder:

               readingEncoder3pin = bitRead(portDstatus,5);
               readingEncoder4pin = bitRead(portDstatus,6);

             if(lastreadingEncoder3pin == 1 && lastreadingEncoder4pin == 0 && readingEncoder3pin == 1 && readingEncoder4pin == 1)
              {

                  encoderPos2 ++;
                   lastreadingEncoder3pin = readingEncoder3pin;
                   lastreadingEncoder4pin = readingEncoder4pin;
              }

              else if(lastreadingEncoder3pin == 0 && lastreadingEncoder4pin == 1  && readingEncoder3pin == 1 && readingEncoder4pin == 1)
              {
                encoderPos2 --;
                  lastreadingEncoder3pin = readingEncoder3pin;
                  lastreadingEncoder4pin = readingEncoder4pin;;
              }
              else
                {

                   lastreadingEncoder3pin = readingEncoder3pin;
                   lastreadingEncoder4pin = readingEncoder4pin;
                }
             // serial print for testing only then remove from ISR
          Serial.print(encoderPos1);
          Serial.println(encoderPos2);

             }

This code has a few issues: 1. portDstatus is set but never used. For consistency, it would be better to read PIND only once, then get the individual pin readings out of portDstatus. 2. lastportDstatus is never set nor used. 3. encoderPos and oldEncPos may overflow, they should thus be unsigned in order to avoid undefined behavior. 4. (last)readingEncoder[12]pin need not be long, byte should suffice. 5. Only encoderPos needs to be volatile, assuming it is going to be used in loop().

(continued...) 6. The pull-ups can be enabled with pinMode(pin, INPUT_PULLUP);, which is clearer that using digitalWrite(). 7. There is no point in enabling PCINT on pins 5, 6 and 7 if the encoder is only connected to pins 3 and 4. 8. The decoding logic looks flawed, e.g. lastreadingEncoder1pin should not be set to zero unless the last reading of the encoder 1 pin was indeed zero. 9. Using Serial.println() within an ISR is asking for trouble.

You have fixed issues 1–4. Great! Still a small issue with the encoder logic: 8′. If the encoder oscillates between readingEncoder(1,2)pin = (1,0) and (1,1), the position will continually increment. And it will decrement if it oscillates as (0,1) ↔ (1,1). This can be fixed by decrementing on (1,1) → (1,0) instead of (0,1) → (1,1). And then: 7′. Only PCINT{20,22} need to be enabled, which would avoid superfluous interrupts.

check the library to see if it debounces the input.
if not, write your own code. usually state machine-based approaches are very resistant to switch bounces.

I too had this problem. I chased my tail in SW for hours. I was making the ISRs non-reentrant (assumed they accidentally were), I was doing SW debouncing etc. I even looked at the signal on a scope but did not see any significant bounces.
I eventually added 0.1uF capacitors to the inputs and that solved all my problems with the ISR.
So don't trust the encoder manufacturers, there WILL be signal bounce and your Arduino WILL detect it and throw multiple interrupts.
Good luck with your project!
LDP

I too had this problem. it isn't fair to blame a coding issue on this topology. But your point about the beauty of hardware debouncing is still valid, and often ignored by newbies wanting to bet their lives on software debouncing.

Everytime I turn the encoder for one step, the interruptFunction gets
  called a bunch of times (about 2~4)

This is due to contact bounces. You should either implement a hardware debouncing circuit (a simple R-C filter could be enough. Do not connect instead large capacitors directly in parallel to your contacts, as when the contact closes, the energy stored on the capacitor will damage over time the contacts. Using large capacitances on an input can also lead to problems when power is removed), or better a good software debouncing strategy.
For instance, when the interrupt is called the first time, disable the pin-change interrupts. Then set up a timer, which will trigger an interrupt when it expires (the time should be larger than the bounce time, usually several ms or more). Then in the timer interrupt, first put your code:
  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }

end re-enable the pin-change interrupts.
  enableInterrupt(2, interruptFunction, CHANGE);
  enableInterrupt(3, interruptFunction, CHANGE);

but the r.process() call never returns a value.

r.process() will ALWAYS returns a value. Maybe you did mean that it returns DIR_NONE ?

The correct solution is to use a debouncing circuit. The MC14490 is a hex debouncing circuit and is perfect for this type of application. No need to block interrupts or set timers. It's available as either SMD or thru hole.

That's not a bad device... except that the SMD version is expensive (~US$11) and the through-hole version is no longer manufactured. There are other, cheaper, smaller, simpler, practical ways of debouncing contacts.

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


text:
Arduino-IDE "while (!Serial)"
I have a Question regarding Arduino IDE:
Many old Arduino setup examples states that the Serial.begin() function always should begin with :
Serial.begin(9600); // (or 115200)

while (!Serial)
 {
   ; // Wait for serial to connect
 }

Now I have read a lot of comments saying that this "Wait-function" is no longer necessary ??
Is this an old routine, that's no longer necessary, or is it still important ???

That function is not obsolete. However, there is gratuitous use of it where it's not really needed.
The usage of the function that you alude to grew from the desire to make ATMega32U4-based boards (such as the Leonardo) which have a native USB interface act similar to the ATMega328P etc boards.
When you open the serial port on an Uno, for example, the main MCU is reset and the sketch runs from the start.  When you do the same on a Leonardo that doesn't happen. So by adding that code snippet to the beginning the sketch is paused until the serial port is opened.  This makes it appear that the board has been reset and the sketch is running afresh, like an Uno - but it isn't.
Placing that while loop at the start of your sketch without thinking about the consequences means that your sketch may never run. If a serial connection is required for your program then that's not such a problem. However, if all you're using the serial for is debugging, then as soon as you try and use your sketch without the computer opening the serial port it will fail.
So I would recommend not using that while loop unless you know that you want the effects that it provides.  That is, stalling the sketch until the serial port is opened by the computer.

This is for the Arduino boards that have native USB to ensure that the serial port is ready before progressing. The while loop is not needed for Arduino boards where the USB is not native to the processor (such as the Arduino Uno).

Indicates if the specified Serial port is ready.
On the boards with native USB, if (Serial) (or if(SerialUSB) on the Due) indicates whether or not the USB CDC serial connection is open. For all other boards, and the non-USB CDC ports, this will always return true.
Ref: Arduino Reference > communication > serial > if(serial)

How  about Wemos D1 Mini and Wemos D32 Pro ?? Is it the same as for Arduino Uno ??

yeah, it's only "needed" for a few less-common ardunio boards. every ESP board should be fine without.

Microcontrolers with native USB interface create an USB connection. It takes a little time. The serial prints right after begin() would be lost without waiting or the connection.
For Uno, Mega, Nano, esp8266/32 boards and other boards with a MCU without native USB support, an external USB-to-TTL-Serial converter chip handles the USB connection.
Leonardo, Micro, MKR have an MCU with built-in USB port. Some boards with Zero or M0 in name have only the native USB port, some have a debugger chip which can serve as USB-to-TTL-Serial converter too.
!Serial is a C++ construct using bool() operator. Then implementation is a function which checks if the USB connection is ready.
The waiting for native USB Serial (called SerialUSB for some boards) is used in examples to see the debug prints from setup(). But if USB is not connected, it waits and the sketch doesn't continue. It can be very confusing. So I rather use a delay(500) after Serial.begin() on boards with native USB.

You could explain some more. What if a Leonardo has that code but then is used with a power supply without usb connector.

I am working on it :-)

I have a timeout of one minute in my Leonardo and then the code continues, Serial or not.

I'm still chuckling about your Majenko comment @Juraj.  :-)

"!Serial" works due to overloading of operator "!" (logical not), not bool()

@iPathツ, what is the parameter of this overloaded operator? Where in class of Serial do you see ! overloaded?

@Juraj you're right. I haven't looked at the source code.

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


text:
strcmp doesn't seem to work
I'm trying to compare a char array that I'm assembling to a string and I'm having trouble comparing the strings.
I'm getting the data for the char array as a set of bytes and I'm compiling it into a char array like this:
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  char buffer[length];
  for (int i = 0; i < length; i++)
  {
    buffer[i] = (char)payload[i];
  }

So grabbing each of the ASCII codes and converting it into a character as I add it to the buffer.
After I do that I'm trying to print the buffer to the monitor and then compare it to a string. Though it's not working:

I know I'm getting all of those extra characters in the println b/c the buffer doesn't end in 0 so print keeps reading out memory bytes till it hits the zero, but I don't know why strcmp isn't showing the buffer matching the string "ravenclaw".
I'm sure it's for the same "missing the null terminator" issue, but I'm not sure how to fix it. Help is appreciated!!

Either I don't understand your question or you're on the verge of answering it yourself.

It would be better if you put the code into your question as text, not a as a screen capture.

You seem to already understand that it's not null-terminated and that's why it's not working the way you expect.  So, I'll take a different tact for "how to fix it".
You can simply not treat the payload as a string, and instead use memcmp, as in:
if (length == 9 && memcmp(payload, "ravenclaw", 9) == 0) {

memcmp behaves similarly to strcmp, except that it isn't looking for a null terminator. It just compares however many bytes (chars) you specify.  In practice you may want to use a variable to hold "ravenclaw" and to strlen() on it rather than specifying the length separately as I've done above, e.g.:
static const char ravenclaw[] = "ravenclaw";
static const size_t ravenclaw_len = sizeof ravenclaw - 1;
if (length == ravenclaw_len && memcmp(payload, ravenclaw, ravenclaw_len) == 0) {

or any number of variations on that which might use strlen(), or a pointer rather than array (if not using sizeof) or PROGMEM with strlen_P() and memcmp_P() or... etc, etc, possibly putting this into a function so you can reuse it.

As a side note, if you know payload contains non-null-terminated text that you want to print, you can use the overload of write() that allows you to specify the length.
Serial.write(payload, length);

Ah awesome, thanks for the extra detail. I wasn't aware of memcmp. That def seems like a better way of doing the comparison.

The easier way to simply the code is to use strcpy to create a buffer that is 1 byte longer than the length and then terminate it with \0.
void messageHandler(char *topic, byte *payload, unsigned int length) {
  char buffer[length+1];
  strcpy(buffer, (const char*) payload);
  buffer[length] = '\0';

  Serial.println(buffer);

  int matched = strcmp(buffer, "ravenclaw");
}

oh nice! I like this take on it. TBH I thought I tried this at one point and it didn't work, though I was noodling a lot at the time so I may have jacked up my code. thanks for the tip!

Ah, the snag in this one is that after casting to a const char pointer you can't add anything to it. You end up with a invalid conversion from 'const char*' to 'char',  buffer[length] = "\0" error.

@ChrisSchmitz, what you seem to have missed is that in their code they used '\0' rather than "\0", single rather than double quote.  The terminator is a single character being written into a single character of an array of characters.  It should compile any Arduino using g++, which is to say all of them that I know of; the run-time-sized local array is making use of a g++ extension.

@ChrisSchmitz However, if you want to try this way of doing it, you need to swap out the strcpy() line  and replace it with memcpy(buffer, payload, length);  Otherwise the strcpy may overflow buffer, because the payload is, again, not terminated.  So there's nothing to tell strcpy to stop, except the next '\0' it finds in memory following payload.


text:
Adafruit_Arcada' does not name a type;
I am trying to program an adafruit pygamer (which says it's compatible with Arduino). I have added the ZIP folder for the library into the library folder om my PC where all of my folders are supposed to be stored, one thing I managed to find out for a start was that the library folder for the library itself that was installed from GitHub contained a dash in the filename so I replaced that for an underscore. The actual error message that seems to come up now is this:
'Adafruit_Arcada' does not name a type; did you mean 'Adafruit_SPITFT'?

This error comes up from when I try to use the:
#include "Adafruit_Arcada.h"

Adafruit_Arcada arcada;

lines
Within the library folder that I want to try and use there are the code examples within the library folder inside the examples sub-folder
I have tried following a step by step guide into one potential way of trying to solve this problem by looking at a tutorial by adafruit on how to step by step install zip folder libraries. Something tells me though that this error that I am getting is to do with one of the .h or .cpp files within the library itself.
The link for the library itself is here: https://github.com/adafruit/Adafruit_Arcada
In addition, when I look in the Adafruit_Arcada.h file I can actually see that there is no Adafruit_Arcada class but there is an Adafruit_SPITFT one. I know this point might seem like a bit of a no-brainer but I just thought it would be useful to try and find out what could potentially be going on and provide evidence of what I have already tried to do.
When I changed the Adafruit_Arcada arcada; to Adafruit_SPITFT arcada; (thinking this could potentially resolve the issue because within the Adafruit_Arcada.h file there is a class called Adafruit_SPITFT and notAdafruit_Arcada`), this brought up another error which was the following:
simpletest:2:17: error: no matching function for call to 'Adafruit_SPITFT::Adafruit_SPITFT()'

The Adafruit_Arcada class is defined in Boards/Adafruit_Arcada_PyGamer.h and inherits from the Adafruit_Arcada_SPITFT class. I guess there are specific versions of the class for each board.

@chrisl So what classes would I need to mention within my code in order for it to work?

There are some instructions at:
Pygamer setup
That need to be followed in order to permit the Arduino IDE to work with the Pygamer.  It's not clear that you have followed any or all of these instructions.
I recommend that you carefully follow ALL the steps and then start with the simple example to test that you are building and uploading properly.
Then move on to the Adafruit example that uses the Arcada library.

So what I have done is followed all of the instructions in the link sent and the board not has its own serial COM port and does work with a very basic blink example program which does not include any libraries at all. the error to do with Adafruit_Arcada' does not name a type;. The next problem occuring is that now another error message is coming up within the code which I am not too sure it is trying to say:

Arduino\libraries\Adafruit_EPD\src\Adafruit_EPD.cpp: In member function 'void Adafruit_EPD::csHigh()':
and                                                        libraries\Adafruit_EPD\src\Adafruit_EPD.cpp:649:12: error: 'class Adafruit_SPIDevice' has no member named 'endTransaction'.

Something is telling me that something is either out of date or I might have potentially installed something wrong because in the guide that was sent there is 5 examples within the adafruit arcada library. But with the one I have installed, there is lots of examples. The guide itself was not updated too long ago. The arcada library I have installed is the one installed from the library manger and the version of the library is 2.5.0. Perhaps the library is too update to date compared to the one in the guide which potentially might be more out of date.


text:
How to get different parsed JSON data?
In my recent project, I have to parse incoming JSON data in Arduino and I successfully did it. But it is only for one constant data string.
For example, if my incoming JSON string like:
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

And Arduino code for parsing this data is below:
#include <LiquidCrystal.h>
#include <ArduinoJson.h>

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

String response = "";
bool begin = false;

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

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  while(Serial.available() || !begin) {
    char in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      response += (in);
    }
    if(in == '}') {
        break;
    }
    delay(1);
  }
  JsonObject& root = jsonBuffer.parseObject(response);
  String TPS = root["TPS"];
  String MAP = root["MAP"];
  String LOAD = root["LOAD"];
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print(MAP);
  lcd.setCursor(0, 1);
  lcd.print(LOAD);
}

Then the output looks like:
TPS  : 0.40
MAP  : 0.95
LOAD : 14

That's fine, but when the incoming JSON string changes, what should I do?
Suppose the incoming JSON string looks like:
{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

Because I have to handle both incoming JSON strings, I can't replace any part like:
  String LOAD = root["LOAD"];
  String RPM = root["RPM"];
  String INJECTION_TIME = root["INJECTION_TIME"];
  lcd.setCursor(0, 0);
  lcd.print(LOAD);
  lcd.setCursor(8, 0);
  lcd.print(RPM);
  lcd.setCursor(0, 1);
  lcd.print(INJECTION_TIME);

Instead of
  String TPS = root["TPS"];
  String MAP = root["MAP"];
  String LOAD = root["LOAD"];
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print(MAP);
  lcd.setCursor(0, 1);
  lcd.print(LOAD);

Any reason you don't just jsonBuffer.parse(Serial)?

@EdgarBonet Means? I can't understand what you mean? Is this catch Serial data and parse it? Something like that?

My question is: Why did you choose to not use jsonBuffer.parse(Serial)?

@EdgarBonet Actually, I have no idea about this sentence. This is the first time I see something like this means to use "Serial" directly and we can parse incoming string or data.

What kind of JSON do you expect to receive? Always an object with 3 key-value pairs of type string, but unknown key names?

@gre_gor As I mentioned above means an object with 3 key-value pairs of type string. There is no key name.

Finally got the solution. I'm using the extra key name.
So, my modified serial data string now looks like:
{"ActionOne":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}
{"ActionTwo":"TWO","LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

and so now using containsKey() function, just check which one is coming. If ActionOne is coming then according to that serial data we got. And If ActionTwo is coming then according to that serial data we got.
#include <LiquidCrystal.h>
#include <ArduinoJson.h>

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

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

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

void loop() {
  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);

  const char* ActionOne = root["ActionOne"];
  const char* ActionTwo = root["ActionTwo"];

  if(root.containsKey("ActionOne"))
  {
    float TPS = root["TPS"];
    float MAP = root["MAP"];
    int LOAD = root["LOAD"];

    lcd.setCursor(0, 0);
    lcd.print(TPS);

    lcd.setCursor(8, 0);
    lcd.print(MAP);

    lcd.setCursor(0, 1);
    lcd.print(LOAD);
  }

  if(root.containsKey("ActionTwo"))
  {
    float LOAD = root["LOAD"];
    int RPM = root["RPM"];
    float INJECTION_TIME = root["INJECTION_TIME"];

    lcd.setCursor(0, 0);
    lcd.print(LOAD);

    lcd.setCursor(8, 0);
    lcd.print(RPM);

    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME);
  }
}

If you want to read 3 values of a object that you don't know the names of the key, you can use an iterator as shown in the ArduinoJson library's docs.
And as already mentioned in the comments, you can also replace all the serial reading code with just Serial passed into the jsonBuffer.parseObject function.
#include <LiquidCrystal.h>
#include <ArduinoJson.h>

const struct LCDPos {
  uint8_t x;
  uint8_t y;
} lcd_pos[] = {
  {0, 0},
  {8, 0},
  {0, 1},
};

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

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

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(Serial);
  if (root == JsonObject::invalid())
    return;

  uint8_t i = 0;
  for (JsonObject::iterator it = root.begin(); it != root.end() && i<(sizeof(lcd_pos)/sizeof(lcd_pos[0])); ++it, i++)
  {
    lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
    lcd.print(it->value.asString());
  }
}

You will need to make sure, that the values are sent in the order that you want them on your LCD.
EDIT:
I don't have an LCD screen, so I didn't test the code with an LCD, but the code that just dumps the parsed data back to serial works.
//#include <LiquidCrystal.h>
#include <ArduinoJson.h>

const struct LCDPos {
  uint8_t x;
  uint8_t y;
} lcd_pos[] = {
  {0, 0},
  {8, 0},
  {0, 1},
};

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

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

void loop() {
  StaticJsonBuffer<100> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(Serial);
  if (root == JsonObject::invalid())
    return;

  Serial.println("JSON received");
  uint8_t i = 0;
  for (JsonObject::iterator it = root.begin(); it != root.end() && i < (sizeof(lcd_pos) / sizeof(lcd_pos[0])); ++it, i++)
  {
    //lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
    //lcd.print(it->value.asString());
    Serial.print(i);
    Serial.print(':');
    Serial.print(lcd_pos[i].x);
    Serial.print(',');
    Serial.print(lcd_pos[i].y);
    Serial.print(' ');
    Serial.println(it->value.asString());
  }
  Serial.println();
}

If I send
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

over the serial, it returns
JSON received
0:0,0 0.40
1:8,0 0.95
2:0,1 14

JSON received
0:0,0 2.40
1:8,0 4200
2:0,1 4.87

I tried out your code, but nothing is displaying on LCD.

I don't have an LCD, so I don't know why the LCD doesn't work, but the JSON parsing works.


text:
About Arrays in Arduino
I have a question about arrays in Arduino. Sorry for my bad English.
I want to put numbers in an array, and I think the code below works properly.
However, it doesn't work and corrupted numbers show up in the Serial monitor. Even delay(1000) doesn't work.
If I change ND_MAC[i]=128; to "ND_MAC[i]=126;", it works properly. So I'm wondering if this array is char type, but I designate int to array.
How to solve it?
int ND_MAC[7];
char i=0;
void setup() {
  Serial.begin(9600);
}
void loop() {
  for(i=0;i<8;i++){
    ND_MAC[i]=128;
    Serial.print(ND_MAC[i],HEX);
  }
  Serial.println();
  delay(1000);
}

First error is iterating outside the array. ND_MAC has 7 elements (0..6).

For an array of size 7, the indexes start from 0 (ND_MAC[0]) and end at 6 (ND_MAC[6]) as @MikaelPatel commented.
So the solution to your issue would be changing the condition in for loop to
for(i=0;i<7;i++) //Changed 8 in your code to 7

Here, the loop iterates from i = 0 to 1 < 7 (i.e., till 6)
and it should work. :)

Oh,I had a terrible mistake...

Oh,I had a terrible mistake... I followed your help, and then it worked properly. thank you very much!

@kishida you're welcome....


text:
Arduino pins LCD and motor controller
I am using an L298N motor control. I want to use my 2*16 LCD. Can I use the code like this?
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(12, 9, 4, 5, 6, 7);

// Motor Control
#define enableA  3
#define enableB  11
#define in1 4
#define in2 5
#define in3 6
#define in4 7

You can not use pins that are used by the LCD for your motors, you have to use other pins.

No, you can't use that pins for both. Use other pins.

You cannot use the pins for distinct purposes at the same time, however as you have the enable pins to the motor drivers wired up, you may be able to communicate with the LCD with the motors disabled, and then drive around while not communicating with the LCD (and making sure not to activate its strobe).

Using that pin configuration you'll have several problems despite you'll use enable pin.
I would use a I2C module for 16x2 lcd like this https://www.amazon.com/SainSmart-Serial-Module-Display-Arduino/dp/B00813HBEQ
Control 16x2 lcd with I2C.

You cannot use same pins for LCD and motor. Data transfer through pins 4,5,6,7(being data pins for LCD) will effect your motor state. You should use different pins and if you does not have sufficient digital pins so you can use analog pins as digital pins (0-LOW,255-HIGH).

What's the 0-LOW 255-HIGH part about?  Surely you are talking about the analog inputs that can also be used as digital pins.  The analog outputs are already all on digital pins.  With the analog pins you'd use pinMode and digitalWrite(pin, LOW) or digitalWrite(pin, HIGH) just like with any other digital pin.

You can use the same pins for both the motor and the LCD.
A condition is that the enable pin decides when the LCD or the motor is accepting inputs from the data pins. This is a normal bus configuration, several devices share data pins and have a enable pin to tell the device when they owns the data bus.


text:
Can't stop my variable value at zero?
In my recent project, I want to set my time according to the requirement. And somehow I'm able to manage that. But when I'm decreasing my time value then one weird problem happens. When decreasing my time value, when I reach ZERO (0) and when I again decrease value then it shows the maximum range of that data type even if I put the condition for stop value at ZERO(0).
My code is below:
const int kPinSw1 = 2;
const int kPinSw2 = 3;

int plusBtnIncState = 0;
int lastPlusBtnIncState = 0;

int minusBtnDecState = 0;
int lastMinusBtnDecState = 0;

unsigned long currentMillis;
unsigned long previousMillis;
unsigned long interval = 0UL;

void setup() {
  Serial.begin(9600);
  pinMode(kPinSw1, INPUT_PULLUP);
  pinMode(kPinSw2, INPUT_PULLUP);
}

void loop() {
  //---------------INC_TIMER---------------//
  plusBtnIncState = digitalRead(kPinSw1);
  if(plusBtnIncState != lastPlusBtnIncState) {
    if(plusBtnIncState == HIGH) {
      interval = interval + 1000;
    }
    delay(50);
  }
  lastPlusBtnIncState = plusBtnIncState;

  //---------------DEC_TIMER---------------//
  minusBtnDecState = digitalRead(kPinSw2);
  if(minusBtnDecState != lastMinusBtnDecState) {
    if(minusBtnDecState == HIGH) {
      interval = interval - 1000;
      if(interval <= 0) {
        interval = 0;
      }
    }
    delay(50);
  }
  lastMinusBtnDecState = minusBtnDecState;

  //---------------------------------------//
  Serial.print("Int:");
  Serial.print(interval);
  Serial.print("\n");
}

And output:
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296

As you can see in output when I reach ZERO and then again decrease the value then the value is like 4294966296 instead of ZERO. I put the logic for that if we reached ZERO or less ZERO then it must stay at ZERO. I don't understand why this happens. Please suggest me something.

do not decrement once you reach zero

The variable "interval" is an unsigned long.  This means it can not go negative.  It also means that it is made up of a 32 bits.
Instead of going negative, an unsigned variable will cycle to its most maximum value by following a modulo 2 math behavior.  So a 32 bit value will become 2^32 or 4294967296 if, for example, decremented 1 past 0.
In the above program the 32 bit value was decremented by 1000 past 0 resulting in 4294967296 - 1000 or 4294966296.
Testing if an unsigned number is negative is futile.  So this code:
  if(interval <= 0)
  {
    interval = 0;
  }

...does nothing.  Instead, test if "interval" is larger than 1000 before subtracting 1000.

As already mentioned in previous answers, the issue is that an unsigned
number wraps modulo MAX+1. The obvious fix would be to make interval a
signed number.
Another option would be to avoid subtracting from interval anything
larger that interval itself. You could do this by replacing
interval = interval - 1000;
if(interval <= 0) {
  interval = 0;
}

by
if (interval >= 1000)
  interval -= 1000;
else
  interval = 0;

Note that the else clause could be dropped if you can guarantee that
interval is always a multiple of 1000.


text:
Connect Two Arduino Uno's
Essentially I am looking to build a remote controlled car using dc motors and one arduino uno to be on the car to supply the power logic and i wanted to use another arduino to be the remote. I was curious what the most effective method would be as to pairing these two devices in a way that it would provide the maximum range possible while still maintaining a decently high bandwidth limit. The reason for this is hopefully i can have the arduino mounted to the car connected to a camera where the camera would send a video feed over to the remote control. I was thinking about using a bluetooth module between the two such as a HM-10 but i wouldn't be able to send a video feed this way because bluetooth cannot transmit that much data at once. However if that is the most practical option i can get over the fact of not having a live video feed and send an image ever 5 seconds or so instead of live. Appreciate any insight on what the most effective method would be in terms of efficiency between range and data stream bandwidth.

i would stick with analog video broadcasting for now, and keep an eye out for faster wifi modules

You wouldn't be able process (acquire, store, resize, output) any sensible video signal with the Uno (or any other Atmega-based board). The amount of memory and clock speed is way too low. Peripherals and instruction set are also lacking - no DMA, FPU, DSP instructions. Arduinos barely cope with audio - any kind of video is out of question, except if you want something like a 5fps 32x32 raw feed. Uncompressed, of course.
If you want another hobby-friendly open source solution, I'd look at something with at least an ARM M4 core, with DMA of course. For communication, regular IEEE 802.11 Wifi is your best bet (high throughput) - those 433Mhz RF modules only transmit 4800bps or so.
There may be better solutions, but I've only used stm32f429 for video: they have DMA(2D), display interface (RGB, 8080 memory interface, ...), DCMI (digital camera interface). Wifi could be handled by something like WifiMCU.
You could use the STM32F429DISCOVERY board with LCD for you remote controller, another STM32F4 board with a camera (ex http://hackaday.com/2014/12/04/serial-camera-courtesy-of-the-stm32f4/) and pair them with two WifiMCUs, if You want to do it with off-the-shelf boards.

You can use raspberry pi and computer to send commands and receive video feed

i was looking to utilize just Arduinos as I'm looking to get more familiar with the architecture

@A.Epstein - you might be hoping to, but that will not work.  This answer is so far the only remotely sensible one that has been posted.  Digital video really requires substantial memory buffers to do right, and no MCU, Arduino or otherwise, has those - the only cost effective solutions going to be those that use a variation of DRAM technology, which isn't something that ends up on the same die as a processor, hence either a stacked assembly like a pi or an S/DD/RAM next to an SoC or special function type CPU..


text:
Serial Write fails to send when Motors moving
I have an unusual bug with the code I have written for my rover V2 robot.
I have a raspberry pi running some computer vision code written in opencv tracking an object doing the heavy processing.
Once the object is detected, a command is sent via serial (USB) to make the robot move left, right, forwards etc.. The pi sends: w, a or d for the direction it wants the rover to move, it then turns off it's ability to send any further commands via a flag and will turn this back on when the rover sends a response confirming it has completed the command.
The idea is, eventually the rover v2 will be able to do some audio processing itself so it can turn and face the direction of a sound impulse but always prioritize any incoming serial data, sending the more accurate movement commands.
So my idea has been to implement an interrupt routine that is called upon receiving a command using the less than perfect approach suggested here.
So now for the weird part.. the code works entirely... until the motors have power!
If the Rover V2 motor power is entirely disabled the interrupt routine will work flawlessly. The Raspberry Pi will send a command and receive every reply from the Rover.
However, if the Rover V2 Motors are powered on, the Rover will receive all commands and send replies accordingly. The issue is for some reason, the Raspberry Pi will occasionally not receive a reply rendering the robot stationary as no more commands can be sent, this happens after varying periods of time all the way from 2 successful command interrupts to 100.
The fact that this occurs only when power is applied to the motors on the Arduino, is leading me to believe it is not a fault in the Pi code.
Why is it, that as soon as the power is applied to the motors there is inconsistency in the transmission of serial replies?
Does anybody have any suggestions on how I could further diagnose the cause of this fault?
Or is there any obvious issues in this code I have not seen?
Thanks in advance!
ohkneel
Code can be  viewed HERE

Without examining your code my immediate thought is EMI. As the motors spin then induce noise in the comms signals which corrupts them making the Pi not receive the right thing. What EMI filtering do you have on your motors?

One thing to try would be doing a dry run - let it "move" the motors but disconnect them.  Also consider if your power source is truly sufficient for the motor demands and sufficiently separated from the logic supply source.  It's possible you will see messages related to USB interference is the dmesg output of the pi.  You might ultimately want to consider using a different interface than USB, and implementing error correction.  Also consider a mechanism (timeout, break, or even watchdog) to get out of unexpected but possible software states - ideally indicate the issue before recovering.

Fixed: Interrupt routine was calling itself nestedly, terrible practice, lesson learnt!
Thanks for the suggestions guys!


text:
What is this green board?

Hi I'm new to arduino and robotics itself. I have no idea what this giant green board is in the middle of the robot. I really need help!

In what way is this question related to the Arduino?

The green board is probably a custom PCB that controls the vehicle. Unfortunately, the image does not have enough quality to determine much else.

Create such PCB is possible in kitchen over one evening without anything costy (maybe except laser printer, if you want high density mask, but permanent marker can go long way too) , I made a lot of similar PCBs (but little smaller, just to fit my needs), like  https://wiki.gilhad.cz/mediawiki/images/8/8f/H-mustek-2-med.png

It's a sheet of FR-4 clad in copper, with much of the copper etched off to form a PCB. That is then coated in green UV cured paint (solder resist) and components are attached.
Other things are then plugged into it.
What function it performs depends on what the designer designed it to do.


text:
How to / is it possible to change Vendor Name in ESP8266-12E?
I am aware of that it is possible to change hostname for ESP8266 but I want to change vendor name also so that it lists my company/product name in routers/firewalls.
Is it possible?

No. The Vendor Name is associated with the OUI.  The OUI is the first three parts of the MAC address.
The OUI's are all registered with IEEE here and Espressif's entries are:
18-FE-34   (hex)        Espressif Inc.
24-0A-C4   (hex)        Espressif Inc.
24-B2-DE   (hex)        Espressif Inc.
2C-3A-E8   (hex)        Espressif Inc.
30-AE-A4   (hex)        Espressif Inc.
3C-71-BF   (hex)        Espressif Inc.
54-5A-A6   (hex)        Espressif Inc.
5C-CF-7F   (hex)        Espressif Inc.
60-01-94   (hex)        Espressif Inc.
68-C6-3A   (hex)        Espressif Inc.
80-7D-3A   (hex)        Espressif Inc.
84-0D-8E   (hex)        Espressif Inc.
84-F3-EB   (hex)        Espressif Inc.
90-97-D5   (hex)        Espressif Inc.
A0-20-A6   (hex)        Espressif Inc.
A4-7B-9D   (hex)        Espressif Inc.
AC-D0-74   (hex)        Espressif Inc.
B4-E6-2D   (hex)        Espressif Inc.
BC-DD-C2   (hex)        Espressif Inc.
C4-4F-33   (hex)        Espressif Inc.
CC-50-E3   (hex)        Espressif Inc.
D8-A0-1D   (hex)        Espressif Inc.
DC-4F-22   (hex)        Espressif Inc.
EC-FA-BC   (hex)        Espressif Inc.

The ESP8266 does not advertise the vendor. The router / other device maintains a list of OUI to Name mappings (on Linux it's stored in /usr/share/ieee-data) and uses them to create a pretty display.
You would need to

Change the ESP8266's MAC address somehow
Subscribe to IEEE and pay the relevant fees
Be allocated an OUI
Hope that every device in the world that would ever talk to your hardware updates its OUI mappings (which they seldom do).

You can change the MAC address in software, using wifi_set_macaddr(). Then you have the problem of storing that address in EEPROM and making sure every piece of code that you write for your product knows how to access it. You also need to add a step in your product release process that figures out what to store, and stores it, or you need to burn a different image in each unit that you sell. Plus you need to keep track of all the mac addresses you've ever issued so you don't issue duplicate ones. Plus, as @Majenko said, you would need to register your own OUI, which costs a few thousand dollars. So unless you plan to sell tens of thousand of your units, it's not worth doing.


text:
is there Raw RTC output?
I have an I2C Real Time Clock, DS3231 RTC module , and I just want something like Unix Time.
I'm using the uRTCLib, looking at the class methods
but dont see anything like that. I'm thinking there must be a raw read that would return all the digits. Is there an easy way to do that?

The DS3231 doesn't report the Unix time. It reports the current time in
broken-down form (year, month... second). If you need Unix time, you
have to compute it.
I suggest using Adafruit's RTClib. This library implements the
computation of Unix time, e.g.
uint32_t unix_time = rtc.now().unixtime();


text:
NodeMCU ESP12 Voltage
I'd like to power an NodeMCU off of four 1.5v batteries.  That's 6v.
Depending on the source I've read that 5.1v will fry the board and, just a few clicks later, that the board will take up to a 20v input.
What is the real, practical input voltage range for an NodeMCU?  Even the spec sheets seem to disagree.

I edited your question and changed ESP-12 to NodeMCU, based on the title and tag.
5.1 V will 'fry' a plain ESP12, but the NodeMCU is development board with esp8266 and the board has a power regulator for USB power or Vin pin. The parameters of the regulator depend on the regulator used by the manufacturer of your board.


text:
Is it possible to print client IP or MAC address from Arduino WiFi web server?
For a school project I want to make a little project with the Arduino Uno. I want to make a project that does something when a client connects to the WiFi shield.
My first thought was to print out the IP address or MAC address of the client but I can't find the codes for it. It is possible for me to print out the host IP? I have searched on the web for some time but only the ethernet shield will appear. Is my question even possible with an WiFi shield or do I have to get an ethernet shield?
Kind regards.

Which WiFi shield? There's two different official ones, plus a handful of third party ones.

It looks like Arduino only thought to provide access to that kind of information for UDP packets. They couldn't be bothered to do it for TCP connections. How **** is that?

***** Assuming it is an ESP8266 based WI-FI shield: *****
Wifi shield > PC
Open serial monitor. Baud rate 155200. Also check COM ports.
Test AT commands by typing AT.
If it responds OK, you're good.
Type AT+CIFSR for IP adress.
Full list of AT commands in this link:
http://www.pridopia.co.uk/pi-doc/ESP8266ATCommandsSet.pdf

You're assuming an ESP8266 based WiFi shield. If it's an official Arduino WiFi shield of either version then it most certainly won't be that.

I edited to have a disclaimer in the anwser. Thanks

Isn't it local address anyways? Question looks like he wanted the IP of the other side. But I'm not sure if he's using AP mode and he wants assigned IP for the client or he wants connected TCP socket client IP.


text:
Humidity sensor for wet environment
I've had a bit of experience with DHT11/DHT22 sensors in a greenhouse environment, and believe that when they get wet they stop working altogether.
Are there any low cost humidity sensors that I can hook up to an Arduino that don't suffer from this problem, or is there a way to protect these sensors from damage when near water? (I'm not talking about immersing them in water - but do expect condensation to get sprayed with water and/or get condensation on them from time-to-time).
Am I correct that the SHTxx sensors are able to withstand this kind of abuse, and that these sensors are about 5-10 times the cost of DHT sensors?  (I did not want to spend that much, but if it's the only possibility I might consider it).

use two temps to calc humidity (wet bulb and dry bulb). that would let a pair of cheap but tough thermocouples measure humidity. a neodymium magnet on an analog dial can also be used with a hall-effect sensor.

Get a proper enclosure for it.

Adafruit has those sinter metal mesh enclosed humidity sensors: https://www.adafruit.com/product/1298 There is a big difference between (near) 100% humidity and water condensation or sprayed with water. A capacitive soil moisture sensor can be submersed, but it can not measure the air humidity: https://wemakethings.net/chirp/ I suggest to protect humidity sensors with an enclosure as @Gerben wrote (an 'open' enclosure of course) and also use those sinter metal mesh enclosed sensors, and perhaps use a few different types of sensors so hopefully they will not all fail.

This HTU21D has a PTFE filter on top of the sensor. Not sure how good they work for water mists. Try checking the data sheet for it.

@dandavis interesting solution Ive not thought of - thank you. Unfortunately I don't think I have the knowledge to pull that off, particularly in my environment with limited airflow (And I don't want to add a fan)

@gerben - can you shed light on what I am looking for with respect if an enclosure? I have not been able find anything for the DHT, and wonder how fine a mesh I would need and how it will impact accuracy.

2022 UPDATE: After ~5 years since I wrote this answer, I'd like to mention that I don't like BME280 anymore, because of its (1) inaccuracy and (2) requirement to make some non-trivial computations to get real values from sensor's data. If you already got a BME280 and your project requires only approximate values of temperature/humidity, it will work, go ahead. Otherwise, consider using SHT3x!
See also this, this, and especially this one.
Original answer:

I'd consider using Bosch BME280 digital sensor. Although it's a bit expensive, it has very good sensitivity, precision and amazingly fast response for humidity changes (for ex. in my project it detects dry human hand lying in 2" away within a 1-2 seconds).
So its features make possible to put it into an enclosure to avoid direct water contact with water spays and it'll still be very responsive for greenhouse needs, I suppose.
Datasheet warns:

Liquids shall not come into direct contact with the device.

Also, I'd use electronic-friendly protective acrylic lacquer (Plasticote 70 for instance) and put two layers to sensor's PCB, avoiding small black tiny vent hole on the chip itself:

UPD: Here's DHT11 with cover removed:

It might be the easiest and cheapest solution to cover all internal contacts and IC (avoiding humidity sensor's stripes) of DHT11 with Plasticote 70.


text:
How to choose SPI type used by RF24 library from application?
I am developing a device with Ethernet shield (with Wiznet W5100) and NRF24L01+. I need to use Soft SPI due to a bug in the Wiznet chip. Next I am developing a different device with NRF24L01+ only. I want to use hardware SPI (besides other things it already contains a socket for NRF24L01+ connected to the default Arduino SPI pins).
It is very inconvenient to enable/disable #define SOFTSPI in RF24_config.h every time I want to work on the other device.
Is there a way how to choose the SPI type used by RF24 library in the application?
My current solution is to make a copy of RF24 to RF24_SoftSpi and RF24Network to RF24Network_SoftSpi. I enabled SOFTSPI in “_SoftSpi” versions (+ renamed all files, fixed includes and #ifndef statements in headers to avoid ambiguous errors).
Then in an application I just include RF24_SoftSpi instead of RF24 and RF24Network_SoftSpi instead of RF24Network to use software SPI.
With this workaround it is difficult to make updates to “_SoftSpi” libraries when a new feature is released.
Do you know of any better solution?

This might help; https://www.itead.cc/wiki/IBoard

Using this RF24 library set, I am able to use or not softspi by doing #define SOFTSPI on my sketch, there's no need to define it on the RF24_config.h, you should be able to define it on your own sketch.
EDIT:
Arduino 1.6.5
#include <SPI.h>
#include "RF24.h"
#include "printf.h"
#define SOFTSPI //Define pins RF24_config.h

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8     */
RF24 radio(8,9);

....
....
void setup() { ... }
void loop() { ... }

thank you for your answer. Would you be so kind and add an example into your answer including Arduino IDE version you use?

See edited answer above

#define directive does not have any impact on library build. Libraries are compiled separately and do not take any directive from sketch into account. Verify your sketch with and without the #define SOFTSPI directive. Size of the result will not change, but it should by approx 2kb.

This solution does not work unless proven otherwise

Try defining Soft SPI before including the RF24 related headers.


text:
Equivalent for PORTB in Arduino Mega 2560
Like I said in the subject, I would like to know the equivalent for the instruction:
PORTB |= 0x01;
PORTB &= ~0x01;

More precisely I was using it to trigger a fast pulse conversion on my shield-ADC on an Arduino Uno. Now I am using an Arduino Mega 2560.
Can you write the exact same instruction for ATMega2560?

This code sends a pulse on pin PB0, which on the Uno is equivalent to
digital 8. On the Mega, digital 8 is PH5, thus you would write
PORTH |= _BV(PH5);
PORTH &= ~_BV(PH5);

The equivalence between the Arduino pins and the AVR pins is provided in
the official
documentation, but
there are nicer versions at pighixxx.com:

Uno pinout
Mega pinout

The other answer has provided correct information and useful documentation on the question as asked.  This answer uses a slightly more portable method of producing a brief pulse on a given digital pin.
This more-portable method uses some standard (although not well-documented at arduino.cc) functions to get port numbers, port pointers, and bit masks from a pin number.  These functions – digitalPinToPort(), portInputRegister(), and digitalPinToBitMask()– can be used at run time to compute physical ports and pins from Arduino pin numbers.  In some cases the computation could occur at compile time if compiler is smart enough or is allowed to optimize.  But avr-gcc as configured for the Arduino IDE is not so allowed, which is a reasonable default for embedded programming.
This method also uses the fact that an AVR pin – as on most Atmel-based Arduinos – will toggle when you write a 1 to its bit in its input register.  For example, see §14.1 in Atmel doc8271, the ATmega48A/PA/88A/PA/168A/PA/328/P datasheet, which states:

Three I/O memory address locations are allocated for each port, one each for the Data Register – PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Port Input Pins I/O location is read only, while the Data Register and the Data Direction Register are read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register. ...

Example program
/*  jiw - Jan 2017 - toggle Arduino digital pin 8 several ways
Re: http://arduino.stackexchange.com/questions/33033/equivalent-for-portb-in-arduino-mega-2560 */
volatile uint8_t *portofpin;
uint8_t bitofpin;
void setup() {
  pinMode(8, OUTPUT);       // Set pin as output
  portofpin = portInputRegister(digitalPinToPort(8));
  bitofpin = digitalPinToBitMask(8);
}
void udelay() {
  delayMicroseconds(5);
}
void loop() {
  PORTB |= 0x01;        // Set Uno pin 8
  PORTB &= ~0x01;       // Clear Uno pin 8
  udelay();
  PINB = 1;         // Toggle Uno pin 8
  PINB = 1;         // Toggle Uno pin 8
  udelay();
  PINB = bitofpin;      // Toggle Uno pin 8
  PINB = bitofpin;      // Toggle Uno pin 8
  udelay();
  *portofpin = bitofpin;    // Toggle Arduino pin 8
  *portofpin = bitofpin;    // Toggle Arduino pin 8
  udelay();
}

Compilation on Uno
loop(), from compilation of the example program for an Uno board:
void loop() {
  PORTB |= 0x01;                // Set Uno pin 8
 10e:   28 9a           sbi     0x05, 0 ; 5
  PORTB &= ~0x01;               // Clear Uno pin 8
 110:   28 98           cbi     0x05, 0 ; 5
  udelay();
 112:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  PINB = 1;                     // Toggle Uno pin 8
 116:   81 e0           ldi     r24, 0x01       ; 1
 118:   83 b9           out     0x03, r24       ; 3
  PINB = 1;                     // Toggle Uno pin 8
 11a:   83 b9           out     0x03, r24       ; 3
  udelay();
 11c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  PINB = bitofpin;              // Toggle Uno pin 8
 120:   80 91 00 01     lds     r24, 0x0100
 124:   83 b9           out     0x03, r24       ; 3
  PINB = bitofpin;              // Toggle Uno pin 8
 126:   80 91 00 01     lds     r24, 0x0100
 12a:   83 b9           out     0x03, r24       ; 3
  udelay();
 12c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 130:   e0 91 01 01     lds     r30, 0x0101
 134:   f0 91 02 01     lds     r31, 0x0102
 138:   80 91 00 01     lds     r24, 0x0100
 13c:   80 83           st      Z, r24
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 13e:   e0 91 01 01     lds     r30, 0x0101
 142:   f0 91 02 01     lds     r31, 0x0102
 146:   80 91 00 01     lds     r24, 0x0100
 14a:   80 83           st      Z, r24
  udelay();
 14c:   0c 94 83 00     jmp     0x106   ; 0x106 <_Z6udelayv>

As you can see in the above, instead of using read/modify/write sequences to implement PORTB |= 0x01; PORTB &= ~0x01;, the compiler produced sbi 0x05,0; cbi 0x05,0;, to directly set and then clear bit 0 of register 5, PORTB.  This uses 4 clock cycles total, producing a pulse that's high for 2 cycles.
avr-gcc implemented PINB = 1; PINB = 1; via ldi r24, 1; out 3,r24; out 3,r24, which takes 3 cycles total and produces a pulse that's high for 1 cycle.
It implemented PINB = bitofpin; PINB = bitofpin; via lds r24, 0x0100; out 3,r24; lds r24, 0x0100; out 3,r24, which takes 6 cycles total and produces a pulse that's high for 3 cycles.  (In setup(), the value of bitofpin was stored in RAM location 0x100, and the value of portofpin was stored in 0x101, 0x102.)
Finally, it implemented *portofpin = bitofpin; *portofpin = bitofpin; via a six-instruction sequence that takes 14 cycles and produces a pulse that's high for 7 cycles.  Obviously, the compiler could have produced a 4-instruction sequence (by not reloading r30, r31, and r24) that takes 8 cycles and a pulse that's high for 1 cycle, but it didn't.

Compilation on Mega
loop(), from compilation of the example program for a Mega or Mega 2560 board:
void loop() {
  PORTB |= 0x01;                // Set Uno pin 8
 218:   28 9a           sbi     0x05, 0 ; 5
  PORTB &= ~0x01;               // Clear Uno pin 8
 21a:   28 98           cbi     0x05, 0 ; 5
  udelay();
 21c:   fa df           rcall   .-12            ; 0x212 <_Z6udelayv>
 21e:   81 e0           ldi     r24, 0x01       ; 1
  PINB = 1;                     // Toggle Uno pin 8
 220:   83 b9           out     0x03, r24       ; 3
 222:   83 b9           out     0x03, r24       ; 3
  PINB = 1;                     // Toggle Uno pin 8
 224:   f6 df           rcall   .-20            ; 0x212 <_Z6udelayv>
  udelay();
 226:   80 91 00 02     lds     r24, 0x0200
  PINB = bitofpin;              // Toggle Uno pin 8
 22a:   83 b9           out     0x03, r24       ; 3
 22c:   80 91 00 02     lds     r24, 0x0200
  PINB = bitofpin;              // Toggle Uno pin 8
 230:   83 b9           out     0x03, r24       ; 3
 232:   ef df           rcall   .-34            ; 0x212 <_Z6udelayv>
 234:   e0 91 01 02     lds     r30, 0x0201
  udelay();
 238:   f0 91 02 02     lds     r31, 0x0202
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 23c:   80 91 00 02     lds     r24, 0x0200
 240:   80 83           st      Z, r24
 242:   e0 91 01 02     lds     r30, 0x0201
 246:   f0 91 02 02     lds     r31, 0x0202
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 24a:   80 91 00 02     lds     r24, 0x0200
 24e:   80 83           st      Z, r24
 250:   e0 cf           rjmp    .-64            ; 0x212 <_Z6udelayv>

The assembly code for Mega is much the same as that for the Uno, except that bitofpin and portofpin values were stored in RAM 0x200–0x202 instead of 0x100–0x102, and rcall or rjmp was used to call udelay();, instead of call or jmp.

Making assembly listings
To make assembly listing files for a program, use a command like
avr-objdump -CSI$PWD $TMPPATH/togglepin8.cpp.elf > togglepin8.ino.mega.asm

where $PWD represents the current working directory that contains a sketch like togglepin8.ino, and $TMPPATH represents whatever temporary directory the IDE stuck the source in to compile and link it.  The C switch (not used for above listings) tells avr-objdump to demangle symbols.  Switch S says to display source code intermixed with disassembly if possible.  Switch I tells location of source code.

Conditional compilation
Conditional compilation is another way to make the source code portable to several Arduinos.  For example, near the beginning of the sketch one could include the following #ifdef and #define statements to set up BITOFPIN and PORTOFPIN values for later use:
#ifdef ARDUINO_AVR_UNO
#define BITOFPIN  1
#define PORTOFPIN PINB
#endif
#ifdef ARDUINO_AVR_MEGA2560
#define BITOFPIN  _BV(PH5)
#define PORTOFPIN PINH
#endif

To find out what board-dependent symbols are defined at compile time, turn on verbose output during compilation and look for flags of the form -Dsym=val.


text:
How to control cold to hot (blue to red gradient) RBG LED strip/bulb with a rotary encoder?
I'm doing a project for university and I am struggling to code and set up a rotary encoder that can control hot-cold variations. Much like the idea of communicating temperature selected by turning a dial. I would either like to control a single strip of RGB LEDs or a single bulb (changing and fading between colours at the same time).
I would like to have the dial turn from 0 - 180 degrees and relate to intense blue changing to intense red and all the colours in between as increments.
I have an Arduino Uno.
Thank you!

Which part of that are you having a problem with? Reading the rotary encoder or making the LED(s) light up in the right way?

The SE format works best asking 1 question and getting 1 answer.  And, you'll get a lot more responses here if you give your project a try first.  Then, if you get stuck, ask a question about the issue you are having problems with.  That said, break your project into two parts.  There are plenty of on line web pages regarding rotary encoders.  And plenty of on line web pages which talk about RGB LEDs.

Did you miss to add your source code, components and wiring?

If you want a dial that turns from 0 to 180, is a rotary encoder the best option? Generally this component is used either (a) as a rotational speed sensor; or (b) because we've got used to having seamless rotary controls. A potentiometer would be better suited, and easier to include.

You probably want to use the HUE color scheme instead of RGB and then just map the HUE value to the analog value of a potentiometer.

Well as I understand you want to use a rotary encoder ? Rotary encoder can turn freely. Which you can read via arduino easily with a library. You can count a number(let's say x) from 0 up to 255, and write that number to one of the color. For the other color write 255-x so when blue is fading down the red is increasing. But I suggest you to use a potentiometer which has a limited turn (about 270 degrees). Connect it to arduino's one of the analog read pins. It will give you a 10 bit value which is between 0-1023 . You can scale this down to 0-255 range with map function. [Example:  "x = map(x,0,1023,0,255);" ] after that just follow the same process as before.

http://playground.arduino.cc/Main/RotaryEncoders is where the rotarty encoder libraries are. From there you can use PWM on the outputs as said. There are also some addressable RGB strips/modules that incorporate a driver IC such as adafruit neopixels where you can just write values for colour and brightness to the IC fairly simply, depending on your level of electronics knowledge.

authors: Александр Савельев

authors: นายอุษามณี เทกอง


text:
problem serial hardware sim7600 arduino due
I am very newbie using arduino. I get a EVB SIM7600 TTL 3V and I am trying to test it using a arduino Due.
I need a help please, my simple code doesnt work.
The serial monitor only show zeros. The baudrate default for SIM7600 is 115200bps. I insert a simcard and then write AT command in serial monitor, for example ATI... I received zero
Here is my code and photo of connection.

void setup() {

  Serial.begin(115200);
  Serial.println("Testing GSM SIM7600");
  Serial1.begin(115200);
  delay(100);

}

void loop() {

  if(Serial1.available())
  {
    Serial.println(Serial1.read());
  }

  if(Serial.available())
  {
    Serial1.write(Serial.read());
  }

}

I didn't see anything like AT Command in your sketch. Share your full sketch.

I send command AT using Serial monitor text box. I can connect to module using the  built in usb serial interface, then using putty com5 baudrate 115200 I can use them and even access to internet like a modem LTE. The complete sketch is same I posted :S still i can not do anything :( with arduino due

let go to step by step and solve the problem. You direct interface of module from USB to you PC and then try to send AT commands. Please don't forget to use EOL characters like \r \n at the end of AT command like this AT\r\n.

the serial usb interface of SIM7600 is working fine in windows. The problem is arduino due communication, but I know can understand the problem is a code I wrote. I checked yesteday the display work better using Serial1.readString (), but still I have searching the solution. sorry my english


text:
How to write code to make the LED’s ﬂash in the following sequence?
How to write code like this sequence? What is the meaning of 4 decimal?
For this, we had to add a delay in the code
led_Pin_1 1 0 0 0
led_Pin_2 0 1 0 0
led_Pin_3 0 0 1 0
led_Pin_4 0 0 0 1

my code, It is working. But I need to convert this code to above sequence?
int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  digitalWrite(led_Pin_1, HIGH);
  delay(200);
  digitalWrite(led_Pin_2, HIGH);
  delay(200);
   digitalWrite(led_Pin_3, HIGH);
  delay(200);
   digitalWrite(led_Pin_4, HIGH);
  delay(200);
  digitalWrite(led_Pin_1, LOW);
  delay(300);
   digitalWrite(led_Pin_2, LOW);
  delay(300);
   digitalWrite(led_Pin_3, LOW);
  delay(300);
   digitalWrite(led_Pin_4, LOW);
  delay(300);
}

your third question makes no sense .... also the comment about the delay makes no sense

please help me to write this code

No sir, I asked Is my code correct or not. If incorrect my code help me

what do you see when you run the code?

read the question that you posted .... you did not ask if your code is correct or not

int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

int led_on = 0; // Start with first (led_Pin_1)

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(led_Pin_1, (led_on == 0) ? HIGH : LOW);
  digitalWrite(led_Pin_2, (led_on == 1) ? HIGH : LOW);
  digitalWrite(led_Pin_3, (led_on == 2) ? HIGH : LOW);
  digitalWrite(led_Pin_4, (led_on == 3) ? HIGH : LOW);
  delay(250);

  led_on = (led_on + 1) % 4;
}

led_on will start with 0 (pin 1), switching only that pin on. Some explanation:
(led_on == 0) ? HIGH : LOW

This means: if (led_on == 0), than the value will be HIGH, otherwise LOW. Resulting in only pin 1 going on, if led_on is 0, and in the next loop, only pin 2 oing on, because led_on is 1 etc.
led_on = (led_on + 1) % 4;

This increases the value of led_on, but when it reaches 4, it reverts back to 0.
I don't know about the delay times you need. I guess you want to change all LEDs at once, than wait.
You can make the 4 almost identical digitalWrite lines into a function as small improvement.
If you want to do more with the LEDs, than consider storing the leds into an array and use a for loop to iterate through them.


text:
Arduino 5V pump digital pin
I am trying to control a 5V pump with arduino and ultrasonic sensor however i can't make it work with the pump connected to a pin.
I saw on the forum that you need transistor or relay but i don't understand why ?
Thanks !

Probably because the pump will use more current (mA) than a GPIO pin of the Arduino can deliver.
A GPIO pin on the Arduino can deliver 20 mA, or 40 mA max (but not advised for longer time).
Therefore, a separate power supplyis used, where the base pin of a transistor is connected to a GPIO pin (with a resistor) to 'switch' the transistor on and off.
The transistor base can be very low current (way within a GPIO's current range), which result in a much bigger current from the collector (connected to the power supply) to the emitter (connected to GND). The pump is somewhere between the external power supply and GND).
If you search for 'transistor as a switch' you will find many examples.
You also can use a relay if you don't need to switch it on often. Relay's are typically used for net-powered devices (110+ volts) and/or high current. See also Duncan's comments for additional notes regarding relays.

Good answer as usual, but if you use a relay the relay's coils will almost certainly need more current than a GPIO pin can provide, so you'll still need a transistor (And a "flyback diode") to drive the relay. There are various "digital relay" modules that have all that built in and are meant to be controlled directly from a  5V GPIO pin. You feed them a 5V supply line, plus the control signal, and they turn the relay on or off based on the digital pin.

Also note that if you drive an inductive load like a pump from a transistor, you should have a "flyback diode" to protect the transistor from back EMF from the inductor.

@DuncanC Good comment as usual :-) ... I have to admit for some tests I indeed did not use a 'bare' relay, but a relay module, which contains the flyback diode and opto coupler probably together with a transistor. I added a line in my answer to read your comments.

Thansk for the answers ! i did with transistor and it worked thanks however if i connect the pump straight to the 5v it work so it means that the pin on the arduino have less voltage/ ampere ?

The pin on the Arduino is 5V ... to get the max. recommended 20 mA your pump should be max 5 * 0.02 A = 0.1 W. However, the Arduino will go dead (or the pin) when using more than 40 mA, but between 20 mA and 40 mA it will work, but it's definitely not good for the Arduino (especially over a longer time). So what you can do, use you a digital multimeter (DMM) to check the current and verify if this is max. 20 mA. Also check how to measure current (Amperes) on a DMM. 0.1 W seems like a very tiny pump to me.

Okok gonna check that ! thanks a lot for your help!

@michel-keijzers has pointed you in the right direction. Depending upon the power requirements for your pump, you might consider looking specifically at logic-level power MOSFETs as the type of transistor in your circuit.
You might also investigate the use of a pull-up resistor to fully turn on a MOSFET.

MOSFET is actually a tag in this forum (https://arduino.stackexchange.com/questions/tagged/mosfet). You might get some ideas from other questions.

Indeed, logic level MOSFETs are often an excellent choice because they draw almost no current from the controlling GPIO pin. They have VERY low "on resistance" so they can control high current (DC) loads while generating very little heat and wasting very little power.


text:
MKR FOx 1200 doesn't upload Sketch
My Arduino MKR Fox 1200 doesn't upload any sketches. First it worked, but now it doesn't.
It compiles the bare minimum sketch (empty loop and empty setup) but then uploads forever and after a long while it says port busy or Board not Found on Port

I think that your Operating System has not found the board.  This could be for any number of reasons, not least a Windows update, if you have Windows :).

Close the IDE and unplug the board.
Wait 10 seconds.
Plug the board in, did the OS detect the board?
If NO, Unplug board and restart computer.
IF NO, When booted plug in board, did it detect the board -> No Stop.
If yes, start the IDE.
Check you have the write COM port selected.
Try loading a sketch again, did it work?

Other things to try:

New USB cable
Different USB port.
Remove other USB devices, my Xbox controller sometimes prevents Arduinos attaching, not idea why.
Different board.
Different computer.


text:
MKR Fox 1200 doesn't wake up from sleep
I have a Sigfox Arduino meassuring some sensors, sending it to the cloud and then falling asleep.
void setup()
{
Serial.begin(9600);
  while (!Serial) {};
  if (!SigFox.begin()) {
    Serial.println("Shield error or not present!");
    return;
  }
  SigFox.debug();
  delay(100);
  SigFox.end();
}

void loop()
{
SigFox.begin();
  delay(100);
  SigFox.status();
  delay(1);
  SigFox.beginPacket();
  SigFox.print("123456789012");
  int ret = SigFox.endPacket(true);

  if (ret > 0) {
    Serial.println("No transmission");
  } else {
    Serial.println("Transmission ok");
  }
  Serial.println();
  SigFox.end();
LowPower.sleep(20000);
}

The Issue I have is that the sending to the backend doesn't work when leaving the sigfox.debug() away and that it doesn't wake up from the sleep. It stays in sleep forever.

Looks like same problem as described in https://forum.arduino.cc/index.php?topic=483636.0
Solution described in that thread:
Add
LowPower.attachInterruptWakeup(RTC_ALARM_WAKEUP, alarmEvent0, CHANGE);

to setup() and create a dummy function
void alarmEvent0() {
}

No that sadly doesn't fix the issue


text:
ESP32 restart each minute with SW_CPU_RESET
running an ESP32 (ttgo), I get strange behavior.  The unit restarts each minute, around 00 seconds.
I get
12:31:02.861 -> rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
as reason.
I checked flash frequency is 40MHz (80 seems to lead to same issues)
Anyway, if I start the device at 10:00:34, it will restart at 10:01:00 and then at 10:02:00 and so on ...
running this code:   https://github.com/xlyric/pv-router-esp32
Powered by a usb-C phone-power, or on computer usb does the same.
The ttgo is plugged on a board connected to a AC/AC transformer and a current mesure device.
using "esp_register_shutdown_handler", I succed to send a mqtt message "gonna die",  it really rise each minute at 00 seconds

Your question does not contain enough information to anwer it. Describe your setup. What code is your ESP32 running? What power supply is it connected to? What other hardware is connected to it?

Thanks all, bug was between chair and keyboard :-) I was getting http calls on "/reset" from a crazy domoticz instance

The restart reason suggests that the ESP32 restarts upon software restart command. One should go over the code and see where in the code the restart command is sent. For instance starting from line 451 there is following:
if (config.restart) {
    //delay(5000);
    Serial.print(PV_RESTART);
    ESP.restart();
  }