text:
Switch Control Between Two Different Techniques
I have implemented PID control of a generator governor to maintain a constant RPM using an Arduino Uno. It works pretty well, but there is a tradeoff between stabilty and response time. Using PID values that allow it to respond without oscillation is also about half as fast as the old mechanical governor.
I came up with a plan to use a CT to sense the AC amps and have the Uno rapid the throttle servo to a known value determined manually. Either using a lookup table or an interpolation algorithm, I haven't yet checked the linearity of the amps vs. throttle angle. The idea is to use a table (or interpolation) to get the governor close, and then let the PID fine tune it.
My hangup is that I'm not sure how to switch between lookup control and PID control as needed.
Pseudo-code:
analogRead(AMPS);
myservo.write(table_Val);
somehow_switch_to_PID;
myservo.write(PID_value);

You can use an if condition, checking if you reached the target RPM within the fine tune range.

If I use some method of getting the RPMs close, won't the PID just swing to one extreme or the other trying to adjust the value with no success because the "get close" operation is in control? I mean, the PID is looking at the RPMs and giving an output but that output is being ignored because another operation has servo control. By the time PID is in control, shouldn't the output have gone full tilt trying to make a change, and now will just slam the servo to that erroneous value?

the PID is looking at the RPMs and giving an output but that output is
  being ignored because another operation has servo control.

PID is not something, that happens somewhere in the background without you having any control. On the Arduino it is done in software, so you can totally control it. Why should you run a PID calculation, if you don't use the value? The solution is to simply only do the appropriate calculation depending on the RPM at any given time. No need to do 2 calculations at the same time. I will form that into a code with explanations:
You have 2 ways of calculating the needed servo values:

Your "getting close" method
The PID method

To switch between those methods you need to make a decision based on the RPM. If the RPM is outside of your interval, the first method is used. If it is inside, the second will be used. Decision/conditionals are often wrote with an if else statement. Look at this (not tested) code snippet:
int target_rpm = 700;
int half_interval = 20;
int current_servo_pos = 0;

void loop(){
    current_rpm = analogRead(AMPS);

    if(current_rpm > target_rpm - half_interval && current_rpm < target_rpm + half_interval){
        // Do the PID calculation here and save the result in current_servo_pos
    } else {
        // Do the "getting close" calculation here and save the result in current_servo_pos
    }

    myservo.write(current_servo_pos);
}

I didn't go into detail about the actual calculation, since that is not important here. You may use any calculation, that you like there. For PID you can find libraries, that do the calculation for you, for example here at github.
The code will simply decide based on the RPM, what calculation should be used. If the RPM goes out of the interval for some reason (maybe is was disturbed and lost some speed), it will automatically use the "getting close" method until it is again inside of the interval.
Note: The numbers, that I used here, are arbitrary. You should change them to what ever you need.

Thanks again Chris! I haven't been successful using the PID outside of void loop(). If I place the PID parameters anywhere else, it doesn't respond. I'll get the code currently in use later today. But that's why I asked about the PID calc already having an output. I can write the PID output into anything I want in any function, but trying to call the PID outside of void loop() has been fruitless.

Yes, please add your code to your question. That way I can add more to my answer to help you with that.


text:
expected unqualified id-before '/' token ------ can someone help, please
/* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

/------------------------------------------------------------------------

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
/-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
/-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  deley(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}

Usually the debugger tells you on which line of the program the error is located...

OK, you just had a couple of minor typos.
It's nice to break up your code for readability, but single-line comments comments start with a double slash //, rather than a single.
Also, you had mis-spelled 'delay' in your loop.

This should compile without errors:
/* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

//------------------------------------------------------------------------

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
//-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
//-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  delay(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}

source: Stack Exchange

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

sort: votes


text:
Can´t load a program into my ESP01 using an ArduinoUno
This is my problem,  I´ve been trying to load a program(any program) into mi ESP01 and because I do not have the usb adapter, I decided to use my Arduino Uno to do the work.
This is my first time working with this board (ESP01), and in my search I found that it is important to have GIO0 LOW ,GIO2, RST and in HIGH to upload a program; besides I already have this board into the list that Arduino´s IDE have and I used 3.3v for VCC.  Yet, when I try to upload a program, the IDE wont let me because of this error: esptool.FatalError: Failed to connect to ESP8266: Invalid head of packet (0xF0
The program that I want to try is the HelloServer example.

Thanks for your help!!

what is your question?

the sketch in Uno should not have Serial.begin(). make it simpler by pulling down io 0 all the time why you try flash the esp (remove the switch)

I would not trust breadboard connections for RX voltage divider. you can test it by wiring RX without voltage divider. esp8266 can tolerate 5 V on pull-up current levels used with TTL Serial.

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


text:
local libraries and include dependencies
I'm using PlatformIO in Atom for Arduino programming. I get dependencies error when build. This is my reproduction sample code:
/lib/mylib/mylib.h
#ifndef MYLIB_H
#define MYLIB_H

#include <Arduino.h>

void fn();

#endif

/lib/mylib/mylib.cpp
#include <mylib.h>

void fn()
{
  Serial.println("fn1");
}

/lib/mylib/myclim.h
#ifndef MYCLIM_H
#define MYCLIM_H

#include <Arduino.h>
#include <DHT.h>

void fnclim();

#endif

/lib/mylib/myclim.cpp
#include <myclim.h>

void fnclim()
{
  Serial.println("fnclim");
}

/src/main.cpp
#include <Arduino.h>
#include <mylib.h>
#include <myclim.h>

void setup() {
  // put your setup code here, to run once:
}

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

The above code is compiled without errors. But, if I remove the line #include <myclim.h> in main.cpp, I get the follow error:

Processing pro16MHzatmega328 (platform: atmelavr; board: pro16MHzatmega328; framework: arduino)
--------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/pro16MHzatmega328.html
PLATFORM: Atmel AVR > Arduino Pro or Pro Mini ATmega328 (5V, 16 MHz)
HARDWARE: ATMEGA328P 16MHz 2KB RAM (30KB Flash)
Library Dependency Finder -> http://bit.ly/configure-pio-ldf

LDF MODES: FINDER(chain) COMPATIBILITY(soft)
Collected 17 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <mylib>
Compiling .pioenvs/pro16MHzatmega328/src/main.cpp.o
Compiling .pioenvs/pro16MHzatmega328/lib2cc/mylib/myclim.cpp.o
In file included from lib/mylib/myclim.cpp:1:0:
lib/mylib/myclim.h:5:17: fatal error: DHT.h: No such file or directory

*************************************************************
* Looking for DHT.h dependency? Check our library registry!
*
* CLI  > platformio lib search "header:DHT.h"
* Web  > https://platformio.org/lib/search?query=header:DHT.h
*
*************************************************************

compilation terminated.
*** [.pioenvs/pro16MHzatmega328/lib2cc/mylib/myclim.cpp.o] Error 1

I'd like to know why it is happen. Some times, I need include myclim.h in main.cpp, but sometimes I don't. Why is it happens if DHT dependency is ok?
Thank you!

it depends if the dht library header is first processed in the sketch or in library?

It looks that when dht library is included in sketch, compiling is ok. But, when dht library is only in mylib, a dependency error occur. The path for dht library is the same. I don't know why builder not find dht library when it is included only in mylib.

did you try it in Arduino IDE?

Yes, I tried, @Juraj . I do not have error, including or not myclim.h in main.cpp. But, I note in Arduino IDE output that DHT.h is always compiled, even if myclim.h is not included in main.cpp.


text:
Why am I getting this error- "exit status 1 expected ';' before '{' token "
void setup()
{

  pinMode{13, OUTPUT};

}

void loop() {

  digitalWrite{13, HIGH};

}

Use digitalWrite(13,HIGH); rather than curly brackets, and do the same for pinMode

Why ard you using {} brackets after function name?

Try parentheses instead of curly braces:
void setup() {

pinMode(13, OUTPUT);

}

void loop() {

digitalWrite(13, HIGH);

}

It's funny and nonsense, but pinMode;  {  ...  is formally correct. That makes error messages hard to understand.

The solution is already give, but here an explanation:
{ and } are used to group multiple statements together, either for a function, if, while, for loop and so on.
E.g.
if (i == 1)
{
  // Statement 1
  // Statement 2
}

or a function
void f()
{
  // Statement 1
  // Statement 2
}

( and ) are used to specify parameters:
void f(int a, int b)
{
  ...
}

A function with two parameters.
When calling this function, the following is used:
f(1, 2);

Calls function f with a = 1, and b = 2.
So in general: { and } is for grouping statements, ( and ) for parameters.

{} is also used in initializer syntax, which might lead to other confusing error messages for incorrect code.

@AnT True, I didn't make a complete list to make my answer not overly difficult for beginners. {} is also used for begin/end of a class as other example.

I made same mistake when I started working with C
you have
pinMode{13, OUTPUT};

which should be
pinMode(13, OUTPUT);

the curly brackets are basically for Start and End of a function.
Bill


text:
Stop getting values from arduino after some time
I have a strange problem, I have Arduino UNO/MEGA and I need to get Gyro sensors's data and I want to see the data in the serial monitor. Seems like a simple task, I wrote a simple C program which collects data from Arduino through serial monitor I can see the data. Everything is working for few minutes and after that, it stops.
#include <Wire.h>
#include <MPU6050.h>
#include <Encoder.h>

MPU6050 mpu;
Encoder myEnc(11, 12);

long newP=0, newPosition=0, newPo=0, oldPo=0;//Encoder values

unsigned long currentTime, previousTime, elapsedTime;
double error, lastError, output, setPoint, cumError, rateError, kp=40, ki=0, kd=0;
// Timers
unsigned long timer = 0,timera=0;
float timeStep = 0.01;
//Yaw values
static double yaw = 0;

const int motor11=6;//LEFT MOTOR FW
const int motor12=7;//LEFT MOTOR BK
const int motor1pwm=3;
const int motor21=8;//RIGHT MOTOR FW
const int motor22=9;//RIGHT MOTOR BK
const int motor2pwm=5;

int thres1=120;//PWM Values
int thres2=120;

int flag1=0, flag2=0, flag3=0, flag4=1, flag5=0;

int x=0, y=0, save=0;

void setup()
{
    Serial.begin(115200);
    // Initialize MPU6050
    while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {
      Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
      delay(500);
    }
    mpu.calibrateGyro();
    mpu.setThreshold(1);

    pinMode(motor11, OUTPUT);
    pinMode(motor12, OUTPUT);
    pinMode(motor21, OUTPUT);
    pinMode(motor22, OUTPUT);
    pinMode(motor1pwm, OUTPUT);
    pinMode(motor2pwm, OUTPUT);
}

void loop()
{
    newP = myEnc.read()/4;
    newPo=newP-newPosition;
    Serial.print("Encoder ");
    Serial.println(newPo);

    Vector norm = mpu.readNormalizeGyro();
    yaw = yaw + norm.ZAxis * timeStep;

    if(abs(newPo)<=600) //Straight line motion
    {
        if(abs(newPo)%60==0)
        {
          if(flag3==0)//Increase x- coordinate
          {
            if(save<abs(newPo))
            {
              if(abs(newPo)>abs(oldPo))
              {
                x=x+1;
                Serial.print("X= ");
                Serial.println(x);
                Serial.print("Y= ");
                Serial.println(y);
                if(x==10)
                {
                  flag3=-1;
                }
                save=abs(newPo);
              }
              else if(abs(newPo)<=abs(oldPo))
              {
                save=abs(oldPo);
              }
           }
         }

          else if(flag4==0)//Decrease x-coordinate
          {
            if(save<abs(newPo))
            {
              if(abs(newPo)>abs(oldPo))
              {
                x=x-1;
                Serial.print("X= ");
                Serial.println(x);
                Serial.print("Y= ");
                Serial.println(y);
                if(x==0)
                {
                  flag4=1;
                }
                save=abs(newPo);
              }
              else if(abs(newPo)<=abs(oldPo))
              {
                save=abs(oldPo);
              }
            }
          }
        }

      if(flag1==0)//Set Point
      {
        setPoint=yaw;
        Serial.print("Set Point= ");
        Serial.println(setPoint);
        flag1=-1;
      }

      if(flag2==0)//slow start
      {
          digitalWrite(motor21, HIGH);
          digitalWrite(motor22, LOW);
          analogWrite(motor2pwm, 75);
          digitalWrite(motor11, HIGH);
          digitalWrite(motor12, LOW);
          analogWrite(motor1pwm, 75);
          delay(500);
          flag2=-1;
      }

      timer = millis();
      currentTime = millis();
      elapsedTime = currentTime - previousTime;
      error = setPoint - yaw;
      cumError = cumError+(error * elapsedTime);
      rateError = (error - lastError)/elapsedTime;
      output = kp*error+ki*cumError+kd*rateError;
      lastError = error;
      previousTime = currentTime;

      if(error>0.001)
      {
        Serial.print("1. YAW= ");
        Serial.println(yaw);
        digitalWrite(motor11, HIGH);
        digitalWrite(motor12, LOW);
        analogWrite(motor1pwm, thres2);
        digitalWrite(motor21, HIGH);
        digitalWrite(motor22, LOW);

        if(thres1+output<255)
        {
          analogWrite(motor2pwm, thres1+output);
        }

        else
        {
          analogWrite(motor2pwm, 255);
        }
      }

      else if(error<-0.001)
      {
        Serial.print("2. YAW= ");
        Serial.println(yaw);
        digitalWrite(motor11, HIGH);
        digitalWrite(motor12, LOW);

        if(thres2-output<255)
        {
          analogWrite(motor1pwm, thres2-output);
        }

        else
        {
          analogWrite(motor1pwm, 255);
        }
        digitalWrite(motor21, HIGH);
        digitalWrite(motor22, LOW);
        analogWrite(motor2pwm, thres1);
      }

      else if((error>-0.001)&&(error<0.001))
      {
        Serial.print("3. YAW= ");
        Serial.println(yaw);
        digitalWrite(motor11, HIGH);
        digitalWrite(motor12, LOW);
        analogWrite(motor1pwm, thres2);
        digitalWrite(motor21, HIGH);
        digitalWrite(motor22, LOW);
        analogWrite(motor2pwm, thres1);
      }

      oldPo=newPo;

      flag5=0;
      delay((timeStep*200) - (millis() - timer));
  }

    else if(abs(newPo)>600)
    {
      digitalWrite(motor21, HIGH);
      digitalWrite(motor22, LOW);
      analogWrite(motor2pwm, 90);
      digitalWrite(motor11, HIGH);
      digitalWrite(motor12, LOW);
      analogWrite(motor1pwm, 90);

      delay(300);

      if(flag5==0)
      {
        y=y+1;
        flag5=-1;
      }

      if(y%2==0)
      {

        while((abs(setPoint)-abs(yaw)<48)&&(yaw<0.2))
        {
          timera=millis();
          Vector norm = mpu.readNormalizeGyro();
          yaw = yaw + norm.ZAxis * timeStep;
          Serial.print("Turning Yaw= ");
          Serial.println(yaw);
          digitalWrite(motor11, LOW);
          digitalWrite(motor12, LOW);
          analogWrite(motor1pwm, 120);
          digitalWrite(motor21, HIGH);
          digitalWrite(motor22, LOW);
          analogWrite(motor2pwm, 120);
          delay((timeStep*2000) - (millis() - timera));
        }
        flag3=0;
      }

      else if((y+1)%2==0)
      {
          while(abs(yaw)-abs(setPoint)<50)
          {
            timera=millis();
            Vector norm = mpu.readNormalizeGyro();
            yaw = yaw + norm.ZAxis * timeStep;
            Serial.print("Turning Yaw= ");
            Serial.println(yaw);
            digitalWrite(motor11, HIGH);
            digitalWrite(motor12, LOW);
            analogWrite(motor1pwm, 120);
            digitalWrite(motor21, LOW);
            digitalWrite(motor22, LOW);
            analogWrite(motor2pwm, 120);
            delay((timeStep*2000) - (millis() - timera));
          }
          flag4=0;
          if(y==5)
          {
            while(true)
           {
              digitalWrite(motor11, LOW);
              digitalWrite(motor12, LOW);
              analogWrite(motor1pwm, 70);
              digitalWrite(motor21, LOW);
              digitalWrite(motor22, LOW);
              analogWrite(motor2pwm, 30);
            }
          }
      }

      digitalWrite(motor11, LOW);
      digitalWrite(motor12, LOW);
      analogWrite(motor1pwm, thres2);
      digitalWrite(motor21, LOW);
      digitalWrite(motor22, LOW);
      analogWrite(motor2pwm, thres1);

      flag1=0;
      flag2=0;

      newPosition = myEnc.read()/4;

      flag5=0;
      save=0;
      oldPo=0;

      delay(2000);
    }
}

This code is supposed to calculate a distance travelled in a line using encoder (PID algorithm implemented using Gyroscope data for straight motion) after reaching desired position, machine takes a U-Turn.
It stop for a second after taking the U-Turn and then starts straight motion again. The problem I'm facing is that the gyroscope readings stop randomly while machine taking the turn. Due to this, the machine keeps rotating about that point without stopping.
The serial monitor just stops displaying the reading. This does not happen every time, and it is very random.

Only some will look through all that code.  Suggest to start simple (rip out all the if() code) and keep adding back in code until it stops working.  First prove to us it is or is not a communications problem.  Then go from there.

Oh, should add.  It is a common problem that high current items such motors will cause the processors to reset / act unexpectedly.  Power your motors off a different power source WRT to the processor's power source.

@st2000 what should I add? Is there any way to solve this problem? Yes, tried with both way when we are connecting a different power source, common ground connected, also tried with the power source.

I think the problem has something to do with poor implementation. Even though I didn't go through all the code I found one that will cause the described behaviour: if y==5 the program will be stuck in the while(true) loop which contains no break condition. There might be other mistakes but the symptoms you descibe are quite vague and the code is so long... you should try to provide us with a minimal example

if y==5 the program will be stuck in the while(true) loop which contains no break condition. It is not even reaching up to this case. I have checked this case with a simple U-turn and stop, it is working fine multiple times. I am checking small case I will update and reduce code length


text:
Servo not moving
I have connected my servomotor (MG996R) to my L293D motor shield, which is connected to an Arduino Uno R3 Board.
I use 4x AA 1.2V NiMH batteries to power the shield, and a regular 9V battery to power the Arduino separately. I've removed the jumper wire on the shield.
I've tried uploading all the example codes I could find, multiple times, yet none of them work. The servomotor simply doesn't move at all.
Is there anyway I could see if my servomotor is broken ?
Maybe the wiring is wrong, but I don't think so. Orange is for signal, Red is for + and Brown is for GND.
Could someone help troubleshoot the problem ? Thanks !
PS : here is the example code I use
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

You said that you are using L293D shield. What is pin 9 then? And why are you trying to use <Servo.h>? Your code is intended to work with servos attached directly to Arduino. It will not work with servos attached to some external shield. Your shield is supposed to have its own library/protocol for controlling stuff attached to it.

Pins 9 and 10 are the ones used to control the Servo pins on the L293D.
I've just tried to plug in another servomotor and it works just fine when I use pin 10, which matches the "SERVO1" pin on the L293D.

You have two problems
Both of them is related to your power supply :

1st, max. Voltage requirement for your servomotor is 6 volts, not 9 volts

2nd، your batteries are weaker than servo's need.
Your servomotor need 2.5 Amps. In the max. Torque.

So, over-voltage and not enough current is your fault
(According to 996R servomotor datasheet).
Change your power supply by suitable one


text:
20x4 LCD Error. 8 black boxes to the left on row 3 and 4
20x4 I2C conected LCD. 8 black boxes to the left on row 3 and 4.
What could the problem be?

Add the (relevant) code

What Arduino? Due or Mega? My guess is that your i2c wires are too long and/or there is a timing issue. Is this the code? https://github.com/johnrickman/LiquidCrystal_I2C/blob/master/examples/HelloWorld/HelloWorld.pde

the picture does not show black boxes ... they look white or light blue to me

@MikaelPatel. im running on a Mega 2560. Yes it is that code. but i have tried diffrent code. same everytime. I dont have shorter Wires, but i have tested extended them to over 100 cm. No diffrence at all to my 20 cm cables. So mayby the length of the cables are not the issue? Mayby its just a bad lcd?

Ok so it is not the wire length. It is the first 8 characters per line and these do not map to the sketch. Or have you changed the sketch? Please add the sketch you are running.

@MiaelPatel  ok my latest code has the same problem as the LiquidCrystal_I2C example code. i wrote to the lcd is a simple calculator. Here is that code. (Im sorry the coments are in swedish. https://create.arduino.cc/editor/halt1/a2917809-ce6d-4dc7-8962-28e274b8fe9b/preview


text:
Problem in defining a variable as multiplication
I have a simplest code to turn on and off a led. The variable holding time definition is onTime, using Arduino Nano.
When it is written as: onTime=1000*30, all is good.
When onTime is greater than this, if loop does not return true value when needed ( see code below ).
BUT when writing it implicit as onTime=60000, and not onTime=1000*60 code run OK.
I'm guessing that value of 30*1000 - has to be something with int value.
CODE:

int enbPin = 10;
bool onState = true;
unsigned long onPeriod = 60*1000; // <----
unsigned long startTime = millis();
void setup() {
  // put your setup code hee, to run once:
  Serial.begin(9600);
  pinMode(enbPin, OUTPUT);
  digitalWrite(enbPin, onState);
  Serial.println("START");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (millis() - startTime >= onPeriod ) {
    onState = !onState;
    startTime = millis();
    digitalWrite(enbPin, onState);
    Serial.println(onState);
  }
}

your code does not have a variable named onTime

unsigned long onPeriod = 60ul * 1000;
ul makes 60 to unsigned long and then the calculation has place for result.
without ul the constants and the result are int and it overflows

thank you for your quick answer. 1) when using NodeMCU, without ul - result was OK, why is that ?  2) to define 1hr should I write 60ul*1000*60 ?

The NodeMCU is a 32-bit chip. int is 32 bits and can hold a massive amount more (same as a long). 2) Sure. Any one (or all of) the numbers can have ul - as long as at least one does.

Thank you very much for comprehensive answer

Juraj already told you how to fix this.
Some more info on why:
(Edited)
By default, the C/C++ compiler uses the smallest size that can hold the specified value for integer constants, starting with the "native" integer size on the platform it's compiling for. For a 16 bit device like an AVR-based Arduino, an int is 16 bits. A signed 16 bit int can hold a value from -32768 to 32767.
(As pointed out by AnT in his comment, if you declare an integer constant of 60,000, the compiler automatically promotes it to the larger long int type.)
It evaluates expressions assuming int constants are of type int unless their value doesn't fit in an int. If you try to do math with an int and a long int, or store the results of int math into a long, the int gets "promoted" to the larger data type first.
In your expression:
unsigned long onPeriod = 60 * 1000;

The compiler first evaluates the right side of the expression, 60 * 1000, as (int)60 * (int)1000). Since it treats both parts of that expression as 16 bit signed ints, it does the multiplication using 16 bit integer math. The result of the multiplication is 60,000, which is too large to store in a signed int, so the intermediate calculation overflows.
It then tries to store the result to an unsigned long. It promotes the now-overflowed value to an unsigned long and stores the (garbled, and thus wrong) result into the unsigned long destination.
By either expressing either or both values as an unsigned long constant, or casting one or both of them to an unsigned long type, the compiler then promotes both values to unsigned longs before doing the math on them, so the result doesn't overflow before being assigned to the destination variable.

"By default, the C/C++ compiler uses the "native" size for integer constants". This is a bit misleading. For an unsuffixed decimal literal, the compiler will automatically chose the smallest type from int -> long -> long long sequence that can accommodate the constant. In this case int is chosen just because the constants fit in it. And int happens to be a 16 bit signed type on this platform. It is more appropriate to say that the compiler uses "native" size for int type, not for integer constants. For example, 2 * 40000 would not overflow, even though 80 * 1000 does.

@AnT. Good point. I struggled a bit with how to word that. Your wording is more accurate.


text:
HD44780 DDRAM addressing on the second line
I write bytes to HD44780 display DDRAM to display characters and it works weird on the second line. I use 16x2 model and I write "0123456789" string from address X on.
According to the datasheet:

In a 2-line display, the cursor moves to the second line when it passes the 40th digit of the first line.

So when I set X to 40, the string appears from the beginning of the second line. So far so good. But when I change X to different values, this appears on the second line:
X=39 ... 123456789
X=40 ... 0123456789
X=41 ... 0123456789
...
X=47 ... 0123456789
X=48 ... 89
X=49 ... 789
...
X=56 ... 0123456789
X=57 ... 0123456789
...
X=64 ... 0123456789
X=65 ...  0123456789
X=66 ...   0123456789

Since address X=64 it works as expected, so increasing X by one shifts the string to the right by 1 character. The datasheet also says

However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH (79). When N is 1 (2-line display),
  AAAAAAA can be 00H to 27H (39) for the first line, and 40H (64) to 67H (103) for the second line.

So the second line starts at 40H (64), not 40, it seems. Is it a confusion? What is the idea between address 40-64? It would make sense if the second line was address 28H-40H. I don't see the explanation in the datasheet. Also, how the DDRAM works for 20 characters per line and 4 lines displays?

Your confusion here is mixing "digit" and "byte". The two are not the same.
HD44780's can never have more than two rows. If you look at the block diagram you can see there are 16 "COM" connections. Those are the rows of the characters - 8 per line. That gives at most 2 lines of text.
20x4 displays are actually 40x2 displays but sliced in half and stacked. The 21st character of the first line is actually the first character of the 3rd line.
These two lines are split into two separate blocks of memory. One starts at 0x00 and the other at 0x40. The two blocks are pretty much completely separate.  There is nothing of any interest to you between 0x28 and 0x3F. In fact that memory may not even exist - however those addresses may map to other addresses within memory. This will purely be an artifact of how the memory is addressed internally.
For simplicity of decoding the addresses the two blocks of memory are distinguished purely by the most significant bits of the address. The lower bits, then, will always be the same for the same location in both lines of text. That is, for the same horizontal character position on the display the first row (COL0-COL7) will have the same address in memory as the second row (COL8-COL15) except the most significant bits.
Since the HD44780 operates in blocks of 40 bits (8 characters, 5 bits per character) for its displays and uses "extension modules" to give each extra block of 8 bits (which is why you get 8, 16, 20, etc widths) having the two lines of text with truly consecutive memory addresses would make decoding the addresses needlessly difficult. So they don't.
If you take an example of the 3rd character horizontally on the display the pixel address in memory will be (note: this is the pixel address, which is 5x what the character address would be after the data has been generated from the internal character set):
Line 1: 0x02 = 0b00000010
Line 2: 0x42 = 0b01000010

Since the memory itself is 80 bytes and designed to be no more than 40 characters wide with 1 or two rows, there necessarily has to be a dead zone between the blocks of addresses. If the addresses were completely contiguous, so that the first character of the second row (character 40) was the 40th address in memory, the memory addresses would look like this:
Line 1: 0x02 = 0b00000010
Line 2: 0x2a = 0b00101010

Mapping those two addresses to the signals COM0-COM7 and COM8-COM15 would be considerably harder and take far more complexity in the design of the chip - which the manufacturer certainly doesn't want.
It is far simpler to add a little bit of logic into the cursor control which says "If the cursor moves from position 39 to 40 then set the memory address to be 0x40".
So when writing successive characters to the display the cursor logic hides the segmented memory from you. But if you are directly manipulating that segmented memory then you have to take that segmentation into account.

I see, I skipped the talks about SEG and COM pins as blackbox and jumped to the instructions part. Now it is clear.


text:
Use ATTiny as a battery-backed RAM?
So, I found an interesting article the other day, and I'm trying to build a project that could benefit from a battery-backed memory (no wear limits, but keeps data over power cycling). The article lists how an extremely small current from an LED (acting as a photocell in the lit room) accidentally powered the AVR during a RAM-endurance test.
But, what if this is done on purpose with a battery?
(Article here: https://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/)
The problem with this idea (since the RAM can already be backed up, as shown in the article, though the author does not seem to have considered this) is that I need a way to keep an array of memory ignored by the C initializer. It would be the height of hilarity to have the memory survive the power-off event only to be nuked by the chip's powerup reset code. The listed example at that article would work, for the first requirement, but would break almost anything else I might try to do (since it overrides the entire initializer). (Comment on the reset issue: https://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/#comment-598)
Also, assuming I tried this, would I simply damage the pin rather than provide power? I plan to use a pin continually set to input attached to the positive side of a lithium coin cell, with a common ground. In theory, powering the AVR (and I think at any voltage) through the VCC pin would cause the chip's diodes to disconnect the battery, but if it's unplugged, the core would receive enough power to keep the RAM alive.
Of course, my question is whether it would instead stupidly try to keep the core running when power is disconnected (in the original article, the nanowatts from the LED couldn't do that, so it's forced to shut down, but I don't know if this is solely due to power limits or if it would shut down the main systems if there's no connection over VCC). In this case, it might try to draw more than the 1mA rating over that parasitic supply, and try to power the entire chip when I don't want it to (thus frying the clamping diode or something equally bad).
I wonder if it would be possible simply to put a large resistor (10K? 1M?) in series with the battery in this case? That would automatically limit the supply to less than 1mA.

You're mad. Just use an NVSRAM chip. https://www.microchip.com/wwwproducts/en/23LCV512

Re “keep an array of memory ignored by the C initializer”: just add __attribute__((section (".noinit"))).

I probably am. But I'm trying to avoid purchasing stuff (and its shipping times) for now. It does seem to work though, so thank you, Edgar. This is actually fairly awesome, in the fact that it can be done, in a "Oh, how is that even a thing?!" fashion...

@EdgarBonet - use the Answer box to answer, please. People are not supposed to look in the comments under the question for the answer. Then it can be accepted and you can get some rep. :)

Please write an answer to this and describe, how you did it. That sounds very interesting, though somewhat mad XD

this is not an Arduino question

Why would you want to depend on zombie ram, if you can just put the ATTiny in deep sleep mode? The ATTiny is able to sleep for years on a single coin cell. Use a diode to connect VCC to the Vcc-pin of the ATTiny. Use another diode to connect the battery to that same Vcc pin. Connect VCC (via a resistor) to the interrupt pin of the ATTiny, so if can see if it's running on battery, or not.

To the above two comments, I'm trying to use an ATtiny that's already in my project as a peripheral (I2C slave and rapid data-sampler) to store data as well. I can't simply put it in sleep mode because it needs to communicate with other components, which would either drain the backup battery faster or require isolating its backup power supply from the main rail. My question was also mostly about the software part of the design (and to a lesser extent chip behavior), which should probably count as Arduino more than electronics.

Expanding on my previous comment...

I need a way to keep an array of memory ignored by the C initializer

You can achieve this by instructing the compiler to store the array in
the “.noinit” memory section:
int my_array[ARRAY_LENGTH] __attribute__((section(".noinit")));

Your array will end up sitting somewhere between the .bss and the heap
(if any), and will not be touched by the __do_clear_bss routine from
the C startup code.

my question is whether it would instead stupidly try to keep the core
  running when power is disconnected

Most likely. In order to avoid that, I suggest you enable the brown-out
detection by setting the BODLEVEL fuses. This feature of the
ATtiny is specifically meant to prevent the CPU core from running if the
supply voltage is below some configurable threshold.

For anyone wanting to know further how I implemented this, I did set the BOD fuse on my device. Still, not wanting that sort of fun (referring to having the chip try to actually run via the backfed power) to happen at all, I wired a 1M resistor in series with the supply backfed through the pin (which was set to INPUT in all cases. HIGH would result in attempting to charge the backup battery, and LOW may well sink the input current and negate the benefits) in an effort to force the current to be high enough to power the RAM but too low for it to run. It also makes sure that too much current cannot flow through the pin.
My results were somewhat inconsistent, and it doesn't help that the device can actually end up powered by whatever indicator LED is added to show that it worked!
Still, there's a good chance that this can be used as an NVRAM if the code is written for it. As for that, just store an array with the values, and write onReceive and onRequest code to index that and send it back out!
Fair warning: If the power bus is connected to other components, the AVR won't keep its memory. Use a diode to prevent power from escaping.


text:
Understanding MOSFET parameters - Dimming/Switching LED strip
I'm trying to create a dimmable/ switchable 12v LED strip using an Arduino board and a MOSFET. Many tutorials can be found doing so such as this youtube link.
I've bought a LM317T before I had any substantial knowledge regarding MOSFETs. Trying to understand using some tutorials ( each one used different MOSFET ) made it partialy clear what parameters to look for in such project mainly using this link, but some left in the dark - and this is the reason for this post ( and to understand why my MOSFET is not suitable ).
I'll compare with one suggested, FDC855N
1) It has to be "Logic Level" MOSFET, meaning Vgs has to be 5v: from what I understand, 0v at the gate you get 0v at the drain and at 5v at the gate you get maximum Vsource. it is correct ?
1a) FDC855N Vgs's value is +/- 20v, how is it Logic Level ? will Vdrain @Vgs=5v will be different when @Vgs=17v ?
1b) Why in FDC855N Vgs have 2 values when Rds(on) is noted?  one is 10V and other is 4.5v ?
2) Vgs(th) stands for minimal voltage needed for current flow at to drain. it is correct ?
2a) why is it noted as @Vgs=Vds ?
3) why Rds(on) is important for ? only for power dissipation purposes ?
I'll be glad to have answers for those question in comparison to the 317T MOSFET, since 317T datasheet has a different terminology :(
Appreciate any help,
Guy

Why are you mentioning LM317T in the same sentence as MOSFET? It's adjustable linear voltage regulator. And about the voltages: gate is insulated from D-S channel by really tiny insulation layer with breaking voltage somewhere just over maximum voltages between G-S or G-D (doesn't matter which one). That also means gate has its capacity. Thats the only current to the gate - charge or discharge gate.

@KIIV - is it not a MOSFET ??

No, LM317T is not a MOSFET.

@KIIV - OK, so it is not :) can you please explain parameters not in comparison to 317

you need mosfet that is fully open with Vgs=5V (most arduinost are 5V). 1a) 20V is maximum voltage between gate and source. Higher voltage may destroy the insulation and whole transistor.

1b) Rds(on) is not only one nor two values. It's a function of Ids and Vgs. 2) Vgs(th) I'm not sure about this one, it might be voltage the transistor starts opening. It's voltage, only current you'll see is current needed to charge/discharge the gate capacitance. 3) yes, it's really huge difference if you have 10A on 20mOhms and 100mOhms. The first gives you voltage drop 200mV and therefore 2W of power dissipation and the second 1V voltage drop and 10W power dissipation (voltage drop times current).

regarding 1 - so even though 20v may be applied, 5v will supply max Vsource ?

@KIIV would you post it as an answer ?

MOSFET aren't binary devices. They aren't just ON or OFF. Think of them like water taps. Vgs(th) is the voltage at with the mosfet starts to turn on. A bit like how much you have to turn a tap before it starts dripping. To turn it on more, you require a higher voltage. The amount of water flow also depend on what's attached to the tap. Like for example a dripper hose, sprinkler, or a kinked/blocked hose.

2a that just what they used during their measurements. That the downside of those datasheets. Sometimes the voltages or currents you use in your applications aren't specified in the datasheet. You'd have to interpolate from the values that are specified. Sometimes you can use the graph to lookup your case.

3 indeed. The lower the Rds(on), the less heat is being generated. This mostly applies to high current loads. This resistance will also generate a voltage drop. The voltage across the load therefor gets (a bit) lower. Depending on the application, this could have unwanted effects.

First of all, the LM317 and the are FDC855N different types of devices.  The LM317 is a voltage regulator whereas the FDC855N is a discrete MOSFET.
A MOSFET will act as a fast switch allowing you to control the LED's brightness using Pulse Width Modulation.
For what you're trying to do, you can think of the MOSFET as a voltage-controlled switch.  If the voltage between the gate and source (Vgs) is greater than the threshold (Vgs(th)), then the current will flow from the drain to the source (Ids).
1) Yes, anything over the typical Vgs(th) of 2.0V, will turn on the switch and cause current to flow; you need to provide a voltage across the drain and source (Vds).
1a) 20V is the maximum rating of Vgs, if you applying anything greater, you'll damage the device.
1b)  In reality, the MOSFET is more complicated than just an on/off switch.  The gate to source voltage (Vgs) determines how hard the switch is turned on, so increasing Vgs will turn the switch on harder and reduce the resistance (RDS(on)) between the gate and source.
2) Yes, this is essentially correct.  The relationship follows a curve and Vds(th) represents an inflection point.  This plot from page 3 in the datasheet shows the curve for different temperatures.  You can see that the 25C line is basically zero until Vgs reaches about 2.75 volts and then it increases rapidly.

3) RDS(on) is the resistance between the drain and source when the MOSFET is on.   You can treat the drain to source path like a resistor and use RDS(on) to determine the power dissipation.  For example if your RDS(on) were 0.1 ohm and the current through the drain is 1.5A, then you would be dissipating I^2*R = (1.5)^2*(0.1) = 0.225 , which is below the maximum allowable steady-state power dissipation of the device (Pd) of 0.8 W.


text:
Sending a union from Arduino via serial communication and parsing it in python
I want to send a union from Arduino to a python script running on a pc, and I want to parse the received union. I have read lots of topics online but I am stuck on how to do it in the most efficient way.
Specifically, the union contains a struct of a string containing a sensor name, and a 32 bit integer containing a sensor value.
I use the union as I understood is one of the best ways to deal with binary struct data as the ones I want to send.
Here my Arduino code

int32_t analog_input0 = 0;

// Variables to send data
struct serial_message {
  char sensor_name[20];
  uint32_t sensor_value;
};

union serial_message_union {
   serial_message ser_msg;
   uint8_t serial_message_bytes[sizeof(ser_msg)];
};

union serial_message_union ser_msg_u;

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

void loop() {
  analog_input0 = analogRead(0);
  strcpy(ser_msg_u.ser_msg.sensor_name, "analog_input0");
  ser_msg_u.ser_msg.sensor_value = 100;
  Serial.write(ser_msg_u.serial_message_bytes, sizeof(ser_msg_u.ser_msg));
}

Here my python code:
import serial
ser = serial.Serial('/dev/tty.usbmodem1225061', 115200, timeout = 2)

while True:
    if(ser.in_waiting > 24): #I set 24 because the message is composed by 20 char + 4 bytes for the uint32_t value
        incoming_data = ser.read(24)
        print('Incoming data: "{}" '.format(incoming_data))

# Here I want to parse the incoming data, where the first
# 20 bytes are the sensor name and the last 4 bytes are the sensor value

Can anyone suggest how can I proceed? Do you see any error/bad software practice so far in my code?

what is the question?

First question: is my code correct so far? Second question: how can I proceed from there? Once I received the data in the variable incoming_data (assuming that I am doing it right) how can I parse it in the way that allows me to have a variable containing the first 20 bytes and a second variable containing the last 4 bytes?

Try your code and then let us know what's the issue you had faced with clear definition of issue.

Why are you using a union? Why not just cast serial_message to uint8_t?

if(ser.in_waiting > 24): - don't you mean >= 24?

thanks, yes, it is >= 24. Could you please give me an example with code about what you intend when using the casting to uint8_t?


text:
Sizes of the original ESP32-DevKitC-32U Wifi board
I know that this topic does not apply to Arduino, but for me it is important to find a solution to the problem. I know the consequences.
I'm creating a pcb board into which the original ESP32-DevKitC-32U module will be inserted. I can not find the original dimensions of the board, in particular the distance between the contact rails. The site espressif has a small description.

27.9mm is indicated here. It is not clear to me, is this the full width of the board or the distance between the contacts?
What I want to do:

It is very important for me to find out the correct dimensions of the original board. Maybe someone has such a board and can measure this size?

The distance of the headers is breadboard and perfboard compatible for 0.1" (2.54 mm) pin standard. 25.4 mm is 10 rows.

I am taking a class and the instructor used a DEVKITC V4, which on a standard breadboard, plugged into columns b and i.  The DEVKITC that I ordered from Mouser plugs into columns b and j.  So one is a pin-to pin width of 25.4 mm and the other is 27.9 mm.  It seems that the newer DEVKITC V4 is 27.9 and is very difficult to work with on standard breadboard.  PITA!


text:
Split serial monitor output to only save part of the output
This is the output i get from the serial monitor from using a HM10 in . How could i go about splitting the data using arduino uno.  I only want to save the last 12 digits before the :- (4CAA0DE091B7) for it to then be in a format to send as an SMS using a GSM module
OK+Set:1OK+Set:1OK+RESETOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-073OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-042OK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-081OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-079OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-059OK+DISC:00000000:00000000000000000000000000000000:0000000000:7D2A86B2A8CD:-082
OK+DISCEOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-073OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-079OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-089OK+DISC:00000000:00000000000000000000000000000000:0000000000:0CF98919DB7C:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-041OK+DISC:00000000:00000000000000000000000000000000:0000000000:56
OK+DISISOK+DISC:00000000:00000000000000000000000000000000:00000OK+DISISOK+DISCEOK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-080OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-081OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:0CF98919DB7C:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-070OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-077OK+DISC:000
OK+DISCEOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-075OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-076OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-078OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-044OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-059OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:7D2A86B2A8CD:

implement a circular buffer of say 30 characters.
clear the circular buffer
read into the circular buffer, char by char
when the last 13 characters in the buffer are: :4CAA0DE091B7 Then the prior 12 characters are the data of interest


text:
NRF24 CE and CSN connections without I/O pins easily accessible
I want 2 Arduinos communicating to each other, but only in one direction.  Arduino A = tx  and Arduino B = rx.
I have this working fine connecting CE and CSN on each NRF24 to pins 4 and 5 on each Arduino and using the nRF24L01 library.  No problem.
Since Arduino A will always ONLY be transmitting and Arduino B will always ONLY be receiving, can I do this with CE and CSN instead:
Arduino A --- put CSN to GND  and put CE to 3.3V
Arduino B --- put CSN to 3.3V and put CE to 3.3V
As to why?  This would simply help me interface the NFR24 to existing custom PCB's I've made which have no easy access to I/O pins.  My PCB's do have easy access to MISO, MOSI, and SCK.

No, you really do need the CE pin for both TX and RX modes.  See the following excerpts from the nRF24L01 datasheet.  They work practically the same for nRF24L01+:

It seems the CE pin is only used for TX, or to put it into standby. I think you can just connect it to VCC.
The CSN is required for SPI.
PS this RF24 library supports using the same pin for both CE and CSN. You'd have to define RF24_TINY for this to work.


text:
What type of power supply is the Arduino Due’s 5v pin and what is its current?
I’m looking to use a Futaba Servo with my arduino Due and was told it requires a “high current 5 volt supply” and I don’t know much about current so excuse my arrogance.
I know the arduino Due has a 5 volt pin. But what type of power supply is it? (Linear power supply, switching power supply, etc.) and how much current does it provide? If I get this information to my instructor he can tell me if it will suffice.
Thank you!

An Arduino should not be used as a power supply for a servo. The 5V pin is connected to the the 5V supply of the USB connector, OR to the output of a step-down buck regulator converting the DC barrel jack to 5V.
None should be considered "high current" for servo or motor use.
Most PC USB ports will max out at 500mA current output unless the device connected asks for more from the PC. The Arduino does not.
The buck-converter controller chip is a LM2434, whose datasheet specifies 1A maximum output current.
Driving motors or servos will draw enough current, intermittently, to overload either of those and will likely cause the Arduino to reset.
If you need to power a motor-type device, power it separately from the control signals. Power should go from the source to the motor, and the control signal from the Arduino to the servo, making sure to connect the ground wires of all to each other (motor, Arduino, power source).

Thank you! So just to confirm.. powering the servos from the 5v pin is a bad idea and I should instead find a 5 volt 1A battery to directly power the servos? Thank you for your help

Don’t power a servo through the 5V pin. However you power the servo, just avoid making the Arduino the power supply.


text:
Sensor to detect whether string is in tension?
I need a sensor to detect whether there is tension on a string or not. I do not need an accurate measurement of the amount of tension- just whether the string is being pulled on or is taut.
Alternatively, if there is some homemade hack of this sensor, please let me know. I'd love to give it a shot!

tie the string to a spring loaded lever that closes a switch when the string is pulled

Tie the string to a momentary pull switch. It's like a button but you pull it, not push it.


text:
Adafruit Circuit Playground Express interrupt not working
I have interrupts attached to pins 4 and 5 which correspond to the left and right inbuilt buttons on the circuit playground express (https://learn.adafruit.com/adafruit-circuit-playground-express/pinouts). For some reason the right button interrupt works perfectly however the left interrupt doesn't even trigger. Here's the code:
#include <Adafruit_Circuit_Playground.h>
#include <Adafruit_CircuitPlayground.h>

volatile bool leftState = false, rightState = false;

void left()
{
    if (CircuitPlayground.leftButton())
        leftState = !leftState;
}

void right()
{
    if (CircuitPlayground.rightButton())
        rightState = !rightState;
}

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

    attachInterrupt(digitalPinToInterrupt(4), left, CHANGE);
    attachInterrupt(digitalPinToInterrupt(5), right, CHANGE);
}

void loop()
{
    Serial.print(leftState);
    Serial.print("\t");
    Serial.print(rightState);
    Serial.print("\n");
}

Pin 4 on Zero can't be used with attachInterrupt. It is pin PA08 of the SAMD21 and this has NMI as interrupt control function in EIC and can't be used as EXTINT.
Adafruit Circuit Playground maps PA28 to pin 4, but the description of the pin is left as for Zero and doesn't declare interrupt capability.
In file arduino/hardware/samd/1.6.21/variants/circuitplay/variant.cpp change the line for pin 4 to
  { PORTA, 28, PIO_DIGITAL, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_8  },                           // GPIO D4 / Left Button

Packages are located in ~/.arduino15/packages/ on Linux and %userprofile%\AppData\Local\Arduino15\packages\ on Windows (AppData is a hidden folder).
Warning: In variant.cpp the overview comment's table describes Zero, not Circuit Playground.
Note: It is not beneficial to read a button with interrupt. You can only set some flag in interrupt and then handle it in the loop(). But then you can directlly check in loop the state of the pin, because it will be active many loops even if the user pushes it for a short time.

I have a lot of delays in my main loop (the code I posted is simplified to isolate the issue), so the button inputs wouldn't register. To be clear, what value should I put as the first parameter when I attach the interrupt for the left button?

wait, so the pinout for the playground express states that button a is an interrupt pin but you can't actually use it as an interrupt pin?

pinout where? I checked the variant.cpp for this board in Arduino SAMD boards package

https://cdn-learn.adafruit.com/assets/assets/000/049/780/original/Adafruit_Circuit_Playground_Express_Pinout.pdf Button A is labelled as an interrupt

the description in variant.cpp doesn't match the true mapping used. I rewrite the answer. you will need to patch variant.cpp

Let us continue this discussion in chat.

I changed the answer

I get compilation errors now

@JamesA, Adafruit has own SAMD boards package with Circuit Playground Express. it has the same error in variant.cpp

I made a change to the code in the repo. It should now be fixed. My issue here was that when I edited the file with vscode, it was inserting special invisible characters which gave me errors. When I changed it with notepad, all was good


text:
Multiple defintion error, Linker error
Trying to create an elf file for two sets of files in different folders.
LIDARBOT.h
-----------
#ifndef LIDARBOT_H_
#define LIDARBOT_H_

#include <avr/io.h>
#include "drivers/motors.h"

#endif

LIDARBOT.C
----------
#include "LIDARBOT.h"
int main(){
  pwmtimersetup();
    while (1) {
    }
}

motors.h
--------
#ifndef MOTORS_H_
#define MOTORS_H_

#include <avr/io.h>

void pwmtimersetup(void);

#endif

motors.c
--------
#include <avr/io.h>
#include "motors.h"

void pwmtimersetup(void){
  // Timer pre-scalar for ~490 Hz is 8
  TCCR0B &= ~((1<<CS02)||(1<<CS00));
  TCCR0B |=  (1<<CS01);
  // Set Compare Output Mode to Toggle PWM
  TCCR0A &= ~(1<<COM0A1);
  TCCR0A |=  (1<<COM0A0);
  // Waveform Generation Mode: WGM02 = 1, WGM01 = 1, WGM00 = 1
  TCCR0B |= (1<<WGM02);
  TCCR0A |= (1<<WGM01)||(1<<WGM00);
  OCR0A = 125;
  DDRD |= (1<<DDD4)||(1<<DDD2);
  PORTD |= (1<<PORTD4);
  PORTD &= (1<<PORTD2);
}

I can make a consolidated object file but not an elf file to load onto my board. Output below:
avr-gcc -g -Os -Wall -Werror -Wextra  -mmcu=atmega328p -DF_CPU=1000000UL -Wa,-ahlmns=LIDARBOT.lst -o objects/LIDARBOT.o \
source/LIDARBOT.c \
source/drivers/motors.c \
-I/home/manu/C/Arduino/LIDARBOT/libraries/

avr-gcc -g -Os -Wall -Werror -Wextra -mmcu=atmega328p -DF_CPU=1000000UL -o elf/LIDARBOT.elf objects/LIDARBOT.o
objects/LIDARBOT.o: In function `__vector_22':
(.text+0x7c): multiple definition of `__bad_interrupt'
/usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.text+0x0): first defined here
objects/LIDARBOT.o: In function `__vectors':
(.text+0x0): multiple definition of `__vectors'
/usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.vectors+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:191: elf] Error 1

I am kind of lost. What could be my mistake here? If I see an error like this how do i start to debug?

I realized that i did not need to add #include <avr/io.h> in the motors.c file. I removed that and tried it again. Same error.

What exactly are you trying to do by the first avr-gcc command line? In that command line I see multiple source files, only one output file and no -c? This looks like a full compile and link, but saving the resultant elf as an .o file. But why? What am I missing?

You forgot the -c flag to your first command. That means you have first compiled your program into a full elf file. Then you try to link that elf file with the standard startup libraries again (it already contains them) into another new elf file.
And so you get duplicate entries in it.
Add -c to your first command, which means "compile only, don't link" to create object files not an elf file.

Thank you guys for your input, AnT and Majenko. I realized my issue which was trying to link a .o file into another one. So I corrected my make file by individually compiling but not linking the source files with the -c option. I then made my final elf file using the unlinked .o files.


text:
Sharing serial output from one to many arduinos (plus a computer) via USB hub
I am trying to send rotary encoder output from an UNO to seven Trinket M0s and a computer via a (powered) USB hub.

Currently the UNO → Laptop bit works great, serial monitoring works via the hub for everyone and I'm able to get a master/slave connection going between the UNO and a Trinket via Arduino's Wire library. But Wire uses pins, and I haven't had any luck finding a similar solution for USB. Thus far, the best leads seem to be around using something like stty in a bash script to listen for what each port is up to but I'm so far in over my head at this point that that might just be wishful thinking.
I'm not looking for a solution here, just some suggestions as to where to head next. Specifically:

Is the Wire library useful for USB communication?  Is there something similar (master/slave-wise) that would be helpful?
Assuming the serial/listen thing works, are there good ways to re-route data to different ports? Currently my best guess is something like $ echo $encoderVal > /dev/cu.usbmodem????? to each one individually ... but that might be a completely noobish notion.)
i2c keeps on coming up in searches, but looks like overkill. Is that a direction to head?
Is this all completely nuts?

Anyways, thanks to everyone in advance.
Update
Ok! Thanks to the advice of @Gerben and @chrisl I ended up routing everything around with PySerial, and (for the extremely limited purposes of this little project) it works well! Here's what is currently working:
import serial
from time import sleep
import os

# Connect to each Arduino individually
serialUno = serial.Serial("/dev/cu.usbmodem141101", 9600, timeout=0)
serialTrinket1 = serial.Serial("/dev/cu.usbmodem1414401", 9600, timeout=0)
# (+ 6 more. serialTrinket2, serialTrinket3, etc)

# Open a text file to save the encoder value in
f = open("encoderVal.txt", "w")

while True:
  # Read encoderVal from the UNO
  data = serialUno.read(9999)
  if len(data) > 0:

    # Send data to each trinket
    serialTrinket1.write(data)

    # Save val to text file to Unity
    with open('encoderVal.txt', 'r+') as f:

      # Wipe the file so it's only the most recent value
      f.truncate()
      dataStripped = data.strip()

      # Return the last int in the data stream
      dataSplit = dataStripped.split('\n')
      f.write(dataSplit[-1])

  sleep(0.05)

# Close serial connections & file on interrupt
serialUno.close()
serialTrinket1.close()
f.close()

As for the laptop end of the equation, I abandoned the serial library that I had been using in favor of this Unity-to-Python tool, which works perfectly.
The only issue thus far is that PySerial loses the occasional few bytes here and there, which outputs a wonky number ever 30 or so. That'll be tomorrow's project.  Thanks everyone for your help!

Why not using Serial (UART) for this? You can connect one transmitter board (the Uno in this case) to multiple receiver boards ( the Trinkets)

I'd use something like Python on the PC, to connect to all the serial ports of the UNO and Trinkets. Have the Python code parse the incoming data (i.e. rotary encoder position), and send it to those boards that need that data. Or even simpler. Read incoming serial data, and send it to all available serial ports (kind of like a repeater). The only thing I don't understand is why you even have a PC in your setup. What's its use? Using something other that USB, means you could run the whole system without the PC attached.

@chrisl Ok, but would that not be adding extra complexity? (First search brought up Emulating UART over USB which gets us to virtual COM ports and ... more.

@Gerben That seems like a solid plan. I'll start researching serial & python.  Re: your question, the PC has to be there because the serial input from the rotary encoder is running a Unity game (the whole HDMI side of this not in the diagram.)

Is the Wire library useful for USB communication? Is there something similar (master/slave-wise) that would be helpful?

The Wire library does I2C communication, which has absolutely nothing to do with USB. Actually the USB connection on the Uno is not native. The Atmega328P on the Uno only has a Serial (UART) interface, which is onboard connected to another chip (Atmega82U or others), which has native USB support. That chip will do the USB communication. The driver on the PC will then emulate a Serial COM port, so that it is something like a "Serial COM port over USB" connection. USB is complex and you should not tinker with it directly, unless you are very advanced in this direction. And I don't think, doing that would help you here.

Assuming the serial/listen thing works, are there good ways to re-route data to different ports? Currently my best guess is something like $ echo $encoderVal > /dev/cu.usbmodem????? to each one individually ... but that might be a completely noobish notion.)

Since you have a complete Unity game, you have to program something in that direction. Using the bash seems not good here. I don't know, if you can communicate with serial COM ports from Unity (since I haven't worked with it yet), but doing this in Python works like a charm. There are many tutorials out there, that show how to do it.

i2c keeps on coming up in searches, but looks like overkill. Is that a direction to head?

If that is an overkill depends on your exact requirements for the system. Sure, the I2C protocol has a bit of overhead, but maybe you need the functionality.

Is this all completely nuts?

Currently it seems a bit like that. I think, this due to you not having a good structure for the project. To help you with that, I will explain some possibilities below.

As I understood, you have the following setup: The Uno has a rotary encoder, that controls a game on the PC. All boards (Uno and Trinkets) have one LED strip, that should light up depending on what happens in the game.
You have now 2 basic structures for the communication:

Doing everything over an own USB connection. This is what you sketched above. Every board has it's own serial COM port (which actually get's emulated over USB by the driver) on the PC and your game/program on it has to connect to all these and send the appropriate data. Sure this is a possible design, but it comes with downsides: Currently it doesn't seem, that you already have implemented the communication program. That is important in this design, but that's not really about Arduino and depends on how you are programming the game in Unity (haven't done that before and don't know how to connect a serial device to it. Maybe through a python script). The second problem is, that you will have choose the serial port for every board, when you start the game. The port numbers/names are not always the same; it's up to the operating system to set these. That's not a great usablity.
You can use other communication interfaces between the boards directly. In this case only the Uno would be connected via USB to the PC and every data would go through the Uno. What kind of interface you should use depends on your exact requirements. Since you didn't specify them in detail, I will explain some examples:

Every Trinket get's the exact same data and nothing must be read from them: In this case you can use the Serial (UART) interface. It uses the pins, that are marked with RX (receiving pin) and TX (transmitting pin). Normally this connection is only between 2 boards, but it is possible to simply connect multiple receivers (with their RX pin) to exactly 1 transmitter (with it's TX pin).
The Uno has one hardware Serial interface, which is also used to communicate with the PC. If it is OK, that the PC also get's the data, which is meant for the Trinkets, (and the Trinkets get the data, that are meant for the PC) you can use this interface and wire the Uno's TX to all Trinket RX pins. You can google how to read data from the interface with the Serial library, which is directly available with Arduino. If you don't want the PC to get the same data, you can set up a SoftwareSerial interface (with the library with that name). That provides the same interface, but is handled in software, because the Uno doesn't have another hardware Serial (UART) interface.
In both cases you would transmit the data from the PC (data out of the game) via the USB serial port to the Uno, which then in turn sends it further to all the Trinket boards. They read the data and act accordingly. Everytime the Uno senses new rotary encoder positions, it will send data to the PC.
For connected the Uno with a Trinket, you only need 2 wires in this design (1 for Uno TX to Trinket RX and 1 ground wire). Of course, you also would have to provide power to the Trinkets. Please see below for that matter.
Every Trinket can be address individually and data can also be read from them: In this case I2C can be the way to go. For the communication you need at least 3 wires (SDA, SCL and ground). Every Trinket joins the I2C bus with a configured address. The Uno acts as master on the bus. He can call a Trinket by it's address and send or request data. The I2C protocol is more structured than serial (UART), because it is divided into transmissions. This works great, if the Trinkets can all get different data, and if you also want to read data from them. Be sure to give very Trinket a unique address on the bus. For the program part look into the Wire library.
Individual sending and receiving in a very fast manner: If you need the individual data transmitting and reading from I2C, but you also need the communication to be very fast, you can use SPI. The SPI bus doesn't use addresses, but Slave Select pins. You need 1 pin on the master (Uno) for every slave device. If you want to communicate with one Trinket, you pull it's Slave Select pin to LOW. This bus needs 5 wires (MISO, MOSI, SCK, Slave Select and ground), but the communication can be very fast; way faster than I2C. Look into the SPI libary for the programming of this.

Providing power: Depending on your design and the number and type of the LEDs, you have to look into, how you supply the needed power to the boards. In the design, that you sketched above, (every board directly to USB) the boards themselves should have enough power, but LED strips can be very power hungry, getting fast to currents over 1A. The pinout of Adafruits Trinket M0 shows a maximal current of 500mA from the Vusb pin. The 5V pin of the Uno can handle about 200mA (as I remember, currently not sure. You can google this).
If you choose a design with only the Uno connected to USB, you might need an extra power supply, so that you can provide the power for all Trinkets and their LEDs with it. Please adhere to the current limits of the components, or you may fry your boards.
I hope, that help's. Have fun

Thanks for putting all the time in to this answer. As you'll see I ended up with a far hackier solution than you'd probably advise, but hey, it kinda works!

First, read a bit about USB, it is an entire protocol, not just a hardware/pin based interface. It is actually quite involved. Then it will be clearer to you why a USB (from the Nano) solution will be... difficult.
Based on my understanding, I would use your #2 idea and what has been suggested, and do the following...

Setup the Uno as a USB slave, not a master.
Using the PC, connect to the Uno and the Trinkets.
When the PC gets data from the Uno have the PC "repeat" it to the Trinkets.

I think this will be the easiest and quickest solution.


text:
2 analog sensors, pulse sensor and LM35 problem
I make a project in which I use two analog sensors. A pulse sensor and the LM35 temperature sensor. When I use them separated everything is normal,the codes are fine, when I combine them the lm35 is not precise, has an error margin of about 10 degrees but the pulse sensor seems to be ok. I read something about the analog to digital convertor that Arduino have and need a delay or something to trick the ADC.
I would be grateful if somebody help me to modify the code.
Thank you very much!

#include <LiquidCrystal.h>
#include <TonePlayer.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int pulsePin = A0;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat

const int sensor=A5; // Assigning analog pin A5 to variable ‘sensor’ temperature
float tempc;
float vout; //temporary variable to hold sensor reading

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P = 512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void setup() {

  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
                                    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

  pinMode(sensor,INPUT); // Configuring pin A1 as input                             //   analogReference(EXTERNAL);

  lcd.begin(16, 2);
  lcd.clear();
}

//  Where the Magic Happens
void loop() {
  serialOutput();
  if (QS == true) { // A Heartbeat Was Found
    // BPM and IBI have been Determined
    // Quantified Self "QS" true when arduino finds a heartbeat
    serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
    QS = false; // reset the Quantified Self flag for next time

    vout=analogRead(sensor);
    vout=(vout*500)/1023;
    tempc=vout; // Storing value in Degree Celsius

    Serial.print ("Temperatura: ");
    Serial.print(tempc);
    Serial.println(" C ");

  }
  delay(20); //  take a break
}

void interruptSetup() {
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

void serialOutput() {   // Decide How To Output Serial.
 if (serialVisual == true){
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
  } else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
   }
}

void serialOutputWhenBeatHappens() {
 if (serialVisual == true) { //  Code to Make the Serial Monitor Visualizer Work

     Serial.print("Batai ");  //ASCII Art Madness
     Serial.print("BPM: ");
     Serial.println(BPM);
     lcd.print("Batai ");
     lcd.setCursor(6,0);
     lcd.print("BPM: ");
     lcd.setCursor(10,0);
     lcd.print(BPM);

     lcd.setCursor(0,1);
     lcd.print("Temp: ");
     lcd.setCursor(6,1);
     lcd.print(tempc);
     lcd.setCursor(11,1);
     lcd.print("C ");

     delay(300);
     lcd.clear();
   } else {
     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
   }
}

void arduinoSerialMonitorVisual(char symbol, int data ) {
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
  const int sensorMax = 1024;    // sensor maximum, discovered through experiment
  int sensorReading = data; // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
  // do something different depending on the
  // range value:
}

void sendDataToSerial(char symbol, int data ) {
   Serial.print(symbol);
   Serial.println(data);
}

ISR(TIMER2_COMPA_vect) { //triggered when Timer2 counts to 124

  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise
                                              //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3) { // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T) { // T is the trough
      T = Signal; // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P) {       // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250) {                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ) {
        Pulse = true;                               // set the Pulse flag when we think there is a pulse
        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
        tone1.tone (1000);  // 1000 Hz

        IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
        lastBeatTime = sampleCounter;               // keep track of time for next pulse

        if(secondBeat) {                        // if this is the second beat, if secondBeat == TRUE
          secondBeat = false;                   // clear secondBeat flag
          for(int i=0; i<=9; i++) { // seed the running total to get a realisitic BPM at startup
            rate[i] = IBI;
          }
        }

        if(firstBeat) { // if it's the first time we found a beat, if firstBeat == TRUE
          firstBeat = false;                   // clear firstBeat flag
          secondBeat = true;                   // set the second beat flag
          sei();                               // enable interrupts again
          return;                              // IBI value is unreliable so discard it
        }
      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                    // clear the runningTotal variable

      for(int i=0; i<=8; i++) {                 // shift data in the rate array
          rate[i] = rate[i+1];                  // and drop the oldest IBI value
          runningTotal += rate[i];              // add up the 9 oldest IBI values
        }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true) {    // when the values are going down, the beat is over
      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
      tone1.noTone ();
      Pulse = false;                         // reset the Pulse flag so we can do it again
      amp = P - T;                           // get amplitude of the pulse wave
      thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
      P = thresh;                            // reset these for next time
      T = thresh;
    }

  if (N > 2500) {                          // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }
  sei();                                   // enable interrupts when youre done!
}// end isr

When you use the sensors separately, are you still using this code you've posted? If not, how is the separate code - especially for the LM35 - different from the above?

I still use this code, my problem is that i don't know how to combine them correctly. the code only for LM35 is the next one. ` const int sensor=A5;
float tempc;
float vout;
void setup() {
Serial.begin(115200);
}
void loop() {
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in Degree Celsius
Serial.print ("Temperatura: ");
Serial.print(tempc);
Serial.println(" C ");
delay(1000);

} `

I have a couple of suggestions:
The combined code is very different from the simple LM35 code that works. I'd suggest you start with the combined code but comment out everything that doesn't directly apply to reading the LM35, and get that working correctly.
The interrupt service routine (ISR) is trying to do too much, and leaves the interrupts off during all of those calculation. Plus, its hard to debug code inside an ISR! ISRs should do the minimum work that they have to do. In this case, it looks like it needs to read & save the pulse sensor value and do the N, lastBeatTime, and sampleCounter calculation. Have it also set a flag every time it runs.
The main loop should check that flag, and if it is set, clear it and call another function to do everything you took out of the ISR. Debug this code, perhaps with the LM35 commented out.
Ideally your loop() function should be as simple as:
void loop(){
   Timers.run();
   maybeCalcHeartbeat();
   maybeDoOtherSubtask();
   ...
}

Then the rest of your code goes into "maybeDo" functions. A "maybeDo" just decides whether the time or conditions are right to do a particular thing; if so, the function does it; but in any case, it returns quickly:
void maybeCalcHeartbeat(void){
   if( !isrFlag )
      return;
   else {
      // everything you took out of the ISR goes here //

      isrFlag = false;
   }


text:
Creating PPM signal from 4 integrers
I am currently building a MultiWii based drone, I have built the emisor-receptor that interface 4 analog signals(4 potentiometers to control the drone) and it works perfect, the receiver(arduino Nano, receives correctly the signal and parses it on 4 diferent integrers as expected (values between 1000 and 2000 because the MultiWii software expects that value range), but the problem is when I connect the receiver Nano to the MultiWii controller(Arduino UNO) the Arduino UNO receives incorrect values from the PPM signal(the four channels gets crazy unless the four potentiometers are turned full) so I think that the problem is the PPM generation process.
The problem is that I have taken code from internet to do that signal generation (because I don't know how to do it), and I don't know how to solve it.
Here I paste the NANO receiver to PPM code:

#define channel_number 4
#define sigPin 2
#define PPM_FrLen 27000
#define PPM_PulseLen 400

#include <SoftwareSerial.h>

int ppm[channel_number];

struct Received_data {
  byte ch1;
  byte ch2;
  byte ch3;
  byte ch4;
};

Received_data received_data;

String input;
int throttle, th;
int aileron, ail;
int elevator, el;
int rudder, rud;

unsigned long lastRecvTime = 0;
int boundLow;
int boundHigh;
const char delimiter = ',';

SoftwareSerial hc12(9, 10);

void setup()
{
  Serial.begin(9600);
  hc12.begin(9600);
  pinMode(13, OUTPUT);

  pinMode(sigPin, OUTPUT);
  digitalWrite(sigPin, 0);

  cli();
  TCCR1A = 0;
  TCCR1B = 0;

  OCR1A = 100;
  TCCR1B |= (1 << WGM12);
  TCCR1B |= (1 << CS11);
  TIMSK1 |= (1 << OCIE1A);
  sei();

  reset_received_Data();
}

void reset_received_Data()
{
  received_data.ch1 = 0;
  received_data.ch2 = 127;
  received_data.ch3 = 127;
  received_data.ch4 = 127;

  PPM_width_Values();
}

void PPM_width_Values()
{
  ppm[0] = map(received_data.ch1,   0, 255, 1000, 2000);
  ppm[1] = map(received_data.ch2,   0, 255, 1000, 2000);
  ppm[2] = map(received_data.ch3,   0, 255, 1000, 2000);
  ppm[3] = map(received_data.ch4,   0, 255, 1000, 2000);
}

void receive_the_data()
{
  if (hc12.available())
  {
    input = hc12.readStringUntil('\n');
    if (input.length() > 0)
    {
      //Serial.println(input);

      boundLow = input.indexOf(delimiter);
      ppm[0] = input.substring(0, boundLow).toInt();

      boundHigh = input.indexOf(delimiter, boundLow + 1);
      ppm[1] = input.substring(boundLow + 1, boundHigh).toInt();

      boundLow = input.indexOf(delimiter, boundHigh + 1);
      ppm[2] = input.substring(boundHigh + 1, boundLow).toInt();

      ppm[3] = input.substring(boundLow + 1).toInt();

      Serial.print(ppm[0]); Serial.print("   ");
      Serial.print(ppm[1]); Serial.print("   ");
      Serial.print(ppm[2]); Serial.print("   ");
      Serial.print(ppm[3]); Serial.print("\n");
      delay(10);
    }

  }
}

void loop()
{
  receive_the_data();
  digitalWrite(13, HIGH);

}

#define clockMultiplier 2

ISR(TIMER1_COMPA_vect) {
  static boolean state = true;

  TCNT1 = 0;

  if ( state ) {
    //end pulse
    PORTD = PORTD & ~B00000100;
    OCR1A = PPM_PulseLen * clockMultiplier;
    state = false;
  }
  else {
    //start pulse
    static byte cur_chan_numb;
    static unsigned int calc_rest;

    PORTD = PORTD | B00000100;
    state = true;

    if (cur_chan_numb >= channel_number) {
      cur_chan_numb = 0;
      calc_rest += PPM_PulseLen;
      OCR1A = (PPM_FrLen - calc_rest) * clockMultiplier;
      calc_rest = 0;
    }
    else {
      OCR1A = (ppm[cur_chan_numb] - PPM_PulseLen) * clockMultiplier;
      calc_rest += ppm[cur_chan_numb];
      cur_chan_numb++;
    }
  }
}

I don't understand, what the problem is. Please make clearer, from where to where you are sending data over which interface and what goes wrong with it. And why do you include the receiver code of the Nano (that you used for testing?), but not the sender code?

@chrisl I use an arduino nano as sender, an arduino nano as receiver and an arduino uno as flight controller, the send and receive process it correct because if I serial monitorize the data that nano receiver receives, it is correct. The problem is that that arduino nano after receive that data wirelessly, it must send the data over a wire in a PPM signal, and thats the problem, the PPM signal isn't sent correctly so I need help with the PPM signal generation.


text:
ESP8266 does not detect WiFi networks
I have an ESP8266-12E, I used it previously and it worked fine (approx 2 years ago)
I can't seem to get it to detect WiFi networks or appear as an Access Point
I can upload the blink sketch and the onboard LED will work correctly and the serial monitor will show output from the ESP8266, but there appears to be no WiFi functionality
I have tried using previous versions of the ESP core board definition via the Arduino board manager
I have tried using an external power supply (wall plug) rather than the powering from a USB port
I have tried erasing the flash using esptool.py
I have checked that the WiFi router I am trying to connect to is operating at 2.4Ghz (also there are other WiFi networks around and I set up a second router to make sure)
I have tried connecting to the Access Point using the SSID (with and without a password) despite it not appearing
I have tried getting it to connect to an Access Point even though none are found
Is there something I am missing or should I order a new module?
Any other suggestions please!
Output when uploading a sketch
    esptool.py v2.6
    Serial port /dev/cu.SLAB_USBtoUART
    Connecting........_
    Chip is ESP8266EX
    Features: WiFi
    MAC: a0:20:a6:12:51:46
    Uploading stub...
    Running stub...
    Stub running...
    Erasing flash (this may take a while)...
    Chip erase completed successfully in 9.0s
    Hard resetting via RTS pin...
    esptool.py v2.6
    Serial port /dev/cu.SLAB_USBtoUART
    Connecting........_
    Chip is ESP8266EX
    Features: WiFi
    MAC: a0:20:a6:12:54:54
    Uploading stub...
    Running stub...
    Stub running...
    Configuring flash size...
    Auto-detected Flash size: 4MB
    Compressed 293920 bytes to 210833...

    Writing at 0x00000000... (7 %)
    Writing at 0x00004000... (15 %)
    Writing at 0x00008000... (23 %)
    Writing at 0x0000c000... (30 %)
    Writing at 0x00010000... (38 %)
    Writing at 0x00014000... (46 %)
    Writing at 0x00018000... (53 %)
    Writing at 0x0001c000... (61 %)
    Writing at 0x00020000... (69 %)
    Writing at 0x00024000... (76 %)
    Writing at 0x00028000... (84 %)
    Writing at 0x0002c000... (92 %)
    Writing at 0x00030000... (100 %)
    Wrote 293920 bytes (210833 compressed) at 0x00000000 in 18.6 seconds (effective 126.4 kbit/s)...
    Hash of data verified.

    Leaving...
    Hard resetting via RTS pin...

try the AT firmware

I tried downloading the default firmware from nodemcu-build.com and flashed it. Is this the one you mean?

Lua firmware? no. and does it work

I got an output saying the version of the Lua firmware and it could not init but I didn't try any AT commands... trying to find the AT firmware currently

https://www.espressif.com/en/support/download/at?keys=&field_type_tid%5B%5D=14 use 1.6.2. instructions: https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf chapter 1.2.2.


text:
How can I make FastLED set every 2 LEDs to the same color?
I'm controlling an WS2812 LED strip in which every 2 leds is controlled together - they are setup as "eyes" in a prop.  I'm looking to control hundreds of these, so in an effort to save RAM I'd like to have each byte in the LED color array represent 2 LEDs.  That is to say that when the FastLED library writes to the data lin I want it to duplicate every byte going out.
I've dug into FastLED code but get lost around the timings deep down in the code.
Any ideas?

use an ESP, they have plenty of RAM. modifying the code to save ram will be a lot of work and probably limit features/updates.

@dandavis I’m trying to use up a pile of atmega328 chips that I have. Saving the 400 or so bytes would be perfect without reworking the board. However, o have a bunch of old atmega1284 chips too. Going that route.

The FastLED community appears to live at this reddit.com site. Consider asking your question there.
It is unknown if the following will exceed the current limitations of the Arduino platform you are using.  But, consider sending the same data to two different strings of LEDs simultaneously.  Briefly, each LED strips off the 1st packet of data and sends the balance of data through to the next LED.  Two different strips should behave the same if given the same data.  Thereby creating the effect you described (pairs of LEDs behaving the same).

I'm dealing with premade strips of eyes, so the two strip idea isn't feasible at this time. Thanks for pointing me to the subreddit. I've posted there.

A quick look at the FastLED repository and it looks like it is very complex and possibly created for multiple Arduino platforms (that is, different processors).  As such you need to specify exactly what hardware you are using.  Something you didn't list here.  And something that is specifically asked for over at the reddit.com site.  More to the point, the transfer rate to feed the LEDs can be very high and direct memory transfer for some of the higher end processors is a possibility.  In such a case it may be difficult to save much on memory.