text:
ESP8266 + DHT11 AWS IOT Thing not updating thing shadow - was working before
I was able to get this working - https://www.youtube.com/watch?v=8hpro1olRK0 - send an SMS and email of temperature and humidity data from AWS IOT using esp8266 + dht11 but all of a sudden it stopped updating the shadow.
Here is the code

#include <ESP8266WiFi.h>
#include <DHT11.h>
#include <AmazonIOTClient.h>
#include <ESP8266AWSImplementations.h>

Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;

AmazonIOTClient iotClient;
ActionError actionError;

const char* ssid = "";
const char* password = "";

// Pin 2 will be used to read sensor data
int pin = 2;

// Initializing the sensor
DHT11 dht11(pin);

//Function to convert Celsius to Fahrenheit
double Fahrenheit(double celsius) {
  return ((celsius * 9 / 5) + 32);
}

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();

  // Connecting to Wi-Fi
  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.println();
  Serial.println("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  iotClient.setAWSRegion("us-west-2");
  iotClient.setAWSEndpoint("amazonaws.com");
  iotClient.setAWSDomain("al1x5kb4rzh0x.iot.us-west-2.amazonaws.com");
  iotClient.setAWSPath("$aws/things/esp8266/shadow/update/accepted");
  iotClient.setAWSKeyID("AKIAJJQ6ASLIDIPBE4PQ");
  iotClient.setAWSSecretKey("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");
  iotClient.setHttpClient(&httpClient);
  iotClient.setDateTimeProvider(&dateTimeProvider);
}

void loop() {
  int err;
  float temp, humi;

//Reading the sensor data
  if ((err = dht11.read(humi, temp)) == 0) {
    Serial.print(" temperature:");
    Serial.print(temp);
    Serial.print(" humidity:");
    Serial.print(humi);
    Serial.println();
  } else {
    Serial.println();
    Serial.print(" Error No :");
    Serial.print(err);
    Serial.println();

  }
// Converting the float data to char arrays
  char sTemp[10], sHumi[10];
  dtostrf(humi, 6, 2, sHumi);
  dtostrf(temp, 6, 2, sTemp);

// Creating the thing shadow to be sent to aws iot
  char shadow[100];
  strcpy(shadow, "{\"state\":{\"reported\": {\"Humidity\":");
  strcat(shadow, sHumi);
  strcat(shadow, ", \"Temperature\":");
  strcat(shadow, sTemp);
  strcat(shadow, "}}}");
  Serial.print(shadow);

  char* result = iotClient.update_shadow(shadow, actionError);
  Serial.print(result);

  delay(60000);
}

Output as expected
Connecting to
NETGEAR53
.........
WiFi connected
 temperature:31.00 humidity:32.00
{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
443
POST $aws/things/esp8266/shadow/update/accepted HTTP/1.1
Content-Type: application/json
Connection: close
Content-Length: 65
Host: al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
x-amz-content-sha256: 923ed1ae613a9e14b45e4d080b092daf5cf61118041dc5225956299d5b0f8d49
x-amz-date: 20180323T034259Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAJJQ6ASLIDIPBE4PQ/20180323/us-west-2/iotdata/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date,Signature=a10f0969043e609743412478567c10290b8c000185f2824e4a9cf07bb96cf279

{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}

#include <ESP8266WiFi.h>
#include <DHT11.h>
#include <AmazonIOTClient.h>
#include <ESP8266AWSImplementations.h>
Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;
AmazonIOTClient iotClient;
ActionError actionError;

A small correction on the output, sometimes its perfect but some other times  i get timeout receiving time server data
{"state":{"reported": {"Humidity": 41.00, "Temperature": 31.00}}}al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
443
POST /things/ESP/shadow HTTP/1.1

{"state":{"reported": {"Humidity": 41.00, "Temperature": 31.00}}}timeout receiving timeserver data

I am also facing the same problem and still, I didn't get any answer...current I am also working on that

Anyone get this solved? I have the same issue

I am planning to try cleaning the AWSiot libraries, that worked last time but again only one device works for me as of now. Probably I might try a different set of code. Please share your code guys -- I will try to help. Also I am trying different AWS keys.

Pls post the aws iot libraries you are using. Ot sure what changed but nothing works and thing shadow not getting updated

I was facing a similar problem: trying to update a thing's shadow on AWS IoT with no success. After some research, I found out that I was using an outdated library. In this question they advise to use heskew's aws-sdk-arduino, on iot-get-shadow-and-cleanup branch:
https://github.com/heskew/aws-sdk-arduino/tree/iot-get-shadow-and-cleanup.
Additionally, I think you have a little error on your code. As far as I know, AWSPath, it should look like:
iotClient.setAWSPath("/things/esp8266/shadow");

At least that works for me, and they use it this way on this video.
That's all I can tell... I am learning at this moment as well.
Hope it helps!!

Thank you so much for your response, really appreciate it. My thing name is actually ESP so i have it set as ---iotClient.setAWSPath("/things/ESP/shadow");--- or should it only be esp8266?
i deleted old libraries and used the one above but still my thing shadow is not updating. Please help. The other example video you referred - that also is not working

https://arduino.stackexchange.com/questions/51059/esp8266-dht11-aws-iot-thing-not-updating-thing-shadow-was-working-before

Just Change the Aws topic :
it should be  $aws/things/esp8266/shadow/update
and you have to add the certificate path also

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


text:
Sleep power down mode with change interrupt
I want to use to use an IR sensor as an interrupt to wake up my Arduino Uno R3 from the deep sleep power mode and then go back to sleep after changing the state of the relay.
Lets say if I press a button on the remote and the relay is on LOW mode, the relay is turned to HIGH mode and vice versa.
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <IRremote.h>

/* Sleep Demo
------------

int relayPin = 8;            // LED connected to digital pin 13
int irPin = 2;            // active LOW, ground this pin momentary to wake up
int sleepStatus = 0;        // variable to store a request for sleep
volatile byte state = LOW;

IRrecv irrecv(irPin);
decode_results results;

void setup()
{
  pinMode(relayPin, OUTPUT);         // sets the digital pin as output
  pinMode(irPin, INPUT);
  irrecv.enableIRIn(); // Start the receiver

  /* Now is time to enable a interrupt. In the function call
     attachInterrupt(A, B, C)
     A   can be either 0 or 1 for interrupts on pin 2 or 3.

     B   Name of a function you want to execute while in interrupt A.

     C   Trigger mode of the interrupt pin. can be:
                 LOW        a low level trigger
                 CHANGE     a change in level trigger
                 RISING     a rising edge of a level trigger
                 FALLING    a falling edge of a level trigger

     In all but the IDLE sleep modes only LOW can be used.
  */

  attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
  // wakeUpNow when pin 2 gets LOW
}

void sleepNow()         // here we put the arduino to sleep
{
  /* Now is the time to set the sleep mode. In the Atmega8 datasheet
     http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
     there is a list of sleep modes which explains which clocks and
     wake up sources are available in which sleep modus.

     In the avr/sleep.h file, the call names of these sleep modus are to be found:

     The 5 different modes are:
         SLEEP_MODE_IDLE         -the least power savings
         SLEEP_MODE_ADC
         SLEEP_MODE_PWR_SAVE
         SLEEP_MODE_STANDBY
         SLEEP_MODE_PWR_DOWN     -the most power savings

     For now, we want as much power savings as possible,
     so we choose the according sleep modus: SLEEP_MODE_PWR_DOWN

  */
  set_sleep_mode(SLEEP_MODE_IDLE);   // sleep mode is set here

  sleep_enable();              // enables the sleep bit in the mcucr register
  // so sleep is possible. just a safety pin

  /* Now is time to enable a interrupt. we do it here so an
     accidentally pushed interrupt button doesn't interrupt
     our running program. if you want to be able to run
     interrupt code besides the sleep function, place it in
     setup() for example.

     In the function call attachInterrupt(A, B, C)
     A   can be either 0 or 1 for interrupts on pin 2 or 3.

     B   Name of a function you want to execute at interrupt for A.

     C   Trigger mode of the interrupt pin. can be:
                 LOW        a low level triggers
                 CHANGE     a change in level triggers
                 RISING     a rising edge of a level triggers
                 FALLING    a falling edge of a level triggers

     In all but the IDLE sleep modes only LOW can be used.
  */

  attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
  // wakeUpNow when pin 2 gets LOW

  sleep_mode();                // here the device is actually put to sleep!!
  //

  sleep_disable();             // first thing after waking from sleep:
  // disable sleep...
  detachInterrupt(0);          // disables interrupt 0 on pin 2 so the
  // wakeUpNow code will not be executed
  // during normal running time.
  delay(1000);                 // wat 2 sec. so humans can notice the
  // interrupt.
  // LED to show the interrupt is handled
}

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  if (irrecv.decode(&results)) {
    if (results.value == 0xff629d) {
      state = !state;
      digitalWrite(relayPin, state);
    }
  }
}

void loop()
{

  sleepNow();                      // sleep function called here
}

The Arduino never seems to wake up from sleep when I use the CHANGE interrupt. But if I use with the IDLE sleep mode, it is working.
Can somebody please help me how to fix this ?
Also will this code work with an Arduino Pro Mini or an ATTiny45?

You actually don't need to to worry about interrupts at all for this
project. The IRremote library is itself based on a timer interrupt. As
soon as you irrecv.enableIRIn(), you start receiving a continuous
stream of interrupts... in addition to the timer interrupt initially set
up by the Arduino core.
If you want to save some power, you can call sleep_mode() once in your
loop. That's it. No need to sleep_enable() or sleep_disable(), as
these are already taken care of by sleep_mode(). No need to
set_sleep_mode() either, as the default sleep mode (IDLE) is the only
one that is appropriate for you. No need to attachInterrupt(), as you
will be waken up by these timer interrupts anyway.
Removing all the cruft, your posted code would become:
#include <avr/sleep.h>
#include <IRremote.h>

const int relayPin = 8;
const int irPin = 2;
IRrecv irrecv(irPin);

void setup()
{
    pinMode(relayPin, OUTPUT);
    pinMode(irPin, INPUT);
    irrecv.enableIRIn();
}

void loop()
{
    decode_results results;
    if (irrecv.decode(&results)) {
        if (results.value == 0xff629d) {
            static byte state = LOW;
            state = !state;
            digitalWrite(relayPin, state);
        }
        irrecv.resume();
    }

    // Sleep until next interrupt.
    sleep_mode();
}

The Arduino never seems to wake up from sleep when I use the CHANGE interrupt.
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function

That's not a CHANGE interrupt, it's a LOW interrupt. Please post code that supports what you say in the question.

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  if (irrecv.decode(&results)) {
    if (results.value == 0xff629d) {
      Serial.println("UP");
      state = !state;
      digitalWrite(relayPin, state);
    }
  }
}

Don't do serial prints inside an ISR. In particular, a LOW interrupt keeps being called continuously while the interrupt pin is low.

// timers and code using timers (serial.print and more...) will not work here

You even have a comment saying that the code won't work, yet you posted it in your question.

I changed the code accordingly

source: Stack Exchange

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

sort: votes


text:
Problem converting character array into integer in arduino using atoi function
I'm receiving a character string from a radio signal on my arduino.  This character string consists of four character digits, which I want to convert into an integer.  The four digit sequence may contain zeros padded in front of the integer, such as '0025' to represent the integer 25.
So, I saved this character string onto a character array of length 5:
char left[5];

The first four characters in this array have the four character digits received in the radio signal.  I have a fifth character which I set to the character '\0' to signify a termination character.
The message received is any number ranging from 0 to 1023, but I need to use values between -255 and +255.  To convert the character into an integer, I use the atoi function as follows:
int leftpower = (atoi(left)-512)/2;

When I print out the variable "leftpower", it seems to give the correct value.  I'm even able to use "leftpower" in an if then statement as follows:
if (myvalue<0){
  Serial.println("inside the if-then statement");
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  //analogWrite(enableA,myvalue);
}

So, as far as I can tell, everything is working fine.  I want to use "myvalue" as a command to an analogWrite function call as follows:
//analogWrite(enablePinA,myvalue);

However, something strange happens when I uncomment this line.  WHen I uncomment it, the program seems to hang at the if statement, as if it paused at that point and neither crashes nor gives any error.  The program no longer prints out "inside the if-then statement" at all, but no other errors seem to be detected.  No other compilation or runtime errors.
The strange thing about this is that if I change "leftpower" to a number like 223 as follows:
analogWrite(enablePinA,223);

the program works as I expected it to, producing a motor command.  So, I know the problem is not with my wiring.  The problem seems to be associated with the variable "leftpower", which was converted from a character array to an integer using the atoi function.
What exactly is going on?  What problem is actually occurring and how can I fix it?  Any help would be greatly appreciated!
For reference, my code is posted below:
#include <RH_ASK.h> //radiohead library to read RF signals
#include <SPI.h> //just because radiohead library depends on it
RH_ASK driver; //default: transmitter data pin goes to arduino pin 11
int in1=4;
int in2=5;
int in3=6;
int in4=7;

int enableA = 9;
int enableB = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  if (!driver.init()){
    Serial.println("receiver init failed");
  }
  pinMode(enableA,OUTPUT);
  pinMode(enableB,OUTPUT);
  pinMode(in1,OUTPUT);
  pinMode(in2,OUTPUT);
  pinMode(in3,OUTPUT);
  pinMode(in4,OUTPUT);
}
int leftpower,rightpower;
void loop() {
  // put your main code here, to run repeatedly:
  uint8_t buf[8];
  uint8_t buflen = sizeof(buf);
  if (driver.recv(buf, &buflen)){ //non-blocking
    //Convert buf (unsigned integer) to a character array
    char temp[8]="";
    sprintf(temp,"%s",(char*) buf);
    //Four characters for first integer, four for the second integer
    //So, we have to split them into two parts (left and right)
    char left[5]="";
    for (int i=0; i<4; i++){
      left[i]=temp[i];
    }
    //Put a terminating character at the end
    left[4]='\0';
    char right[5]="";
    for (int i=0; i<4; i++){
      right[i]=temp[4+i];
    }
    //Put a terminating character at the end
    right[4]='\0';
    leftpower=(int) (atoi(left)-512)/2;
    rightpower=(int) (atoi(right)-512)/2;
    constrain(leftpower,-255,255);
    constrain(rightpower,-255,255);
    Serial.println(leftpower);
    Serial.println(rightpower);
    if (leftpower<0) {
      //switch H-bridge to forward direction
      Serial.println("inside the if-then statement");
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      analogWrite(enableA,255);
      Serial.println("got this far");
    }
    else {
      digitalWrite(in1,LOW);
      digitalWrite(in2,HIGH);
      analogWrite(enableA,255);
    }
//    if (rightpower<0) {
//      //switch H-bridge to forward direction
//      digitalWrite(in3,LOW);
//      digitalWrite(in4,HIGH);
//      analogWrite(enableA,abs(rightpower));
//    }
//    else {
//      digitalWrite(in4,LOW);
//      digitalWrite(in3,HIGH);
//      analogWrite(enableA,abs(rightpower));
//    }

  }
}

analogWrite does not support negative values. You should probably use abs(leftpower).

You have a few issues here.

if (driver.recv(buf, &buflen)) { ... }

You don't check the value of buflen after calling the recv() method.
I didn't read the doc of the RH_ASK library you are using. Are you sure
it does preserve message boundaries? I let you check. If it only
transports bytes (rather than full messages), then you will have to
repeatedly recv() until you have a full message.
Edit: Looked at the doc. The communication is indeed packetized, so
you don't need to collect the message chunk by chunk. It is, however,
still a good idea to check whether the received size is what you expect:
if (driver.recv(buf, &buflen) && buflen == 8) { ... }

sprintf(temp,"%s",(char*) buf);

This is a serious bug, and most probably the reason your program behaves
inconsistently. Here buf is not a NUL-terminated string. The
sprintf() function will copy bytes from buf into temp until it
finds a NUL. It can potentially overwrite the receiving buffer and start
clobbering whatever happens to be past temp in your memory. This is
called “memory corruption” and can lead to any kind of unpredictable
behaviors.
Note that the whole copying you do here serves no useful purpose. You
can work from the initial buffer to start with:
char left[5];
memcpy(left, buf, 4);
left[4] = '\0';
char right[5];
memcpy(right, buf+4, 4);
right[4] = '\0';

constrain(leftpower,-255,255);

You are implicitly discarding the value computed by constrain(). You
probably mean
leftpower = constrain(leftpower, -255, 255);

The reason for the copy step is that the message received by the radio signal is actually 8 characters (two 4 character digit commands).  To convert to an integer, i need to split the message into 2 separate 4 character arrays.

@Paul: That's why I suggest doing the splitting using two partial copies (with memcpy()), as buf → (left, right). However, your original code did the splitting as buf → temp → (left, right), where you first make a full copy (buf → temp) for no good reason. Note that the splitting could even be made zero-copy if we were after that kind of optimization.

I think the reason i used sprintf is because the message received in the buffer was originally an unsigned integer uint8_t (not a character array) and i thought converting to a character array would be simpler (for parsing purposes) using sprintf.  Could i have parsed the two numbers out to a regular integer without converting to a character array first?

@Paul: Yes. buf is just an array of bytes. Same for temp. uint8_t, which is the same as unsigned char, means the bytes are interpreted as 8-bit unsigned integers. With int8_t (or signed char, or just char on Arduino), it's interpreted as a signed integer. The difference is irrelevant unless you plan to do arithmetics on those bytes, which you don't.

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


text:
Why do people complain when I call my functions voids?
I have posted questions about "my void loop" or "my void setup" and people complain that they aren't really voids. But they are! See this example code:
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

Clearly setup and loop are voids because they have the word void right before them!

Note: this is a reference question.

Sorry Nick, but this reference question looks more like a general C++ prgramming question (belonging to StackOverflow then) than an Arduino question, except for the actual functions content. Some members might well vote to close this kind of question as "off topic".

Yes I realize that, but Arduino users tend to be beginners to programming in general and C++ in particular. The constant references to "the Arduino language" makes me think that they might not consider checking StackOverflow for an answer. Indeed, it is addressing a problem that beginners might not even realize exists (terminology). By posting this Q&A I am attempting to provide a reference point for people who talk about their "void loop" problem.

Don't get me wrong, I'm not insulting people who don't know C++. There was a time when I didn't have the faintest idea about C or C++. Previously I had been using Turbo Pascal, and was used to procedure and function declarations, and thought that C had very weird syntax. And before Turbo Pascal, well that's a whole other story. :)

Don't worry Nick, no risk I get you wrong, you are one of my electronics rock stars (I really appreciate your posts about electronics on your site)! I agree with the fact that many Arduino newcomers will first come here for a C++ question. My comment was more about how some Arduino.SE members (including myself) might react on such a question and might consider it off-topic. No hard feelings!

This is an easy mistake for a beginner to C++ to make. Let's look at other languages, like PHP:
function add ($a, $b)
  {
  return $a + $b;
  }

Or Lua:
function add (a, b)
  return a + b
end

Or JavaScript:
function add (a, b)
  {
  return a + b;
  }

Or VBscript:
Function add (a, b)
  add = a + b
End Function

All those languages have the word "function" there to indicate that you are declaring a function.

So what does C++ look like:
int add (int a, int b)
  {
  return a + b;
  }

So this must be an "int" right? Or what if it doesn't return a value?
void loop ()
  {
  }

Now it's a "void"? Kind of a weird name for a function!
Actually int and void in these examples are not weird names for functions. They are the return types of those functions. int add (int a, int b) is a function that returns an int. And void loop () is a function that returns nothing.
The C++ compiler can deduce when it is seeing a function declaration from some clues:

A return type (eg. int, float, long)
A name (the function name)
Some parentheses (for the function arguments)

Think of the word function as being there in spirit:
int [function] add (int a, int b)
    ^^^^^^^^^^   <-- don't actually type this!
    {
    return a + b;
    }

I think if you use a phrase like " my int a or my CustomType a " people would interpret those phrases to mean that you have a variable a that is an instance of an int or a CustomType.
According to http://en.cppreference.com/w/cpp/language/types you can't have an object or reference of type void.
If you have a phrase like "my void setup", I think most people would try to read that as implying you have a variable setup of type void, which I don't think makes sense, to most people.
What you actually have is this:
void setup() {
...
}

I think most people would phrase this as "my function setup, which takes no arguments are returns nothing".

you missed the "Note"?

I guess I did,  and I later noticed that the same person answered it as asked it, which seemed weird.  I have never seen or heard of such a thing as a "reference question, at least not on stackoverflow,  is it documented somewhere?  I searched the meta site and did not find it.

See Can I answer my own question? and It’s OK to Ask and Answer Your Own Questions. From that: it is not merely OK to ask and answer your own question, it is explicitly encouraged.

Thanks,  I guess I have seen cases were people answer their own question, after the find a solution, but not this type of case.  I can see cases were it would be a value add.   But I guess then I don't see the point of someone pointing out the fact that it is a "reference" question, after all a question is a question and someone could still have a better answer than the person that asked it.


text:
Proto Threading 2 functions
I would like to proto thread two functions to run pseudo-simultaneously. One function takes the input of a force sensor and moves a servo accordingly, and the other takes the input of a gyroscope (MPU650) and moves a different sensor accordingly. Below is my code where I attempt to use timers to handle this.
#include <Wire.h>
#include <Servo.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"

int FSR_Pin = A0;
bool isClosed = false;
unsigned long lastMillis = 0;
unsigned long lastMillis2 = 0;

MPU6050 mpu;

int16_t ax, ay, az;
int16_t gx, gy, gz;

Servo handServo;

Servo wristServo;

int pos = 0;
int val;
int prevVal;

void setup(){
  Serial.begin(9600);
  handServo.attach(9);

  Wire.begin();
  Serial.begin(38400);

  Serial.println("Initialize MPU");
  mpu.initialize();
  Serial.println(mpu.testConnection() ? "Connected" : "Connection failed");
  wristServo.attach(8);
}

void handleFingers () {
  int FSRReading = analogRead(FSR_Pin);
  Serial.println(FSRReading);

if (FSRReading > 9) {
 if (pos < 90) {
     handServo.write(pos);
      pos ++;
 }
  isClosed = true;

} else if (isClosed == true && FSRReading < 10) {
  pos = 0;
  handServo.write(pos);
  isClosed = false;
}
}

void handleWrist() {
  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    val = map(ay, -17000, 17000, 0, 179);
    if (val != prevVal)
    {
        wristServo.write(val);
        prevVal = val;
    }

}

void loop(){
  if (millis() - lastMillis > 1000) {
    handleFingers ();
  }
   lastMillis = millis();

 if (millis() - lastMillis2 > 1000) {
    handleWrist();
  }
   lastMillis2 = millis();

}

When I run the code above, the servos move a few degrees each and then do nothing at all. It appears that none of the servos are responsive to the sensor feedback. Something is wrong with my timing or my method of proto threading. I would really appreciate your help, thanks.

Update the previousMillis (lastMillis and lastMillis2) inside the loop with the interval. When enough time has passed the code is executed and the previousMillis will be updated for the next interval. See: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

note: your code formatting (indentation) is inconsistent throughout the code.

Jot provided the answer in a comment: you are updating lastMillis in
the wrong place. The correct way is:
if (millis() - lastMillis >= 1000) {
    handleFingers();
    lastMillis = millis();
}

Optionally, you can use lastMillis += 1000 instead of
lastMillis = millis() if you want to precisely control the average
(rather than minimum) update period.
Just to elaborate a bit, the idiom I like for doing this kind of stuff
is as follows:
const unsigned long FINGER_UPDATE_PERIOD = 1000;
const unsigned long WRIST_UPDATE_PERIOD  = 1000;

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

    // Handle the fingers.
    static unsigned long last_finger_update;
    if (now - last_finger_update >= FINGER_UPDATE_PERIOD) {
        last_finger_update = now;
        handleFingers();
    }

    // Handle the wrist.
    static unsigned long last_wrist_update;
    if (now - last_wrist_update >= WRIST_UPDATE_PERIOD) {
        last_wrist_update = now;
        handleWrist();
    }
}

Note that:

The update periods are constants defined at the top of the
program.
millis() only needs to be called once per loop iteration: if the
loop takes many milliseconds to run you would be doing something
wrong anyway.
last_finger_update and last_wrist_update stand for lastMillis
and lastMillis2, which are very poor naming choices.
These two variables are local to loop(), as they are not needed
anywhere else.
These variables are also declared static, which means they are
implicitly initialized to 0 and they preserve their values from call
to call.
I update the timing variables before doing the actual work. This
helps keeping all the timing code together, which makes the code
clearer, especially if the actual work takes many lines of code (e.g.
you do the work inline instead of having it in separate functions).

Some people prefer using libraries for this kind of proto-threading. If
you use the ArduinoThread library, the same could be written as:
const unsigned long FINGER_UPDATE_PERIOD = 1000;
const unsigned long WRIST_UPDATE_PERIOD  = 1000;

Thread updateFingers(handleFingers, FINGER_UPDATE_PERIOD);
Thread updateWrist(handleWrist, WRIST_UPDATE_PERIOD);
StaticThreadController<2> scheduler(&updateFingers, &updateWrist);

void loop() {
    scheduler.run();
}


text:
handling array from post data on espwebserver
I think I have a supplement question. If irrelevant , then sorry in advance.
I have nested array in post like:  from apache web server page index.php
$_POST['colorsarray'][0] = '#ff0000';
$_POST['colorsarray'][1] = '#2d67ea';
$_POST['colorsarray'][3] = '#7cf325';
$_POST['mode'] = 'none';
$_POST['singlecolour'] = '#ff0000';
Can you suggest me how to assign this array (coloursarray) directly to another array in espwebserver. In other use cases , only the list (length) of array will increase and is not know until the variable arrives from client.
Thanks in advance.

The ability for PHP to do this is special to PHP. The PHP program parses the field names as PHP arrays if they are named thus:
<form ....>
<input name="[colorsarray][0]" value="#ff0000" />
<input name="[colorsarray][1]" value="#2d67ea" />
<input name="[colorsarray][2]" value="#000000" />
<input name="[colorsarray][3]" value="#7cf325" />
[...]
</form>

But since the ESP8266's core doesn't use PHP or understand PHP arrays, you will have to use the literal field name [colorsarray][3], parse it yourself, and determine at run-time the length of the array and how much memory is needed, etc.

Thanks for the help, So I need to take care of the length of array at runtime and have to manually parse the array data. Note: not using form data just using ajax to collect data and send typically array of hex colours.
But cannot change or resolve the array into any other convenient form, so stuck with arrays for now. I had the ultimate resolution as to use indices for the array but was here to be sure that there is not any KISS (keep it simple silly) method available.


text:
Can't read JSON data from client (webpage) with Arduino Leonardo ETH
I'm reading a digital pin and count how many times that pin is enable, after that the data is sent in JSON format. All is working well till here. But I want to introduce a value from webpage to arduino, so the arduino will know from what number it should count. I modified the webpage, I'm converting the value in JSON format, everything. But I can't get it on arduino. I see the value on Serial Monitor right before client disconnect. But I just cannot figure what I'm doing wrong, maybe you guys have a suggestion ?
Here is my Arduino code ( is a bit messy, and I haven't did the part were I tell to arduino the number where it should start to count, I will do that after i can get my numbers from webpage ). If needed i can also add the webpage code.
#include <SD.h>
#include <SPI.h>
#include <Ethernet2.h>
#include <ArduinoJson.h>

int pin = 3;
int state = 0;
//==========================
int push = 0;
//==========================
int laststate = 0;
const int chipS = 4;

byte mac[] = {0x00, 0x08, 0xDC, 0x1C, 0xB8, 0x4C}; // Enter the MAC address that is on your Ethernet shield (sticker) - eg. 00-08-DC-1C-B8-4C  (but use hexidecimal format eg. 0x00)
IPAddress ip(192, 168, 0, 88);                     // The IP address that you will give the Server - will depend on your local network range
EthernetServer server(8880);                       // The port to listen for Web Browsers - the default is 80, but some routers will block this port.. so change to 8081.

//*************************************************************************************************
// setup function
//=================================================================================================
void setup()
{
    Serial.begin(9600); // Begin Serial communication (baud rate = 9600).
    while (!Serial)
    {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    Ethernet.begin(mac, ip); // Initialise the ethernet library and network settings: https://www.arduino.cc/en/Reference/EthernetBegin
    server.begin();          // Tell the server to begin listening for incoming connections (on port 8081 in this example)
    Serial.print("Server IP address : ");
    Serial.println(Ethernet.localIP()); // If you see the IP address within the Serial monitor - you know that the server started successfully
    Serial.println(" ");

    // cardlaif  -  SD CARD INITALIZATION
    Serial.println("Initializare card...");
    if (!SD.begin(chipS))
    {
        Serial.println(" Initializarea cardului a esuat sau cardul lipseste ");
        while (1)
            ;
    }
    Serial.println(" Card initializat ");
    Serial.println(" ");
    pinMode(3, INPUT);
}

//*************************************************************************************************
// loop function
//=================================================================================================
void loop()
{
    //=====================================================================================================
    // contor  PIN 3 COUNTER
    //======================================================================================================
    state = digitalRead(pin);

    if (state != laststate)
    {
        if (state == HIGH)
        {
            push++;
        }
        delay(50);
    }
    laststate = state;

    Serial.print(" nr. citiri: ");
    Serial.println(push);
    //====================================================================================================
    // card SD CARD WRITE CODE
    //====================================================================================================
    String dataString = " ";
    dataString += String("nr. citiri: ");
    dataString += String(push);

    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile)
    {
        dataFile.println(dataString);
        dataFile.close();
    }
    else
    {
        Serial.println("error opening datalog.txt");
    }
    //========================================================================================================
    //    net
    //========================================================================================================
    EthernetClient client = server.available(); // assign any newly connected Web Browsers to the "client" variable.

    if (client.connected())
    {
        Serial.println("Client Connected");
        // char c = client.read();
        // Serial.print(c);
        while (client.available())
        {
            Serial.write(client.read()); // Uncomment if you want to write the request from the Browser (CLIENT) to the SERIAL MONITOR (and comment out the next line)
            // client.read();                               // This line will clear the communication buffer between the client and the server.
        }

        // Send the Server response header back to the browser.
        client.println(F("HTTP/1.1 200 OK"));                                                                                // This tells the browser that the request to provide data was accepted
                                                                                //    client.println("GET");
        client.println(F("Access-Control-Allow-Origin: *"));                                                                            // Tells the browser it has accepted its request for data from a different domain (origin).
        client.println(F("Access-Control-Allow-Methods:  GET,POST,PUT,DELETE,OPTIONS"));                                                // The arduino will accept JSON format data using this
        client.println(F("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")); // The arduino will accept JSON format data using this
        client.println(F("Content-Type: application/json;charset=utf-8"));                                                              // Lets the browser know that the data will be in a JSON format
        client.println(F("Server: Arduino"));                                                                                // The data is coming from an Arduino Web Server (this line can be omitted)
        client.println(F("Connection: close"));                                                                                // Will close the connection at the end of data transmission.
        client.println();                                                                                // You need to include this blank line - it tells the browser that it has reached the end of the Server reponse header.

        // Example Transmission: [{"key":0, "value":300},{"key":1, "value":320},{"key":2, "value":143},{"key":3, "value":24},{"key":4, "value":760},{"key":5, "value":470}]
        client.print("[");            // This is tha starting bracket of the JSON data
        client.print("{\"value\": "); // The value I read on pin 3 and send in JSON format to webpage
        client.print(push);           //  The value I read on pin 3 and send in JSON format to webpage
        client.print("}");            //  JSON things
        client.println("]");          // This is the final bracket of the JSON data
    }

    //=================================================================================================
    // trying to print on serial json data
    //=================================================================================================
    char json[] = "{\"index\" }";
    StaticJsonBuffer<300> jsonBuffer;
    JsonObject &root = jsonBuffer.createObject();
    if (!root.success())
    {
        Serial.println("Parsing failed");
    }
    int index = root["index"];
    Serial.print(" index: ");
    Serial.print(index);
    Serial.println(" ");

    client.stop();                       // This method terminates the connection to the client
    Serial.println("Client has closed"); // Print the message to the Serial monitor to indicate that the client connection has closed.
} // VOID LOOP END

And this is what I get on serial monitor:
Client Connected
POST / HTTP/1.1
Host: 192.168.0.88:8880
Connection: keep-alive
Content-Length: 1
Accept: application/json, text/javascript, */*; q=0.01
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,ro;q=0.8,es;q=0.7

5 index: 0

At the end, that 5 before the " index " word should be where the 0 is.
The 5 it's my JSON data. The reason why I see it it's because I enabled to see the reqest from the browser.
Someone have any idea ?
P.S Sorry for my bad english ^_^

Below, you create a static string, which is never used again.
char json[] = "{\"index\" }";

Here you create a buffer and instantiate an empty JsonObject.
StaticJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

Here you check if root (your newly created JsonObject) is valid. Because it's empty and fresh, it is valid.
if (!root.success())
{
  Serial.println("Parsing failed");
}

Here, you try to ask for the value of index from your empty object.
int index = root["index"];
Serial.print(" index: ");
Serial.print(index);

If you never provide the JsonObject with any structure or content to parse, how can it give you anything back besides nothing?
The examples from the ArduinoJSON library prove to be helpful:
Documentation on parseObject

char json[] = "{\"hello\":\"world\"}";
StaticJsonBuffer<200> jsonBuffer;
JsonObject& object = jsonBuffer.parseObject(json);
const char* world = object["hello"];

Note the differences from what you are doing:

The initial JSON string to parse has both a key and a value.
The StaticJsonBuffer declaration includes a buffer size
The JsonObject declaration uses parseObject and passes in the json string, instead of creating a blank/empty object.

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


text:
Arduino reduces the laser power
Its important to mention that I'm noob.
I bought 500mw 405nm TTL module laser(5-12 volt) driver circuit. When I supplied laser with 12 volt, it turns on with max power. but when i connects laser TTL module to arduino (pin 11) in order to control turning on & off of laser through GRBL(CNC machine language) command with full power, the output of laser reduces.
"M05 S0" turns off the laser while
"M03 S255" should turns on the laser with full power as it is turning on with direct 12 volt supply, but its not happening.
so how can I make laser turn on with full power with arduino control?
Laser I,m using
https://www.amazon.in/gp/product/B071J2W7V8/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
Laser driver circuit

What laser? What's your circuit?

Did you set the maximum spindle speed in GRBL to 255? If not, than it is correct, that the laser power goes down. GRBL outputs a simple PWM signal, but that does not mean, that the duty cycle of the PWM output directly translates to the spindle speed set by the S command

I'm voting to close this question as off-topic because it is about a laser power supply, and not about Arduino.  If you want to pursue this project (despite the rather obvious potential hazards) you will need to use other resources to figure out how to make the power supply operate correctly from an approximately 5v logic input, which is what the Arduino can provide as a control signal.

Did you try a simple PWM sketch?

Possible duplicate of How to connect TTL logic laser with arduino?

Also asked at: https://electronics.stackexchange.com/q/364287 and http://forum.arduino.cc/index.php?topic=537202 If you're going to do that then at least be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

It also helps if you post a link to the datasheet.

The first thing I would recommend is to log into your Amazon account and contact the seller. Ask them to send you product documentation.
If the seller is not able to provide any, then you could return the product for a refund or try to figure it out how it works.
According to this document: TTL Laser
TTL modulators emit 100% of their power when a TTL "0" (0 VDC) is input and less than 5% of their power when a TTL "1" (5 VDC) is input.
gre_gor's comment about trying a simple PWM sketch sounds like an excellent place to start.


text:
Code compatibility with Arduino Due
I am currently working on a quadcopter project that involves an MPU6050 accelerometer+gyroscope module, an ultrasonic sensor and control of electronic speed controllers. I have used existing examples and modified them to get raw values of acceleration, yaw pitch and roll angles, and the distance from the ultrasonic. Here is the long code.
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

const int trigPin = 9;
const int echoPin = 10;

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3], yprd[3] = {0, 0, 0};

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = {'$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================
volatile bool mpuInterrupt = false;
void dmpDataReady() {
  mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================
int16_t yo = 0, po = 0, ro = 0;
int lv = 1, flag = 0;
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
int32_t AcXo = 0, AcYo = 0, AcZo = 0, prev, curr;
int32_t AcXd = 0, AcYd = 0, AcZd = 0;
int i = 1, flaggl = 0;
int  glc = 0, lv2 = 1;
long duration;
int distance, distanced;
void setup() {

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif
  Serial.begin(115200);
  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
  // wait for ready
  Serial.println(F("\nSend any character to begin DMP programming and demo:
                   "));
  while (Serial.available() && Serial.read()); // empty buffer
  while (!Serial.available());                 // wait for data
  while (Serial.available() && Serial.read()); // empty buffer again
  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();
  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Arduino external
                     interrupt 0)..."));
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

  // configure LED for output
  pinMode(LED_PIN, OUTPUT);
  glc = 0;
  distance = distanced = 0;
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================
void loop() {
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize) {
  }
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();
  // get current FIFO count
  fifoCount = mpu.getFIFOCount();
  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);
    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;
    //#ifdef OUTPUT_READABLE_YAWPITCHROLL
    // display Euler angles in degrees
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    if (millis() > 30000 && flag == 0) {
      if ( flag == 0 && lv  < 21) {
        yo += ypr[0] * 180 / M_PI;
        po += ypr[1] * 180 / M_PI;
        ro += ypr[2] * 180 / M_PI;
        ++lv;
      } else if (flag == 0) {
        flag = 1;
        yo /= 20;
        po /= 20;
        ro /= 20;
      }
    }
    //#endif
    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    mpu.resetFIFO();
    if (i < 21 && !flaggl) {
      AcXo += AcX;
      AcYo += AcY;
      AcZo += AcZ;
      ++i;
      Serial.println();
      Serial.println("***************************************************************************");
    } else if (!flaggl) {
      flaggl = 1;
      AcXo  = AcXo / 20;
      AcYo = AcYo / 20;
      AcZo = AcZo / 20;
    }
    curr = (AcZ - AcZo / 100);
    if (prev == curr )
      ++glc;
    else {
      glc = 0;
      prev = curr;
    }
    if (glc == 10) {
      Serial.println("lock broken!!!");
      glc = 0;
      loop();
    }
    if (flag == 1 && flaggl == 1) {
      if (lv2 < 21) {
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, HIGH);
        distance = duration * 0.034 / 2;
        AcXd += (AcX - AcXo) / 100;
        AcYd += (AcY - AcYo) / 100;
        AcZd += (AcZ - AcZo) / 100;
        yprd[0] += ypr[0] * 180 / M_PI - yo;
        yprd[1] += ypr[1] * 180 / M_PI - po;
        yprd[2] += ypr[2] * 180 / M_PI - ro;
        distanced += distance;
        ++lv2;
      } else {
        AcXd /= 20;
        AcYd /= 20;
        AcZd /= 20;
        yprd[0] /= 20;
        yprd[1] /= 20;
        yprd[2] /= 20;
        distanced /= 20;
        lv2 = 1;
        Serial.print("AcX = ");
        Serial.print(AcXd);
        Serial.print(" | AcY = ");
        Serial.print(AcYd);
        Serial.print(" | AcZ = ");
        Serial.print(AcZd);
        Serial.print(" | yaw = ");
        Serial.print(yprd[0]);
        Serial.print(" | pitch = ");
        Serial.print(yprd[1]);
        Serial.print(" | roll = ");
        Serial.print(yprd[2]);
        Serial.print(" | distance = ");
        Serial.println(distanced);
        AcXd  = 0;
        AcYd = 0;
        AcZd = 0;
        yprd[0] = 0;
        yprd[1] = 0;
        yprd[2] = 0;
        distanced = 0;
      }
    }
  }
}

The code involves offset calculation and displays the averaged instantaneous values. After overcoming the problems of FIFO buffer overflow and some other typical issues, I've managed to get the code running but the the Arduino hangs after sometime (code tested on both Uno and Nano).
Therefore, it seems that maybe I need a higher clock speed. So, I had a look through other Arduino boards and Due seemed to be the solution, as it has a clock speed of 84MHz, compared to Uno's 16 MHz. Therefore, my question is that will the libraries and functions used in this code be compatible with the Due? Also, can the 3.3V operation of the Due, compared to  Uno's 5V, present any problem in interfacing it with other sensors mentioned?

You should probably spend some time looking at existing post-ATmega open source aircraft designs.  The chip from a DUE can probably be made to a work; a lot of incumbent designs use comparable STM32, GigaDevices, and Nuvoton ARM Cortex MCUs... and also some other MCUs and especially MCU/radio chips basically undocumented in the west.

Arduino Due is a dead product, and has been from its birth. It is too powerful to be used just for flashing LEd's.Yes, you can make it work for your project but caveat emptor - do not expect much sympathy from Arduino.

Therefore, my question is that will be the libraries and functions used in this code be compatiable with Due?

The I2Cdev library is made for abstracting the hardware I2C functions to a more user friendly interface for each chip. Since the Arduino Due has hardware TWI (which is basically I2C) the normal Wire library from the Arduino IDE should work with it.

Also, can the 3.3V operation of Due, compared to Uno's 5V present any problem in interfacing it with other sensors mentioned?

You cannot put 5V from your sensor on a 3.3V pin on the Arduino Due, since this would destroy the pins hardware. I don't know how exactly you are using the MPU6050, but this one from Adafruit runs on 3.3V, which would be perfect. If your MPU6050 board only works with 5V maybe you can level shift the lines (but note that I2C would need 2-way level shifting, because SDA is used as output and input).
Also this Article may help you, where they are porting MultiWii to an Arduino Due.

I am working with the ArduinoDue and ArduinoMega2560 boards and I have found that programs that compile with the Mega2560 board don't necessary compile with the Due board.
This is because there is a limited amount of available libraries that are compatible with the Due board.
Try compiling (verifying) your code with the Due options set, you don't need to buy one to try verifying it.


text:
tinkercad arduino simulator integers being outputted as larger numbers than they are?
I am using an Arduino simulator on www.tinkercad.com (a seemingly nice free product from Autodesk).  Working on conversion of an integer to a 16 bit binary string for output to a DAC, but unfortunately even at the first step I am getting unexpected behavior.
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.print("Sanity Check\n");
  uint16_t num = 12000;
  Serial.print("\nNumber: " + String(num) + "\n");
  delay(3000);
}

Surprisingly the above code gave the following output:
Sanity Check

Number: 12222

Is there something I am doing wrong, or something wrong with the simulator?   The error seems to crop up with any value over 10000.  10001, 10002, 10003 all print as 10000.  11000, 11001, 11002, 11003 all print as 11111.  etc, etc.  What could be going on?

My Uno prints “Number: 12000”.

Bug. No other explanation. Real hardware (Arduino Uno) prints 12000.
Even the debugger tells me that the value of that variable is 12000.

Outputs:
Number: 12222
12000
12222 something

Most interestingly if you Serial.println() the number, it is outputted correctly. The bug must be in the constructor of the String object, as demonstrated by the "test" String. This bug also occurs on other data types, e.g. int.
If you only use direct Serial.print[ln] calls you should be able to workaround that bug.

Tinkercad is (was) a very good simulator but it has stopped updates.
Here is the output from the free Arduino simulator from here
This project is used for the below screenshot

Here is an article pointing some more features of the simulator


text:
On a motor after a continuous input of a certain amount of time
I would like to produce an output after a constant input is detected for a certain amount of time. Below is a simple code of what I am trying to do minus the time factor. Can someone help me on how to code out the duration of an input occurrence?  i.e.
if (sensorValue > threshold);
    //if this occurs for more than 4 hours, then
    digitalWrite (3, HIGH);

A constant input would be an analog value between two bounderies. Not just a check if it is above a threshold. Use millis for timing, it can count up to 50 days. The blink-without-delay uses an interval, but it explains the use of millis: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay Provide a minimal but complete working sketch please.

You must store the state of the last readings and do something like this:
    //Off-loop:
    bool state_changed = false;
    unsigned long time_in_state = 0;
    unsigned long last_reading = 0;

    //On-loop:
    if (sensorValue > treshold && !state_changed) {
        time_in_state += millis() - last_reading;
        last_reading = millis();
    }
    else {
        state_changed = true;
        time_in_state = 0;
    }

    if (time_in_state > TIME_REQUIRED) {
      digitalWrite (3, HIGH);
    }


text:
Arduino IDE : 'tansig' was not declared in this scope
I am working on a simple NN sketch, everything looks fine and also i have added #include math.h .but when i try to compile it gives an error i-e 'tansig' is not defined in this scope
I am trying to implement neural networks on obstacle avoiding robot.
Weights(Constants) are extracted from matlab training file.
How to make tansig work with arduino IDE
#include <math.h>
byte p1,p2,p3;
float n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,s1,s2,s3,s4,s5,s6,s7,s8;

int Echo1 = A4; //LEFT_SENSOR ECHO
int Trig1 = A5; //LEFT_SENSOR TRIG
int Echo2 = A2; //MID_SENSOR ECHO
int Trig2 = A3; //MID_SENSOR TRIG
int Echo3 = A0; //RIGHT_SENSOR ECHO
int Trig3 = A1; //RIGHT_SENSOR TRIG

//Motor driver outputs

#define m11 3
#define m12 4
#define m21 5
#define m22 6

int Left_Distance = 0,Right_Distance = 0,Middle_Distance = 0 ;

/*Ultrasonic distance measurement Sub function*/
int Left_Distance_test()
{
digitalWrite(Trig1, LOW);
delayMicroseconds(2);
digitalWrite(Trig1, HIGH);
delayMicroseconds(20);
digitalWrite(Trig1, LOW);
float Fdistance = pulseIn(Echo1, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

int Middle_Distance_test()
{
digitalWrite(Trig2, LOW);
delayMicroseconds(2);
digitalWrite(Trig2, HIGH);
delayMicroseconds(20);
digitalWrite(Trig2, LOW);
float Fdistance = pulseIn(Echo2, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

int Right_Distance_test()
{
digitalWrite(Trig3, LOW);
delayMicroseconds(2);
digitalWrite(Trig3, HIGH);
delayMicroseconds(20);
digitalWrite(Trig3, LOW);
float Fdistance = pulseIn(Echo3, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

void setup()
{

pinMode(Echo1, INPUT);
pinMode(Trig1, OUTPUT);
pinMode(Echo2, INPUT);
pinMode(Trig2, OUTPUT);
pinMode(Echo3, INPUT);
pinMode(Trig3, OUTPUT);

  pinMode(m11, OUTPUT);
  pinMode(m12, OUTPUT);
  pinMode(m21, OUTPUT);
  pinMode(m22, OUTPUT);

}

void loop()
{
  Left_Distance = Left_Distance_test();
delay(10);
Middle_Distance = Middle_Distance_test();
delay(10);
Right_Distance = Right_Distance_test();
delay(10);

p1=Left_Distance;
p2=Middle_Distance;
p3=Right_Distance;

n1=(0.0588*p1)+(-2.7382*p2)+(-2.2898*p3)+(5.2586);
n2=(-3.1601*p1)+(-2.2137*p2)+(1.7397*p3)+(1.4386);
n3=(2.2931*p1)+(0.3145*p2)+(3.5053*p3)+(-1.0167);
s1=tansig(n1);
s2=tansig(n2);
s3=tansig(n3);

n4=(1.1021*s1)+(1.2825*s2)+(-1.9864*s3)+(-2.3891);
n5=(-0.5501*s1)+(1.8527*s2)+(-2.0468*s3)+(1.4314);
n6=(0.4322*s1)+(-0.2474*s2)+(-2.5017*s3)+(-0.5222);
n7=(-0.2658*s1)+(-2.0624*s2)+(-2.2511*s3)+(1.0958);
n8=(1.7401*s1)+(1.1111*s2)+(1.2254*s3)+(2.4701);
s4=tansig(n4);
s5=tansig(n5);
s6=tansig(n6);
s7=tansig(n7);
s8=tansig(n8);

n9=(1.0819*s4)+(-1.0897*s5)+(0.0658*s6)+(-0.1232*s7)+(0.3510*s8)+(1.2990);
n10=(-1.0865*s4)+(1.0899*s5)+(-0.062*s6)+(0.1241*s7)+(0.5818*s8)+(-0.7316);
n11=(-0.2292*s4)+(-0.0606*s5)+(1.0508*s6)+(-0.9711*s7)+(1.1635*s8)+(0.2269);
n12=(0.2262*s4)+(0.0607*s5)+(-1.0482*s6)+(0.9717*s7)+(-0.5215*s8)+(0.6312);

digitalWrite(m11,n9);
digitalWrite(m12,n10);
digitalWrite(m11,n11);
digitalWrite(m11,n12);

}

error: 'tansig' was not declared in this scope

Show the code and the error. We cannot guess.

Maybe we can guess -- tansig is not defined in math.h and math.h does not provide any functions for neural networks. Are you coding for an Arduino?

@josecanuc Code Added.

@jsotola Code Added and statement redefined

I'm re-opening this question because it seems clear enough. How to get the function tansig to compile?

@NickGammon Yeah i tried that, But output of tanh are not suitable to write for motor inputs. They are [ -0.xxx or 1.xxx  or 0.xxx].

If it is mathematically equivalent, wouldn't tansig be the same? What motor inputs? What numbers are you expecting? Can't you translate the range you are getting into the range needed by the motors?

@NickGammon that is what i wanted to ask,Motors get only HIGH or LOW or we can say 0,1. But i am getting range in negative and postive decimal numbers. How to translate those outputs to some other which suits motor driver

See my amended answer.

You have quite a lot of floating point math here, and the tanh() calls are going to be expensive. You will have to measure the speed of your program and make sure it is fast enough for the application. If not, you may have to replace tanh() by a cheaper alternative, or go fixed-point, or get a more capable processor.

According to: http://au.mathworks.com/help/nnet/ref/tansig.html

Algorithms
a = tansig(n) = 2/(1+exp(-2*n))-1

This is mathematically equivalent to tanh(N).

So, replace calls to tansig by tanh. Or, make a define to do it:
#define tansig(n) tanh(n)

But output of tanh are not suitable to write for motor inputs. They are [ -0.xxx or 1.xxx or 0.xxx].

...

How to translate those outputs to some other which suits motor driver

There is a map function in the IDE which lets you translate from one range to another.

map() works only on long integers (comment by Edgar Bonet)

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

OK, well write your own function that does the same thing to floats. Example:
float fmap(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

map() works only on long integers.

See amended answer.


text:
6 wire 3 digits 7 segment display and arduino question
Here's a brain teaser for you:
I have the following 3 digit 7 segment display that has only 6 wires

Experimentally I found out how it works, even though I don't understand it, but anyways every segment is lit by a combination of HIGH and LOW of certain two pins, the combinations are below:

So I tried to make it work, but encountered the following problem (as you can see in the first picture): if, for example, I want to activate the segment that requires pin 5 high and pin 6 low, it also activates the other segments that require 5 to high, because apparently if a digital output is not high, it's automatically pulled to ground, and that's a problem.
I tried by setting the other pins I don't use in a segment to high, but then the segments that require 6 low are being activated, so that didn't work.
Other option I have would be transistors or a tri-state buffer, but for that I need all 12 digital inputs of arduino for the two states of each pin of the display.
Hope you understand what my problem is and maybe you have some advice on how to solve it.
Thanks in advance!
Edit: I managed to drive every segment individually using a small delay, and it works if the sketch has only the code for the display, but as soon as I add more code (for the temperature sensor I want to use) it starts to malfunction. You can find the code below.
LE: I managed to make it work by leaving only the display function in the loop and calling every 5 seconds the function for the temperature sensor. It still refreshes the display when it is called, but that doesn't bother me.
Here's the code: http://www.mediafire.com/file/2bs5r8u5rkzpu8g/6w_3D_7S_display.rar

You can emulate tri-state by setting a pin to INPUT.  That gives you your three states that you need: OUTPUT & HIGH, OUTPUT & LOW, and INPUT.

Sometimes the simplest solution is the best solution, thanks Majenko!

The link to your code is not working.

I changed the upload site, try now.

Still not working. I can download the file but it's corrupted. Try and upload a .ino or .txt file.

It’s a hassle because I split the code into tabs and would mean to upload everything individually. Anyways, I solved the issue.

What you have is a Charlie-Plexed display like the one in the picture below.  You need one more wire than this example because your display also includes the decimal point.  If you go through the electrical paths where for each pair one line is driven high, the other is driven low and all other lines are set to input, only one LED at a time will be forward biased.

Yes, that’s exactly how i did it, glad to find out how it works, thanks !


text:
Arduino Uno with Kubuntu 16.04: Unable to enumerate device
I try to connect my arduino uno R1 in order to program the atmega8u2 but I am not able to do so. When I run sudo dfu-programmer atmega8u2 erase I get the following results:
dfu-programmer: no device present.

So in order to diagnose it i run dmeesg with the following results:
 [ 1395.921051] usb 2-3: new full-speed USB device number 30 using
 xhci_hcd [ 1396.041175] usb 2-3: device descriptor read/64, error -71
 [ 1396.269135] usb 2-3: device descriptor read/64, error -71 [
 1396.497109] usb 2-3: new full-speed USB device number 31 using xhci_hcd [ 1396.617169] usb 2-3: device descriptor read/64, error -71
 [ 1396.845177] usb 2-3: device descriptor read/64, error -71 [
 1397.073163] usb 2-3: new full-speed USB device number 32 using xhci_hcd [ 1397.073371] usb 2-3: Device not responding to setup
 address. [ 1397.281311] usb 2-3: Device not responding to setup
 address. [ 1397.489086] usb 2-3: device not accepting address 32,
 error -71 [ 1397.609173] usb 2-3: new full-speed USB device number 33
 using xhci_hcd [ 1397.609382] usb 2-3: Device not responding to setup
 address. [ 1397.817200] usb 2-3: Device not responding to setup
 address. [ 1398.025176] usb 2-3: device not accepting address 33,
 error -71 [ 1398.025235] usb usb2-port3: unable to enumerate USB
 device

Do you know fellows how to make my arduino connect back into my computer?
Furthermore II forgot to mention my user is in dialout group as groups gnu/linux command mentions:
pcmagas adm dialout cdrom sudo dip plugdev lpadmin sambashare libvirtd docker wireshark

PS: That thing happened after soldering the resistor into the board so it is a new problem.

Looks like your board is either electrically damaged, or by previous attempts you put it in a bad software state where it does not function as a USB device.  If it is recoverable over USB, it would be by doing something electrically on startup to force it into a factory firmware recovery mode.  Likely you need to read the instructions you are following more thoroughly.  Did you solder the resistor as instructed at https://www.arduino.cc/en/Hacking/DFUProgramming8U2 ??

Well the board has already this problem: https://arduino.stackexchange.com/questions/50807/how-to-re-solder-the-resistor-in-order-to-reprogram-the-atmega8u2 I somehow managed to solder back the resistor in order to reprogram it in order to fix this problem but the problem still remains. The poer led works as ussual and the led in pin 13 blinks when I press the reset button.

Possible duplicate of How to re-solder the resistor in order to reprogram the Atmega8U2

And how do you know you were successful in soldering the resistor?  You have not achieved what the resistor should, so either it is not connected, or you're not doing the reset required after plugging in the USB, or there's another electrical fault on your board that disables the 8u2 but not the 328p.  This looks like a duplicate.

You should solder the resistor (in case you do not have the skills I reccomend doing into a proffessional, a professional close to me managed to solder it with a cost about 5 euros) and then hardware reset the atmega8u2 the documentation mentions. For quick reference just look over in this image:

In the dmesg you will see similar the same or message:
[ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
[ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
[ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 1544.808356] usb 1-6: Product: Arduino Uno DFU

Then look on the similar question for R1 boards or in case you have a newer board then follow the instructions mentiones to the documentation.


text:
How to use digital pin as ground?
I have recently brought an arduino nano. It has only two ground pins but I needed three for my project. Is there a way to use a digital or analog pin as ground pin? Please show me how to do it

ground is only one. connect every ground wire to one ground pin

Careful with using GPIOs as GND sinks.. An I/O pin can sink only so much current. For a GPIO bank, 100mA max, one pin recommended 20mA (https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations). I would connect directly to the main GND (from the power supply). Solder a few more wires if you have to.

If your project is on a breadboard, you can use one of the "rails", typically the blue longways row at either edge of the breadboard, to collect all of the necessary grounds, and wire that to one Ground pin on the Arduino.
If you're building a printed circuit board to connect to the Arduino, do the same thing - collect all of the PCB grounds together and wire that to one Arduino Ground pin.
If you're using a manufactured shield, you may have to get creative about collecting your grounds. A tiny breadboard is one way. Another is to solder a number of wires together in star-formation, insulate the solder joint with tape or shrink-tube, and connect one of the star's points to the Arduino ground.
If some of your devices needing grounds are low-current devices such as LEDs, you could set an unused pin to OUTPUT mode, and LOW, and use it as a ground, but the device must not be passing more current than an Arduino pin driver can sink. From Atmel's data sheet for the AtMega328p (used in the Uno):

Although each I/O port can sink more than the test conditions (20mA at
      VCC = 5V, 10mA at VCC = 3V) under steady state conditions
      (non-transient), the following must be observed:
ATmega48A/PA/88A/PA/168A/PA/328/P: 1] The sum of all IOL, for ports C0 - C5, ADC7, ADC6 should not exceed 100mA.
2]     The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.
3]     The sum of all IOL, for ports D0 - D4, RESET should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

There is no need to separate grounds, you can connect all grounds together. In fact they are connected together on the board itself.

You can just try converting two digital pins as 5V VCC and ground.
This will be useful when we use multiple sensors.
#define VCC2  5 // define pin 5 or any other digial pin here as VCC2
#define GND2  2 // define pin 2 or any other digital pin as Ground 2

void setup() {
  pinMode(VCC2,OUTPUT);//define a digital pin as output
  digitalWrite(VCC2, HIGH);// set the above pin as HIGH so it acts as 5V

  pinMode(GND2,OUTPUT);//define a digital pin as output
  digitalWrite(GND2, LOW);// set the above pin as LOW so it acts as Ground
}

void loop() {
}

I'm not sure I'd recommend this, but if you're going to do it you should know that it will have very limited current available, which will depend heavily on the Arduino involved, or rather its MCU.  You might allowed up to 40mA, but also perhaps only 4mA. And that your new "VCC" will drift toward ground as you draw more current.  Likewise with "GND" raising toward VCC.  They may not start as near the board VCC and GND as you like, as they're not intended for this purpose but only to produce logic levels.

It can be useful if you need to turn on/off the sensor during operation, but as timemage said, it is not advised. Using a transistor controlled by the Arduino's pin is way better.


text:
LED Strip Effect without delay
so a brief introduction about the project which I am working on before I go onto my issue.
I am working on a love-o-meter project (Not similar to the arduino example), whereby 2 people place 1 of their hands on a pad and with their other hand holding each other. Making use of a pulse sensor, I measure the BPM for 10s and then indicate the score on a LED strip.
Apart from indicating the compatibility score, I also plan to use the LED strip (cylon/fire effect) to indicate that the arduino is in the progress of calculating (when it is measuring the BPM for 10s) and also to indicate idling (rainbow cycle effect, when there is no one is using the love-o-meter).
However, here comes my issue: Performing the BPM measurement and displaying the cylon/fire effect function at the same time. I know that I cannot use the delay function and instead use millis(). However, the functions in the NeoPixel library already uses the delay effect and it seems like a tough job to edit the function to it using millis(). Is there another way to do so?

How do you take your BPM measurements? You could hack it work on a hardware timer interrupt and/or ADC 'conversion finished' interrupts and periodacally check for "BPM result ready" in the main loop. Hard to say without knowing your code.

@MaximilianGerhardt I am using the code from this link: https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/tree/master/PulseSensorAmped_Arduino_1.5.0 though I have tweaked it to perform the measurement for 10s. If you would like my entire code, I can send you the paste bin link

That code already uses timer interrupts to run 'concurrently' to your normal code, so you should be able to display whatever you want with delay. It does not affect interrupts.

Measuring BPM with a hardware timer will be tricky unless your input is bounce-free.

@ChrisStratton So does that mean my BPM measured will be inaccurate the first few readings? If so, what do you recommend? Because my code is from taken from the pulse sensor example which I assume to be the best way to measure BPM.

If your sensors is a switch with contact bounce, a hardware counter would be wildly inaccurate.  To use that approach you either need a bounce-free sensor or a hardware debounce circuit - or to count in software after a software debounce delay, rather than with a hardware counter.

it is unclear how you are doing the measurement ... the PulseSensor uses optical measurement and detects the heartbeat of only one person at a time .... are you using two sensors for simultaneous measurement of two people?

@ChrisStratton I am using the Pulse Sensor which I doubt requires debounce.

@jsotola I apologise. I am using the code from this link instead: https://github.com/WorldFamousElectronics/PulseSensorAmped_2_Sensors/tree/master/PulseSensorAmped_2_Sensors_1.5.0

@MaximilianGerhardt I apologise. I provided the wrong link. It is this link instead: https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/tree/master/PulseSensorAmped_Arduino_1.5.0 but it is still the same right as it still uses timer interrupts.

If you can find another way of calculating the BMP during displaying an effect on the strip depends highly on your BMP sensor. If you can do the measurement with interrupts, it should work. In this case you should make sure, that the interrupt cannot be fired during the execution of the Adafruit_NeoPixel.show() function, since it is quite timing sensitive.
But since I recently worked on a project with a NeoPixel LED strip, I have already edited functions from the strandtest example for use with the millis() function. So you will not have to reinvent the wheel again :D I will try to strip away my custom code, so that you can easily use it.
float brightness = 1.0;
uint32_t strip_state=0;

uint32_t Wheel(Adafruit_NeoPixel *strip, byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip->Color((255 - WheelPos * 3)*brightness, 0, WheelPos * 3*brightness);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip->Color(0, WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness);
  }
  WheelPos -= 170;
  return strip->Color(WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness, 0);
}

void fill_color(uint32_t color){
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);
  for(unsigned int i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
  }
  strip.show();
}

void fade_color(){
  for(unsigned int i=0;i<strip.numPixels();i++){
    strip.setPixelColor(i,Wheel(&strip,strip_state));
  }
  strip.show();
  strip_state++;
  if(strip_state>255) strip_state = 0;
}

void moving_rainbow(){
  for(unsigned int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, Wheel(&strip,((i * 256 / strip.numPixels()) + strip_state) & 255));
  }
  strip.show();
  strip_state++;
}

void colorWipe(uint32_t color) {
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);

  strip.setPixelColor(strip_state, color);
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c) {
  byte r= ((c & 0xFF0000) >> 16) * brightness;
  byte g= ((c & 0xFF00) >> 8) *brightness;
  byte b= (c & 0xFF) * brightness;
  c = strip.Color(r,g,b);
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, c);    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow() {
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, Wheel(&strip, (i+strip_state) % 255));    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

The functions use the float variable brigthness to modulate the overall brightness of all LEDs. You can set it to every value between 0.0 and 1.0.
The variable strip_state holds the current state of the effect on the strip. It is incremented everytime one of the functions is executed. Reset it to 0 if you want to restart an effect.
You yourself have to declare the variable strip as from the type Adafruit_NeoPixel.
So now you only have to call these function from the typical millis() code (like from the BlinkWithoutDelay example) in an interval, that you chose.


text:
What is wrong with this code?
So I am writing code to control a servo with an RC radio. I am using an Arduino Mega.  I get this error whenever I compile.  I am not that experienced with Arduino so I am probably not doing something right. Thanks for the help!

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Mega or Mega
  2560, ATmega2560 (Mega 2560)"
C:\Users\ethan\Desktop\Periferals_control\Periferals_control.ino: In
  function 'void loop()':
Periferals_control:46: error: expected ';' before '{' token
{
^
exit status 1 expected ';' before '{' token
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

#include <Servo.h>
Servo servo1;
Servo servo2;
//the following are all ~PWM capable ports
int servoElevator_PwmIn = 6; //Elevator Servo
int servoGrabber_PwmIn = 7; //Grabber Servo

//Channels on AT9
int leftStickVertical = 2; //Channel 3
int rightStickVertical = 3; //Channel 7

int elevatorServoStop = 50;

void setup() {

  //pinMode(servoGrabber_PwmIn, OUTPUT);
  //pinMode(servoElevator_PwmIn, OUTPUT);
  pinMode(leftStickVertical, INPUT);
  pinMode(rightStickVertical, INPUT);
  Serial.begin(9600);

  servo1.attach(6);
  servo2.attach(servoGrabber_PwmIn);
}

void loop() {

  int leftStickVerticalPwm = pulseIn(leftStickVertical, HIGH, 25000);
  int rightStickVerticalPwm = pulseIn(rightStickVertical, HIGH, 25000);
  Serial.print(leftStickVerticalPwm);
  Serial.print("\t");
  Serial.print(rightStickVerticalPwm);
  Serial.print("\n");

  if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }
}

  if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }

You cannot have another comparison in an else statement. You might have meant else if in the last clause.
Clarification if you're not well familiar with C/C++: If you have an if statement, it can be followed by arbitrary many else if clauses and at maximum one else clause which will execute when all other conditions fail. For example:
 int a = 10;
 if( a == 9 ) {
       //Executed if a = 9
 } else if( a < 20 ) {
   //If above not executed, this will be executed if a < 20
 } else {
   //This is executed if none of the conditions above hold.
   //A pure "else" does not have a condition and only one may
   //exist in an `if` statement.
 }

you should not provide conditions for " else " statement because it focuses on what action should happen if all " if and else if " conditions are not fulfiiled.


text:
RFID reader code to identify more than one tag
I'm new to using Arduino and I have managed a few changes to this sketch. But I want to check for a second tag if the first one is not correct. I just can't seem to get it to work. I think it would be good if the tag is not a match to ask it to check the next tag and carry on, but I'm not sure how to make this happen.
//RFID Password Typer
//If a matching tag is found, the keyboard types
//CTRL-ALT-DEL, then types the password and presses enter
//Which should log you on to a Windows computer
//Or Lock the computer if you're already logged in

#include <SPI.h>
#include <MFRC522.h>
#include "Keyboard.h"
#include <Mouse.h>

#define RST_PIN 9
#define SS_PIN 10

byte tag[10]={0x64,0xAE,0xDD,0xFC,};
char pswd[]="********\n";      //password, end with just \n
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
  SPI.begin();              //start SPI
  mfrc522.PCD_Init();       //start RC522 module
  Keyboard.begin();         //start USB keyboard
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);     //LED off
}

void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()){ return; }
  if (!mfrc522.PICC_ReadCardSerial()){ return; }
  for(byte i = 0; i < mfrc522.uid.size; i++) {
    if(mfrc522.uid.uidByte[i]!=tag[i]){ return; }
  }
  mfrc522.PICC_HaltA(); //stop tag so we don't get repeats
  digitalWrite(13, HIGH); //LED on so we know we've got tag match
  Mouse.click();
  delay(1000);
  Keyboard.press(KEY_LEFT_CTRL);
  delay(1000);
  Keyboard.releaseAll();
  Keyboard.press(KEY_LEFT_CTRL);
  Keyboard.press(KEY_LEFT_ALT);
  Keyboard.press(KEY_DELETE);
  delay(100);
  Keyboard.releaseAll();
  delay(300);
  Keyboard.print(pswd);
  delay(100);
  digitalWrite(13, LOW); //LED off
}

Please edit your post and format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

What have tried? You are looping through the UID of the card and exit if one of the bytes are not values. (This is by the way a timing side-channel.). You can just add a second for loop to see if it's equal to another constant tag value. For that you should put the "compare two byte arrays of a given size" logic in a function for easy re-use.

here's how I'd do it ... allowing for 4, 7 and 10 byte uid's (which are all possible apparently)
struct tagInfo {
  byte len;
  byte uid[10];
};
struct tagInfo tag[] = { // add your tags here
  // the len is 1, 2 or 3, for lengths 4, 7, and 10
  // you could just use 4, 7, 10 here and not bother
  // with the len * 3 + 1 calculation later
  // the choice is yours, really
  {1, {0x01, 0x02, 0x03, 0x04}},
  {1, {0x02, 0x03, 0x04, 0x05}},
  {2, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}},
  {1, {0x02, 0x02, 0x02, 0x02}}
};
const int numtags = sizeof(tag)/sizeof(struct tagInfo);

Then, your loop
void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()) { return; }
  if (!mfrc522.PICC_ReadCardSerial()) { return; }
  int i; // declare before the loop because we want to check the value after the loop ends
  for (i = 0; i < numtags; i++) {
    byte len = tag[i].len * 3 + 1;
    if(len == mfrc522.uid.size) { // 4, 7, 10?
      if(!memcmp(mfrc522.uid.uidByte, tag[i].uid, len)) {
        break; // found an exact match so stop the loop
      }
    }
  }
  if (i == NUMTAGS) { return; } // no matches
  // all good here - run the rest of your code
}

Got it. Not sure if it's the best way but it works. Thanks for your help.
//RFID Password Typer
//If a matching tag is found, the keyboard types
//CTRL-ALT-DEL, then types the password and presses enter
//Which should log you on to a Windows computer
//Or Lock the computer if you're already logged in

#include <SPI.h>
#include <MFRC522.h>
#include "Keyboard.h"

#define RST_PIN 9
#define SS_PIN 10

byte tag[10]={****,****,****,****,};
byte tag1[10]={****,****,****,***^,};
byte tag2[10]={****,****,****,**^^,};
byte tag3[10]={****,****,****,*^^^,};
char pswd[]="*********\n";      //password, end with just \n
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
  SPI.begin();              //start SPI
  mfrc522.PCD_Init();       //start RC522 module
  Keyboard.begin();         //start USB keyboard
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);     //LED off
}

void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()) { return; }
  if (!mfrc522.PICC_ReadCardSerial()) { return; }
  for(byte i = 0; i < mfrc522.uid.size; i++) {
    if(mfrc522.uid.uidByte[i]!=tag[i]) {
    } else if(mfrc522.uid.uidByte[i]!=tag1[i]) {
    } else if(mfrc522.uid.uidByte[i]!=tag2[i]) {
    } else if(mfrc522.uid.uidByte[i]!=tag3[i]) { return; }
  }
  mfrc522.PICC_HaltA(); //stop tag so we don't get repeats
  digitalWrite(13, HIGH); //LED on so we know we've got tag match
  Keyboard.press(KEY_LEFT_CTRL);
  Keyboard.press(KEY_LEFT_ALT);
  Keyboard.press(KEY_DELETE);
  delay(100);
  Keyboard.releaseAll();
  delay(300);
  Keyboard.print(pswd);
  delay(100);
  digitalWrite(13,LOW); //LED off
}

no, not the best way at all - look at the logic in testing for a match ... work through it on paper, you'll see it is wrong

This is not the logic you want. You are looping through the UID and looking if any of the constant tags have that value in the current place. If you have tag1 = { 0x1, 0x2, 0x3} tag2 = {0x4, 0x5, 0x6} the tag {0x4, 0x2, 0x6} will be accepted although it does not match any tag completely. The other answer is what you'll want.


text:
How to determine the SPIFFS size on an esp8266-01?
I'm confused about my esp8266-01 if they have SPIFFS or not. Is there a way to find it out? If they have, how to get their size?
I've got the following flash id: 0x1440e0.
Example SPIFFS apps keep crashing with wdt reset and lots of dumped hexes.

SPIFFS size is determined by you when you upload the sketch

First you need to know the size of the flash memory attached to esp8266 on your module. Common sizes are 512 kB (4Mbit), 1 MB (8Mbit) and 4 MB. Espressif Flash Download Tool (Windows) or esptool can determine it.
You can choose the size of the SPIFFS in your flash 'layout' by selecting the option in IDE Tools menu. Take one according to for you flash size and size of the files you want to put into SPIFFS.
If you have 1 MB flash on your module and you want to use OTA upload, let flash space for twice a space taken by the sketch.

All the data like WiFi config and binaries go to the flash memory? There is no other dedicated memory for those?

no. esp8266 uses the flash memory like a PC uses a hard-drive

Also, more importantly, I'm getting wdt reset errors with sometimes lots of hex dumps after uploading SPIFFS example apps. I've set the SPIFFS size to 512 (of 1M flash), but not sure if the Flash mode is correct. Any idea? Thanks

did you upload the SPIFFS image with the SPIFFS upload IDE plugin?

I've tried that as well as formatting the SPIFFS using the example code. Not sure what would be a working strategy. I've tried the following among others https://www.pastiebin.com/5ab790f66e9a1

Please have a look that pastebin code I placed. I'm unable to single upload and then run it without getting wdt reset errors. I have erased the esp with esptool prior to uploading it, didn't make any difference.

try some readonly example first. without formating. upload the spiffs from IDE https://github.com/esp8266/arduino-esp8266fs-plugin#arduino-esp8266-filesystem-uploader-

Tried with a different device and it worked. Both have 1M flash but differ in manufacturer. Does this mean the ESP lib doesn't support one?

do you use esp8266 core 2.4.1? the issue is known, but I do not know if it is fixed in the release https://github.com/esp8266/Arduino/issues/4061

I was using 2.4.1, then I removed it and manually installed the latest via git, so that I could apply both patches (not at the same time) from the link you showed. I might retry it as it was really late yesterday, might have done something wrong. Although some guy had no problem with his 001440E0 device which I am having problem with.

erase the flash or upload empty SPIFFS before the next test with the patch

The command with esptool is esptool flash_id and its output will contain something like Detected flash size: 512KB.


text:
Using Due (SAM3X8E) native USB port for programming?
I would like to make my own version of the Arduino Due.
What I can't find the answer to is;
Can I program a blank SAM3X8E using the native USB port from within the Arduino IDE, or do I first need to program some bootloader or similar?
My board will not have the Mega16U2 which is normally used for programming.

Regardless of the answer to that question, it would be extremely unwise to design an ARM Cortex-M series board which did not make the SWD pins available at least on tiny test pads; they are just too useful during early development, and key to hardware-assisted breakpoint debugging (especially if your board ever gets used for non-Arduino purposes).  About 4 via-sized through holes will let you pick them up with wire wrap wire or similar.

I have decided to go down the SAMD21 path and have put a SWD header on my board. I use my Segger to put the Arduino boot loader into the chip and I am good to go.

The SAM3X8E comes with a bootloader in ROM.

Memories

256 to 512 Kbytes embedded Flash, 128-bit wide access, memory accelerator, dual bank
32 to 100 Kbytes embedded SRAM with dual banks
16 Kbytes ROM with embedded bootloader routines (UART, USB) and IAP routines
Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC with 4 Kbyte RAM buffer and ECC

Since this bootloader does all that the Arduino IDE asks of it, and has a freely available cross-platform command-line upload tool (bossac) the IDE just uses that. No need to invent the wheel when the wheel does everything you need and even comes with a tin of axel grease.
While technically it is possible to use your own bootloader in conjunction with the existing one (use the existing one to install yours, and then use yours to upload sketches) it requires in-depth knowledge of both the chip and GCC linker ("ld") scripts to set aside a block of memory for your bootloader to reside in and relocate the compiled code around it properly. Too much work when the bootloader that already exists does what you want.
However other chips either don't have a bootloader (like the M0 in the Feather) or don't have one that works as desired (like the DFU bootloader in the ATMega32U4) so a custom bootloader is used on those.
The IDE itself is pretty dumb. It just has a configuration file that says "Execute this command with these parameters to upload the HEX file". It neither knows, nor cares, what the bootloader at the other end of the connection is, nor how it works. As long as there is a command-line executable to do the work it just hands over to it.

Hi @Majenko, I am not sure if that fully answers the question. Is that boot loader compatible with Arduino IDE?

@gjt211 That is the "bossac" bootloader that the Due uses. The question "is it compatible with the IDE" makes no sense. The IDE has no concept of bootloaders, only configuration files that specify executables to run to install the compiled file into the target. If there is a binary you can execute to interface with a bootloader you can make the IDE run that executable. Regardless: it's what the Due uses, so "yes".

Maybe it makes no sense to you, but for the thousands (millions) of Arduino users that have very little experience, the question makes a lot of sense. To those users (me included) who have no idea what bossac is, or config files that specify executables, let alone where they are or how to obtain them, where to put it if we worked all that out. All we know, select the serial port, then click upload.

@gjt211 It's expected that if you are technically adept enough to consider building your own SAMD based board that at least you understand the basics of the datasheet. Without that basic level of knowledge what are you doing even considering building something as non-trivial as a DUE-based system? ARM is considerably more complex than little AVR chips. You can't just slap one in a breadboard and expect it to work.

I appreciate your comments, but I am a full time professional hardware design engineer with over 25 years of multilayer, high speed, and RF design experience. Building something with a SAMD processor would be one of the simplest designs I have ever done. The design is for a customer, he is an Arduino guy. He wants to know if the board I designed for him will work the same as an original Arduino DUE with respect to the Arduino IDE.

Ok, so it's lack of Arduino knowledge not lack of electronic design knowledge then. Ok. The Arduino IDE is dumb (in more ways than one). It just runs executables to do jobs, including upload via a bootloader. The SAMD chips come with a bootloader in ROM, and a freely available cross-platform command line tool bossac to upload to it. So the IDE just uses that. Why re-invent the wheel when the wheel does what you want?  Other ARM based chips (like the M0 one used in the Feather) don't have a bootloader and need one installing.

I have fleshed out my answer with how the IDE interacts with the bootloader.

Most users that come here have a certain amount of Arduino knowledge but almost zero electronics knowledge. You're kind of the opposite end of the scale, so please forgive the confusion.

Microchips needs some kind of bootloader to be able programmed over USB. Arduino boards cames with default bootloader loaded (from Arduino company at least, net necesarry from Chine, probably without, if you byu just the chip from manufacturer), so on official boards it is all done for you to have aesy life.
Being able to properly communicate over USB is not exactly easy task and there are many different protocols for sending program to bootloader, which is then resposible to put the program at flash memory at proper place and give it controll later.
Also keep in mind, that there are other ways, how to put program in memory and that not all devices using some microcontroler are even meant to be programable by user over it. (For example they may idetyfy themself as keybords, mouses, joysticks and such to computer and be closed to reprogramming by manufactor of such device. Arduino community is only small part of industry, which uses the same chips for totally different tasks).